text:
Q: How to access pixels in Opengl? I'm trying to collect all pixels color, than change same color and at the end render!
I searched for that and the results are:
glReadPixels() and glDrawPixels(), glReadPixels() works fine but glDrawPixels() not!
The problem is I have info in the array filled by glReadPixels but how can I pass this to OpenGL for render?
I tried to use glDrawPixels() but it doesn't work, neither with an array filled with red color (1,0,0);
do{

        int size = 1024*768*3;
        std::vector<GLfloat> pixel(size);
        for (int i = 0; i< size; i+=3)
            pixel[i] = 1.0;
        glWritePixels(1024, 768, GL_RGB, GL_FLOAT, &pixel[0]);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
           glfwWindowShouldClose(window) == 0 );

So searching again, and I found a tutorial on how render on a texture:
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <windows.h>
// Include GLEW
#include <glew.h>

// Include GLFW
#include <glfw3.h>
GLFWwindow* window;

// Include GLM
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
using namespace glm;

#include "shader.hpp"

int main( void )
{
    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        return -1;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);

    // Open a window and create its OpenGL context
    window = glfwCreateWindow( 1024, 768, "Cube", NULL, NULL);
    if( window == NULL ){
        fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" );
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // Initialize GLEW
    glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return -1;
    }

    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    // Dark blue background
    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    // Enable depth test
    glEnable(GL_DEPTH_TEST);
    // Accept fragment if it closer to the camera than the former one
    //glDepthFunc(GL_LESS);

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // Create and compile our GLSL program from the shaders
    GLuint programID = LoadShaders( "TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader" );

    // Get a handle for our "MVP" uniform
    GLuint MatrixID = glGetUniformLocation(programID, "MVP");

    // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
    // Camera matrix
    glm::mat4 View       = glm::lookAt(
                                glm::vec3(4,3,-3), // Camera is at (4,3,-3), in World Space
                                glm::vec3(0,0,0), // and looks at the origin
                                glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                           );
    // Model matrix : an identity matrix (model will be at the origin)
    glm::mat4 Model      = glm::mat4(1.0f);
    // Our ModelViewProjection : multiplication of our 3 matrices
    glm::mat4 MVP        = Projection * View * Model; // Remember, matrix multiplication is the other way around

    // Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle.
    // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices
    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f, 1.0f,
        -1.0f, 1.0f, 1.0f,
         1.0f, 1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f,-1.0f,
         1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f,-1.0f,
         1.0f,-1.0f,-1.0f,
         1.0f, 1.0f,-1.0f,
         1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,
        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f,-1.0f,
         1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f, 1.0f,
        -1.0f,-1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,
        -1.0f,-1.0f, 1.0f,
         1.0f,-1.0f, 1.0f,
         1.0f, 1.0f, 1.0f,
         1.0f,-1.0f,-1.0f,
         1.0f, 1.0f,-1.0f,
         1.0f,-1.0f,-1.0f,
         1.0f, 1.0f, 1.0f,
         1.0f,-1.0f, 1.0f,
         1.0f, 1.0f, 1.0f,
         1.0f, 1.0f,-1.0f,
        -1.0f, 1.0f,-1.0f,
         1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f,-1.0f,
        -1.0f, 1.0f, 1.0f,
         1.0f, 1.0f, 1.0f,
        -1.0f, 1.0f, 1.0f,
         1.0f,-1.0f, 1.0f
    };

    // One color for each vertex. They were generated randomly.
    static const GLfloat g_color_buffer_data[] = {
        0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f,
                0.583f,  0.771f,  0.014f
    };

    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    GLuint colorbuffer;
    glGenBuffers(1, &colorbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW);

    glUseProgram(programID);

        // ---------------------------------------------
    // Render to Texture - specific code begins here
    // ---------------------------------------------

    // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer.
    GLuint FramebufferName = 0;
    glGenFramebuffers(1, &FramebufferName);
    glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);

    // The texture we're going to render to
    GLuint renderedTexture;
    glGenTextures(1, &renderedTexture);

    // "Bind" the newly created texture : all future texture functions will modify this texture
    glBindTexture(GL_TEXTURE_2D, renderedTexture);

    // Give an empty image to OpenGL ( the last "0" means "empty" )
    glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, 1024, 768, 0,GL_RGBA, GL_UNSIGNED_BYTE, 0);

    // Poor filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // The depth buffer
    GLuint depthrenderbuffer;
    glGenRenderbuffers(1, &depthrenderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1024, 768);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);

    //----------------------------

    // Set "renderedTexture" as our colour attachement #0
    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, renderedTexture, 0);

    // Set the list of draw buffers.
    GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
    glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers

    // Always check that our framebuffer is ok
    if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    {
        printf("\nFrameBuffer Error\n");
        return false;
    }

    // The fullscreen quad's FBO
    static const GLfloat g_quad_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
        -1.0f,  1.0f, 0.0f,
        -1.0f,  1.0f, 0.0f,
         1.0f, -1.0f, 0.0f,
         1.0f,  1.0f, 0.0f,
    };

    GLuint quad_vertexbuffer;
    glGenBuffers(1, &quad_vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);

    // Create and compile our GLSL program from the shaders
    GLuint quad_programID = LoadShaders( "Passthrough.vertexshader", "WobblyTexture.fragmentshader" );
    GLuint texID = glGetUniformLocation(quad_programID, "renderedTexture");

    do{

        // Render to our framebuffer
        glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
        glViewport(0,0,1024,768); // Render on the whole framebuffer, complete from the lower left corner to the upper right

        // Clear the screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use our shader
        glUseProgram(programID);

        // Send our transformation to the currently bound shader,
        // in the "MVP" uniform
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );

        // 2nd attribute buffer : colors
        glEnableVertexAttribArray(1);
        glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
        glVertexAttribPointer(
            1,                                // attribute. No particular reason for 1, but must match the layout in the shader.
            3,                                // size
            GL_FLOAT,                         // type
            GL_FALSE,                         // normalized?
            0,                                // stride
            (void*)0                          // array buffer offset
        );

        // Draw the triangle !
        glDrawArrays(GL_TRIANGLES, 0, 12*3); // 12*3 indices starting at 0 -> 12 triangles

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);

        // Render to the screen
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glViewport(0,0,1024,768); // Render on the whole framebuffer, complete from the lower left corner to the upper right

        // Clear the screen
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Use our shader
        glUseProgram(quad_programID);

        // Bind our texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, renderedTexture);
        // Set our "renderedTexture" sampler to user Texture Unit 0
        glUniform1i(texID, 0);

        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );

        // Draw the triangles !
        glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles

        glDisableVertexAttribArray(0);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
           glfwWindowShouldClose(window) == 0 );

        // Cleanup VBO and shader
    glDeleteBuffers(1, &vertexbuffer);
    glDeleteBuffers(1, &colorbuffer);
    glDeleteProgram(programID);

    glDeleteFramebuffers(1, &FramebufferName);
    glDeleteTextures(1, &renderedTexture);
    glDeleteRenderbuffers(1, &depthrenderbuffer);
    glDeleteBuffers(1, &quad_vertexbuffer);
    glDeleteVertexArrays(1, &VertexArrayID);

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}

But again I don't know how access to pixels before render them on screen, in the previous example I think all data are store in FrameBufferName variable, but how can I access to this buffer and take all the pixels color data?


text:
Q: Suitable javascript parser to be used with urlopen I am trying the following:
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
url = 'http://search.wcad.org/Property-Detail?PropertyQuickRefID=R000017&PartyQuickRefID=O0532572'

soup = BeautifulSoup(urlopen(url).read())
print soup

The print statement displays very complicated text structure and it is difficult to extract variables. What is the better way to extract variables like Legal Description

A: You don't need to parse JavaScript to get the "Legal Description" value - you need to parse HTML and BeautifulSoup HTML parser can do the job. Locate the td element "by 'Legal Description' text" and then get the next td element:
soup.find("td", text="Legal Description").find_next_sibling("td").get_text()

Note: you are using BeautifulSoup version 3 - it is very outdated and not maintained - switch to the 4th version:
pip install beautifulsoup4

And change your import from:
from BeautifulSoup import BeautifulSoup

to:
from bs4 import BeautifulSoup

A: Though you can do this with urllib2 I would recommend to use requests.
The id is unique for each field, so you can get the text directly by finding the element using id.
import requests
from bs4 import BeautifulSoup

url = "http://search.wcad.org/Property-Detail?PropertyQuickRefID=R000017&PartyQuickRefID=O0532572"

html = requests.get(url)
soup = BeautifulSoup(html.text, "lxml")
text = soup.find("td", id="dnn_ctr1460_View_tdGILegalDescription").get_text()
print(text)

NOTE: I've used Beautifulsoup version 4. To install it use this command - pip install bs4.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split words between UPPER CASE and lower case If anyone could help me this would be awesome!
I have this:
TYLLON kevin -convert-> familyname: TYLLON; prename: kevin
VAN AZERTY bert -convert-> familyname: VAN AZERTY; prename: bert
YAHOO BE AWESOME rabbit -convert-> familyname: YAHOO BE AWESOME; prename: rabbit
Maybe regex, anyone?

A: I believe shortest possible answer is by using preg_split here using look-arounds:
Use this regex for splitting:
/(?<=\p{Lu})\h+(?=\p{Ll})/u

Which matches 1 or more horizontal space that is preceded by a uppercase unicode letter and followed by a lowercase unicode letter.
PS: This solution is unicode compatible.
Examples:
print_r(preg_split('/(?<=\p{Lu})\h+(?=\p{Ll})/u', 'YAHOO BE AWESOME rabbit'));
Array
(
    [0] => YAHOO BE AWESOME
    [1] => rabbit
)

print_r(preg_split('/(?<=\p{Lu})\h+(?=\p{Ll})/u', 'VAN AZERTY bert'));
Array
(
    [0] => VAN AZERTY
    [1] => bert
)

print_r(preg_split('/(?<=\p{Lu})\h+(?=\p{Ll})/u', 'TYLLON kevin'));
Array
(
    [0] => TYLLON
    [1] => kevin
)

A: You could loop through your name strings using the php function ctype_upper:

Checks if all of the characters in the provided string, text, are uppercase characters.

You would first have to explode() your names and put them in an array. Once you have them in an array you can check for upper case / lower case…
<?php
$name_array = array('VAN', 'AZERTY', 'bert');
foreach ($name_array as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase is upper case.";
    } else {
        echo "The string $testcase is lower case / mixed case.";
    }
}
?>

