text:
Q: How to make VK_LAYER_KHRONOS_validation available? Solution:

*

*Uninstall vulkan

*In registry HKLM\SOFTWARE\Khronos\Vulkan\ExplicitLayers and HKLM\SOFTWARE\WOW6432Node\Khronos\Vulkan\ExplicitLayers remove everything

*reinstall vulkan

I recently started learning how to use Vulkan. I'm following this tutorial but even with a copy/paste of their code I got an error because VK_LAYER_KHRONOS_validation is not listed when I call vkEnumerateInstanceLayerProperties().
In the Vulkan configurator, VK_LAYER_KHRONOS_validation appear in the right panel but not in the bottom one (I'm not sure about what this configurator is for but there is an "Available Layers" category in the bottom panel and the names written there are the one listed by vkEnumerateInstanceLayerProperties()).
Vulkan Development Status:
- Layers override: "Validation" configuration
- VULKAN_SDK environment variable: D:\Games\lib\Vulkan\1.2.176.1
- Vulkan Loader version: 1.2.141
- User-Defined Layers Paths from VK_LAYER_PATH environment variable: None
- User-Defined Layers Paths from Vulkan Configurator: None
- Available Layers:
    - VK_LAYER_NV_optimus (1.2.142)
    - VK_LAYER_VALVE_steam_overlay (1.2.136)
    - VK_LAYER_VALVE_steam_fossilize (1.2.136)
    - VK_LAYER_EOS_Overlay (1.2.136)
    - VK_LAYER_EOS_Overlay (1.2.136)
    - VK_LAYER_OBS_HOOK (1.2.131)
    - VK_LAYER_OBS_HOOK (1.2.131)
- Physical Devices:
    - GeForce GTX 950 (Discrete GPU) with Vulkan 1.2.142

Other tutorials I found use VK_LAYER_LUNARG_standard_validation but it don't work too and is Deprecated.
So do I need to install validation layer manually, if yes where?
And if no, why is VK_LAYER_KHRONOS_validation unavailable and how can I use it?
I'm sure I'm missing something obvious ç_ç.

Additional information :

*

*I'm compiling x64

*I've uninstalled/reinstalled the sdk and it's still not working

*The error message is : validation layers requested, but not available!

*The sdk is the 1.2.176.1 from 05-May-2021. I downloaded the SDK Installer (.exe the first one)

*To get available layer the code is:

uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());

*

*If I skip the verification the error message is: (btw why Rockstar Game line 3??)

validation layer: loaderGetDeviceRegistryFiles: GUID for 23 is not SoftwareComponent skipping
validation layer: loaderGetDeviceRegistryFiles: GUID for 24 is not SoftwareComponent skipping
validation layer: loader_get_json: Failed to open JSON file C:\Program Files\Rockstar Games\Social Club\SocialClubVulkanLayer.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_api_dump.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_device_simulation.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_gfxreconstruct.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_khronos_synchronization2.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_khronos_validation.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_monitor.json
validation layer: loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_screenshot.json
validation layer: verifyMetaLayerComponentLayers: Meta-layer VK_LAYER_LUNARG_override can't find component layer VK_LAYER_KHRONOS_validation at index 0.  Skipping this layer.
validation layer: Removing meta-layer VK_LAYER_LUNARG_override from instance layer list since it appears invalid.
validation layer: loaderValidateLayers: Layer 0 does not exist in the list of available layers
failed to create instance!

*

*I'm not a native English speaker nor a regular user of StackOverflow so if I made a mistake please tell me so I can progress

EDIT:
In the BIN folder VkLayer_khronos_validation.dll/.json/.pdb exists
so I run vulkaninfoSDK.exe and notice that it try to load from the file D:\Games\lib\1.2.176.1\Bin instead of D:\Games\lib\Vulkan\1.2.176.1\Bin so I think I found the problem. But WHY? The file is not here why is it skipping a folder ?
EDIT2:
I changed the folder (removed the \Vulkan\ in the directory) and now errors are (with vulkaninfoSDK.exe):
ERROR: [Loader Message] Code 0 : loader_get_json: Failed to open JSON file C:\Program Files\Rockstar Games\Social Club\SocialClubVulkanLayer.json
WARNING: [Loader Message] Code 0 : loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_api_dump.json invalid layer manifest file version 1.2.0.  May cause errors.
WARNING: [Loader Message] Code 0 : loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_device_simulation.json invalid layer manifest file version 1.2.0.  May cause errors.
WARNING: [Loader Message] Code 0 : loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_gfxreconstruct.json invalid layer manifest file version 1.2.0.  May cause errors.
WARNING: [Loader Message] Code 0 : loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_khronos_synchronization2.json invalid layer manifest file version 1.2.0.  May cause errors.
WARNING: [Loader Message] Code 0 : loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_khronos_validation.json invalid layer manifest file version 1.2.0.  May cause errors.
WARNING: [Loader Message] Code 0 : loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_screenshot.json invalid layer manifest file version 1.2.0.  May cause errors.