A: Try this solution.
<?php
   preg_match_all('/\b([A-Z]+)\b/', $fullname, $upper);
   preg_match_all('/\b([a-z]+)\b/', $fullname, $lower);
   $familyname = implode(' ', $upper[0]);
   $prename = implode(' ', $lower[0]);
   echo $prename.' '.$familyname;
?>

A: I found the answer in combination of multiple answers:
preg_match_all('/\b([A-Z]+)\b/', 'BLA BOEM BABA Kevin', $matches);

RESULT: BLA BOEM BABA
preg_replace('/\b([A-Z]+)\b/', '', 'VAN MELKEBEKE BLA BOEM BABA Kevin');

RESULT: Kevin


text:
Q: Joining more table is reducing execution time I was under the impression that the more number of tables you join in your query the more its execution time increases, but something really opposite is happening in my case.
Here is the query where I am joining two tables task_group_attempt and task_group -
select count(*) from (
select ga.id, ga.task_group_id from task_group_attempt ga
where ga.started_on >= '2015-05-30 18:30:00' and ga.started_on < '2015-06-30 18:30:00'
) tab1
inner join task_group tg on tg.id = tab1.task_group_id and tg.task_group_type_id != 6

The value it is returning is 585856 and the execution time is 17.6 secs.
For the table task_group_attempt id is the primary key and indexing has been done to the column task_group_id.
For the table task_group id is the primary key and indexing has been done to the column task_group_type_id.
Now the second query which is just the extension of the first one and here we are joining one more table named task_attempt -
select count(*) from (
select ga.id, ga.task_group_id from task_group_attempt ga
where ga.started_on >= '2015-05-30 18:30:00' and ga.started_on < '2015-06-30 18:30:00'
) tab1
inner join task_group tg on tg.id = tab1.task_group_id and tg.task_group_type_id != 6
inner join task_attempt ta on tab1.id = ta.task_group_attempt_id

The value it is returning is 1109682 and the execution time is 7.88 secs.
For the table task_attempt indexing has been done to the column task_group_attempt_id.
I have checked it multiple times and every time the query execution time is almost or close to the above mentioned time.
ADDITION INFO -
Number of rows in task_group_attempt is 8565011
Number of rows in task_group is 1057
Number of rows in task_attempt is 15156598
It would be really helpful is somebody can help me understand how is this possible?


text:
Q: PyCharm-style docstring containing code with `>>>` I just figured out that PyCharm supports a docstring with code prefixed by >>> like this:
def foo(x):
  """
  Use it like:

  >>> foo(42)
  """
  print(x)

PyCharm then even applies the usual code highlighting on this.
I tried to find any documentation on this syntax. It doesn't seem to be part of reStructuredText. Also Sphinx does not mention this. Was this introduced in some PEP? Or is this PyCharm specific? But I did not find any PyCharm documentation on this.
(It's hard to use Google search for this. I don't know how to call this. "3-times greater sign"?)

A: The comments have answered the question. I'm just putting it here for completeness:
It's three fleshes (>>>).
It's used for doc test.
In PyCharm, when you rightclick it, it allows you to Run Doctest.
The syntax probably comes from the Python interactive shell.


text:
Q: how to constant object or remain object values same in javascript? Here is basic example where I want to explain my requirement . I want not to change object a values after assigning it to const b and changing its values .I want console result original object a values not after assign values . how can I achive this in console name :abc, number 123

const a ={
name:"abc",
number:123
}
const b = a
b.name ="xyz";
b.number = 321
 console.log(a);

A: simply do this with b so that b will not reference to a
const b = {...a}

A: Use Object.freeze() to prevent modifying an object.
Just, before doing so you might want to (optionally) spread  your original object {...a} values into b beforehand, (or by using Object.assign()) in order to keep the a object values still modifiable:

const a = {
  name: "abc",
  number: 123
};

const b = {...a};
Object.freeze(b);

a.name = "Still modifiable";
a.number = 999;
console.log(a); // {"name": "Still modifiable!", "number": 999}

b.name = "xyz";
b.number = 321;
console.log(b); // {"name": "abc", "number": 123}


text:
Q: How to fix problem with text not showing in Preview mode for SSRS 2019 using Microsoft Visual Studio Community 2019? I just got the latest versions today for working with SSRS: SSRS 2019, Visual Studio Community 2019 (Version 4.8.03752) with SSRS Templates (Microsoft SQL Server Reporting Services Designers Version 15.0.1659.0).
I have a textbox with the report title which doesn't show in preview (both in header or body) and a textbox in footer with page counts that doesn't show. In the body I have a Table with a few columns that don't show values but do show the table cells. I noticed that values did show for returned records on first try but not for column headers; however, when I resized one cell, no values were shown at all for anything.  Now, no text values show at all in Preview mode.
When I export report to PDF, everything shows (title, body, footer). This also works when I published to the Portal.
Here is what I tried without success:

*

*Changed the font color to all texts to red but text values still don't show.

*Deleted the report data files (.data) but text values still don't show.

*Open the report file (.rdl) with Report Builder but text values still don't show.

So, it is in the editors (VS and Report Builder) that the problem only exists as rendering (PDF, Word) works and running in Report Portal works.
Thanks.

A: My issue was resolved by unticking the "Allow height to increase" check box for the text box.
enter image description here

A: I faced this same issue using the standalone Report Builder application, and I resolved it by placing the textbox inside a rectangle. From then on, it rendered in preview mode as expected. However, I'm not sure how that would affect auto-growth.


text:
Q: Visual Studio Performance when editing XAML/Silverlight files When I work on Silverlight projects within Visual Studio 2008, I regularly notice that the XAML editor hangs for up to 10 seconds. This because Visual Studio consumes 100% CPU during that timeframe.
Any ideas how I could fix that? I assume this is some kind of background compiling for itellisense or something similiar. It happens during editing, multiple times an hour, without me doing any special actions.
System:

*

*Server 2008 Std

*Visual Studio 2008 SP1

*latest updates...

I wonder if anyone else experienced this issue. Any help would be appreciated.

A: The problem is that the xaml editor takes so long to draw the preview.  Do you need the visual preview?  If you don't, you can turn it off, and that's what we do on the Silverlight Tour.  Tools->Options->Text Editor->XAML->MIscellaneous->"Always open documents in full XAML view".  This option gives you all of the benefits of auto-complete without the killer wait times ;)

A: right click on the xaml file
select open with
select the source code editor
You will not get the visual preview however the file will open instantly and still have intellisense.

A: I totally agree with Hugo. I'm running VS2010 with a monster computer (64 bit, 24 GB RAM, i7 X980 3.33 GHZ 12 core processor), and the XAML performance is horrific. Yes, my solution is very large. Yes, we have a lot of XAML files. So what? There is ZERO conceivable reason why editing a XAML file (wysiwyg turned off) should have intolerable lags and delays.
UPDATE: I found a possible fix... I have been using the "Source Code (Text) Editor" as my default editor for XAML files. I did that to get rid of the wysiwyg designer, and hoping to improve XAML text editing performance, which did not happen. I just switched to "XML (Text) Editor", and editing is now snappy -- and intellisense still works. Such a simple change, and apparently a total fix. Just close all XAML files, then right-click on a XAML file, choose "Open With", selected "XML (Text) Editor", and click "Set as Default" and click "OK".

A: I don't know how the XAML performance is in VS2008, but in VS2010 it is terrible. With beta SP1 it completely breaks down to eternal refreshing. Using i7 with 8Gb ram, brand new computer.

A: 1.Close all other apps you are running.Only use VS 2008 SP1.
2.Install KB958017 - Rollup Hotfix for several issues in WPF designer Visual Studio 2008
3.Move to VS 2010 !!! This is what it should have been like !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
4.Get more RAM.
5.Defragment HDD...
????

A: I'd recommend using Expression Blend. It doesn't suffer the same terrible performance as VS.Net for XAML and is more powerful and flexible for designing interfaces. I curse everytime I accidentally double click a XAML file in VS.Net and am franticalyl hitting the escape key.

A: What is your systems RAM? I have 3 GB ram and XAML editor hangs for 1/2 seconds sometimes but not 10 seconds.
I usually close all other apps while working with WPF applications. I also use Blend which is more faster comapred to VS xaml editor.


text:
Q: Wordpress scroll animation to id i'm trying to get my wordpress site to do the animate scroll to id, by using the scroll to id by malihu
I can't get it to work. When i click the link it just jump down to the page.
it´s a one page site..

Et

To

Tre

Fire

Et

to

tre

fire

Heading 2

A: If you are ok with an alternate method, take a look at this demo http://codepen.io/mattsince87/pen/exByn.


text:
Q: Docker Quickstart Terminal unable to locate bash.exe I have installed docker toolbox on Windows 7 64 bit machine. Installation showed a success message. However when i try to run a quick start terminal through shortcut created by installer is not working. It gives me an error
"Unable to locate bash.exe "

A: It was a silly mistake. The default location with which the shortcut was created was pointing to
C:\Program Files\Git\bin\bash.exe --login -i "C:\Program Files\Docker Toolbox\start.sh"
after i pointed the correct path of bash.exe, it stated working.
C:\Softs\Git\bin\bash.exe --login -i "C:\Program Files\Docker Toolbox\start.sh"
Regards,
Vikrant Korde

A: I had the error:

Windows is searching for bash.exe

and was able to fix it by reinstalling Docker Toolbox with the Git option selected (I had unselected it on the first install).


text:
Q: Moving unsupported file extensions by python I'm trying to move files from one directory to another using Python - spyder.
My file extension is *.OD which python does not support or read.
I have tried using the wildcard and leaving out the file extension (which does not work). Another file extension cannot be used for this particular file.
Moving python supported extensions such as .txt and .csv works fine.
import shutil
source = '//Original_Filepath/Extract*.od'
target = '//NewFilePath/Extract_*.od'

shutil.copy(source, target)

There are no errors, it just doesn't move/copy the file.
Thanks,

A: There are a couple of basic mistakes with how you're trying to copy the files.  With shutil.copy you should not specify a glob, but instead the exact source and destination.
If instead you want to copy a set of files from one directory to another and (presuming the added underscore isn't a mistake) change the target, then you should try using pathlib in combination with shutil (and re if needed).
pathlib - Object-oriented filesystem paths
Try adapting this:
import pathlib
import shutil
import re

source = pathlib.Path('//Original_Filepath') # pathlib takes care of end slash
source_glob = 'Extract*.od'
target = pathlib.Path('//NewFilePath')
for filename in source.glob(source_glob):
    # filename here is a Path object as well
    glob_match = re.match(r'Extract(.*)\.od', filename.stem).group(1)
    new_filename = "Extract_{}.od".format(glob_match)
    shutil.copy(str(filename), str(target / new_filename)) # `/` will create new Path

If you're not interested in editing the target nor using any other advanced feature that pathlib provides then see Xukrao's comment.

A: Thank you all for your help. Much appreciated! :)
I was also able to copy the file with the below as well (a bit simpler).
I left out the * and used a date string instead.
import shutil
from datetime import datetime
now = datetime.now()
Org_from=os.path.abspath('//Original FilePath')
New_to=os.path.abspath('//New Path')
shutil.copy(os.path.join(org_from, 'File_' + now.strftime("%Y%m%d") + '.od'), os.path.join(New_to, 'File_' + now.strftime("%Y%m%d") + '.od'))
Cheers,
Jen


text:
Q: How can I set path so it can be read from GUI and command line by the same program? I installed texlive and I want to add it as an environment variable to my Path so that Emacs AucTeX can read it when I start emacs from the GUI or from the command line. So far I've read that emacs only reads files from ~/.profile.
Therefore my plan is to add texlive to my path in .profile to enable emacs GUI to read it and then source ~/profile from .bashrc in order for emacs that is started inside my non-login interactive GNOME terminal to see the path.
Note: I do not have a .profile file in my home directory, only in my /etc directory, and I'd rather not touch that one, but I have a .bash_profile in my home directory. However I read that .bash_profile is only run for an interactive login session aka console mode which I don't use.
My plan is to create a .profile file in my home directory and do the following:
step 1: Create ~/.profile
Step 2: Add texlive environment variable to path in .profile
export PATH=/usr/local/texlive/2018/bin/x86_64-linux:$PATH
export MANPATH=/usr/local/texlive/2018/texmf-dist/doc/man:$MANPATH
export INFOPATH=/usr/local/texlive/2018/texmf-dist/doc/info:$INFOPATH

Step 3: Source .profile from .bashrc
#Adding this at the bottom or start of .bashrc to source .profile when the terminal is opened.

if [-s ~/.profile]; then;
    source ~/.profile;
fi

I know that there is a lot of apprehension towards sourcing .profile from .bashrc due to the risk of causing an infinte loop. However since I am creating a .profile file from scratch this will not be a problem as it will not contain any code that references .bashrc.
My Questions:

*

*What do you think of my plan?

*Do you think it will work?

*Do you have any suggestions on how to improve it or perhaps other alternatives

Additional info: My .bashrc only contains code that sources ~/etc/bashrc and one environment variable that was automatically added by Anaconda: export PATH="/home/Fedora_User/Anaconda3/bin:$PATH"
Keep in mind that I know gnome-terminal can be run as an interactive login shell but I have never done this and don't know if it will impact the performance of my terminal sessions.

A: Firstly, note that if you want ~/.profile to be read, you'll need to remove ~/.bash_profile, otherwise ~/.profile will be ignored by Bash.
You are actually overcomplicating this a bit. PATH is set in /etc/environment. It is always exported already, so it does not need to be exported again.
If you make changes to your PATH in ~/.profile they will be inherited by every shell, whether it is a login shell, interactive or otherwise.
Other variables exported in ~/.profile will also be passed into the environment, and will be available in every shell. ~/.profile is read once when you log in to your session, and exported variables stay exported.
Sourcing ~/.profile in ~/.bashrc is a bad idea. ~/.profile sources ~/.bashrc so you will get an infinite loop. Even if ~/.profile does not source ~/.bashrc it is a bad idea to have ~/.bashrc source ~/.profile or any other file with assignments like
PATH=$PATH:/some/other/place

because every time an interactive shell starts another interactive shell the PATH will get extended... you'll end up with your PATH being
/original/path:/some/other/place:/some/other/place:/some/other/place