and with the code I get:
validation layer: loaderGetDeviceRegistryFiles: GUID for 23 is not SoftwareComponent skipping
validation layer: loaderGetDeviceRegistryFiles: GUID for 24 is not SoftwareComponent skipping
validation layer: loader_get_json: Failed to open JSON file C:\Program Files\Rockstar Games\Social Club\SocialClubVulkanLayer.json
validation layer: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_api_dump.json invalid layer manifest file version 1.2.0.  May cause errors.
validation layer: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_device_simulation.json invalid layer manifest file version 1.2.0.  May cause errors.
validation layer: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_gfxreconstruct.json invalid layer manifest file version 1.2.0.  May cause errors.
validation layer: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_khronos_synchronization2.json invalid layer manifest file version 1.2.0.  May cause errors.
validation layer: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_khronos_validation.json invalid layer manifest file version 1.2.0.  May cause errors.
validation layer: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_screenshot.json invalid layer manifest file version 1.2.0.  May cause errors.
validation layer: Searching for ICD drivers named .\nvoglv64.dll
validation layer: Build ICD instance extension list
validation layer: Instance Extension: VK_KHR_device_group_creation (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_external_fence_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_external_memory_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_external_semaphore_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_get_physical_device_properties2 (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.2
validation layer: Instance Extension: VK_KHR_get_surface_capabilities2 (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_surface (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.25
validation layer: Instance Extension: VK_KHR_surface_protected_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_win32_surface (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.6
validation layer: Instance Extension: VK_EXT_debug_report (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.9
validation layer: Instance Extension: VK_EXT_debug_utils (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.2
validation layer: Instance Extension: VK_EXT_swapchain_colorspace (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.4
validation layer: Instance Extension: VK_NV_external_memory_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Loading layer library D:\Games\lib\1.2.176.1\Bin\.\VkLayer_khronos_validation.dll
validation layer: Loading layer library C:\ProgramData\obs-studio-hook\.\graphics-hook64.dll
validation layer: Loading layer library C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll
validation layer: Build ICD instance extension list
validation layer: Instance Extension: VK_KHR_device_group_creation (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_external_fence_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_external_memory_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_external_semaphore_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_get_physical_device_properties2 (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.2
validation layer: Instance Extension: VK_KHR_get_surface_capabilities2 (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_surface (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.25
validation layer: Instance Extension: VK_KHR_surface_protected_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Instance Extension: VK_KHR_win32_surface (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.6
validation layer: Instance Extension: VK_EXT_debug_report (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.9
validation layer: Instance Extension: VK_EXT_debug_utils (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.2
validation layer: Instance Extension: VK_EXT_swapchain_colorspace (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.4
validation layer: Instance Extension: VK_NV_external_memory_capabilities (C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll) version 0.0.1
validation layer: Unloading layer library C:\WINDOWS\System32\DriverStore\FileRepository\nv_dispi.inf_amd64_60daf66a00f2e0b6\.\nvoglv64.dll
validation layer: Unloading layer library C:\ProgramData\obs-studio-hook\.\graphics-hook64.dll
validation layer: Unloading layer library D:\Games\lib\1.2.176.1\Bin\.\VkLayer_khronos_validation.dll

so why Rockestar Game? and why

invalid layer manifest file version 1.2.0.
?

EDIT:
So I change the file location and I think it's working.
the final question is: loaderAddLayerProperties: D:\Games\lib\1.2.176.1\Bin\VkLayer_api_dump.json invalid layer manifest file version 1.2.0.  May cause errors. why "May cause errors" and is it important?
And just for fun: why is it trying to load C:\Program Files\Rockstar Games\Social Club\SocialClubVulkanLayer.json?
Is Rockstar in the development of Vulkan or anything?
Re edit:
I re-uninstall/re-reinstall the sdk and ?????
This time I'm 100% sure I did not move the file and it still try to load from \lib\1.2.176.1 and is skipping the \vulkan\ ???
tbh the first install of the sdk was there (without the \vulkan) and probably didn't work bcs I renamed a folder but why it kept the old path after re-install?
but anyway if I move it to match these directory it seems to work x)
I rerere-uninstall/reinstall the sdk in a totally different folder and guess what?
sdk installed in D:\Prgm\1.2.176.1
when I run vulkaninfoSDK.exe : ERROR: [Loader Message] Code 0 : loader_get_json: Failed to open JSON file D:\Games\lib\1.2.176.1\Bin\VkLayer_api_dump.json
So I guess I'm stuck with the path of my first install
just for the joke:(yes I'm talkative)
I rererere-uninstall/reinstall the sdk at its original location and now it try to load the file from D:\Games\lib\Vulkan\1.2.176.1\Bin\VkLayer_api_dump.json ? I probably messed-up with the installation but damn
In the Vulkan installation analysis tool I find duplicates.
Idk why but it look at the previous and wrong directory first but the right directory is present
So I'm trying to remove unnecessary directory

A: The warnings are normal, as per SDK release notes. The Rockstar thing is some overlay or something that was uncleanly uninstalled (you could remove it in registry similar to below instructions if you want).
You should check the value of %VULKAN_SDK% variable if it is correct.
Then you should check HKLM\SOFTWARE\Khronos\Vulkan\ExplicitLayers and HKLM\SOFTWARE\WOW6432Node\Khronos\Vulkan\ExplicitLayers if it is correct and has no duplicates. (Alternatively you could uninstall first, and in that case there should be no SDK paths left in there)
Also the configurator app allows overrides, so you need to check it is Tools->Reset, and set to "Fully controled by Vulkan apps". When closing it should warn that no Vulkan overrides are active, and you should click Yes.

A: For the Rockstar problem, It seems that many game launchers install implicit layers for Vulkan. In my case It was a GOG layer causing the problem, but it seems that when you uninstall many of these programs, they do not remove their keys from the registry.
To fix the problem, check both

*

*Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ImplicitLayers

and

*

*Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ExplicitLayers

for a key that matches the .json that can not be found and delete it. The error should then stop.
I have that exact Rockstar key in the ExplicitLayers folder and found my GOG key in the ImplicitLayers folder.


text:
Q: sshpass through regular ssh client I am using an application that uses /usr/bin/ssh and requires passwordless authentication. Meanwhile I want to use this with a server that requires both publickey and password authentication at the same time. Just using sshpass is a good solution in most circumstances (given that my secret password is safe and that I am also using safe public key authentication at the same time), but sshpass wraps around ssh and not the other way around.
How can I use sshpass when /usr/bin/ssh x is called? My current workaround is the config below. It works, but it hops from the target server to itself. I would rather not have this overhead.
Host x
    HostName xxx.xxx.xx
    ProxyCommand sshpass -f passwordfile ssh -W %h:%p xxx.xxx.xx

Is there a way to get the same result without hopping to the server itself?
(Otherwise - for future people with the same problem - the above config is a workable solution.)

A: Given that the application that I'm using is a CLI program that searches for ssh in $PATH, it is possible to modify PATH to include a special ssh command that is actually a sshpass wrapper.
Wrap sshpass into a executable called ssh:
/path/to/bin/ssh:
#!/usr/bin/env bash
sshpass -f /path/to/passwordfile ssh "$@"

Then prepend the parent dir of the custom ssh to PATH when running myapp by adding the following alias in .zshrc or .bashrc:
alias myapp="PATH=/path/to/bin:$PATH myapp"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problema com consulta utilizando SQL no PHP Eu tenho o seguinte código:
$nomeConteudo = $_POST['tipoConteudo'];
echo $nomeConteudo;
$id = $conteudo_fkid->cataId($nomeConteudo);
echo $id;

Nele, a variável nomeConteudo recebe o valor de um formulário e logo em seguida o imprimi. Até ai funciona corretamente.
Acontece que preciso utilizar essa variável para comparação e fazer um SELECT na minha tabela conteudo, e retornar o valor do ID.
Este é o código do método:
function cataId($nomeConteudo){
  $query = "select id from conteudo where nomeConteudo = {$nomeConteudo}";
  $resource = mysqli_query($this->conexao, $query);
  return $resource;
}

Acontece que ele não me retorna nada no echo $id. Por outro lado, tem informações certas no banco para poder retornar.
Onde estou errando? Não visualizo nada errado na consulta.

A:
$query = "SELECT c.id id_conteudo FROM conteudo c WHERE nome = '$nomeConteudo'";

//Buscar
  $resource = mysqli_query($conexao, $query);

//Resultado
  if ($resource == null) {
  echo"Nenhum registro encontrado!";
  }else {
        while ($row = mysqli_fetch_assoc($resource)) {
        echo "ID: " . $row['c.id'];
        }
      }

não entendi bem esse seu problema, mas ver isso resolve! ele retorna o id de acordo com seu WHERE $nomeConteudo..

A: Paulo. Provavelmente você está com problema na sua consulta.
Assumindo que o usuário digitou "Igreja" no formulário e fez um submit você terá o seguinte código dentro da própria página (ou em outra) para receber os dados e realizar a consulta pelo tipo;
if (isseet($_POST['tipoConteudo']) && $_POST['tipoConteudo'] != "") {
   $nomeConteudo = $_POST['tipoConteudo'];
   echo $nomeConteudo;
}

Se foi feito um $_POST e esse valor é diferente de vazio você irá realizar a consulta. Então vamos a função:
function requestID($nomeConteudo){
    $query = "SELECT id FROM conteudo WHERE nomeConteudo LIKE '%$nomeConteudo%'";
    $id = mysqli_query($this->connection, $query);

    return $id;
}

Caso você não tem certeza de que a palavra que o usuário digitou no formulário é igual a do banco de dados eu recomendo usar o operador LIKE do SQL. Caso contrário você pode usar usar um simples =, mas terá que garantir que as palavras são iguais.
Voltando ao script da página do formulário vamos fazer a chamada ao método. Para isso, vou usar um classe chamada Conteudo, onde se encontra o método requestID.
if (isseet($_POST['tipoConteudo']) && $_POST['tipoConteudo'] != "") {
   $nomeConteudo = $_POST['tipoConteudo'];
   echo $nomeConteudo;
   $Conteudo = new Conteudo();
   $id_consulta = $Conteudo->requestID($nomeConteudo);
   echo $id_consulta;
}

Tendo o método da consulta pronto o resto foi simples. Bastou instanciar a classe onde o método estava e passar a variável recebida pelo $_POST como parâmetro.
Dica:
Não trabalhe com Strings para realizar consulta (ao menos que seja necessário). O ideal, caso consiga, seria trabalhar com o ID, que traria mais performance para a consulta e uma maior garantia de "sucesso" na mesma.
Veja mais:
Operador LIKE
Guia prático de mysqli no PHP


text:
Q: Prevent the System from Entering Sleep or Turning off the Display while Application is Running I'm using Delphi XE Rio in Windows 8.1
My goal is to prevent system going into sleep mode and turning off the monitor.
I tried this one but not getting works.

http://delphidabbler.com/tips/127

I'm using this
SystemCritical.IsCritical = true;
try
  // do critical operation here
  // without going in to sleep or turning off the display
finally
  SystemCritical.IsCritical = false;
end;

My computer just still turning off monitor then going to sleep.


text:
Q: Line graph not displayed with plotly in R My final aim is to create 2 time series line graphs on the same plot, with the one being static and the other being animated (the former refers to the actual data and the latter on my model's fitted values). I am trying to accomplish that with plotly, however I am completely new and have crossed difficulties.
In order to get familiar with plotly first before attempting the above I initially tried to create just one animated graph on a plot. However I cannot even make that ostensibly simple script work. When running the below no graph is displayed on my plot area, like there are no data. My script is created based on following link: https://plot.ly/r/cumulative-animations/
plot_ly(data
        , x=~data$RequCreatedFull_Date
        , y=~data$fitted_TotalRequ_Qnt_pm
        , name="Fitted"
        , type='scatter'
        , mode = "lines"
        , line = list(color = "rgb(255,128,0)")
        , frame = ~data$RequCreatedFull_Date
        , line = list(simplyfy = F)) %>%
layout(title="name"
       , xaxis = list(range =
                           c(as.numeric(min(data$RequCreatedFull_Date))*1000
                           ,as.numeric(max(data$RequCreatedFull_Date))*1000)
                      , type = "date"
                      , title = "Requisition Date"
                      , zeroline = F)
       , yaxis = list(title="Total Requisition Qnts"
                      , range = c(1000,30000)
                      , zeroline = F)) %>%
  animation_opts(frame = 100,
                 transition = 0,
                 redraw=FALSE) %>%
  animation_button(x = 1, xanchor = "right", y = 0, yanchor = "bottom")

data is a 53 obs, 4 variables (dates, actuals, fits, index) data frame.
When 'Play' button for animation is clicked and while the animation's frames proceed, when hovering on the plot area the data points' tooltips are displayed for a moment, however no graph is displayed.
Thank you in advance for all your assistance, hope I provided you with sufficient info.

A: I mistakenly took part of the script the below link for the animated plotting (https://plot.ly/r/cumulative-animations/). The problem is that I did not modify the to-be-framed variable (variable to be used in frame parameter of plot_ly function) before using it.
Therefore, in order for the plot to work properly I should: 1. define accumulate_by function, 2. use it with the to-be-framed variable as input, 3. the output column produced from step 2 will be the value for the frame parameter of 'plot_ly' function.
Initial working data frame is data2, with columns RequCreatedFull-Date(as POSIXct), Requs_Qnt_pm(as num), Type(as Factor), date(as num) where
date=(year(RequCreatedFull_Date)+(month(RequCreatedFull_Date)-1)/12).
Please refer to working script below:
library(plotly)
library(dplyr)
library(lubridate)

#step 1: function definition
accumulate_by <- function(dat, var) {
  var <- lazyeval::f_eval(var, dat)
  lvls <- plotly:::getLevels(var)
  dats <- lapply(seq_along(lvls), function(x) {
   cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
  })
  dplyr::bind_rows(dats)
}

#step 2: creation of to-be-used for framing variable
data2mod <- data2 %>%
  accumulate_by(~date)

#graph creation
my_graph<-data2mod %>%
             plot_ly(
               x = ~date,
               y = ~Requs_Qnt_pm,
               split = ~Type,
               frame = ~frame, #step 3, to be frame variable insertion
               type = 'scatter',
               mode = 'lines',
               line = list(simplyfy = F)
            ) %>%
             layout(
                xaxis = list(
                  title = "x axis title",
                  zeroline = F
               ),
                yaxis = list(
                  title = "y axis title",
                  zeroline = F
               )
            ) %>%
            animation_opts(
              frame = 100,
              transition = 0,
              redraw = FALSE
            ) %>%
            animation_slider(
              hide = T
            ) %>%
            animation_button(
               x = 1, xanchor = "right", y = 0, yanchor = "bottom"
            )

A: In xaxis and in yaxis showline=TRUE


text:
Q: What is the spin rotation operator for spin > 1/2? For spin $\frac{1}{2}$, the spin rotation operator $R_\alpha(\textbf{n})=\exp(-i\frac{\alpha}{2}\vec{\sigma}\cdot\textbf{n})$ has a simple form:
$$R_\alpha(\textbf{n})=\cos\biggl(\frac{\alpha}{2}\biggr)-i\vec{\sigma}\cdot\textbf{n}\sin\biggl(\frac{\alpha}{2}\biggr)$$
What about spin > $\frac{1}{2}$ ?

A: What one has for the spin 1/2,
\begin{equation}
 \exp(i\alpha \mathbf{J}\cdot\hat{\mathbf{n}}) = \cos(\alpha/2) + i\sin(\alpha/2)\mathbf{J}\cdot\hat{\mathbf{n}},
\end{equation}
as well for spin 1 through Rodrigues formula,
\begin{equation}
 \begin{aligned}
  \exp(i\alpha \mathbf{J}\cdot\hat{\mathbf{n}}) & = 1 + i\hat{\mathbf{n}}\cdot\mathbf{J}\sin\alpha + (\hat{\mathbf{n}}\cdot\mathbf{J})^2(\cos\alpha-1) \\
& = 1 + \left[2i\hat{\mathbf{n}}\cdot\mathbf{J}\sin(\alpha/2)\right]\cos(\alpha/2) + \frac{1}{2}\left[2i\hat{\mathbf{n}}\cdot\mathbf{J}\sin(\alpha/2)\right]^2,
 \end{aligned}
\end{equation}
is a spin representation of rotation operators as finite order polynomials of the rotation generators for $j=1/2,1$, where the coefficients are sines and cosines of half the angle of rotation. It was known that this could be extended for higher spin representations, but the exact polynomial expression for any spin $j$ remained unknown. Fortunately, in 2014 this general expression was found by Curtright, Fairlie & Zachos. I leave here their publication: http://arxiv.org/abs/1402.3541

A: The same, except that the $\sigma_k$ are now not Pauli matrices but the generators of a su(2) representation of the desired spin. For example, the $3\times 3$ matrices
$$ \sigma_\ell:=(2\epsilon_{jk\ell})_{j,k=1:3}$$
define the spin 1 representation on 3-vectors. [Maybe the factor 2 should take a different value.] The corresponding explicit formula comes from the Rodrigues formula
$$e^{X(a)}=1+\frac{\sin|a|}{|a|}X(a)+\frac{1-\cos|a|}{|a|}X(a)^2,$$
where $X(a)$ is the matrix mapping a vector $b$ to $X(a)b=a \times b$.
For higher spin, the corresponding formula will depend on how you write the representation. Numerically, one would just diagonalize the matrix in the exponent; then computing the exponential is trivial. I don't know whether for general spin if there is any advantage in having an explicit formula.


text:
Q: Conditional formatting in webi Rich Client 4.1 of multiple values I'm in BO 4.1 using a crosstab table.  It is summary data based off specific detail information.  Example:
Area-Days Late-Order #-Reason
1 - 5 - 12345-Lost
1 - 2 - 843254 - Lost
2 - 4 - 7532384 - Lost
1 - 7 - 12353 - Not home
So the output would be
     Area 1    Area 2

Lost       2          1
Not home   1          0
Now for the conditional formatting part, I want it to highlight the Area 1 Lost cell as red because two of the orders are greater than 3 days late.
For whatever reason it seems to not be doing it because it's getting hung up line item 2 because that one is less than 3 days late.
Thank you!

A: I cheated and created a new object and then summed and did an if statement.  Thanks for looking at this.


text:
Q: Topological properties of $A = \{ (x,y) \in \Bbb{R}^{2} \mid y = mx \} \setminus \{ ( 0,0 ) \} \subset \Bbb{R}^{2}$ Let $A = \{ (x,y) \in \Bbb{R}^{2} \mid  y = mx \} \setminus \{ ( 0,0 ) \} \subset \Bbb{R}^{2}$. Then $A$ is
(a) open,
(b) closed,
(c) connected,
(d) nowhere dense.
This question was asked in NBHM test for PhD scholarship 2005 (I think they forgot to mentioned that $m$ is a real number).
The correct answer is (d) nowhere dense (according to the answer key they have provided).
For (b): Here I can prove that given set is not closed since $(0,0)$ is a limit point of this set which doesn't belong to the set.
For (a): Intuitively I'm feeling that it is not open, since this set is set of lines passing through the origin in $\Bbb{R}^{2}$. We are unable to draw open ball at any point of the set which is contained in the set. (Is my reasoning correct? Please mention if there is another method to prove that the set is not open).
For (c): This set is the union of disjoint sets, since the intersection of lines passing through origin is singleton set $\{(0,0)\}$ but here that point doesn't belong to the set. but I don't think this argument is enough to prove given set is not connected. Since we know the example of broken comb space which can be written as union of disjoint sets but broken comb space is connected. (I know that there are several other methods of proving given set not connected for eg: there will be a continuous function from given set to discrete space $\{0,1\}$, but I'm unable to construct such function).
For (d) Given set is union of straight lines passing through origin (line in real plane is nowhere dense) and since real plane is complete under usual metric, by Baire's theorem given set is nowhere dense. Is my argument correct?
Please help.
Thanks in advance.

A: I think $m$ is fixed.
Any line in the plane is connected, closed and nowhere dense and it contains no non-empty open set of the plane. Leaving out the origin kill connectedness (like the reals minus a point) and closedness (as the origin is still a limit point, but no longer in the set). Subsets of nowhere dense sets are still nowhere dense, so indeed (d) must be correct.
If we take the union over all $m$ then we get $\mathbb{R}^2$ minus the $y$-axis which is open, not closed, not connected and not nowhere dense.. This seems unlikely to me.


text:
Q: Flash / AS : animation when SWF is called I have 2737 buttons calling as many SWF (all on the same level, replacing each other when loaded).
I'd like to add a loading animation in my root file that would run every time an url is called or a SWF is loading. is it possible?
I gave up on the idea of incorporating a percentage pre-loader as I would have to add code on all the 2737 buttons... right?
FIY, this is a 2001 CD-Rom project I want to bring back online, so no pre-loader was required then.
any help is greatly appreciated!
here's an example of one of the many buttons:
on (release) {
loadMovieNum("04.12.01.swf", 1);}


text:
Q: django- host a website without python app on cpanel? I am going to host a website build on the Django framework. There are tutorials on youtube on how to host but they all are using the python app already on Cpanel. But my hosting provider Hostgator does not give the python app in Cpanel. is there any other way to host the Django website without the python app on Cpanel?

A: you can host django on digital ocean, with ssh command in the terminal, where you can configure your server with nginx and gunicorn.
tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04-pt
follow the taps.


text:
Q: how to refine this code mental block Rails I have these two methods that I would like to combine into one.  But for the life of me I can't see how. NOOB big time. any help appreciated.
  def is_active_no_category
      'active' if params[:category].blank?
  end

  def is_active(category)
      'active' if  params[:category] == category.name.parameterize
  end

A: With the below function passing a category as an argument is optional. If you do not pass an argument it will work like your is_active_no_category method. If you do pass an argument. It will work like your is_active method.
def is_active(category = nil)
  'active' if (category.present? && params[:category] == category.name.parameterize) || (category.nil? && params[:category].blank?)
end

You may be able to make the if statement more compact, but you haven't stated the exact requirements for your function, so I gave you the most complete solution.


text:
Q: JSP Include textfile if it isn't empty I have a jsp page that is supposed to include the content of a multiline text file (wrapped up in some markup) if, and only if, there is content in that file.
The file always exists, but some times it will be empty, and some times it will have content.
I was thinking of reading the file into a string (or stringBuffer?), and then test the length of it. But since it is a multiline file, my code breaks up on linebreaks.
P.S. I'm a jsp n00b, so bear over with me, if this is a stupidly easy (or impossible) task! :)


text:
Q: how to replace multiple lines in a file after a specific character with null in unix For example, if my file contains
{z:
abdc
cabdfd
cabdfd
casfdbf
cdff
-}$

Once find the string value {z: the multiple lines after that upto -} must be replaced by null character and it should follow the same procedure globally throughout the file.
This must be done in Unix I tried using sed command to search for multiple lines but unable to succeed with it though.

A: You can specify an address range in sed so that the action is performed for lines within the range
To delete the lines within the two pattern
$ cat input
{z:
abdc
cabdfd
cabdfd
casfdbf
cdff
-}$
hello
world

$ sed '/^{z:$/, /$-}\$$/d' input
hello
world

*

*/^{z:$/, /^-}\$$/ specifies the start and end of the range.

To replace with null string
You can use the substitute command as
$ sed '/^{z:/, /-}\$$/s/.*//' input

hello
world

A: If I understand correctly try the following perl solution
#!/usr/bin/perl

undef $/;     ## register separator is undefined
my $t=<>;     ## slurp all input to $t

$t =~ s/\{z:.*?\n-\}/\0/gs;   ## substitute patt by \0
print $t;

Usage: perl thisscript input
If you need a more complex transformation inside the pattern I would suggest:
#!/usr/bin/perl

undef $/;     ## register separator is undefined
my $t=<>;     ## slurp all input to $t

$t =~ s/(\{z:.*?\n-\})/norm($1)/gse;   ## substitute patt by its norm
print $t;

sub norm{ my $s = shift;
    ## transform $s
    return $s
}


text:
Q: MySql Trigger, before insert delete a row in the same table Is this possible? Before a row is inserted into tableA, I need to delete any rows in tableA containing duplicate data.The trigger below does not generate an error but doesn't work either.
CREATE TRIGGER remove_old_user
BEFORE INSERT ON userStatus
FOR EACH ROW
DELETE FROM userStatus WHERE username = NEW.username

Any ideas?

A: Is it essential that the previous record be deleted, rather than updated to match the new info? Sounds like INSERT ... ON DUPLICATE KEY UPDATE would meet most of your needs. More info in the MySQL manual.
(I'm assuming based on the question that the field is unique, and can be part of the primary key)


text:
Q: placing the media uploads in a subdirectory Hi I want all my uploads to be uploaded to a subdomain on my site instead of 'wp-content/uploads'
I created a subdomain cdn.mysite.com and i want all the uploads to go there instead.
I want my uploads to be cdn.mysite.com/uploads/year/month/mediafile
Just as the uploads automatically create a folder for the uploads i want it to do the same when uploading to the subdomain.
How can I accomplish this.
EDIT:
I found this plugin that is suppose to place the image path options back on wordpress but I'm not so sure i should use it, I don't know if it actually works, I don't want to mess anything up
http://wordpress.org/extend/plugins/wp-original-media-path/installation/
Also I found this tutorial of how to do this from the wp-config.php file but it's only explaining changing the name of the folder not changing the path as in placing a subdomain.
http://www.techgyd.com/how-to-change-media-uploads-folder-in-wordpress-3-5/17/
I want to try the second option, editing the wp-config.php file but I don't know how to edit that line of code for subdomains, also I'm afraid that if we do figure out how to add the subdomain option to the wp-config file that when I upgrade wordpress it will disappear and my images may mess up.
What should I do?

A: Add the following to your theme's functions.php file, making sure you replace the example CDN URL with your own:
function my_cdn_upload_url() {
    return 'http://mk124.yourcdn.com/yoursite/wp-content/uploads';
}
add_filter( 'pre_option_upload_url_path', 'my_cdn_upload_url' );

A: Are the sites hosted in such a way that you could create symbolic link within your primary site's directory structure to the physical storage location of cdn.mysite.com? You'd be linking wp-content/uploads -> /path/to/storage/for/cdn.mysite.com/uploads .
You'd likely need both sites' hosting running under the same user, but if they're co-located, this might be as simple as a symlink.


text:
Q: How do I customize the format of data results in R I have get lots of result from my model and I need to copy the results to MS word. But it's too much!! I'm going to copy over 30,000 results!
my result just like down here.
I want to every disease in every sheet. I can do this with code like this:

list <- split(df,df$disease)
ImportExport::excel_export(list,'result.xlsx')

That's not enough. The best format of the results I wanted should like the picture. For better observation, when P is less than 0.05, the value is bold.
Can R do this job?
Any help will be highly appreaciate!
disease people  pollutant   lag value   p
I21 total   PM2.5   0   0.07(-0.4,0.55) 0.01
I21 total   PM2.5   1   0.35(0.1,0.61)  0.3
I21 total   PM2.5   2   0.33(0.11,0.54) 0.04
I21 total   PM10    0   0.07(-0.4,0.55) 0.01
I21 total   PM10    1   0.35(0.1,0.61)  0.3
I21 total   PM10    2   0.33(0.11,0.54) 0.04
I21 man PM2.5   0   -0.02(-0.45,0.41)   0.01
I21 man PM2.5   1   0.39(-0.02,0.8) 0.3
I21 man PM2.5   2   0.2(-0.14,0.54) 0.04
I21 man PM10    0   0.12(-0.39,0.63)    0.01
I21 man PM10    1   -0.1(-0.74,0.55)    0.3
I21 man PM10    2   0.19(-0.57,0.95)    0.04
I21 woman   PM2.5   0   -1(-2.7,0.74)   0.01
I21 woman   PM2.5   1   -0.05(-1.52,1.45)   0.3
I21 woman   PM2.5   2   -0.3(-1.63,1.04)    0.04
I21 woman   PM10    0   -0.17(-1.45,1.13)   0.01
I21 woman   PM10    1   -0.9(-2.17,0.38)    0.3
I21 woman   PM10    2   -1.64(-2.92,-0.35)  0.04
I24 total   PM2.5   0   -0.8(-2.77,1.21)    0.01
I24 total   PM2.5   1   -0.2(-2.56,2.2) 0.3
I24 total   PM2.5   2   -1.31(-4.07,1.52)   0.04
I24 total   PM10    0   -0.76(-1.95,0.43)   0.01
I24 total   PM10    1   0.5(-0.34,1.34) 0.3
I24 total   PM10    2   0.32(-0.35,1)   0.04
I24 man PM2.5   0   -0.09(-0.74,0.58)   0.01
I24 man PM2.5   1   -0.49(-1.14,0.17)   0.3
I24 man PM2.5   2   -0.45(-1.08,0.19)   0.04
I24 man PM10    0   0.22(-1.13,1.59)    0.01
I24 man PM10    1   0.27(-0.99,1.56)    0.3
I24 man PM10    2   -0.47(-1.83,0.91)   0.04
I24 woman   PM2.5   0   -1.47(-4.9,2.09)    0.01
I24 woman   PM2.5   1   1.51(-0.47,3.53)    0.3
I24 woman   PM2.5   2   1.61(-0.14,3.4) 0.04


text:
Q: How to create a Layout were I can place anything where I want? I'm designing an app with many images, buttons and textViews strewn across the screen. At the moment I am using the relative layout as it seemed the most flexible of the lot. However were I place my elements and their size is still restricted to being aligned with other elements. Even worse if an element changes size any elements aligned to it will also change size.
There must be a simple solution to this! Apple's nib files perform this so easily with an effortless drag and drop to any location; yet android appears to be stuck with restrictive table/linear/relative/grid layouts.
If possible can the solution be performed via eclipse. If not please guide me to the relevant documentation to learn to create my own layouts via xml, create a huge grid layout or whatever horrors await me :)
Thanks

A: I think what you want is something like an absolute layout tho these were deprecated a while ago, Im pretty sure you can still do this via a Relative layout, you don't necessarily need to align the via with another view, I guess you could just do something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="70dp"
        android:layout_marginTop="82dp"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="172dp"
        android:layout_marginRight="84dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

all I'm doing here is aligning it with the side of the parent and having a margin between it

A: You can do what you ask with a Frame Layout and setting the position of each object. But do so at your own risk. The reason Apple nib files let you arbitrarily place objects is taht the aspect ratio of all their devices is the same. So your layouts just scale up and down evenly.
Android is a more diverse ecosystem, and you should try to embrace layouts that adapt to different screen sizes and orientations.

A: Take a look at Android custom layout and Android - How to draw a letter at a specific point?
Are you planning to only use the app on a single android device model? If yes, check AbsoluteLayout's Alternatives. (FrameLayout or RelativeLayout)
It's not a good idea to put "Anything Anywhere you want" since Android devices have a lot of different screen sizes and properties. The only option would be to define your own custom layout.
I actually really like the way Android tries to make your layout compatible with as much devices as it can using alignment and structured layout views.
The reason it's simple for Apple is that you're only targeting iPhone, which has a fixed screen properties accross all devices.
Hope it helps. Good luck.


text:
Q: Actions on key pressing, one after the other. (Jquery : RPG Dialogue Box) I'm trying to make a little game in Jquery, I want to show a dialogue box.

*

*When I press enter, I want the text1 to appear.

*I press enter again it shows the text2 etc, until maybe 7 texts.

If I press enter, I get immediatly text2, which is obvious, and I dont know how to figure this out.
Also if you have suggestions of a better optimised solution in Jquery, feel free to submit it, I'm a new student.
Thanks all !

var i = 0;
$(document).keypress(function(e) {
    if(e.which == 13 && i == 0) {
     $( ".text" ).empty();
        $( ".text" ).append( "Text1" );
        i++;
    }
});
$(document).keypress(function(e) {
    if(e.which == 13 && i == 1) {
     $( ".text" ).empty();
        $( ".text" ).append( "Text2" );
        i++;
    }
});

A: Don't add the keypress event multiple times, use your variable i logic inside the event callback function like so:
Also, if you are just going to clear the text on each evaluation of i, you can just use .text() to set the elements text instead of clearing it and appending...
var i = 0;
$(document).keypress(function(e) {
    if(e.which == 13) {
        switch(i){
            case 0:
               $( ".text" ).empty();
               $( ".text" ).append( "Text1" );

               //Could do it in one line like:
               //$(".text" ).text("Text1");
               break;
           case 1:
               $( ".text" ).empty();
               $( ".text" ).append( "Text2" );
               break;
           etc....
        }

        i++;
    }
});

A: I think this might get you closer. Create an array of the text messages you want to display (var text). Then on enter key press iterate through the messages until you run out. Check if you've ran out by using the ol' typeof !== 'undefined' trick.
There's probably a more elegant answer but I think this one is fairly straight forward and easy to understand.


text:
Q: Getting some strings with using Regex Could someone help me how I can get the strings after the English > srt
I only wanna grab this strings:

/20200623/c1/51/1777469aba625657d69b3cbaefed1387.srt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3

"_name": "Vietnamese",
      "_sort": 6,
      "mver": "101",
      "lid": 23,
      "xml": "/20200623/c0/72/e00ed17c479f2700194837e1d3901e32.xml?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=23",
      "srt": "/20200623/c0/72/41619b14d41606def042d6d267b72de2.srt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=23",
      "_selected": false,
      "pre": 0,
      "ie": 0,
      "uuid": "b908453e2869285ef8a1f75599ae85d9",
      "_limited": 1,
      "ssv": 1,
      "webvtt": "/20200623/c0/72/cbc73fb5b7da5282d0697f265e08c87c.vtt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=23",
      "ss": 0
    },
    {
      "_name": "English",
      "_sort": 1,
      "mver": "101",
      "lid": 3,
      "xml": "/20200623/c1/51/445603c545708bf234430da417a9469f.xml?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3",
      "srt": "/20200623/c1/51/1777469aba625657d69b3cbaefed1387.srt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3",
      "_selected": true,
      "pre": 0,
      "ie": 0,
      "uuid": "c802506ad202e27680b8096ccc18f36d",
      "_limited": 1,
      "ssv": 1,
      "webvtt": "/20200623/c1/51/da547e3c9d716037190173eabfbf4eaf.vtt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3",
      "ss": 0

A: I finally figure it out to get the English link only
string json = richTextBox1.Text;
JObject jObject = JObject.Parse(json);
var subtitle = jObject["data"]["program"]["stl"][8]["srt"]; //[8] is the English
output.Text = subtitle.ToString();


text:
Q: Background Running Process logging Am having a java program which listens to ApacheMQ and runs in background and am using Linux Server. Here I have used System.out.println() for my logging andI have to transfer those contents to a file.
Is it possible, am completely novice to this and Whether I have to use Log4J or nohup to write this sysout() value to a file.
Thanks in advance.

A: You can use
PrintWriter out = new PrintWriter("my-output.txt");

// write text.
out.println("hello world");

// when finished.
out.close();

Just replace System.out with out
I am surprised you can use JMS but don't know how to work out how to write to a file.

A: As you observe, using nohup you get out redirected to a file. More generally, a linux process can have its output redirected to a file
 myApp > someFile.log

or maybe better appended to a file
 myApp >> someFile.log

so that when you restart you don't lose previous output.
Alternatively, as you indicate, you can put the app in charge of choosing where to write, and then using a library such as Log4j instead of System.out is very helpful.
I would use both approches: I recommend using some such logging library in any serious application, and I would start my application from a script that ensures that all output is captured in log files, this ensures that should you use some library code that writes to a stdout or stderr that the output is kept. I like to create output files whose names include date and time that the app was started, this makes it easier to find particular output.


text:
Q: Android Studio: Compare existing string with TextField.text I want to compare two strings in android studio. I have a textfield and want to compare this string with a given string.
For a better discription I added a picture.
My existing string is for example "A", I want to check now, if the textbox contains this value, by pressing the button.
I tried this but there is a mistake in the code, that I don't find...
    final TextField textField = (TextField) findViewById(R.id.editText);
    final String text1 = textField.getText().toString();
    final String text2 = "A";

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.v("Button2", "click");
            if(text1.contains(text2)){
                toast.show();
            }
        }
    });

I hope, that this improves my first (bad) question!

A: try this code
final EditText editText = (EditText) findViewById(R.id.editText);
    final String text1 = editText.getText().toString();
    final String text2 = "A";

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.v("Button2", "click");
            if(text1.equals(text2)){
                toast.show();
            }
        }
    });

A: I guess you declared your Button2 as you did with the EditText, going on...
You want to check if the String you have provided and the String is being written at the EditText is the same when you press a button, your code is right but you need to compare the value of the EditText dynamically, so you must change this:
            if(text1.contains(text2)){
            toast.show();
        }

To this:
            if(editText.getText().toString().equals(text2)){
            Toast.makeText(getApplicationContext(),"Your message/Your String",Toast.LENGTH_LONG).show();
        }

Hope this helps a little :)

A: Method contain only check the text1 contain text2 or not. You should use equals() method.

A: You can do something like this
    final EditText editText = (EditText) findViewById(R.id.editText);
    final String text1 = editText.getText().toString();
    final String text2 = "A";

 button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.v("Button2", "click");
            System.out.println("text1: " + text1);
            System.out.println("text2: " + text2);
            if (text1.length()>0&&!text1.equalsIgnoreCase("")) {
                if(text1.equalsIgnoreCase(text2)){
                    toast.show();
                }
            } else {
                System.out.println("text1 is null " );
            }

        }
    });

A: Use like this
if (text1.equals(text2)) {
        Toast.makeText(getApplicationContext(), "Equal", Toast.LENGTH_LONG)
                .show();
    }

A: you have to youse something like this because when you compare the text you must have an updated version of text1.
If you ask the text at the beginning it is nothing inside.
You have to ask the text1 at every OnClick event.
public OnClick(View v){

   text1 = editText.getText().toString();
   if(text1.equals(text2)){
          //doStufg
   }
}

A: Thanks for all the good and helpful answers!
I have even tried some way and it works well so far.
Thanks to everyone here. Good Work!
// editText.getText().toString().contains("A");


text:
Q: Background video disabling the link I have a container with a background video and some content. The problem is the background video is disabling the content (the button).
JSbin link: http://jsbin.com/vehonetoxa/edit?html,output
Code:

        <video autoplay="autoplay" id="video_background" loop="loop" preload="auto" style="position: absolute; top: 0px; left: 0px; bottom: 0px; right: 0px; z-index: -100; min-width: 100%;min-height:100%;">
            <source alt="ekin care preview" src="https://dhqfzvce2gbm4.cloudfront.net/assets/video/preview-41f7830386411c84a3ecb1e33407aee340d0f51e0f2bc4960397b17b73e44e52.mp4" type="video/mp4">
                <source alt="ekin care preview" src="https://dhqfzvce2gbm4.cloudfront.net/assets/video/preview-b73e242581b99456fb569e1dba4ce6a21972e59c458432329a4b48eb8db5d3fe.ogv" type="video/ogg">
                    <source alt="ekin care preview" src="https://dhqfzvce2gbm4.cloudfront.net/assets/video/preview-2919a66a9f41eb7bb41adfb66d347a01ec94d5cf989d776668a190fcbdac9df0.webm" type="video/webm">
                    </source>
                </source>
            </source>
        </video>

Take Charge of your health

India's first personel digital health assistance

                GET STARTED-FREE FOREVER

A: Your video is overlapping content. Give it position: relative with higher z-index.
.container-fluid {
    position: relative;
    z-index: 10;
}

A:

...

A: Just add position absolute to your btn, as below.
GET STARTED-FREE FOREVER

A: Your video is overlapping content.
Take a look at this i have updated your bin.
Background Video


text:
Q: Meteor JS event emitter error when loading cordova plugins Hi guys I have gone through a lot of sources here:
node.js - request - How to "emitter.setMaxListeners()"?
http://www.jongleberry.com/understanding-possible-eventemitter-leaks.html
and a lot more sources regarding "eventemitter".
All of the suggestions about adding setMaxListeners on both client/server did not work due to the error occurs when building the mobile app on the part where it downloads the cordova plugins.
Does anybody encounter this issue? Any solution or suggestions? Please advice. Thank you.


text:
Q: Exercício em Python - Somar os algarismos de um número inteiro qualquer Estou tentando resolver o seguinte exercício:

Escreva um programa que leia um número inteiro maior do que zero e
devolva, na tela, a soma de todos os seus algarismos. Por exemplo, ao
número 251 corresponderá o valor 8(2 + 5 + 1). Se o número lido não
for maior do que zero, o programa terminará com a mensagem "Número
inválido".

Minha dúvida é como separar cada algarismo para possibilitar a soma. Minha ideia foi gerar uma lista a partir da variável inteira, convertendo-a antes para uma string, mas não obtive sucesso. O código que eu implementei seque abaixo:
print("Informe um número inteiro maior que zero: ", end="")
num = int(input())

if num <= 0:
    print("\nNúmero inválido!")
else:
    lista = list(num.__str__())
    soma = 0
    for n in lista:
        soma = soma + int(lista[n])
    print(f"\n{soma}")

Agradeço qualquer orientação.


text:
Q: Recursividad en c++ Quisiera saber como puedo crear una funcion recursiva para leer los numeros desde 1 a N.
He tenido problemas para crear el codigo base lo cual podria pensar que N seria como un limite dado por el usuario y cuando se compare con el Numero 1 que va aumentando ahi deberia parar , y tambien como podria imprimir estos mismo numeros hasta donde el usuario seleccionó


text:
Q: Is there a Pomodoro app available? Is there a pomodoro app that's available for Ubuntu 12.04 that can be installed using sudo or from the package manager?

A: It's not exactly an app, but I've posted an answer to a similar question on Super User That basically revolved around using the terminal to program your Pomodoros.
You'd be basically issuing the following terminal command to start a Pomodoro:
sleep 1500 && notify-send -u critical "break"

In order to introduce breaks, you'd be running the following:
sleep 300 && notify-send -u critical "back to work"  # a short, 5-minute break
sleep 900 && notify-send -u critical "back to work"  # a long, 15-minute break

That's the gist of it. You can find more details here.

A: Tomate

If you have installed the program using the old ppa repository uninstall the old version first. If you use an Ubuntu-based distro, such as Mint, manually set the RELEASE variable to the Ubuntu version number, such as 16.04, rather than running the sed script bellow.

RELEASE=`sed -n 's/VERSION_ID="\(.*\)"/\1/p' /etc/os-release`
sudo wget -O- http://download.opensuse.org/repositories/home:/eliostvs:/tomate/xUbuntu_$RELEASE/Release.key | sudo apt-key add -
sudo bash -c "echo 'deb http://download.opensuse.org/repositories/home:/eliostvs:/tomate/xUbuntu_$RELEASE/ ./' > /etc/apt/sources.list.d/tomate.list"
sudo apt-get update && sudo apt-get install tomate-gtk

A: gnome-shell-pomodoro
For Gnome-shell. You can use this extension in GNOME shell for pomodoro indicator. It works out of the box in many distros, like Ubuntu 17.10 (which doesn't come with Unity anymore).
Old versions were installed through:

*

*https://extensions.gnome.org/extension/53/pomodoro/
Current version that works on my Ubuntu 20 is install-able through apt:
sudo apt-get install gnome-shell-pomodoro

Homepage with instructions for installing on different OS distributions and versions: http://gnomepomodoro.org/
malev's pomodoro-indicator
For Unity. The pomodoro-indicator as referenced by the other answerer doesn't work straight out of the box. We first have to fix the icon so it appears on the Unity panel.
Follow the commands and hopefully it works for you:
wget https://launchpad.net/pomodoro-indicator/trunk/0.0.2/+download/pomodoro-indicator-0.0.2.tar.gz
wget https://launchpad.net/pomodoro-indicator/trunk/0.0.1/+download/pomodoro-indicator-0.0.1.tar.gz
tar xvf pomodoro-indicator-0.0.2.tar.gz
tar xvf pomodoro-indicator-0.0.1.tar.gz
cp -R pomodoro-indicator-0.0.2/* pomodoro-indicator-0.0.1/
cd pomodoro-indicator-0.0.1; gedit setup.py

In line 112, remove # from the following line:
#package_data = {"pomodoro": ["images/*.png", ]}

Save the file.
sudo python setup.py install
pomodoro-indicator

Pomodoro indicator will now appear in the Unity panel.
Reference

*

*https://answers.launchpad.net/pomodoro-indicator/+question/198506

A: Atareao's pomodoro-indicator
Having tried others, I recommend Atareao's Pomodoro Indicator App.
Why? It is simple, beautiful, configurable, has been tested in ubuntu 14.04, 14.10, 15.04, 16.04. It has a PPA and the developer is known for writing quality indicator apps such as my-weather-indicator.
My favourite thing is that the icon changes to reflect how much time is left. Here's a time-lapse screen capture I made:

This is what the preferences look like (polar night gtk theme):

Installation:
Copy and paste the following in the terminal:
sudo add-apt-repository ppa:atareao/atareao
sudo apt-get update
sudo apt-get install pomodoro-indicator

A: The PomoDoneApp looks good. Worked fine in Ubuntu 16.04, don't know about Ubuntu 12.04.

A: Tomighty

Download link <-- Link does not work (404)
Tomighty can't be installed from package manager (it's java applet), but it's my favorite because it has an indicator with countdown timer right on taskbar. The downside is that indicator background looks ugly when idle because of white background.
So I edited default png and filled it with ambiance background color. Save the image as "tomato-24.png" and put it tomighty's .jar file. http://i.imgur.com/Lf92P.png

A: TeamViz Lite (or Pro) app (proprietary software). it's available for Ubuntu, for more information see this downloads link.
Last update: Jul 13, 2013.

A: Someone has already mentioned Tomighty here but I've gone ahead and packaged it for Ubuntu here
To install
sudo add-apt-repository ppa:pwr22/tomighty
sudo apt-get update
sudo apt-get install tomighty

A: Another option: Google timer
Pros: no package required to install, no dependencies, no manually creating a Desktop icon (Zeegaree).
Cons: requires internet connection
https://www.google.co.uk/search?q=google+timer

A: I just created a new minimalistic pomodoro counter. See https://bitbucket.org/dvtomas/osd-pomodoro
A simple, ultra-lightweight, transparent, unobtrusive pomodoro countdown for Linux. Always on top, yet so small that it doesn't really bother you. And if it does for a moment, just send it a UNIX signal to toggle visibility.

A: XFCE4: xfce4-timer-plugin (~500kB for XFCE users)
Add the plugin to panel. Add a timer for 25 minutes in preferences.
If you also want a sound, use any of these: Link.

A: pomelloapp.com
If you are a Trello user, then you should definitely check Pomello. I'm using it on CentOS.
Is proprietary software, electron-based. Is not affiliated, associated, authorized, endorsed by or in any way officially connected to Trello, Inc.


text:
Q: How to apply session on JSP page without using <% page session =""%> Is it possible to use existing session in jsp without using  <% page session="false"%>?
Are there any alternatives for it?
Since our project has 200 jsp's, it is not easy to write that code for each and every jsp.
Thanks.

A: The servlet spec allows you to automatically import a jsp for a set of pages using jsp property groups.
You can add session="false" in the top.jsp so that it will be applied to all jsps
<jsp-property-group>
  <description>JSP configuration</description>
  <url-pattern>/*.jsp</url-pattern>
  <include-prelude>/includes/top.jsp</include-prelude>
</jsp-property-group>


text:
Q: Xmlbeans setter not working in gradle test When I run java tests that use xmlbeans generated objects, sometimes in gradle test when using the setter the object gets into some unknown state. Here is an example (pseudocode):
XmlBeansDoc doc = SomeXmlBeansGeneratedDocument.factory.newInstance();
doc.addSomeObject();
XmlbeansObj obj = doc.getSomeObject();
obj.setSomeIntValue(1);

Right after using the 'setSomeIntValue()' method, if you try and get the value it returns an error. However, if you use the 'setSomeIntValue()' method again, everything works fine and the value is actually set.
This ONLY seems to happen when running the test in Gradle. If I use the exact same jar that Gradle is using, but run the test in ANT, everything works fine. I have confirmed that both ANT and Gradle are using the same version of java (1.7.45).
Any ideas as to why this might be happening? We are in the process of switching our build system from ANT/ivy to Gradle, but if we can't get this working it might be a show stopper. Thanks for all the help

A: It looks like this was ultimately due to gradle having Java Assertions enabled by default, which ant does not.


text:
Q: How to accurately measure time in c++? I want to measure the execution time of a function very accurately, in picoseconds. Can it be so precise in C++? The methods I currently know to measure time are:

*

*__rdtscp()

*std::chrono clock

*clock.h clock_t

Does anyone know how accurate these three functions can be? Which one can achieve picosecond time measurement, if all not, is there any way to reduce noise and make time measurement more accurate?
target system is Linux version 4.15.0-122-generic (buildd@lcy01-amd64-010) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.12)) #124~16.04.1-Ubuntu SMP

A: No clock on a consumer grade computer is going to measure with picosecond accuracy.  The call to get the current time alone is going to take at least tens of nanoseconds.
However you can time your target in a loop and measure the entire elapsed time. Then compute the average time per iteration.  <chrono> allows you to easily do this and compute the results to picosecond precision:
#include <chrono>
#include <iostream>

int
main()
{
    using picoseconds = std::chrono::duration<long long, std::pico>;
    constexpr auto N = 1000;
    auto t0 = std::chrono::steady_clock::now();
    for (int repeat = 0; repeat < N; ++repeat)
    {
        // measure this
    }
    auto t1 = std::chrono::steady_clock::now();
    auto d = picoseconds{t1 - t0}/N;
    std::cout << d.count() << "ps\n";
}

If you really want to get precise, you can measure the loop overhead (being sure it isn't optimized away), and subtract that off your total prior to averaging.
for (int repeat = 0; repeat < N; ++repeat)
{
    // measure empty loop overhead
    asm volatile("");
}

The syntax for discouraging the optimizer from removing a loop is not portable.

A:
How to accurately measure time in c++?

Most accurate standard way to measure time is to use std::chrono::high_resolution_clock or std::chrono::steady_clock.
There may exist a more accurate way provided by the system. To find out about that, the first step is to figure out what the target system is.

Does anyone know how accurate these three functions can be?

Depends on implementation and potentially also hardware.

Which one can achieve picosecond time measurement

Probably none of those in practice. The fastest CPU's have cycle times measured in hundreds of pico seconds.


text:
Q: detail or detailing In the following extract from Frankenstein, which of the two possibilities do you think makes more sense?

and although I loved him with a mixture of affection and reverence that knew no bounds, yet I could never persuade myself to confide in him that event which was so often present to my recollection, but which I feared the detail/detailing to another would only impress more deeply.

A: The word is "detail" since that is what is in the published version.
To understand this you need to look at obselete meanings of detail (as is often the case if you choose to read 200 year old books.

detail: a narrative that relates to minute points of focusses on particulars (paraphrased from wiktionary)

And read this with an understanding of grammar that also is 200 years old.


text:
Q: Create location route to subdirectory I want to create a Preview URL for my project. Each User has some directorys (home directory) on the drive, which contains a folder named /docs/.
When the user calls their URL (for example https://preview.example.com/microsoft/VisualStudioCode):
http(s)://preview.example.com/<company>/<project>/
How i can tell nginx, that he should internal append the /docs to the URL?
Following Directory structure is given:
 - /opt
   - /users
     - <company>
       - <project>
       - <project>
     - /microsoft
       - /VisualStudioCode
         - /docs
         - /downloads
         - /temp
         - config.json

The DocumentRoot of nginx is by default /opt/users/ and the <company>/<project> exists as a real directory.
How i can create an Alias or another configuration to navigate to the /docs directory, if the user opens the URL?

A: Assuming the rest of your nginx.conf is set up correctly you'd have to add this server block:
server {
  server_name preview.example.com;
  root /opt/users;

  location / {
    try_files $uri/docs =404;
  }
}

If you want to serve ANY file from within the secret docs directory then you're gonna have to do regex in your location block, like so:
location ~ ^/(?<company>.+)/(?<project>.+)/(?<filepath>.+)$ {
  try_files /$company/$project/docs/$filepath =404;
}


text:
Q: Does the Single Sign On Paradigm respects the HTTP protocol rules? We are using the CAS server for a JAVA web application.
 The authentication system is as follows:

*

*A user tries to access a resource (1) on the system

*It get redirects (302 Found)

*The User Enters the username password

*The Server answers with a cookie and redirects to the original page (1)

I am debated on the fact that this interaction respects the HTTP protocol.
If I do not have the authorization to access a resource
shouldn't the system answer with a 401 Unauthorized or even better a 407 Proxy Authentication Required  ?
And the Authorization Resource, couldn't be instead of a Cookie string a full SSL-Level authorization key ?
Added:
Header dump using curl -L -D
HTTP/1.1 301 Moved Permanently
Server: nginx/0.8.54
Date: Sat, 10 Dec 2011 02:07:55 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://server.com/service/

HTTP/1.1 302 Found
Server: nginx/0.8.54
Date: Sat, 10 Dec 2011 02:07:55 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-store, max-age=0, must-revalidate
Expires: Thu, 01-Jan-1970 00:00:00 GMT
Set-Cookie: JSESSIONID=q7rjikj4spvd1fxaowjl9XXX
Location: https://server.com/login/

HTTP/1.1 200 OK
Server: nginx/0.8.54
Date: Sat, 10 Dec 2011 02:07:55 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/5.3.2
Content-Length: 6650

A: You're right - the SSO system in your examples is really at a different level than the HTTP protocol itself.  If the application returned a 401 then the browser itself will likely handle the authentication (e.g.: prompt the user for username/password, then send the next request with this base-64 encoded in the HTTP Authorization header).  In the case of HTTP Basic authentication the username & password would then be sent with every request to your system.  You may do authentication with Kerberos or NTLM, in which case the authentication could be transparent if the user is already logged into the network.
That said - many SSO systems take the approach of redirecting the user to a login HTML form, and then maintaining session state with a cookie.  One of the main benefits is you have more control over the look & feel of the login interface.  With the SSO system having a session cookie it can take ownership of maintaining the state in its own (likely proprietary) way.


text:
Q: How does Mathematica find a series expansion of expressions containing logarithms when there is a singularity at the expansion point? I am looking for a good approximation to a function containing logarithms, especially at values close to zero. When I used Mathematica's Series command I found something unexpected.
Mathematica seems to expand expressions containing a logarithm differently when there is a singularity at the expansion point. For example, the function $(a+\log[x^3+x^7])/(b+x)$ has a singularity at $x=0$. If I use Series with an expansion point greater than zero, I get the expected Taylor expansion. However, at the expansion point zero I get
$$
\frac{a + 3 \log(x)}{b} + \frac{(-a - 3 \log(x)) x}{b^2} + O(x)^2.
$$
It strikes me that the logarithm is retained as a function in $x$. And this result approximates the function much better than that of a simple Taylor series. Mathematica somehow separates the logarithm from the expansion, which I find quite intelligent. I would like to know what technique Mathematica uses and how it is called. I never came across such a thing and would be interested in learning more about it.
I understand that Series can use several expansions and choses an appropriate one depending on the problem, so maybe this is a special procedure to treat expressions with logarithms.
I also found (with some trial and error) that Mathematica's result equals the one I would get if I first did a Taylor expansion of the expression, but treating all logarithms as constants, and then reduced all logarithmic arguments to the lowest power of $x$. Why is this justified?

A: One good thing about Mathematica is that when doing Series[], Mathematica understands that the singularity of $log(x)$ is different from $x^{\alpha}$ (for any $\alpha$) (for $x \rightarrow 0$), thus treated separately.
Like this:
Series[Log[x^2 + x], {x, 0, 1}]

Output
Log[x]+x+O[x]^2

Because mathematically,
$$
  \log(x^2+x) = \log(x (x+1)) = \log(x) + \log(x+1) = \log(x) + x + O(x^2)
$$
The same procedure applies to your slightly complex expression. i.e. take out the common factor in $\log(\cdot)$, (conceptually) expand everything except $\log(x)$, truncate the Taylor series based on the hierarchy (for $x \rightarrow 0$)
$$
  \cdots,\quad x,\quad x\log(x),\quad 1,\quad\log(x),\quad x^{-1},\quad \cdots
$$


text:
Q: Grails 3 list-plugins lists profiles I have installed Grails 3 by downloading and unloading the zip on CentOS 6.2.
grails --version shows
| Grails Version: 3.1.10

| Groovy Version: 2.4.7

| JVM Version: 1.7.0_111

grails list-plugins shows
Usage:
     create-app [NAME] --profile=web
     create-plugin [NAME] --profile=web-plugin

| Available Profiles
--------------------
* angular - A profile for creating applications using AngularJS
* rest-api - Profile for REST API applications
* base - The base profile extended by other profiles
* plugin - Profile for plugins designed to work across all profiles
* web - Profile for Web applications
* web-plugin - Profile for Plugins designed for Web applications

Type 'grails help' or 'grails -h' for more information.

Which mostly the same as grails list-profiles.
I thought list-plugins listed all of the plugins that were available for Grails in a central repository.
Is this a bug in Grails 3.1.10? (Which is the latest version for download and the version that sdkman tries to install as well).

A: Most Grails commands have to be run inside an existing application or plugin, with create-app and create-plugin being exceptions, so that's what the usage message is telling you. Since list-plugins doesn't work outside of an existing app/plugin (I'm not sure why tbh) you're seeing this low-information response.
You can see all of the available Grails 3 plugins here.


text:
Q: Filter content on Userlanguage in SharePoint 2013 Is there any possibility to filter content with the actual selected language of the user?
I've created a document library with metadata where I have filled up the language of the content.
Now it should only show English content when a user has English as default SharePoint language and German content when the user has German as default language.

A: There are various options depending on the requirements and technical limitations.
If you are able to put the language of the user in the URL you can use a filter webpart and connect it to the view web part. The view web part then filters the results based upon a value comming from the filter web part.
Second option.
In the SharePoint on premise version. You can program your own "connected webpart". This way you have full control over where to get the language information of that user.
A third option.
Create two audiences. One for english users and one for the german users. You can configure webparts so they are only visible if the user is in a certain audience. When the audiences are created you put two list view webparts on a page, set the filters correctly and set the audience in the web part properties. One list view web part is only displayed to english users. The other one is only displayed to german users.


text:
Q: Am I able to output and view Frisby.js requests? I'm getting started with frisby.js and I'm also new to Jasmine and node.js.
After stumbling over some of my first frisby tests, I wanted to know if it were possible to output the requests in my tests to the console so that I could validate I have the correct request headers and request body etc. each time  I run my tests with
jasmine-node myproj/spec

I think this might be useful if the requests would also be included into the reports when I run my tests with the --junitreport option
I was originally hoping that running my tests with --verbose would provide this, but --verbose only seems to output the request method and URL of the top level test and not any tests nested under it using after() or afterJSON(), which is also disappointing!
I've tried searching around but did not find an answer to this simple question, any help would be much appreciated thanks!

A: In case anyone else runs into this, frisby also has the following inspector:
inspectRequest()

For example, if you have the following a simple test
frisby.create('My Test')
      .get('http://httpbin.org/get?foo=bar&bar=baz')
      .inspectRequest()
      .expectStatus(200)
      .toss();

This will output something similar to the following in your console:
{ json: false,
  uri: 'http://httpbin.org/get?foo=bar&bar=baz',
  body: null,
  method: 'GET',
  headers:
     { 'content-type': 'application/json' },
  timeout: 5000 }


text:
Q: C# Checking for primitives and string I have the following method to replace all key's and values recursively while stepping through json:
   private static void ReplaceKeyValue(IDictionary<string, object> dictionary, dynamic keys)
    {
        foreach (dynamic item in keys)
        {
            if (dictionary.ContainsKey(item.Key))
            {
                dictionary.Add(item.Value, dictionary[item.Key]);
                dictionary.Remove(item.Key);

                var nextItem = dictionary[item.Value];
                Type type = nextItem.GetType();
                if (type != typeof(string) && !type.IsPrimitive)
                {
                    if (dictionary[item.Value].Count > 0)
                    {
                        ReplaceKeyValue(nextItem, keys);
                    }
                }
            }
        }
    }

The code has to check whether the nextItem has any children and then replace all of them again and if not then step out. As soon as the code enters the second level of the json where I have several items with only string and integer values it enters the type check step and then errors with:
$exception  {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'string' does not contain a definition for 'Count'

I have tried checking for GenericType and GenericTypeDefinition as well to no avail. Please advise on what the best approach would be to check for that? I am missing something simple?
EDIT: To clarify.
As I said I am looping ovr a json object already deserialized by JSON.net. I am casting to IDictionary because the value type is unknown and can be anything therefore I need to check the type and handle accordingly. If it has children then I need to loop through them as well and do the same. The items can be several levels deep.
EDIT 2:
I resolved it.
I just needed to add a step to check for ExpandoObject so that I dont check for Count and capitilize the type for string from string to String(I thought there is no difference?). Here is the final piece:
                if (nextItem is ExpandoObject)
                {
                    ReplaceKeyValue(nextItem, keys);
                }
                else {
                    Type type = nextItem.GetType();
                    if (type != typeof(String) && !type.IsPrimitive)
                    {
                        if (nextItem.Count > 0)
                        {
                            ReplaceKeyValue(nextItem, keys);
                        }
                    }
                }


text:
Q: How can I baseline-align two blocks with different font-height? I've got a table with 2 cells. One cell contains a number, the other contains text in a larger font. I want to align the baselines of the two texts. I've tried lots of combinations of display-align, vertical-align, alignment-baseline etc. Nothing seems to work: the blocks are always aligned as if alignment-baseline="center".
<fo:table>
    <fo:table-column column-width="20mm" column-number="1"/>
    <fo:table-column column-width="100mm" column-number="2"/>
    <fo:table-body>
       <fo:table-row>
           <fo:table-cell column-number="1">
               <fo:block font-size="9pt" line-height="22pt">1.</fo:block>
           </fo:table-cell>
           <fo:table-cell column-number="2">
               <fo:block font-size="20pt"line-height="22pt">Title</fo:block>
           </fo:table-cell>
       </fo:table-row>
    <fo:table-body>
</fo:table>

I can fake the correct alignment by putting a padding on the block in column 1, but I'd rather use a non-hack solution.

A: Use relative-align="baseline".  See https://www.w3.org/TR/xsl11/#relative-align
relative-align exists because of this problem.  It applies only to fo:table-cell and fo:list-item since they are (or were expected to be) the only places where it's needed.


text:
Q: NameError DataFrame is not defined when importing class I recently learned about the np.select operation and decided to create a class to experiment with it and also learn a bit more on OOP.
Here the definition of my class followed by an example (the class uses the translate function defined at the beginning):
def translate(text, conversion_dict, before = None):
    if not text: return text
    before = before or str.lower
    t = before(text)
    for key, value in conversion_dict.items():
        t = t.replace(key, value)
    return t

class Conditions:
    def __init__(self, base_conditions, composed_conditions, groups, default_group):
        self.base_conditions = base_conditions
        self.composed_conditions = composed_conditions
        self.groups = groups
        self.default_group = default_group
        self.readable_conditions = [translate(c, self.base_conditions) for c in self.composed_conditions]
        self.ok_conditions = []

    def run_condition(self, condition, df_name):
        return eval(condition.replace("(","("+str(df_name)+"."))

    def run_conditions(self, df_name):
        return [self.run_condition(c, df_name) for c in  self.readable_conditions]

Example
First, we create a simple DataFrame to play with:
import pandas as pd
import numpy as np

example = {"lev1" : [-1, -1, -1, 1, 0 , -1, 0 , 3],
           "lev2" : [-1, 0 , 1 , 5 , 0 , 7 , 8 , 6]}

ex_df = pd.DataFrame.from_dict(example)
print(ex_df)

   lev1  lev2
0    -1    -1
1    -1     0
2    -1     1
3     1     5
4     0     0
5    -1     7
6     0     8
7     3     6

Next, we create a new instance of our class where we pass our conditions and groups:
mycond = Conditions({"(m1)" : "(lev1 < 0)",
                     "(m2)" : "(lev2 > 2)",
                     "(m3)" : "(lev1 == 0)"},
                    ["(m1)", "(m2) & (m3)", "(m2)"],
                    ['A', 'B', 'C'],
                    999)

Finally, we use the np.select operation on our ex_df DataFrame and print the result:
ex_df['MATCH'] = np.select(condlist = mycond.run_conditions("ex_df"),
                           choicelist = mycond.groups,
                           default = mycond.default_group)
print(ex_df)

   lev1  lev2 MATCH
0    -1    -1     A
1    -1     0     A
2    -1     1     A
3     1     5     C
4     0     0   999
5    -1     7     A
6     0     8     B
7     3     6     C

As you can see, everything works well with one exception.
When I tried to import my class from a separate file (conditions.py which also contains the translate function) it does not work anymore. Here is how my folders/files are organized:
├── classes
│   ├── __init__.py
│   └── conditions.py
└── test-notebook.ipynb

In my test-notebook.ipynb, I import my class the usual way (which works):
from classes.conditions import *

Then, after creating my DataFrame, I create a new instance of my class (that also works). Finally, when a run the np.select operation this raises the following NameError: name 'ex_df' is not defined.
I have no idea why this outputs an error and how to fix it. I'm looking for an answer on both the why and how. Here's the traceback of the error if needed:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-1d4b3ba4a3c0> in <module>
----> 1 ex_df['MATCH'] = np.select(condlist = mycond.run_conditions("ex_df"),
      2                            choicelist = mycond.groups,
      3                            default = mycond.default_group)
      4 print(ex_df)

~/Projects/test/notebooks/classes/conditions.py in run_conditions(self, df_name)
     20
     21     def run_conditions(self, df_name):
---> 22         return [self.run_condition(c, df_name) for c in  self.readable_conditions]

~/Projects/test/notebooks/classes/conditions.py in <listcomp>(.0)
     20
     21     def run_conditions(self, df_name):
---> 22         return [self.run_condition(c, df_name) for c in  self.readable_conditions]

~/Projects/test/notebooks/classes/conditions.py in run_condition(self, condition, df_name)
     17
     18     def run_condition(self, condition, df_name):
---> 19         return eval(condition.replace("(","("+str(df_name)+"."))
     20
     21     def run_conditions(self, df_name):

~/Projects/test/notebooks/classes/conditions.py in <module>

NameError: name 'ex_df' is not defined

A: I think this will solve the problem
FIRST FILE NAME Stackoverflow2.py
import pandas as pd
import numpy as np

def translate(text, conversion_dict, before = None):
    if not text: return text
    before = before or str.lower
    t = before(text)
    for key, value in conversion_dict.items():
        t = t.replace(key, value)
    return t

class Conditions:
    def __init__(self, base_conditions, composed_conditions, groups, default_group):
        self.base_conditions = base_conditions
        self.composed_conditions = composed_conditions
        self.groups = groups
        self.default_group = default_group
        self.readable_conditions = [translate(c, self.base_conditions) for c in self.composed_conditions]
        self.ok_conditions = []

    def run_condition(self, condition, df_name):
        return eval(condition.replace("(","("+str(df_name)+"."))

    def run_conditions(self, df_name):
        return [self.run_condition(c, df_name) for c in  self.readable_conditions]

class DataFrame(Conditions):

    def __init__(self):
        pass
    def makeDataFrame(self):

        example = {"lev1" : [-1, -1, -1, 1, 0 , -1, 0 , 3],
        "lev2" : [-1, 0 , 1 , 5 , 0 , 7 , 8 , 6]}

        ex_df = pd.DataFrame.from_dict(example)

        return ex_df

obj=DataFrame()

print(obj.makeDataFrame())

# mycond = Conditions({"(m1)" : "(lev1 < 0)",
#                      "(m2)" : "(lev2 > 2)",
#                      "(m3)" : "(lev1 == 0)"},
#                     ["(m1)", "(m2) & (m3)", "(m2)"],
#                     ['A', 'B', 'C'],
#                     999)

# ex_df['MATCH'] = np.select(condlist = mycond.run_conditions("ex_df"),
#                            choicelist = mycond.groups,
#                            default = mycond.default_group)
# print(ex_df)

SECOND FILE NAME: Stackoverflow3.py
from Stackoverflow2 import *

print(obj.makeDataFrame())

The problem is the global variables in python does work as in c or c++.
So instead make them an instance variables.
for further info check this
https://stackoverflow.com/questions/15959534/visibility-of-global-variables-in-imported-modules

A: In your context, the variable ex_df is not accessible as a global or local variable, ie, the function run_conditions knows the name "ex_df" but doesn't know what it is.
You need to pass the reference to the DataFrame instead of its name:
ex_df['MATCH'] = np.select(condlist = mycond.run_conditions(ex_df),
                           choicelist = mycond.groups,
                           default = mycond.default_group)

Then change the definition of run_condition to accept the DataFrame instead of a variable name:
def run_condition(self, condition, df):
    return eval(condition.replace("(","(df."))

def run_conditions(self, df):
    return [self.run_condition(c, df) for c in  self.readable_conditions]

Explanation: Inside the context of the function run_condition, the variable name is df. There is no "ex_df" - that is just how you called it somewhere else. Running eval() at that point, the interpreter knows df by that name, which is an argument to the function.


text:
Q: Entities related by many to many not persisted I try to build a form for creating an entity Campaign, in which I can link users. The problem is that when I persist the campaign entity, nothing happens in the jointable.
Here is an extract of the campaign entity :
/**
 * Campaign
 *
 * @ORM\Table(name="campaign")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CampaignRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Campaign
{
/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="campaigns", cascade={"all"})
 */
private $players;

/**
 * Add players
 *
 * @param \AppBundle\Entity\User $players
 * @return Campaign
 */
public function addPlayer(\AppBundle\Entity\User $players)
{
    $players->addCampaign($this);
    $this->players[] = $players;

    return $this;
}

/**
 * Remove players
 *
 * @param \AppBundle\Entity\User $players
 */
public function removePlayer(\AppBundle\Entity\User $players)
{
    $this->players->removeElement($players);
}

/**
 * Get players
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getPlayers()
{
    return $this->players;
}
}

Here is an extract of the User entity :
/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\HasLifecycleCallbacks
 */
class User extends \FOS\UserBundle\Model\User
{
/**
 * @ORM\ManyToMany(targetEntity="Campaign", inversedBy="players", cascade={"all"})
 * @ORM\JoinTable(name="users_campaigns")
 */
protected $campaigns;

/**
 * Add campaign
 *
 * @param \AppBundle\Entity\Campaign $campaign
 * @return User
 */
public function addCampaign(\AppBundle\Entity\Campaign $campaign)
{
    $campaign->addPlayer($this);
    $this->campaigns[] = $campaign;

    return $this;
}

/**
 * Remove campaign
 *
 * @param \AppBundle\Entity\Campaign $campaign
 */
public function removeCampaign(\AppBundle\Entity\Campaign $campaign)
{
    $this->campaigns->removeElement($campaign);
}

/**
 * Get campaign
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getCampaign()
{
    return $this->campaigns;
}
}

Here is my form type :
class NewCampaignFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', 'text', array(
        "label" => 'form.name',
        'required' => true,
        ))
        ->add('description','ckeditor',array(
            "label" => 'form.description',
            "required" => true,
        ))
        ->add('players','entity',array(
            'label'=>'form.campaign.players',
            'class'=> 'AppBundle\Entity\User',
            'multiple' => true,
        ));
}

public function getName()
{
    return 'campaign';
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Campaign',
    ));
}
}

And finally, here is my controller :
 public function createAction(Request $request){
    $em = $this->getDoctrine()->getManager();
    $campaign = new Campaign();

    $form = $this->createForm(new NewCampaignFormType(),$campaign);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid())
    {
        $user = $this->getUser();
        $campaign->setMJ($user->getId());
        $players = $form->get('players');
        var_dump($players);
        $em->persist($campaign);
        $em->flush();
        return $this->redirectToRoute('show_campaign', array('id'=>$campaign->getId()));
    }

    return $this->render('campaign/createCampaign.html.twig', array(
        'form' => $form->createView(),
        'campaign' => $campaign,
    ));
}

I am stuck on this for quite a while now, so anyone who has an idea, just try it.
Thank you for reading

A: You work on Campain object which is not owning side of that relation so by default it will not be checked and persisted by Doctrine.
Change sides of relation like here:
Campaign
/**
 * @ORM\ManyToMany(targetEntity="User", inversedBy="campaigns" , cascade={"all"})
 * @ORM\JoinTable(name="users_campaigns")
 */
private $players;

User
/**
 * @ORM\ManyToMany(targetEntity="Campaign", mappedBy="players", cascade={"all"})
 */
protected $campaigns;

Read more here: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/unitofwork-associations.html#important-concepts


text:
Q: Go language interview question about defer behavior I've 2 code examples:
func test() int {
    var x int
    defer func() {

        x++
    }()
    x = 1
    return x
}

func main() {
    fmt.Println(test())
}

It returns: 1. However, the following code example behaves differently:
func test() (x int) {
    defer func() {

        x++
    }()
    x = 1
    return
}

func main() {
    fmt.Println(test())
}

It returns 2.

In order to understand what's going on, I disassembled the code.
For the first code snippet (whose output is 1):
  main.go:19            0x48cf40                64488b0c25f8ffffff      MOVQ FS:0xfffffff8, CX
  main.go:19            0x48cf49                483b6110                CMPQ 0x10(CX), SP
  main.go:19            0x48cf4d                7678                    JBE 0x48cfc7
  main.go:19            0x48cf4f                4883ec58                SUBQ $0x58, SP
  main.go:19            0x48cf53                48896c2450              MOVQ BP, 0x50(SP)
  main.go:19            0x48cf58                488d6c2450              LEAQ 0x50(SP), BP
  main.go:20            0x48cf5d                e83effffff              CALL main.test(SB)
  main.go:20            0x48cf62                e8c9bff7ff              CALL runtime.convT64(SB)
  main.go:20            0x48cf67                488b442408              MOVQ 0x8(SP), AX
  main.go:20            0x48cf6c                0f57c0                  XORPS X0, X0
  main.go:20            0x48cf6f                0f11442440              MOVUPS X0, 0x40(SP)
  main.go:20            0x48cf74                488d0d05090100          LEAQ 0x10905(IP), CX
  main.go:20            0x48cf7b                48894c2440              MOVQ CX, 0x40(SP)
  main.go:20            0x48cf80                4889442448              MOVQ AX, 0x48(SP)
  print.go:274          0x48cf85                488b0524020d00          MOVQ os.Stdout(SB), AX
  print.go:274          0x48cf8c                488d0d0dd70400          LEAQ go.itab.*os.File,io.Writer(SB), CX
  print.go:274          0x48cf93                48890c24                MOVQ CX, 0(SP)
  print.go:274          0x48cf97                4889442408              MOVQ AX, 0x8(SP)
  print.go:274          0x48cf9c                488d442440              LEAQ 0x40(SP), AX
  print.go:274          0x48cfa1                4889442410              MOVQ AX, 0x10(SP)
  print.go:274          0x48cfa6                48c744241801000000      MOVQ $0x1, 0x18(SP)
  print.go:274          0x48cfaf                48c744242001000000      MOVQ $0x1, 0x20(SP)
  print.go:274          0x48cfb8                e84397ffff              CALL fmt.Fprintln(SB)
  print.go:274          0x48cfbd                488b6c2450              MOVQ 0x50(SP), BP
  print.go:274          0x48cfc2                4883c458                ADDQ $0x58, SP
  print.go:274          0x48cfc6                c3                      RET
  main.go:19            0x48cfc7                e8d447fcff              CALL runtime.morestack_noctxt(SB)
  main.go:19            0x48cfcc                e96fffffff              JMP main.main(SB)

For the second code snippet (whose output is 2):
  main.go:18            0x48cf30                64488b0c25f8ffffff      MOVQ FS:0xfffffff8, CX
  main.go:18            0x48cf39                483b6110                CMPQ 0x10(CX), SP
  main.go:18            0x48cf3d                7678                    JBE 0x48cfb7
  main.go:18            0x48cf3f                4883ec58                SUBQ $0x58, SP
  main.go:18            0x48cf43                48896c2450              MOVQ BP, 0x50(SP)
  main.go:18            0x48cf48                488d6c2450              LEAQ 0x50(SP), BP
  main.go:19            0x48cf4d                e84effffff              CALL main.test(SB)
  main.go:19            0x48cf52                e8d9bff7ff              CALL runtime.convT64(SB)
  main.go:19            0x48cf57                488b442408              MOVQ 0x8(SP), AX
  main.go:19            0x48cf5c                0f57c0                  XORPS X0, X0
  main.go:19            0x48cf5f                0f11442440              MOVUPS X0, 0x40(SP)
  main.go:19            0x48cf64                488d0d15090100          LEAQ 0x10915(IP), CX
  main.go:19            0x48cf6b                48894c2440              MOVQ CX, 0x40(SP)
  main.go:19            0x48cf70                4889442448              MOVQ AX, 0x48(SP)
  print.go:274          0x48cf75                488b0534020d00          MOVQ os.Stdout(SB), AX
  print.go:274          0x48cf7c                488d0d1dd70400          LEAQ go.itab.*os.File,io.Writer(SB), CX
  print.go:274          0x48cf83                48890c24                MOVQ CX, 0(SP)
  print.go:274          0x48cf87                4889442408              MOVQ AX, 0x8(SP)
  print.go:274          0x48cf8c                488d442440              LEAQ 0x40(SP), AX
  print.go:274          0x48cf91                4889442410              MOVQ AX, 0x10(SP)
  print.go:274          0x48cf96                48c744241801000000      MOVQ $0x1, 0x18(SP)
  print.go:274          0x48cf9f                48c744242001000000      MOVQ $0x1, 0x20(SP)
  print.go:274          0x48cfa8                e85397ffff              CALL fmt.Fprintln(SB)
  print.go:274          0x48cfad                488b6c2450              MOVQ 0x50(SP), BP
  print.go:274          0x48cfb2                4883c458                ADDQ $0x58, SP
  print.go:274          0x48cfb6                c3                      RET
  main.go:18            0x48cfb7                e8e447fcff              CALL runtime.morestack_noctxt(SB)
  main.go:18            0x48cfbc                e96fffffff              JMP main.main(SB)

A: The Golang spec says this about defer statements:

[...] if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned.

(my emphasis)
In your first snippet, function test has no named return parameter; x is merely a local variable. Therefore, your defer statement cannot modify the result of function test.
In your second snippet, function test has a named return parameter x, which is in scope within your function literal. Therefore, the defer statement can (and does) modify the result of function test.