etc.
Your MANPATH assignment does not need to include $MANPATH but it should start with a leading colon. Please see this question and its answer. By default MANPATH is unset and the correct path is dynamically determined (in some way I don't understand), so including the existing MANPATH does nothing. You may need to start the MANPATH assignment with a colon to avoid preventing the path being determined dynamically. As far as I know, the same goes for INFOPATH
Therefore, I suggest:
Rename ~/.bash_profile ~/.profile
Add the lines:
PATH="$PATH:/usr/local/texlive/2018/bin/x86_64-linux"
export MANPATH=":/usr/local/texlive/2018/texmf-dist/doc/man"
export INFOPATH=":/usr/local/texlive/2018/texmf-dist/doc/info"

Notes that I have appended to the PATH rather than prepending. You can prepend (put $PATH at the end instead of the beginning) if you want to. The first executable found in path lookup is run, so if two programs in different PATH locations have the same name, the one in the directory that comes first (further to the left) in PATH will be run.
Do not add anything to your ~/.bashrc. Environment variables modified, or new variables exported in ~/.profile will be available to every shell and don't need to be additionally set elsewhere.
Also note that you should not source /etc/bash.bashrc in ~/.bashrc, because /etc/bash.bashrc is already sourced by every interactive shell first*, and we use ~/.bashrc to make subsequent adjustments.
*An exception - /etc/bash/bashrc checks that the shell is interactive using an unreliable method - it checks that PS1 is set. If you start a shell unsetting PS1, /etc/bash.bashrc will not be sourced, even though the shell is interactive. Another exception is when the shell is started with --norc, but that's more obvious.


text:
Q: Mapping min and max value to 0.1 and 1 and found equivalent number between I'm trying to find a solution for this problem, I have a min and a max value that i want always map as min 0.1 and max 1, so for example:
i have 48 and 97, so 48 will be my 0.1 and 97 will be my 1. Now i want map a number between 0.1 and 1 in the range of 48 and 97. So for example if I have 60 (that is between 48 and 97) what is the mapped 0.1-1 number?

A: Use linear interpolation. The function is given by
$$f(x)=0.1+\frac{1-0.1}{\max-\min}(x-\min).$$
Then if $x=\min$ we have $f(x)=0.1$ and if $x=\max$, we have $f(x)=1$. In case $\max=97$, $\min=48$, and $x=60$, we have $f(x)\approx 0.32$.


text:
Q: Border Radius Error only on Safari Browser I am trying to make a node that can zoom its picture when hovered upon. Everything works fine on Chrome and Mozilla. However, for some reason Safari gets buggy every time the image is on hover. The border radius disappears when hovered into a sharp edge and reappears when un-hovered. Here is an example: FIDDLE

.img-zoom {
  top: 0;
  left: 0;
  margin: 0;
  display: block;
  width: 100%;
  height: 60%;
  position: relative;
  overflow: hidden;
}

.img-zoom img {
  -webkit-transform: scale(1.04);
  -ms-transform: scale(1.04);
  transform: scale(1.04);
  transition: all 1.1s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.img-zoom img:hover {
  -webkit-transform: scale(1.1);
  -ms-transform: scale(1.1);
  transform: scale(1.1);
}

.blogDesc {
  background-color: whitesmoke;
  width: 100%;
  height: 40%;
}

.blogContent {
  width: 200px;
  height: 200px;
  word-wrap: break-word;
  border-radius:25px;
  overflow: hidden;
  display:inline-block;
  margin:10px;
}

.blogTitle {
  font-weight: bold;
  font-family: "Courier New";
  text-align: center;
  padding: 10px;
}

.blogText {
  -webkit-column-width: 150px;
  column-width: 150px;
  height: 100%;
  margin-left: 10px;
  margin-right: 10px;
}
.blogAlign{
  text-align:center;
}

      My Multimedia Agency Tool

      BBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLAB

      My Multimedia Agency Tool

      BBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLAB

      My Multimedia Agency Tool

      BBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLABBBLALBLABLALBALBLBALBALBALBLABLABLABLABLABLALBLABLABLABLALBALBLABLABLABLABLALBLAB

Does anyone know how to fix this? Thanks in advance.

A:

.activity_rounded {
    display: inline-block;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    -khtml-border-radius: 50%;
    border: 3px solid #fff;
}

.activity_rounded img  {
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    -khtml-border-radius: 50%;
    vertical-align: middle;
}

it should work properly.


text:
Q: How can I know if a table is already arranged in ascending order in MySQL? Example, I have a table and I want to know if it is pre-arranged alphabetically descending or ascending, is there a built-in function that can do this?
Letters | Numbers |
A    |  1     |
B    |  2     |

Letters | Numbers |
B   |   2     |
A   |   1     |

thanks.

A: Data in a table is not arranged in any order.
You have to explicitly specify an order when selecting the data. If you do not specify an order when selecting the data then the returned order is neither predictable nor reliable.

A: Other answers are correct that SQL at a logical level does not guarantee that the rows are stored in any order.
But at a physical level, of course the data is stored in some order.  Most indexes in MyISAM and InnoDB are B-tree data structures, which by definition store values in ascending order.  In InnoDB, the table itself is stored as a clustered index in primary key order.
So the following two queries against an InnoDB table return results in the same order:
SELECT * FROM innodb_table;
SELECT * FROM innodb_table ORDER BY primary_key;

But that's a coincidence of storage implementation, not based on anything in the SQL language.
The issue is more complex if you do index-only queries against a non-primary key.  The following query will return rows in ascending order by the index used as a covering index:
SELECT indexed_column FROM innodb_table;

But as soon as you break the covering index, it reverts back to some other choice for default order (probably clustered index order again):
SELECT indexed_column, non_indexed_column FROM innodb_table;

MyISAM is totally different, because it doesn't use a clustered index.  So the default order is storage order -- which is not necessarily insertion order.

A: Tables dont store data in a particular order. Ordering is done in order to view the data, so thats where you use order by clause.

A: You should never rely on how data is retrieved until you use ORDER BY Clause explicitly

A: To add my voice to the concert of answers...
In relational databases (such as MySQL) tables must be seen as unordered set of rows.
As a matter on fact, you shouldn't even rely on the fact that two identical SELECT statements will return the rows in the same order.
If you want to retrieve or sort your rows according to a particular order, you will have to explicitly request it (i.e.: using the adequate ORDER BY clause) and provide a column that allow to deterministically order the rows.


text:
Q: SSRS Arrow indicators im looking to add some arrow indicators to compare 2 values within my Matrix. Current week v Last week.
I'm getting confused on where to put my expression which I'm currently using (for a Red arrow going down)
=Fields!COUNT_Signed.Value<Fields!COUNT_Signed_lw.Value

I have entered this into the Start Expr and have -1 in the End Expr.
all I'm getting is Green arrows going up as I'm also using > for green
Any help would be grateful

A: I think you have Fields!COUNT_Signed_lw.Value as the Value and you just need to use =Fields!COUNT_Signed_lw.Value as your END and -1 as the START.
The START and END values are the range of values to compare the Value with.
In this example, the indicator would be RED if ADMIT is Between 0 and 33.

MSDN - Indicators


text:
Q: Try to define should or should_not by method option I need test sidebars on every site page.
I define user method test_all_sidebars and fill in
def test_all_sidebars
    test_header
    test_contacts
    test_news
    test_footer
end

then I need test for one page 2 sidebars will not show. Example:
describe "Home page" do
    before { visit root_path }

    test_all_sidebars
end
describe "Contact page" do
    before { visit contact_path }

    test_header
    test_footer
    test_news(false)
    test_contact(false)
end

I try to define test_news and test_contact with option like this
def test_contacts(flag: true)
    describe "sidebar with contacts" do
        it { (:flag ? should : should_not) have_content('phone: ') }
    end

but it doesnt work. I have  unexpected tIDENTIFIER, expecting '}'
I tried use let
def test_contacts(flag: true)
    if :flag then
        let(:sh) { should }
    else
        let(:sh) { should_not }
    end
    it { sh have_content('phone: ') }
end

but this still doesnt work.
My question: HOW? How I can use should/should_not in same method using input data condition?

A: def test_contacts(flag: true)
  describe "sidebar with contacts" do
    it { (:flag ? should : should_not) have_content('phone: ') }
  end
end

So much is wrong with this code:

*

*:flag is always truthy, since it is a symbol. If you want to check if the value passed it true you should use flag (the variable), not :flag (the symbol)

*should and should_not are methods, so actually you need to call either should(have_content('phone: ') or should_not(have_content('phone: ') - you can't separate the method call from the variables you send it.

So, inside your describe your code should look like:
it { flag ? should(have_content('phone: ')) : should_not(have_content('phone: ') }

Beside this, I've never seen this kind of pattern for writing rspec test cases, and I'm pretty sure you are better off using better idioms like shared_examples_for


text:
Q: How to refresh registry keys without reboot? I use the following code to change region data in the Registry.
procedure TForm1.Button1Click(Sender: TObject);
var
  reg: TRegistry;
begin
  reg:=TRegistry.Create;
  try
    reg.RootKey:=HKEY_CURRENT_USER;
    reg.OpenKey('\Control Panel\International\',true);
    reg.WriteString('iCountry','1');
    reg.WriteString('iCurrDigits','2');
    reg.WriteString('iCurrency','0');
    reg.WriteString('iDate','1');
    reg.WriteString('iDigits','2');
    reg.WriteString('iLZero','0');
    reg.WriteString('iMeasure','1');
    reg.WriteString('iNegCurr','0');
    reg.WriteString('iNegNumber','1');
    reg.WriteString('iTimePrefix','0');
    reg.WriteString('iTLZero','1');
    reg.WriteString('Locale','00000409');
    reg.WriteString('LocaleName','en-US');
    reg.WriteString('sCountry','United States');
    reg.WriteString('sDate','/');
    reg.WriteString('sDecimal','.');
    reg.WriteString('iNegCurr','0');
    reg.WriteString('sShortDate','dd/MM/yyyy'); reg.CloseKey;
  finally
    reg.free;
  end;
end;

but this requires restarting the machine before the changes take effect. Can it be done without rebooting?

A: After changing the Registry, broadcast a system-wide WM_SETTINGCHANGE message by calling SendMessageTimeout() with its hWnd set to HWND_BROADCAST:

Applications should send WM_SETTINGCHANGE to all top-level windows when they make changes to system parameters.
...
wParam
  ... When the system sends this message as a result of a change in locale settings, this parameter is zero.
When an application sends this message, this parameter must be NULL.
...
lParam
  ... When the system sends this message as a result of a change in locale settings, this parameter points to the string "intl".

For example:
procedure TForm1.Button1Click(Sender: TObject);
var
  reg: TRegistry;
begin
  reg := TRegistry.Create;
  try
    reg.RootKey := HKEY_CURRENT_USER;
    reg.Access := KEY_SET_VALUE;
    if reg.OpenKey('\Control Panel\International\', true) then
    try
      reg.WriteString('iCountry','1');
      reg.WriteString('iCurrDigits','2');
      reg.WriteString('iCurrency','0');
      reg.WriteString('iDate','1');
      reg.WriteString('iDigits','2');
      reg.WriteString('iLZero','0');
      reg.WriteString('iMeasure','1');
      reg.WriteString('iNegCurr','0');
      reg.WriteString('iNegNumber','1');
      reg.WriteString('iTimePrefix','0');
      reg.WriteString('iTLZero','1');
      reg.WriteString('Locale','00000409');
      reg.WriteString('LocaleName','en-US');
      reg.WriteString('sCountry','United States');
      reg.WriteString('sDate','/');
      reg.WriteString('sDecimal','.');
      reg.WriteString('iNegCurr','0');
      reg.WriteString('sShortDate','dd/MM/yyyy');
    finally
      reg.CloseKey;
      SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LPARAM(PChar('intl')), SMTO_NORMAL, 100, PDWORD(nil)^);
    end;
  finally
    reg.free;
  end;
end;

And before you ask, yes it is safe to use nil in the last parameter in this manner:
Passing nil to a variable parameter
Prior to XE2, Delphi's Windows unit declares the last parameter of SendMessageTimeout() as:
var lpdwResult: DWORD

But the Win32 API defines the parameter as:
_Out_opt_ PDWORD_PTR lpdwResult

Which allows a NULL pointer to be passed in.  The above nil trick is the only way for Delphi code to pass a NULL value to a var parameter.  The machine code generated by the compiler will be correct - it will simply pass a value of 0 to the parameter, it will not actually try access memory address $00000000.
In XE2, the Windows unit was changed to declare the last parameter as:
lpdwResult: PDWORD_PTR

To match the Win32 API definition.
So, if you ever upgrade your code to XE2 or later, simply replace PDWORD(nil)^ with nil instead.  Or, you can account for it now and not worry about it later:
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LPARAM(PChar('intl')), SMTO_NORMAL, 100, {$IF RTLVersion >= 23}nil{$ELSE}PDWORD(nil)^{$IFEND});


text:
Q: Combining multiple Queries to single one postgres based on revision I am a newbie into postgresql and database. I am trying to prepare a birt report where I have to take data from 5 table based on parameters Unit, Year and Month. Results are saved as revision in each table and I have to pick latest revision data
The individual query as below
select wccb_pc$p,wccb_abufm,wccb_budm,wccb_revno
from wb_capacity_chrg_bill_month
where unit=? and bill_year=? and bill_month=? order by wccb_revno desc limit 1;

select wocb_wvf$p, wocb_flag, wocb_revno
from wb_output_chrg_bill_month
where unit=? and bill_year=? and bill_month=? order by wocb_revno desc limit 1;

select su_sum, revno
from wb_startup_pay_month
where unit=? and bill_year=? and bill_month=? order by revno desc limit 1;

select sdm, revno
from wb_startup_ded_month
where unit=? and bill_year=? and bill_month=? order by revno desc limit 1;

select dasm, dagcm, dasagcm, revno
from billing_as_agc_month
where unit=? and bill_year=? and bill_month=? order by revno desc limit 1;

A: Maybe you can use a JOIN?
select a.wccb_revno, a.wccb_pc$p, a.wccb_abufm, a.wccb_budm,
       b.wocb_wvf$p, b.wocb_flag,
       c.su_sum,
       d.sdm,
       e.dasm, e.dagcm, e.dasagcm
  from wb_capacity_chrg_bill_month a
  JOIN wb_output_chrg_bill_month b ON (a.wccb_revno = b.wocb_revno)
  JOIN wb_startup_pay_month c ON (b.wocb_revno = c.revno)
  JOIN wb_startup_ded_month d ON (c.revno = d.revno)
  JOIN billing_as_agc_month e ON (d.revno = e.revno)
where a.unit=? and a.bill_year=? a.and bill_month=? order by wccb_revno desc limit 1;

Depending on whether all 5 tables are guaranteed to have a revno in common, you may need to change your JOIN to a FULL OUTER JOIN


text:
Q: Unable to add an eventListener to a through JavaScript created div I am working on an Etch-A-Scetch project. I created grid which contains a certain amount of squares of the same size (the user is able to type in the amount of squares which should be displayed). To create the squares I used CSS grid and a Javascript for loop. Now I want to add event listeners, which change the background of each Square when moving over it. Unfortunately, it always shows errors when I try to add some. The current code doesn't show an error, it just doesn't do anything.
The method createSquares() should just create and add the amount of squares to the DOM. The user types in an amount, for example 10, and the displayed squares are 10 in x-direction and 10 in y-direction --> makes 100 squares in total. After that I want to add an event listener, which changes the background color of the square the user hovers over (the background color should stay changed). I am thankful for any help, because I'm really clueless :D

let squareDiv = document.querySelector('.squareDiv');
let squares = document.getElementById('#squares')
let squareAmount = 10;

function blackColor() {
  this.style.backgroundColor = '#000';
  this.style.border = '0px';
}

function createSquares() {
  for (i = 0; i < squareAmount * squareAmount; i++) {
    squares = document.createElement('div');
    squares.setAttribute("id", "squares");
    // squares.setAttribute("onmouseover",  "addEventListener")
    squares.style.display = 'grid';
    squareDiv.style.setProperty('--columns-amount', squareAmount);
    squareDiv.style.setProperty('--rows-amount', squareAmount);
    squareDiv.appendChild(squares);
  }
}
createSquares();

if (squares) {
  squares.addEventListener('mouseover', _ => {
    squares.style.backgroundColor = blackColor;
  });
}

A: You likely need something like this
I fixed the script, now fix the CSS

let container = document.getElementById("container")
let squareAmount = 5;

function getRandom() {
  return '#'+Math.floor(Math.random()*16777215).toString(16);
}

function colorIt(sq) {
  sq.style.backgroundColor = document.getElementById("random").checked? getRandom() : '#000';
  sq.style.border = '0px';
}

function createSquares() {
  let grid = document.createElement('div');
  grid.setAttribute("id","squares")
  grid.classList.add("grid");
  for (i = 0; i < squareAmount * squareAmount; i++) {
    square = document.createElement('div');
    square.classList.add("square");
    grid.appendChild(square);
  }
  container.innerHTML="";
  container.appendChild(grid)
}
createSquares();

container.addEventListener('mouseover',
  e => {
    const target = e.target;
    if (target.matches(".square")) colorIt(target)
  }
);
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));
  grid-auto-rows: 1fr;
}

.grid::before {
  content: '';
  width: 0;
  padding-bottom: 100%;
  grid-row: 1 / 1;
  grid-column: 1 / 1;
}

.grid > *:first-child {
  grid-row: 1 / 1;
  grid-column: 1 / 1;
}

/* Just to make the grid visible */

.grid > * {
  background: rgba(0,0,0,0.1);
  border: 1px white solid;
}
<input type="checkbox" id="random" />Random

A: *

*You have already created the element in DOM, please remove this.

*while creating the element using function createSquares assign class instead of ID. Since, you should have only element with one ID.

*Move the addEventListener inside the function after you have created the element.

A: When creating similar html elements with same properties it is better to group them together with class and not id. This is good because it becomes simple to loop these html elements with forEach or other looping methods you may prefer.

let squareDiv = document.querySelector('.squareDiv');
let squares = document.getElementById('#squares')
let squareAmount = 10;

function blackColor() {
  this.style.backgroundColor = '#000';
  this.style.border = '0px';
}

function createSquares() {
  for (i = 0; i < squareAmount * squareAmount; i++) {
    squares = document.createElement('div');
    squares.setAttribute("class", "squares");
    squares.setAttribute("style", "width: 100px; height: 100px; background: #090; margin-bottom: .3rem;");
    // squares.setAttribute("onmouseover",  "addEventListener")
    squares.style.display = 'grid';
    squareDiv.style.setProperty('--columns-amount', squareAmount);
    squareDiv.style.setProperty('--rows-amount', squareAmount);
    squareDiv.appendChild(squares);
  }
}
createSquares();

if (squares) {
  squares.addEventListener('mouseover', _ => {
    squares.style.backgroundColor = blackColor;
  });
}


text:
Q: Why is $\mathbb{Q}(\zeta_7)$ not a radical extension? My script states that there are $2$ non-trivial subfields of $\mathbb{Q}(\zeta_7)$, where $\zeta_7$ is a $7$-th primitive root of unity. These subfields are $\mathbb{Q}(\zeta_7 +\overline \zeta_7)$ and $\mathbb{Q}(\sqrt{-7})$.
Definition of radical extension I am using:
An extension $L/K$ is a radical extension, if $\exists\gamma_1,...,\gamma_r\in L, n_1,...,n_r\in\mathbb{N}$, such that
$L=K(\gamma_1,...,\gamma_r)$ and $\gamma_i^{n_i}\in K(\gamma_1,...,\gamma_{i-1})\ \forall i$
Ok, so using the definition on $\mathbb{Q}(\zeta_7)$ I obviously have the first condition satisfied and the second with $\zeta_7^7=1\in\mathbb{Q}$.
I am not sure what I don't understand at this point. Also I am unsure of why the subfields are even mentioned. In my script the lattice of the subfields is drawn at it says (translated from german): "Not a radical extension because $\zeta_7$ is only present at the the top of the lattice". I have no idea what this means.


text:
Q: Continue is not inside a loop I was writing a method for TCPServer. I've written a code as below:
    // thread run
protected void threadRun(){
    // continue running. don't stop
    while(true){
        try{
            try{
            }
            catch(Exception e1){
                try{
                } catch(Exception e2){}
                finally{
                    // skip
                    continue;
                }
            }
        }
        catch(Exception e3){
        }
    }
}

Content is not important. There were codes to accept client etc, but I have removed them to make sure about that it is not about details. Anyway, when I try to compile this code, compiler says for that continue line:
Error: continue is not inside a loop
By thinking that maybe I know it wrong, I've written the complete same code in Java as seen below:
class test{
public static void main(String[] args){
    while(true){
        try{
            try{
            }
            catch(Exception e1){
                try{
                } catch(Exception e2){}
                finally{
                    continue;
                }
            }

        }
        catch(Exception e3){
        }
    }
}
}

As I expected, java compiler doesn't give any error message and compiles successfully. What exactly can the problem be?

A: Apparently, continue (and break) can't break out of a finally block. Compiling this:
void run() {
loop:
    while (true) {
        try {}
        catch (Exception e) {}
        finally {
            continue loop;
        }
    }
}

will give you this (omitting the label gives the same error you got):
Error: cannot continue out of finally block

I haven't yet found a justification or explanation of this restriction (edit: see ratchet freak's comment below). However, I can't imagine it's a super-common use case. You probably want to look at other options.


text:
Q: when adding a  tag to div element, margin becomes 1/2 of parent div I'm trying to align a row of - icon |text| - icon |text| - icon |text|
It seems okay when just having the div's next to eachother and they seem to align proper as well. But when I add a  tag between the child div, it behaves really weird and set's its margin to 1/2 of the parent div.
This is what my HTML looks like:

hafjadljla;j kfaj lfjadklj;af kl;aj a

And this is whay the CSS looks like:
#subber {
height: 10%;
width: 100%;
}

.subber-element{
height: 100%;
display: inline-block;
border: 1px black solid;
width: 30%;
}

.subber-element p{
font-family: vegur regular;
color: grey;
display: inline;
margin: 0;
padding: 0;
}

.subber-element-icon{
height: 100%;
width: 10%;
border: 1px black solid;
display: inline-block;
}

Hopefully one of you guys can help out!

A: I'll post the solution also here with DEMO
HTML

PROVA PROVA PROVA CON DEL TESTO

PROVA PROVA PROVA CON DEL TESTO TESTO TESTO

PROVA PROVA PROVA CON DEL TESTO TESTO TESTO

CSS
.icon{
height:50px;
width:50px;
border:1px solid black;
float:left;
}
.text{
border:1px solid black;
float:left;
height:50px;
max-width:300px;
color:red;
}
.text p{
height:50px;
padding:0px;
}

#subber{
float:left;
width:400px;
height:50px;
}


text:
Q: ¿Por qué el resultado esperado no es exacto en el entrenamiento de una red neuronal? Estoy empezando a estudiar e investigar un poco por mi cuenta sobre inteligencia artificial, así que para practicar me encontré con esta librería de javascript para trabajar con redes neuronales, según leo en su documentación, si entreno una red, ella va a poder decidir por si misma un resultado entre ciertas opciones dadas, mi pregunta es la siguiente, si le enseño a la red que la entrada es un arreglo de cuatro unos ([1,1,1,1]) y que la salida esperada es un uno [1]

¿por qué nunca me da un resultado exacto cómo lo tendría que ser: ( [ 1 ] )?

Entiendo también que esto depende del número y la cantidad de entrenamientos que se le den a la red, pero ya probé con el máximo de iteraciones posibles según las opciones del objeto:
net.train(data, {
    errorThresh: 0.005,  // error threshold to reach
    iterations: 20000,   // maximum training iterations
    log: true,           // console.log() progress periodically
    logPeriod: 10,       // number of iterations between logging
    learningRate: 0.3    // learning rate
})

var log = console.log.bind(console)
var net = new brain.NeuralNetwork();

var data = [{
  input: [1, 1, 1, 1],
  output: [1]
}]

net.train(data, {
  errorThresh: 0.005, // error threshold to reach
  iterations: 5, // maximum training iterations
  log: true, // console.log() progress periodically
  logPeriod: 10, // number of iterations between logging
  learningRate: 0.3 // learning rate
})

var output = net.run([1, 1, 1, 1]); // casi siempre es mayor a [0.9...]

log(output);
<script src="https://cdn.rawgit.com/harthur/brain/gh-pages/brain-0.6.3.min.js"></script>

A:
Versión resumida
No existe un método general para saber de antemano si una red neuronal puede representar la distribución de entradas y salidas correctamente. Debido a esto el algoritmo de aprendizaje solo intenta minimizar el error de salida hasta que se pueda considerar suficientemente pequeño.
¿Cómo funciona la red neuronal y algoritmo de aprendizaje? -> Ver Explicación paso a paso
¿Porqué es posible que red neuronal no pueda representar la distribución de entradas y salidas correctamente? -> Ver explicación geométrica.

Explicación paso a paso
Esta red neuronal esta funcionando de la siguiente forma:

*

*Empieza con una red neuronal. Por defecto esta red neuronal tendrá tres capas:
a. Una capa de entrada, cuyo tamaño es el de la primera entrada que pasas para entrenar. En tu caso será de cuatro neuronas.
b. Una capa oculta. Que será el valor mayor entre tres neuronas y la mitad de neuronas de la capa de entrada (Ver fuente). En tu caso la mitad de la capa de entrada serían dos neuronas, por ser menos de tres, la capa oculta será de tres neuronas. Nota: es posible especificar más de una capa oculta.
c. Una capa de salida, cuyo tamaño es el de la primera salida que pasas para entrenar.
Cada neurona estará conectada a cada neurona de la capa siguiente con pesos al azar. También hay valores de prejuicios (bias) que serán al azar.

*Luego se van a hacer ciclos de entrenamiento. En cada ciclo se le presenta a la red neuronal los valores de entrada. Los pasaos para calcular la salida son como sigue:
a. Guarda los valores de entrada en la capa de entrada:
    Entrada   Capa de
              Entrada
    +- -+
    | 1 |   ->  (I1)
    | 1 |   ->  (I2)
    | 1 |   ->  (I3)
    | 1 |   ->  (I4)
    +- -+

b. Calcula para la capa oculta el valor para cada neurona. Esto se hace iterando sobre la lista de neuronas de la capa anterior, y calcular la suma de multiplicar el valor de la neurona por el peso de la conexión (que como dije antes al principio es un valor al azar)※, sumar al resultado el valor de prejuicio, y aplicar la función de activación.
※: Lo cual es equivalente a un producto punto entre el vector de valores y el de pesos.
Paso a paso, para cada neurona:

*

*Calcula el producto los valores de la capa anterior y los pesos de conexión a la neurona actual:
Capa de   Pesos de   Producto
Entrada   Conexión

(I1)  --> (*p1) --> (I1*p1)
(I2)  --> (*p2) --> (I2*p2)
(I3)  --> (*p3) --> (I3*p3)
(I4)  --> (*p4) --> (i4*p4)

*Calcula la suma de esos productos:
Capa de   Pesos de   Producto              Total
Entrada   Conexión

(I1)  --> (*p1) --> (I1*p1) -> (I1*p1 + I2*p2 + I3*p3 + I4*p4)
(I2)  --> (*p2) --> (I2*p2) ->----------/       /       /
(I3)  --> (*p3) --> (I3*p3) ->-----------------/       /
(I4)  --> (*p4) --> (i4*p4) ->------------------------/

Nota: Recuerda que esto se hace para cada neurona de la capa.

*Suma el prejuicio (bias):
Capa de   Pesos de   Producto            Total + prejuicio
Entrada   Conexión

(I1)  -> (*p1) --> (I1*p1) -> (I1*p1 + I2*p2 + I3*p3 + I4*p4 + bias)
(I2)  -> (*p2) --> (I2*p2) ->----------/       /       /
(I3)  -> (*p3) --> (I3*p3) ->-----------------/       /
(I4)  -> (*p4) --> (i4*p4) ->------------------------/

*Aplica la función de activación:
Capa de   Pesos de   Producto            Valor de la neurona
Entrada   Conexión

(I1)  -> (*p1) -> (I1*p1) -> f(I1*p1 + I2*p2 + I3*p3 + I4*p4 + bias)
(I2)  -> (*p2) -> (I2*p2) ->-----------/       /      /
(I3)  -> (*p3) -> (I3*p3) ->------------------/      /
(I4)  -> (*p4) -> (I4*p4) ->------------------------/

Esto te da el valor de la neurona. Este valor es el que será utilizado como entrada para la capa siguiente.
Para esta librería la función de activación es:
f(x) = 1/(1 + e^-x)

(Ver Fuente).
Esta es una gráfica de la función:

Como se puede observar, la función cruza la vertical en 0.5. Además podemos determinar que el limite de la función cuando la entrada tiende a infinito es 1, y cuando tiende a infinito negativo el limite es 0. Estas características hacen de esta una buena función de activación.
c. Repetir el paso anterior para cada capa oculta, y para la capa de salida.
d. Ahora empezamos el proceso de Propagación hacia atrás. El objetivo es utilizar el error de la salida para ajustar los pesos (que antes teníamos al azar) para minimizar el error.
Tomar los valores de la capa de salida y compararlos con la salida esperada. Se calcula la diferencia (error) y el valor de la regla delta para cada neurona. La regla delta es delta = error * output * (1 - output) (Ver Fuente).
e. Para cada neurona de la capa oculta tomamos los valores delta de la capa siguiente, los multiplicamos por el peso de la conexión, y los sumamos para obtener el error de la neurona:
             Error de la              Producto   Pesos de   Delta de la
             neurona                             Conexión  capa siguiente

    (d1*p1 + d2*p2 + d3*p3 + d4*p4) <- (d1*p1) <--- (*p1) <----- (d1)
       \       \        \-----------<- (d2*p2) <--- (*p2) <----- (d2)
        \       \-------------------<- (d3*p3) <--- (*p3) <----- (d3)
         \--------------------------<- (d4*p4) <--- (*p4) <----- (d4)

Debido a que utilizamos los pesos, tendremos un valor de error mayor para neuronas que tuvieron una mayor influencia en el resultado.
f. Calcular el delta de la neurona en función del error:
             Delta de               Producto   Pesos de   Delta de la
             la neurona                        Conexión  capa siguiente

    g(d1*p1 + d2*p2 + d3*p3 + d4*p4) <- (d1*p1) <--- (*p1) <---- (d1)
       \       \        \------------<- (d2*p2) <--- (*p2) <---- (d2)
        \       \--------------------<- (d3*p3) <--- (*p3) <---- (d3)
         \---------------------------<- (d4*p4) <--- (*p4) <---- (d4)

g. Calcular el de cambio para neurona a partir del delta (Ver Fuente). Y modificar el peso de la neurona por este valor.
De nuevo, debido a que utilizamos los pesos, estaremos modificando en mayor medida las neuronas que tuvieron mayor influencia en el resultado.
h. Repetir para cada cada capa oculta hasta llegar a la capa de entrada.
El resultado es que tras el cambio la red neuronal devolverá un valor que se acerca más al valor esperado. Que tanto más se aproxima depende de los parámetros learningRate y momentum. Sin embargo nunca llegan a devolver el valor esperado, solo se aproximan.
Hay que tener en cuenta que el número de ciclos que se realizan está limitado por iterations. Además el proceso de aprendizaje se detiene cuando error sea menor que errorThresh, lo que significa que el proceso comúnmente se detendrá antes que el error sea 0.
De hecho, la red neuronal no puede capturar todas las posibles distribuciones de entrada... esto es más fácil de entender con una explicación geométrica.

Explicación geométrica
Como hemos dicho antes, cuando calculamos la suma de los productos de los pesos y los valores de una capa, estamos haciendo un producto punto.
Esto hace que calcular el resultado de una capa tenga un equivalente geométrico. Este equivalente es un Hiperplano en N dimensiones, donde N = numero de entradas, que divide el espacio en dos. Todos los valores en un lado resultan en activación de las neuronas y los que están en el otro no.
Nota: en realidad es un gradiente de activación debido a que usamos una función de activación continua y no discreta. Pero hablar de hiperplanos ya es complicarlo bastante... así que voy a tratar la versión simple primero, y luego vuelvo a este punto.
Para entender el concepto mejor diremos que N = 2. Así que consideramos una red neuronal donde hay dos neuronas de entrada solamente. Si hacemos una gráfica donde el valor de una neurona es la horizontal y la de la otra es la vertical, podemos representar cada posible combinación de valores de entrada como un punto.
Por ejemplo, el valor de entrada (5, 2):
  I2

  |
  |
2-|    x
  |
  +----------- I1
       |
       5

Nota: aprovecho para recordarte que los valores no tienen que ser positivos.
Ahora podemos entender los valores de entrada como vectores. Y hacer producto punto con ellos tiene un sentido geométrico.
Ahora, recuerdas la función de activación? La función de activación tiende a 1 en los positivos y a 0 en los negativos. Cuando el producto punto es 0, cuando es positivo y cuando es negativo?
Bueno, veamos cuando el producto punto es positivo o negativo.
Sabemos que el producto punto cumple la siguiente equivalencia:
 X·Y=|X||Y|*cos(theta)

Así que será 0 en dos casos:

*

*El caso trivial cuando uno o ambos vectores tienen magnitud `0.

*Cuando el angulo entre los vectores es tal que cos(theta) = 0. Esto ocurre cuando los vectores son perpendiculares.

Además será positivo cuando el angulo entre los vectores tienda a 0 (ambos vectores van más o menos en la misma dirección) y negativo en caso contrario (ambos vectores van más o menos en dirección contraria).
Esto se puede observar en la gráfica de la función cos que es positiva entorno a 0, desde -PI/2 hasta PI/2.
Esto significa que dado un vector w. Todos los vectores que van en dirección similar darán un resultado positivo. Y todos los que van en dirección opuesta darán un resultado negativo. Existirá una linea que pasa por el origen donde el resultado es 0:

Todos los vectores de entrada en el área positiva son los dan un resultado positivo al calcular el producto punto con el vector w. De forma similar, todos los que están en el área negativa resultan en un valor negativo.
Si además agregamos el valor bias, podemos correr esa linea:

Todos los vectores de entrada en el área positiva son los dan un resultado positivo al calcular la suma de bias y el producto punto con el vector w. De forma similar, todos los que están en el área negativa resultan en un valor negativo.
De esta forma, un escalar (bias) y un vector (w) pueden dividir el espacio en dos. Esta es una definición valida para una linea en 2D, un plano en 3D, y un hyperplano en ND, donde hiperplano es una figura de N-1 dimensiones que divide el espacio en dos (y tiene curvatura 0, aunque eso no nos interesa para entender redes neuronales).
Teniendo en cuenta que la función de activación no es discreta, sino continua, el resultado de la función de activación sería algo así:

El color representa el valor de la función de activación. Con los tonos rojos siendo valores que tienden a 1, los tonos azules valores que tienden a -1. La franja blanca en el medio son los valores que se aproximan a 0.
Esto corresponde al resultado de una sola neurona, con los pesos de conexión representados por el vector w. El resultado de hacer esta operación con todas las neuronas será la entrada para la capa siguiente de la red neuronal.
Ahora que entendemos las neuronas como divisiones del espacio, es posible imaginar como para cada neurona de salida existe una región (definida por la combinación de divisiones dadas por las capas anteriores) en la cual los valores de entrada dan una salida positiva.

Recuerda que al trabajar en 2D es equivalente a trabajar con solo dos neuronas. Al tener más neuronas de entrada realizar gráficos para demostración es más complicado, si es que es posible, pero los principios geométricos son los mismos.
Así que puedes imaginar que tres neuronas corresponden a un espacio 3D, y que cada neurona de la siguiente capa divide ese espacio 3D en dos utilizando un plano inclinado. Luego para la capa de salida existirá una región del espacio 3D definida por estos planos para la cual la salida es positiva. Lo equivalente aplica para 4D, 5D, etc.

El proceso de aprendizaje corresponde a buscar y ajustar las regiones en proporción a su influencia en el resultado. Sin embargo, que tan compleja puede ser esta estructura depende del tamaño de la red neuronal.
Por ejemplo, una red con dos neuronas de entrada, y una sola neurona en la capa siguiente solo distinguirá dos grupos de entradas. Si los valores de entrada están distribuidos de forma tal que no se pueden separar con una recta, entonces esa sola neurona no es suficiente. Será necesario agregar tantas neuronas como lineas se necesiten para separar los grupos de valores.

Te recomiendo que pruebes Sharky Neural Network que permite entrenar redes neuronales con dos neuronas de entrada, mostrando las regiones del plano que corresponden a cada valor de salida durante el proceso de aprendizaje.
Ejemplo de red neuronal que no puede separar los datos debido a que no tiene suficientes neuronas:

Nota: en la imagen puedes ver que hay dos neuronas de salida. Las regiones amarilla y azul corresponden a las regiones de activación positiva para la primera y segunda neurona de salida respectivamente. La imagen solo muestra el color de la que de un mayor resultado.
Te recomiendo este vídeo de demostración de Sharky Neural Network:

Two Spirals Problem - classification with Sharky Neural Network (SNN) (Ver Vídeo)

Debido a esto, no hay garantía que sea posible llegar a un estado tal en que la red neuronal dada pueda responder correctamente a la entrada (Es posible que los datos de entrada sean muy complejos para el tamaño de la red neuronal. No hay una forma simple de saber de antemano). Por esta razón, el algoritmo de aprendizaje no pretende llegar a un resultado exacto, sino minimizar el error, y se detiene cuando el error sea suficientemente pequeño (menor que errorThresh) o se hayan hecho demasiados ciclos sin lograr eso (más que iterations) y así evitar que algoritmo se quede en un bucle infinito.


text:
Q: Different links to ultimately the same page on Magento I'm wondering if some of you could help me out a bit here as I'm a bit consfused.
the way it's setup is that you can get to the same page via 3 or 4 different routes as below:
https://tesorotiles.co.uk/type/wall-tiles/rho
https://tesorotiles.co.uk/by-area/bathroom-tiles/rho
and there another 2-3 pages which lead to the RHO range
These 3 are the exact same page and we've done it this way to make sure there is no break in the breadcrumb. Is this ok SEO wise or anyone have any recommendation.
Thanks in advance

A: Afaik it is ok, as long as you activate the "canonical url" for products. Then every search engine knows, that this is only a representation of the "offical" url which is the product url without any category

A: I'm not an SEO expert but as I understand it you should not include category paths in URL's.  If you do then as far as Google is concerned you have duplicate content which you can be penalised for.  If you are concerned about the breadcrumbs then you don't need to be, they will still reflect the category path you took to reach that product page.


text:
Q: mobx `makeAutoObservable` and inheritence I have a base class B which is a mobx store and a derived class A which is not a mobx store.
As an example, it looks something like
class B {
  name = ""
  get firstName () {
    return this.name.split(" ")[0]
  }
  constructor() {
    makeAutoObservable(this)
  }
}

class A extends B {
  // some other fields and methods
  constructor() {
    super(this)
  }
}

When I run the code new A() I get this error:
Error: [MobX] 'makeAutoObservable' can only be used for classes that don't have a superclass

This is because mobx correctly complains that it cannot automatically enumerate fields/methods of A in an object which is in a derived class B which doesn't have them as own properties, but they are up the prototypes chain instead.
But still, because I know that I want mobx to automatically go through class A's property (i.e. only one step up the prototype chain), I think that there should be a way for me to tell mobx that.
Is there a way?

A: See this post:
Is it possible to create inheritance between two mobx stores?
You have to do makeObservable and it should be in the later store.


text:
Q: Table having column with multiple rows having comma separated values, want to insert each value in column of other table enter code hereI need a query to insert. Maybe:
insert tblTestTable (TestData)
select value from STRING_SPLIT((select MyData from tblMyTable), ',')

refer attachmentRefer image

A: Something like this:
CREATE TABLE TableA
(ColumnToSplit VARCHAR(500))
GO
INSERT INTO TableA
SELECT 'A,B,C'
UNION ALL
SELECT 'A,F,G'
UNION ALL
SELECT 'D,E,H'
GO
SELECT value
FROM TableA
 CROSS APPLY STRING_SPLIT(ColumnToSplit, ',')
GO


text:
Q: Data augmentation for Deep learning I am working on grass weed detection using CNN. I have 2 classes at the moment and for each class, I have 18 images. Can I apply data augmentation method to increase the dataset to use CNN? and how much data would be sufficient?
Also, which methods I can compare with the CNN to show the better performance of CNN than other methods?

A: Normally you plan to have 5.000 images by class (http://www.deeplearningbook.org/), if you want to use straight up deep learning. You can decrease this number by using fine tuning (medium number of samples ~1000) or transfer learning (low number samples ~100). Those are numbers before using augmentation.
Sure you can use augmentations to increase the effective size of your dataset, but that is not the same as having at least 100 images. Deep Learning is very data intensive and therefore is not a good fit to 18 images.
Other methods are mostly handcrafted. You can do something like a hog features and use any kind of other ML technique as classification like SVM/Boosting/Bagging/etc.

A: *

*With just 18 images CNN will work good but won't achieve outstanding results

*With 18 images there are chances of CNN to overfit the training data so which CNN model you would use might be tricky

*I would suggest to use HOG+SVM for this problem and they will perform very well

*But If you do use Data Augmentation then yes your CNN will perform outstanding results

*you can use keras.preprocessing.image.ImageDataGenerator that will generate data for you. You have to just specify how many images do you want to generate

*You can also flip the 18 images and rotate the images and translating the images to augment data by yourself

*For more sophisticated Image Augmentation you can refer this link


text:
Q: publish_actions vs publish_stream issue while submitting open graph I have my application up which asked for the following permissions:
email,user_birthday,status_update,publish_stream,offline_access

I've implemented open graph now and tested it. It works perfectly, but after submission I have the following message from facebook

Your code is currently configured to publish a stream story. You must
  change your code so that when the test user triggers the action it
  produces an open graph story. Please make the appropriate changes and
  resubmit.

From this blog post on facebook dev blog from april, it seems that 'publish_actions' is a subset of 'publish_stream' based on that I have some questions.

*

*If that is true why do I need the publish_actions permission?

*Do I need to take publish_stream out and put in publish_actions? But my game uses publish_stream to publish images from the game to albums. Which it will still be doing. What do I do about that?

*How do I ask users for publish_actions at run time for these permissions if required and authenticate them without a reauthentication or reload. Any resources on that?

And for clarity here is my open graph publishing code
FB.api(
        '/me/'+fAction,
        'post',
        sObject,
    function(response)
    {
           if (!response || response.error)
           {
              for (var prop in response)
              {
                console.log(response[prop]);
                callbackToFlash(0);
              }
           } else
           {
              console.log('success'+object);
              callbackToFlash(1);
           }
        }
    );


text:
Q: Best practices to use logging or print on Python I see some posts claims to use logging function instead to show debugging message. I know logging provides various message levels like info, debug..., etc. info level should be used when messages is important for user to trace process on runtime. Just like info level in logging, print uses in the same case. When to use logging or print for best practice? Thanks!
logging.basicConfig(level = logging.INFO)
logger = logging.getLogger(__name__)
def process():
    #### "Create a connection" is a critical message for user to know what operation is processing now
    logger.info("Create a connection with ...")
    # or
    print("Create a connection with ...")

A: If you are working on your own little projects, you can go with print but in a bigger project environment you really don't want to use print statements as it can quickly become confusing. Especially if you don't know where messages are printed out to your stdout. The logging module gives you a lot of advantage as:
1) There are Streamformatters that allow you to standartize output messages (with timestamps for example and username)
2) Multiple Streamhandlers. Most of the time, when something goes wrong, you don't only want to print something to the user through the stdout but want to keep that data to see later what went wrong.


text:
Q: Load/Stress Test Java application All,
We have a Java application built on HTTP Servlets , EJB and POJO's. Clients access the application using HTTPServlet and the application consumes webservices.
I need to stress test this application to test the load, thread safety and response times
The webservice is consumed using HTTPURLConnection API and JAXB api.
As JAXB marshalling/unmarshalling has thread safety issues need to load test and thread safety
I have seen applications load testing by specifying the number of transactions and no of threads . I want to do the same to my application as well
Any piece of advice is truly appreciated

A: Use Apache JMeter:

The Apache JMeter™ desktop application is open source software, a 100% pure Java application designed to load test functional behavior and measure performance. It was originally designed for testing Web Applications but has since expanded to other test functions.

A: After comparing Apache JMeter™ against Grinder I have choosen JMeter because of GUI for creating test plans.   Learning curve is flat- it is easy to create simple scenarios.
If you are ok with wrinting test plans in jython, those tools seems to be pretty close. Both

*

*have GUI for running and coordinating distributed testing (must have for stress test)

*can create text/xml reports for further analisys

*have build-in reporting plugins

Follow links how-to-get-my-website-load-test-with-jmeter for links about stress tests in jMeter and better plugins to visualise results.
I had performance problems with default graph plugins for large datasets (>100.000 entries). Follow Suggestions and Recipes for Log Analysis for ideas how to make graphs for such data volumes

A: Yes, you can use JMeter to test response times although I doubt you will find all the concurrency problems by using JMeter. JMeter can be great in load testing an application but remember to:
1 Ensure your tests are replicating your actual use-cases.

*

*You aren't running the application and JMeter on the same box.

*You are using realistic new and existing data.
Writing tests for concurrency can be very tricky. A better method can be to check the code which uses known unsafe classes very carefully. For example, a work around for JAXB can be to create a new Unmarashaller on every request handler using a local variable.
For example
 public void handler(HttpServletRequest req) {
    Unmarshaller u = context.createUnmarshaller();
    u.unmarshal(...);
}

Obviously this has performance issues so it might be better to use an different library if possible. You are much more likely to encounter very difficult to reproduce bugs if you deploy code that isn't thread-safe.
If you do wish to write concurrent integration tests then have a read of Chapter 12 Testing Concurrent Programs in Java Concurrency in Practice beforehand because its much harder to write good tests than you probably think.


text:
Q: a column in a dataframe having list of dictionary i want to convert that into seperate column
data = [{'category': 'A', 'maxvalue': '6', 'minvalue': '0'}, {'category': 'B', 'maxvalue': '11', 'minvalue': '6'}, {'category': 'C', 'maxvalue': '21', 'minvalue': '11'}, {'category': 'D', 'maxvalue': '31', 'minvalue': '21'}, {'category': 'E', 'maxvalue': '41', 'minvalue': '31'}, {'category': 'F', 'maxvalue': '9999999999', 'minvalue': '41'}]

this data is inside a data frame and now that dataframe, the format i want is like below along with other columns inside dataframe
A     B     C      D      E      F
0-6   6-11  11-21  21-31  31-41  41-51

A: One solution could be as follows:
import pandas as pd
import numpy as np

# data set without duplicates in "category"
lst = [[{'category': 'A', 'maxvalue': '4', 'minvalue': '0'},
        {'category': 'B', 'maxvalue': '51', 'minvalue': '41'}],
       np.nan,
       [{'category': 'A', 'maxvalue': '6', 'minvalue': '0'},
        {'category': 'B', 'maxvalue': '21', 'minvalue': '11'}]
       ]

df = pd.DataFrame(columns=['bucket'])
df['bucket'] = lst

# code
from itertools import chain

# select notna rows
out = df[df['bucket'].notna()]

# get dict keys in separate cols with their associated vals as the vals
# repeat index from df according to len of each list
out = pd.DataFrame(list(chain.from_iterable(out['bucket'])),
                   index=pd.Index.repeat(out.index, out['bucket'].str.len()))

out['result'] = (out.minvalue.astype(str)+'-'+out.maxvalue.astype(str))

# =============================================================================
# solution 1: no duplicate categories per row
# =============================================================================

out1 = out.copy()
out1 = out1.pivot(index=None, columns='category', values='result').fillna('')

print(out1)

category    A      B
0         0-4  41-51
2         0-6  11-21

# =============================================================================
# solution 2: duplicate categories per row, e.g. 2x "A" in row 0
# =============================================================================

lst = [[{'category': 'A', 'maxvalue': '4', 'minvalue': '0'},
        {'category': 'A', 'maxvalue': '51', 'minvalue': '41'}],
       np.nan,
       [{'category': 'A', 'maxvalue': '6', 'minvalue': '0'},
        {'category': 'B', 'maxvalue': '21', 'minvalue': '11'}]
       ]

# continue after `out['result'] = (out.minvalue...)`
out2 = out.copy()

out2['result'] = out2.groupby([out2.index,'category'])['result']\
    .transform(lambda x: ','.join(x))

out2.set_index('category', append=True, inplace=True)
out2 = out2[~out2.index.duplicated(keep='first')]['result']

out2 = out2.reset_index().set_index('level_0').rename_axis(None, axis=0)
out2 = out2.pivot(index=None, columns='category', values='result').fillna('')

print(out2)

category          A      B
0         0-4,41-51
2               0-6  11-21

# =============================================================================
# solution 3: same data as 2, but only keeping first of duplicates
# =============================================================================

# continue after `out['result'] = (out.minvalue...)`
out3 = out.copy()

out3 = out3.reset_index(drop=False)\
    .drop_duplicates(['index','category'])\
        .set_index('index', drop=True).rename_axis(None, axis=0)

out3 = out3.pivot(index=None, columns='category', values='result').fillna('')

print(out3) # only printing 0-4, not 41-51 for "A" in row 0

category    A      B
0         0-4
2         0-6  11-21

A: For an example of data as following :
import pandas as pd
import numpy as np
data=[[{'category': 'A', 'maxvalue': '6', 'minvalue': '0'},
       {'category': 'B', 'maxvalue': '11', 'minvalue': '6'},
       {'category': 'C', 'maxvalue': '21', 'minvalue': '11'},
       {'category': 'D', 'maxvalue': '31', 'minvalue': '21'},
       {'category': 'E', 'maxvalue': '41', 'minvalue': '31'},
       {'category': 'F', 'maxvalue': '9999999999', 'minvalue': '41'}],
      [{'category': 'A', 'maxvalue': '5', 'minvalue': '0'},
       {'category': 'B', 'maxvalue': '10', 'minvalue': '5'},
       {'category': 'C', 'maxvalue': '20', 'minvalue': '10'},
       {'category': 'D', 'maxvalue': '30', 'minvalue': '20'},
       {'category': 'E', 'maxvalue': '40', 'minvalue': '30'},
       {'category': 'F', 'maxvalue': '9999999999', 'minvalue': '41'}],[]]

df=pd.DataFrame(columns=['bucket'])
df['bucket']=data
df

df2=df.bucket.apply(lambda x:pd.DataFrame.from_dict(x))
df2
data=[]
for i in range(len(df2)):
  if not(df2.iloc[i].empty):
    df2.iloc[i]['value']=df2.iloc[i]['minvalue']+'-'+(df2.iloc[i]['maxvalue'])
    data.append(df2.iloc[i].T.loc['value'].to_list())
  else:
      data.append(np.zeros(len(df2.iloc[0].T.loc['category'].to_list())))

dfinal=pd.DataFrame(data,columns=df2.iloc[0].T.loc['category'].to_list())
final

Else if you want it to reconfigure in the same dataframe :
df[dfinal.columns]=data
df


text:
Q: Field initialization when invoking a method overridden in a derived class from the constructor So I was messing with classes today when I found this weird bug/feature.
First example

class a { constructor () { this.load() } load () {} }
class b extends a { loaded = false; load () { this.loaded = true } }
const bInstance = new b()
console.log(bInstance.loaded);

I expected the result to be true but the actual result was false.
Second example

class a { a = true; constructor () { this.load() } load () {} }
class b extends a { b = true; load () { console.log(this.a, this.b) } }
const bInstance = new b()

Once again, I expected the console.log to log true true but it was true undefined.
The weirdest part is that bInstance.a is true and bInstance.b is true

A: Class fields will run only after a super call finishes. In your subclass, the loaded = false runs after the super calls this.load(), which results in this.loaded = true running. See below, logging will make things clearer:

class a {
  constructor() {
    this.load()
  }
  load() {}
}
class b extends a {
  loaded = console.log('class field assigning to instance');
  load() {
    console.log('load() called');
    this.loaded = true
  }
}
const bInstance = new b()

In general:
class X {
  /* class fields here */
  constructor() {
    super();

is equivalent to
class X {
  constructor() {
    super();
    /* class fields assign to instance at this point */

It's not a bug, nor exactly a "feature", it's just how the language was designed.

class a {
  a = true;
  constructor() {
    this.load()
  }
  load() {}
}
class b extends a {
  b = true;
  load() {
    console.log(this.a, this.b)
  }
}
const bInstance = new b()

For your second example - load is called by the super constructor, and, as mentioned previously, super() will run before class fields run - so your
class b extends a {
  b = true;
  load() {
    console.log(this.a, this.b)
  }
}

is equivalent to
class b extends a {
  constructor() {
    super();
    this.b = true;
  }
  load() {
    console.log(this.a, this.b)
  }
}

Which makes it quite clear why this.b isn't assigned at the point that load is called inside the super constructor.


text:
Q: How to find the visible pushViewController from the navigation controller? My app layout consists of a tabbar, from each tab there is a navbar to which is attaches a UITableViewController.
When I didSelect a row, I push a view controller with becomes nicely embedded in the navigation bar.
I would like to find this latter view controller programmatically.
Here is how I push my visible view controller (streamlined version):
    @objc
    func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {

        let vc = WebPageViewController()

        navigationController?.pushViewController(vc, animated: true)

    }

I did not managed to find a way. I am using this extension:
public extension UIWindow {
    public var visibleViewController: UIViewController? {
        return UIWindow.getVisibleViewControllerFrom(rootViewController)
    }

    public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(pvc)
            }
            else if let pushed = vc?.childViewControllers.last {
                return pushed
            }
            else {
                return vc
            }
        }
    }
}


text:
Q: values.get is not a function in redux form validate function im facing a very weird issue for the first time. I'm have a container through which i connect a component to redux form. My code is here:
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form/immutable';
import PayrollSearch from './payrollSearch';
import { requestPayrollInfo } from '../../actions/payrollActions';
import { PAYROLL_SEARCH } from '../../common/constants';

export const validate = (values) => {
  const errors = {};
  const onlyNumbers = /^([0-9])+$/g;
  if (!values.get('processId')) {
    if (onlyNumbers.test(values.get('processId'))) {
      errors.processId =
        'Ο μοναδικός αριθμός αρχείου πρέπει να περιέχει μόνο αριθμούς';
    }
  }
  return errors;
};

export const mapDispatchToProps = dispatch => (
  {
    onSubmit: formData =>
      dispatch(requestPayrollInfo(formData))
  }
);

const PayrollSearchForm = reduxForm({
  form: PAYROLL_SEARCH,  // a unique identifier for this form
  validate
  initialValues: {
    from: new Date(),
    to: new Date()
  }
})(PayrollSearch);

const PayrollSearchContainer = connect(
  null,
  mapDispatchToProps
)(PayrollSearchForm);

export default PayrollSearchContainer;

PayrollSearch code is here:
import React, { PropTypes } from 'react';
import { Field } from 'redux-form/immutable';
import moment from 'moment';
import MenuItem from 'material-ui/MenuItem';
import {
  SelectField,
  DatePicker
} from 'redux-form-material-ui';
import RaisedButton from 'material-ui/RaisedButton';
import inputTextField from '../../../widgets/inputTextField/index';

const PayrollSearch = props => (
  <form onSubmit={props.handleSubmit}>

      <Field
        name={DATE_FROM_FIELD}
        component={DatePicker}
        floatingLabelText={PAYROLL_DATE_FROM}
        autoOk
        formatDate={date => moment(date).format('DD-MM-YYYY')}
      />
      <Field
        name={DATE_TO_FIELD}
        component={DatePicker}
        floatingLabelText={PAYROLL_DATE_TO}
        autoOk
        formatDate={date => moment(date).format('DD-MM-YYYY')}
      />

      <Field
        name={PROCESSID_FIELD}
        component={inputTextField}
        floatingLabelText={PAYROLL_PROCESS_ID}
        style={styles.f1}
      />
      <Field
        name={FILENAME_FIELD}
        component={inputTextField}
        floatingLabelText={PAYROLL_FILENAME}
        style={styles.f1}
      />

      <Field
        name={STATUS_FIELD}
        component={SelectField}
        hintText={PAYROLL_STATUS}
      >
        <MenuItem value="all" primaryText="'Ολα" />
        <MenuItem value={3} primaryText="Εκκρεμεί επιβεβαίωση" />
        <MenuItem value={954} primaryText="Μη εκτελέσιμο" />
        <MenuItem value={998} primaryText="Μερικώς εκτελεσμένο" />
      </Field>
      <Field
        name={KEYWORD_FIELD}
        component={inputTextField}
        floatingLabelText={PAYROLL_KEYWORD}
        style={styles.f1}
      />

      <RaisedButton
        onClick={() => props.reset()}
        label="Clear search"
        style={styles.f2}
      />
      <RaisedButton
        type="submit"
        primary
        label={PAYROLL_SEARCH_BUTTON}
      />

  </form>
);

PayrollSearch.propTypes = {
  handleSubmit: PropTypes.func,
  reset: PropTypes.func
};

export default PayrollSearch;

When the PayrollSearcComponent is rendered an error appeared that values.get is not a function. Why in hell is this happening? It is an issue that i havent seen before


text:
Q: CSS - first-child selector not working I am using bulma as css framework, and have a section on my page where I am looping over items, and creating multiline columns.

{{ key }}

                            {{employee.title}}

                               {{getExtras(employee, 'position')}}

I would like to remove left padding for each first child column, I have tried with setting even to both classes padding left 0 as important but nothing worked:
.employees {

     .column:first-child, employee:first-child {
          padding-left: 0!important;
     }
}

What am I doing wrong?

A: A .column will never be a first-child, because there is always a div.title-with-line before it.
From MDN:

The :first-child CSS pseudo-class represents the first element among a group of sibling elements.

You would need the :nth-child or :nth-of-type selector.

A: .column is not the first child as you have a div with class title-with-line proceeding it. What you're looking for is:
.employees {
   .column:nth-child(2), .employee:nth-child(2) {
      padding-left: 0!important;
   }
}