text:
Q: TK/TCL, trouble understanding this tic tac toe code snippet Can anyone help explain to me what the snippet below does. This code snippet is taken from http://wiki.tcl.tk/12374. It is meant to create a tic tac toe game. There are not many resources out there for understanding Tk/Tcl so this is giving me significant difficulty.
proc DrawBoard {{redraw 0}} {
    global S B GAME C

    if {$redraw} {                              ;# Must redraw everything
        .c delete all
        set w2 [expr {$B(w2) - 15}]             ;# Make a little margins
        set h2 [expr {$B(h2) - 15}]
        set hbar [expr {$h2 / 3.0}]
        set vbar [expr {$w2 / 3.0}]

        set B(0) [list -$w2   -$h2   -$vbar -$hbar] ;# All 9 cells
        set B(1) [list -$vbar -$h2    $vbar -$hbar]
        set B(2) [list  $vbar -$h2    $w2   -$hbar]
        set B(3) [list -$w2   -$hbar -$vbar  $hbar]
        set B(4) [list -$vbar -$hbar  $vbar  $hbar]
        set B(5) [list  $vbar -$hbar  $w2    $hbar]
        set B(6) [list -$w2    $hbar -$vbar  $h2]
        set B(7) [list -$vbar  $hbar  $vbar  $h2]
        set B(8) [list  $vbar  $hbar  $w2    $h2]

        for {set i 0} {$i < 9} {incr i} {       ;# Rectangle for each cell
            .c create rect $B($i) -tag b$i -fill {} -outline {}
            .c bind b$i <Button-1> [list DoClick $i]
            set B($i) [ShrinkBox $B($i) 25]
        }
        .c create line -$w2 $hbar $w2 $hbar -tag bar ;# Draw the cross bars
        .c create line -$w2 -$hbar $w2 -$hbar -tag bar
        .c create line $vbar -$h2 $vbar $h2 -tag bar
        .c create line -$vbar -$h2 -$vbar $h2 -tag bar
        .c itemconfig bar -width 20 -fill $::C(bars) -capstyle round
    }
    .new config -state [expr {$GAME(tcnt) == 0 ? "disabled" : "normal"}]

    for {set i 0} {$i < 9} {incr i} {
        .c itemconfig b$i -fill {}              ;# Erase any win lines
        DrawXO $GAME(board,$i) $i
    }
    foreach i $GAME(win) {                      ;# Do we have a winner???
        .c itemconfig b$i -fill $C(win)
    }
}

Ok, the most significant question I have regards w2, h2, hbar, vbar variables. Particularly with how they are declared. For instance, set w2 [expr {$B(w2) - 15}]. How can w2 be defined referring to itself??? The author uses these variables to draw the tic tac toe lines, but I don't even know how what these variables mean. Does these variables specify some dimension of the canvas so that the author can use it to bind particular regions to click activities?
If I understand these four variables, everything else will make sense!
Here is the image of what the board looks like:

A: Variables in Tcl (Tk is just a window drawing toolkit that lives on top of Tcl) are defined when they are written to; there's usually no explicit declaration. The only exception to this is with variables directly in a namespace, where it is best practice to use the variable command to declare them before first use, like this:
namespace eval exampleNamespace {
    variable xmpl1 "abc def"

    # Or equivalently...

    variable xmpl2
    set xmpl2 "abc def"

    # You have to use the second style with arrays...

    variable arrayXmpl
    set arrayXmpl(1) "pqr stu"
    set arrayXmpl(2) "qwerty uiop"
}

Local variables in procedures don't need declaring, though if you want to access a variable that isn't local you have to use a command (often global or upvar) to bring it into scope.
proc variableExample {formalArgument1 formalArgument2} {
    set localVar1 "abc"
    set localVar2 "def"
    global thisOtherVar
    append thisOtherVar "ghi" $formalArgument1
    puts "Currently, got $localVar1 $localVar2 and '$thisOtherVar'"
}

It's pretty conventional to put the global at the top of the procedure, but it's totally not necessary. It's effect persists from where you do it until the end of the procedure call. Tcl's semantics are strictly operational with extremely tightly defined evaluation order (it's left-to-right, always).
Now, arrays are aggregate variables. Each element of an array is a variable itself. They're distinct from normal simple variables, though the name of the overall array is in the same naming scheme as the simple variables. You can't have a simple foo and a foo(bar) in the same scope (without unsetting one first, which removes the variable). The keys into the elements are strings — the implementation behind the scenes is a high-performance hash table — that are entirely not variables and this means that the B(w2) and w2 variables are entirely distinct; they're not the same thing at all. However, we can use variables (and other Tcl substitutions) in computing the string to use as a key, so we can do this:
set name "w2"
set B($name) "example of "
append B(w2) "array key handling"
puts "this is an $B($name)"

Let's look at the example that you were puzzling over:
set w2 [expr {$B(w2) - 15}]

Breaking it into pieces:
set w2 […]

It's going to write to the variable w2. That's what the set command does with two arguments. The thing that is going to be written in is the result of evaluating another command. We need to look deeper.
expr {$B(w2) - 15}

Breaking it into pieces:
expr {…}

That yields the result of evaluating the expression in the braces. It's strongly recommended that you put braces around all your expressions; it's safer and much faster. What's the expression? (Note that expressions use a different syntax to the rest of Tcl.)
$B(w2) - 15

OK, that's subtracting 15 (the number) from the value read (because of the $) from the w2 element of the array B. The w2 here is just a string. That there's a variable elsewhere with the same name is coincidence.
And that's it. Reassembling the pieces, we see that:
set w2 [expr {$B(w2) - 15}]

Assigns the result of subtracting 15 from the contents of B(w2) to the variable w2. That's all it does. (The array B is a global array; see the global at the top of the procedure.)

The lines:
    set w2 [expr {$B(w2) - 15}]             ;# Make a little margins
    set h2 [expr {$B(h2) - 15}]
    set hbar [expr {$h2 / 3.0}]
    set vbar [expr {$w2 / 3.0}]

These get the half height and width of the canvas from the global array B, remove 15 pixels for a margin, and then set hbar/vbar to a third of that value so that the coordinates for drawing are easier. It helps once you realize that the canvas has had its drawing origin moved (similar to in scrolling) to the center of its window. And be aware that doing -$hbar is actually being a bit naughty, though cute; it's using string concatenation to negate a value, which is OK when the value is positive and doesn't have an explicit sign, but would be fragile if that ever changed. And it's slow by comparison with doing [expr {-$hbar}], though that's longer; the cost of computation isn't exactly matched with the length of the command.


text:
Q: "sqlplus as sysdba" startup error My setup:

*

*Oracle 11g

*32G RAM

*8 CUP threads

Three oracle instances have been running. But running this:
sqlplus "/as sysdba"

gives me a prompt:

Connected to an idle instance.

When I issue the startup  command, I get this error:

ORA-04031 unable to allocate 2048 bytes shared memory  ("shared pool","unknow object","sga heap(1,0)","procs:ksunfy");

But three Oracle instances are working now.
Maybe I changed some config incorrectly. What can I do to fix this?

A: Launch this command on OS prompt and will obtain:
[oracle@datab ~]$ oerr ORA 04031
04031, 00000, "unable to allocate %s bytes of shared memory (\"%s\",\"%s\",\"%s\",\"%s\")"
// *Cause:  More shared memory is needed than was allocated in the shared
//          pool.
// *Action: If the shared pool is out of memory, either use the
//          DBMS_SHARED_POOL package to pin large packages,
//          reduce your use of shared memory, or increase the amount of
//          available shared memory by increasing the value of the
//          initialization parameters SHARED_POOL_RESERVED_SIZE and
//          SHARED_POOL_SIZE.
//          If the large pool is out of memory, increase the initialization
//          parameter LARGE_POOL_SIZE.

You can try to increase values as help says, or go and take a look here, for example.

A: This message means ORACLE is requesting Shared memory from the operating system, but is receiving less than expected or none at all.
Are you sure no other (non-ORACLE) applications on the operating system are using shared memory?
As a last resort, rebooting the server will clear the shared memory allocated.  If the error happens after rebooting the server, there is either not enough shared memory or a problem with the way ORACLE was installed. Make sure the all the kernel parameters were set based on the ORACLE installation document to the recommended values, including shmmax, shmmni, ETC.

A: There may have been enough memory to start the 3 instances at the time but now that you are trying to connect to one of the instances, the OS is trying to allocate some memory to your session process and cannot get as much as it is asking for.
Check the sum total of the maximum memory currently configured for your 3 instances and look at what else is running on the server and may be consuming memory. This may be lots of local database sessions as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When breaking on an exception, is there a local name for the exception object? When breaking on exception, in the local scope I see "<exception>" which is not a valid name. Is there some way to access the exception object in console?

A: Right-click on the value after <exception>, and choose "Store as Global Variable". Then you can play with the exception if you wish.


text:
Q: Same Facebook comments plugin for different URLs Lets assume you have 2 website versions that share single database: a mobile version and a desktop version of your main website. Their URLs differ significantly.
Is it possible to implement the same Facebook plugin (using one the same Facebook app) on each of them? What I need to achieve is to show same comments below same articles no matter that their URLs differ.
Sample URLs for one article:
1) On the desktop version: https://www.somesite.com/somepath/article1
2) On the mobile version: https://m.somesite.com/differentpath/article1
They show the same content but totally differ as URL. So they should include the same comments. Is that doable with a single Facebook app?

A: Yes, that is possible.
All you have to do is set the og:url meta tag for both "versions" of an article (desktop and mobile) to the same URL – so decide on one as the "main" URL, and use that.
(And make sure that the FB scraper does not automatically redirected to the other one, if you have any such thing in place.)


text:
Q: IDE для ActionScript 3 под Linux/Mac ? IDE для ActionScript 3 под Linux/Mac ?
A: World famouse intellij idea, жаль что только платная версия. Работает еще и на винде. Есть на 30 дней тирал.
Из свободного есть as3ide - надстройка над eclipse. Но последняя версия вышла в прошлом году, до сих пор пре альфа версия. Крайне не стабильна.
A: Пробовали Realaxy ActionScript Editor?


text:
Q: Deleting a redundant parameter results in a segmentation fault, seemingly for no reason The following program finds and deletes words that begin and end with the same character. It works just fine, except I decided to take the code for printing result text in from deleteWords() and put it inside of main(). Therefore, the *fpOut parameter in became redundant in deleteWords(). Deleting the parameter results in
/bin/sh: line 1:  1371 Segmentation fault: 11  ./main duom.txt rez.txt make: *** [main] Error 139
However if I compile it and run it any third parameter (e.g. int useless argument instead of FILE *fpOut), it works without errors.
Has anybody have a clue what could be causing this problem?
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    int checker (char zodis[]) {
        size_t last = strlen(zodis);
        if (zodis[0] == zodis[last-1])
            return 0;
        return 1;
    }

    void memAlloc (char **text, char **buffer, FILE **fp, char *fileName) {
        int fileLength;
        *fp = fopen(fileName, "r");
        fseek(*fp, 0L, SEEK_END);
        fileLength = fseek(*fp, 0L, SEEK_SET);
        *text = malloc(fileLength * sizeof(char));
        *buffer = malloc(fileLength * sizeof(char));
    }

    void deleteWords (FILE *fp, int anyUselessParameter, char *buffer) {
        char *text;
        while (fscanf(fp, "%s", text) == 1) {
            if (checker(text)) {
                printf("%s ", text);
                sprintf(buffer + strlen(buffer), "%s ", text);
            }
        }

        printf("\n");
    }

    int main(int argc, char *argv[]) {
        FILE *fp, *fpOut;
        int anyUselessParameter;
        char *text, *buffer, *inputFileName = argv[1], *outputFileName = argv[2];

        if (argc < 2)
            return 0;

        fpOut = fopen(outputFileName, "w");

        memAlloc(&text, &buffer, &fp, inputFileName);
        deleteWords(fp, anyUselessParameter, buffer);
        fputs(buffer, fpOut);

        fclose(fp);
        fclose(fpOut);
        free(text);
        return 0;
    }

A: char *text;
while (fscanf(fp, "%s", text) == 1) {

scanf needs the buffer to be allocated. Here it dereferences an uninitialized pointer text and writes to it. scanf tries to write to text[0], text[1].. and so on, so accesses text out of bounds and undefined behavior happen.
*buffer = malloc(fileLength * sizeof(char));
...
sprintf(buffer + strlen(buffer), "%s ", text);

buffer is uninitialized, so strlen(buffer) will result in some undefined value. Explicitly initialize buffer[0] = '\0' if you wish to use strlen later. Also you don't include memory for terminating '\0' character inside your buffer.
As you are trying to read the file into a buffer, that is allocated using the file size
if (fread(buffer, fileLenght, 1, fp) != fileLength) { /* handle error */ }

If you have to, use snprintf instead of sprintf just to be safe. snprinttf(buffer+strlen(buffer), fileLength - strlen(buffer), ...);
Also, try to never use scanf without specifing field length inside %s modifier. You can try:
char text[256]; // or other maximum word length
while (fscanf(fp, "%255s", text) == 1) {

As you already have allocated memory for the file, you can use it as a parameter to scanf, if you have to. One would need to prepare the format string for scanf as argument - it is a bit hard. See below:
 for (;;) {
      // prepare scanf %s format modifier to use with printf to write to buffer end
      char fmt[20];
      size_t buffer_size = fileLenght;
      size_t free_in_buffer = buffer_size - strlen(buffer);
      snprintf(fmt, 20, "%%%ds", free_in_buffer);
      // we will write here: up to free_in_buffer
      char *in = buffer + strlen(buffer);
      if (fscanf(fp, fmt, in) != 1) break;
      // we now check the last readed word form the file
      if (!checker(in)) {
         // if the last readed word is bad, we can revert it
         in[0] = '\0'
      }
  }

A: This is wrong:
fileLength = fseek(*fp, 0L, SEEK_SET);

Per POSIX:

RETURN VALUE
The fseek() and fseeko() functions shall return 0 if they
  succeed.
Otherwise, they shall return -1 and set errno to indicate the error.


text:
Q: jquery .live('click',function(event) work only once when page loads I am using jquery dialog in which i put 2 textbox and 1 button. Which works fine, everything renders. On button in dialog I am appling validation on my textbox if its empty. So the validation work fine for the first time when page renders but  not working after that on another dialog.
Have a look at my both function.
The first one is for dialog ,second is for updating  the textbox in dialog
$('.update_service_name').live('click',function(event){
    var $tr = $(this).closest('tr');
    var old_value        = $tr.children('td:eq(1)').text(),
        phone_service_id = $tr.children('td:eq(2)').text();
    var old_value_textbox = "
Current Service Name
<input class='large' type='text' value='"+old_value+"' disabled='disabled'/>

" ;
    var new_value_textbox ="
New Service Name
<input class='large' type='text' value='' id='new_service_name' />

";
    var update_button ="Update " ;

    var $dialog = $('
',{title:'Update Service Name'}).dialog({
            autoOpen: false,
            width: 250
    });

    $('
').html(old_value_textbox).appendTo($dialog);
    $('
').html(new_value_textbox).appendTo($dialog);
    $('
').html(update_button).appendTo($dialog);

    $dialog.dialog('open');
    return false;
});

Validating the textbox in dialog
$('.update_service_name_btn').live('click',function(event){
    var pass = true;
    var new_service_name = $("#new_service_name").val();
    $("#error_message_div_new_value").html(' ');

    if(!new_service_name){
        $("#error_message_div_new_value").html('New Serrvice Name Please!');
        pass = false;
        return false;
    }
});

Updated
$('.update_service_name').live('click',function(event){
 var $tr = $(this).closest('tr');
 var old_value        = $tr.children('td:eq(1)').text(),
phone_service_id = $tr.children('td:eq(2)').text();
  var old_value_textbox = "
Current Service Name
<input class='large' type='text' value='"+old_value+"' disabled='disabled'/>

" ;
 var new_value_textbox ="
New Service Name
<input class='large' type='text' value='' id='new_service_name' />

";
 var $update_button = $("Update ");

 $update_button.find('.update_service_name_btn').live('click',function(event){
   var pass = true;
  var new_service_name = $("#new_service_name").val();
  $("#error_message_div_new_value").html(' ');
  if(!new_service_name){
    $("#error_message_div_new_value").html('New Serrvice Name Please!');
    pass = false;
    return false;
  }
 });

 var $dialog = $('
',{title:'Update Service Name'}).dialog({
      autoOpen: false,
    width: 250
 });

 $('
').html(old_value_textbox).appendTo($dialog);
 $('
').html(new_value_textbox).appendTo($dialog);
 $('
').append($update_button).appendTo($dialog);

 $dialog.dialog('open');
 return false;
});

Validating the textbox in dialog(remain same as old)
 $('.update_service_name_btn').live('click',function(event){
var pass = true;
var new_service_name = $("#new_service_name").val();
$("#error_message_div_new_value").html(' ');

if(!new_service_name){
    $("#error_message_div_new_value").html('New Serrvice Name Please!');
    pass = false;
    return false;
}
});

plz Notice
i just figured out that the whole problem is in my dynamically creating text box.i alerted the value of text box and at the first click it alert the correct value and after that with each alert i mean with new dialog i am getting the old text box value that is the first one i entered.can any please help me how to get solve this issue ???

A: You have to  run your validation code for each time you recreate your dialog. Now the event is getting registered only once, then for the next time you open the dialog, a new update_service_name_btn is created but you do not register the event again!
For example:
...
var $update_button = $("Update ");
$update_button.find('.update_service_name_btn').live('click',function(event){
  var pass = true;
  var new_service_name = $("#new_service_name").val();
  $("#error_message_div_new_value").html(' ');
  if(!new_service_name){
    $("#error_message_div_new_value").html('New Serrvice Name Please!');
    pass = false;
    return false;
  }
});

var $dialog = ...
...
$('
').append($update_button).appendTo($dialog);
...

Full code:
$('.update_service_name').live('click',function(event){
  var $tr = $(this).closest('tr');
  var old_value        = $tr.children('td:eq(1)').text(),
    phone_service_id = $tr.children('td:eq(2)').text();
  var old_value_textbox = "
Current Service Name
<input class='large' type='text' value='"+old_value+"' disabled='disabled'/>

" ;
  var new_value_textbox ="
New Service Name
<input class='large' type='text' value='' id='new_service_name' />

";
  var $update_button = $("Update ");

  $update_button.find('.update_service_name_btn').live('click',function(event){
    var pass = true;
    var new_service_name = $("#new_service_name").val();
    $("#error_message_div_new_value").html(' ');
    if(!new_service_name){
      $("#error_message_div_new_value").html('New Serrvice Name Please!');
      pass = false;
      return false;
    }
  });

  var $dialog = $('
',{title:'Update Service Name'}).dialog({
        autoOpen: false,
        width: 250
  });

  $('
').html(old_value_textbox).appendTo($dialog);
  $('
').html(new_value_textbox).appendTo($dialog);
  $('
').append($update_button).appendTo($dialog);

  $dialog.dialog('open');
  return false;
});

A: just do so & i am sure you problem will be solved
var $dialog=null;
$('.update_service_name').live('click',function(event){
if($dialog!=null){
$dialog.remove();
}
var $tr = $(this).closest('tr');
var old_value        = $tr.children('td:eq(1)').text(),
phone_service_id = $tr.children('td:eq(2)').text();
var old_value_textbox = "
Current Service Name
<input class='large' type='text' value='"+old_value+"' disabled='disabled'/>

" ;
var new_value_textbox ="
New Service Name
<input class='large' type='text' value='' id='new_service_name' />

";
var $update_button = $("Update ");
$dialog = $('
',{title:'Update Service Name'}).dialog({
    autoOpen: false,
    width: 250
 });

$('
').html(old_value_textbox).appendTo($dialog);
$('
').html(new_value_textbox).appendTo($dialog);
$('
').append($update_button).appendTo($dialog);

  $dialog.dialog('open');
return false;
 });


text:
Q: PS error when enforcing Smartcard attribute I am receiving error message when running the following script, any idea why?
PS C:\Users\npevltdisdddtda_1> $userList = Import-Csv C:\temp\Text.csv
foreach ($user in $userList) {

       # Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" | {Set-ADUser -SmartCardLogonRequired:$true}
        Get-ADUser -filter "SamAccountName -eq '$($user.SamAccountName)'" | {Set-ADUser -SmartcardLogonRequired:$true}
}

At line:5 char:77
+ ... ($user.SamAccountName)'" | {Set-ADUser -SmartcardLogonRequired:$true}
+                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline


text:
Q: When you have a control condition, does it has to exactly the same way as the experimental condition? So I am carrying out a research project for which I have multiple DV and covariates; A lengthy battery of questionnaires will measure these.
I am wondering if, in the control conditions, I also need to give participants the battery of questionnaires or if there is a way around this to spare the participants from extra fatigue.


text:
Q: Make this automatic Is there a way to make this carrousel slide through slides by itself?
var main = function() {

    $('.arrow-next').click(function() {
        var currentSlide = $('.active-slide');
        var nextSlide = currentSlide.next();

        var currentDot = $('.active-dot');
        var nextDot = currentDot.next();

        if(nextSlide.length === 0) {
            nextSlide = $('.slide').first();
            nextDot = $('.dot').first();
        }

        currentSlide.fadeOut(600).removeClass('active-slide');
        nextSlide.fadeIn(600).addClass('active-slide');

        currentDot.removeClass('active-dot');
        nextDot.addClass('active-dot');
    });

    $('.arrow-prev').click(function() {
        var currentSlide = $('.active-slide');
        var prevSlide = currentSlide.prev();

        var currentDot = $('.active-dot');
        var prevDot = currentDot.prev();

        if(prevSlide.length === 0) {
            prevSlide = $('.slide').last();
            prevDot = $('.dot').last();
        }

        currentSlide.fadeOut(600).removeClass('active-slide');
        prevSlide.fadeIn(600).addClass('active-slide');

        currentDot.removeClass('active-dot');
        prevDot.addClass('active-dot');
    });

}

$(document).ready(main);

Hope you can help,
Thanks in advance.

A: Use setInterval and trigger("click") and the carousel will be "clicked" every seconds.
setInterval(function() {
  $(".arrow-next").trigger("click");
}, 3000);

A: You can use setInverval function.
The setInterval take a function (the one that will trigger next slides in your case) and a time in milliseconds, this is a the delay between every call to the function.
stInterval return a value that you must stored in memory and pass to clearInterval when your object is destroyed
Documentation : http://www.w3schools.com/jsref/met_win_setinterval.asp


text:
Q: How can i move these vertices in world space instead of moving in local space? I'm using a "Dymanic Batch Renderer System", and i have an "Object.cpp" that has a function, and when it's call it returns the data it needs for the Batch to render a "Quad" on screen (also i'm gonna mention that this is on a 3D space so the Z movement, Z scaling and the XY rotation exist).
And for the math calculations i'm using the GLM library.
The rendering works fine and the batch too, the problem is the movement. The rotation actually works the way i want it to work, but the movement is what i'm not satisfied because it moves in the "Local Space" of the object. Meaning that, for example, if i rotate an object inside a batch 90° on the Y Axis, the X movement becomes Z movement, and Z movement becomes X movement.
I've been trying to look for an answer and i couldn't find anything. I think the problem probably is from the "rotationMatrix" that allows the object to rotate correctly, but i don't know if there's an extra "function" i have to add to move the object in the "World Space" instead of the "Local Space", and if there is, i don't know what "function" can be.
Now i'm gonna put here the entire code of "Object.cpp" so you guys can see how it works.
Object::Object(glm::vec3 pos, glm::vec3 rot, glm::vec3 sca, int ObjId)
            : translationMatrix(glm::mat4(0)), rotationMatrix(glm::mat4(0))
        {
            id = ObjId;
            position = pos;
            lastPosition = pos + glm::vec3(1.0f);
            scale = sca;
            rotation = rot;
            lastRotation = rot + glm::vec3(1.0f);
        }

        glm::mat4 One(1.0f);
        Vertex* Object::UpdateObject(Vertex* target)
        {
            if (lastPosition != position)
            {
                translationMatrix = glm::translate(glm::identity<glm::mat4>(), -position);
                lastPosition = position;
            }

            if (lastRotation != rotation)
            {
                glm::mat4 rotMatrixTemp(1.0f);
                rotMatrixTemp = glm::rotate(rotMatrixTemp, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
                rotMatrixTemp = glm::rotate(rotMatrixTemp, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
                rotMatrixTemp = glm::rotate(rotMatrixTemp, glm::radians(rotation.z + 180.0f), glm::vec3(0.0f, 0.0f, 1.0f));

                rotationMatrix = -translationMatrix * rotMatrixTemp * translationMatrix;
                lastRotation = rotation;
            }

            float x = 1.0f, y = 1.0f;
            if (flipX)
                x *= -1;
            if (flipY)
                y *= -1;

            target->position = rotationMatrix * glm::vec4(position.x - 0.5f * scale.x, position.y + 0.5f * scale.y, position.z, 1.0f);
            target->color = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
            target->texcoord = glm::vec2(0.0f, y);
            target++;

            target->position = rotationMatrix * glm::vec4(position.x - 0.5f * scale.x, position.y - 0.5f * scale.y, position.z, 1.0f);
            target->color = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
            target->texcoord = glm::vec2(0.0f, 0.0f);
            target++;

            target->position = rotationMatrix * glm::vec4(position.x + 0.5f * scale.x, position.y - 0.5f * scale.y, position.z, 1.0f);
            target->color = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
            target->texcoord = glm::vec2(x, 0.0f);
            target++;

            target->position = rotationMatrix * glm::vec4(position.x + 0.5f * scale.x, position.y + 0.5f * scale.y, position.z, 1.0f);
            target->color = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f);
            target->texcoord = glm::vec2(x, y);
            target++;

            return target;
        }

So, to recap, what i'm trying to accomplish is moving these objects in the "World Space" instead of the "Local Space" (while also, keeping the rotation system in the "Local Space", if possible. Because otherwise the object's center is always gonna be (0, 0, 0) instead of being its own position).

A: To position an object in the world with a given orientation, you usually apply the rotation first then the translation, unless you are indeed trying to rotate the objects about the origin after translating it out. So either check that, or make sure you have a good reason to do have the translationMatrix in
rotationMatrix = -translationMatrix * rotMatrixTemp * translationMatrix

Because it seems like you have translation logic both in and out of the if blocks


text:
Q: Ubuntu 16.04 running excruciatingly slow when external HDDs are connected I have been though quite a few threads here (and other forums) but have been unable to find an answer to this.
I have recently setup Ubuntu 16.06 on a Asus VivoMini U45 miniPC (Celeron N3060). Installation went fine and the OS is stable and performing quite fast as expected. This machine is to be used as a Samba fileserver (tried NFS but could not get it to work but that's another story) and a Plex server.
When I connect my two external HDDs the system slows down to halt. Simply starting terminal takes about 45 seconds and gfx rendering is frame-lagging. If the drives are removed and the pc restarted it is responding as it should. fstab shown below:
Notes: The /export/users mount is probably leftover from the attempted NFS setup, so it has been commented out.
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/mapper/ubuntu--vg-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/sda1 during installation
UUID=8f11ce71-6e25-4ec0-824b-84387fc2af41 /boot           ext2    defaults        0       2
/dev/mapper/ubuntu--vg-swap_1 none            swap    sw              0       0
#/home/users    /export/users   none    bind  0  0
UUID=DC666A53666A2F08   /mnt/2Tb ntfs-3g rw,nosuid,nodev,allow_other,default_permissions,uid=1000,gid=1000,umask=002,x-gvfs-show 0 0
UUID=5694066194064449 /mnt/1Tb ntfs-3g rw,nosuid,nodev,allow_other,default_permissions,uid=1000,gid=1000,umask=002,x-gvfs-show 0 0

I have checked for CPU throttling (s-tui and i7z) and it does not seem to be the issue both under normal operation monitoring and under stress.
Internet / LAN speeds and USB transfer rates appear to be fine (have not measured either but i have not noticed any considerable delays).
TL;DR: Ubuntu 16.04 is running very slow when USB HDDs are connected but fine when they are unplugged.
Any help on this will be appreciated.

A: This has now been resolved, on second examination, there was another variable.
When I was plugging in the HDDS I was also unplugging the monitor which was causing the apparent frame lag and slow response from Ubuntu.
This has been resolved by installing a "dummy" monitor using xserver tools as per post TeamViewer slow on Ubuntu without monitor 16.04


text:
Q: Trying to perform two different functionality on button click which is in jQuery dialog box I am doing project in MVC 4. And I'm using  dialog boxes to perform operations. I am using Views and partial views for accomplishing my task.

What I meant by trying to perform two operation is I want to call a
  action method which will save existing data in database and also close
  the dialog box properly and same for the add functionality i.e. add
  new row in database and close the dialog box properly.

Right now what happening is

*

*I can successfully edit record and save it in database.
But once I click on Create New link it
displays records which were entered in edit pop up.

*If I click on create new link for the first time I get the pop up for save and once I click on save button it dooes not get save in database.

In short

I am not able to call close method of dialog and action method in my
  controller both at the same time

I will post code for everything that I have done till now.
CurrentLocation View
@model PITCRoster.RosterManagementEntities

@{
    ViewBag.Title = "CurrentLocation";
}

CurrentLocation

@*<input type="button" value="List All Current Locations" onclick="Display('DisplayCurrentLocation')" />*@
@{
    Html.RenderPartial("_DisplayCurrentLocation", Model.tblCurrentLocations);
}

@using (Html.BeginForm("AddLocation", "Lookups", FormMethod.Post))
{
    Html.RenderPartial("_AddLocation", new PITCRoster.tblCurrentLocation());
}

This view when rendered shows list of all the location that are in database including links to create new location , edit and delete location.
Depending on that I render partial views for them.
_AddLocation partial view is rendered and in jQuery(which I will post next)
I have set autoOpen of dialog to false.
Follwing is code for partial views.
_DisplayCurrentLocation Partial View
   @model IEnumerable<PITCRoster.tblCurrentLocation>

    Create New

            @Html.DisplayNameFor(model => model.LocationId)

            @Html.DisplayNameFor(model => model.Location)

            @Html.DisplayNameFor(model => model.Description)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.LocationId)

                @Html.DisplayFor(modelItem => item.Location)

                @Html.DisplayFor(modelItem => item.Description)

                Edit

                @using (Html.BeginForm("DeleteLocation", "Lookups", new { id = @item.LocationId }, FormMethod.Post, new { @class="deleteForm"}))
                {
                    @Html.AntiForgeryToken();
                    <input type="submit" value="Delete" />
                }

    }

_AddLocation Partial View
@model PITCRoster.tblCurrentLocation

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>tblCurrentLocation</legend>

            @Html.LabelFor(model => model.Location)

            @Html.EditorFor(model => model.Location)
            @Html.ValidationMessageFor(model => model.Location)

            @Html.LabelFor(model => model.Description)

            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)

            <input type="submit" value="Create" />

    </fieldset>

_EditLocation Partial View
    @model PITCRoster.tblCurrentLocation

@using (Html.BeginForm("SaveLocation", "Lookups", null, FormMethod.Post, new { @class = "saveForm" }))
{

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>tblCurrentLocation</legend>

            @Html.LabelFor(model => model.LocationId)

            @Html.EditorFor(model => model.LocationId)
            @Html.ValidationMessageFor(model => model.LocationId)

            @Html.LabelFor(model => model.Location)

            @Html.EditorFor(model => model.Location)
            @Html.ValidationMessageFor(model => model.Location)

            @Html.LabelFor(model => model.Description)

            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)

            <input type="submit" value="Save"/>

    </fieldset>

Now I will post my Action Methods in controller
return CurrentLocation view
  public ActionResult CurrentLocation()
        {
            return View(rosterManagementEntities);
        }

Add Location
[HttpPost]
    public ActionResult AddLocation(tblCurrentLocation tblCurrentLocation)
    {
        unitOfWork.tblCurrentLocation.Insert(tblCurrentLocation);
        unitOfWork.Save();
        return View("CurrentLocation", rosterManagementEntities);
    }
Edit Location
public ActionResult EditLocation(string id)
        {
            int locationId = Convert.ToInt32(id);
            tblCurrentLocation tblCurrentLocation = unitOfWork.tblCurrentLocation.GetByID(locationId);
            return PartialView("_EditLocation", tblCurrentLocation);
        }

Save Location
[HttpPost]
    public ActionResult SaveLocation(tblCurrentLocation tblCurrentLocation)
    {
        Response.Cache.SetExpires(DateTime.Now);
        unitOfWork.tblCurrentLocation.Update(tblCurrentLocation);
        unitOfWork.Save();
        return View("CurrentLocation", rosterManagementEntities);
    }

Delete
[HttpPost]
    public ActionResult DeleteLocation(int id)
    {
        unitOfWork.tblCurrentLocation.Delete(id);
        unitOfWork.Save();
        return View("CurrentLocation", rosterManagementEntities);
    }

I will post my script for dialog
When a user clicks on edit link it it will send a url with unique ID and in jQuery $.get() will retrieve that data and display dialog as follows
 $('.edit').click(function () {
        $.get($(this).data('url'), function (data) {
            $('#dialog').dialog({
                autoOpen: true,
                modal: true,
                bgiframe: true,
                width: 800,
                height: 250,
                open: function () {

                    document.getElementById('dialog').innerHTML = data;
                },
                close: function () {
                    debugger;
                    document.getElementById('dialog').innerHTML = "";
                    document.getElementById('dialog').innerText = "";
                    $("#dialog").empty().dialog("destroy");

                }
            });
        });
    });

When form is loaded it will create one dialog and set it's autoOpen to false
and when user clicks on create new link it will just open that dialog
This is for Creating new location
   $(".create").click(function CreateNewUser() {
        debugger;
        try {

            $("#dialog").dialog('open');
        }
        catch (e) {
            alert(e.message);
        }
    });

$("#dialog").dialog({
        autoOpen: false,
        modal: true,
        bgiframe: true,
        width: 800,
        height: 600,

        close: function () {
            debugger;
            document.getElementById('dialog').innerHTML = "";
            document.getElementById('dialog').innerText = "";
            $("#dialog").empty().dialog("destroy");
            window.location.reload();
        }

    });

So I will state my problem again
My code either performs destroy the dialog operation or saves the data in the database; but not both.

I am not able to call close method of dialog and action method in my
  controller both at the same time

What code should I change to do both the tasks?
I have a hunch that Ajax should be used... But how?
Please help...
Sorry for the long post...
Thank you for being patience.. :)


text:
Q: Image format which is editable as plaintext I'm trying to find an image file format which features plaintext editable source code. So far in my searches i've found text-in-image scanning with output in plaintext, But that's not what i'm after.
My project is intended to create fractal images using seed integers derived from the binary content of an audio file. I have a solution for the first part. I seem to recall an image format which used tables of hexadecimal pairs to describe a 256 color palette in plaintext source.
A way to convert an image to a space delimited text file table of hex pairs and back again would probably get me past this wall.
Thanks in advance.

A: try SVG

https://picsvg.com/

example in HTML

<!-- `<use>` shape defined ON THIS PAGE somewhere else -->
<svg viewBox="0 0 100 100">
   <use xlink:href="#icon-1"></use>
</svg>

<!-- `<use>` shape defined in an EXTERNAL RESOURCE -->
<svg viewBox="0 0 100 100">
   <use xlink:href="defs.svg#icon-1"></use>
</svg>


text:
Q: Loop to remove only the ith character of the string I have a loop function called removeand wish to show every loop result of removing only the ith character of the string.
Let say I have a string "hello", and the expected output of the loop function is shown below:
remove("hello")
Remove the position 1: ello
Remove the position 2: hllo
Remove the position 3: helo
Remove the position 4: helo
Remove the position 5: hell

My codes for the function:
def remove(string):
    i=0
    for i in range(len(string)):
        removed=string.replace(string[i],"")
        print("Remove the position",i+1,":",removed)
        i=i+1
    return None

And the output of my code:
remove_one("hello")
Remove the position 1 : ello
Remove the position 2 : hllo
Remove the position 3 : heo
Remove the position 4 : heo
Remove the position 5 : hell

Seems that my codes not only remove the letter of the ith position, they also remove the letters when they are the same as the letter of the ith position.
How can I fix the codes that only remove the letter of the ith position?

A: Using replace removes all the occurrences of the letter. What you want is simply:
string = string[:i] + string[i+1:]

You can also use del:
del string[i]

With the first solution, your code becomes:
def remove(string):
    i = 0
    for i in range(len(string)):
        removed = string[:i] + string[i+1:]
        print("Remove the position", i+1, ":", removed)
        i = i + 1
    return None

A: A couple of points about the code...
range returns the values from 0 to the length of the string, so there is no need to set i equal to zero. In addition, the for loop cycles through the range values for you, so you don't need to set i (using i = i +1) at the bottom of the for loop.
def remove(string):
    for i in range(len(string)):

        # We can use string slicing to find the substring prior to the
        # character to be removed AND the subtring after the character to
        # be removed.

        # since we will be using the position indicator several times, we can
        # save that

        result = string[:i] + string[i+1:]

        print("Remove the position", i+1 ,":", removed)

remove("hello")

yields:
ello
hllo
helo
helo
hell

Other notes:
All Python functions return None if you don't provide an explicit return value, so we can remove that line.


text:
Q: Spring Boot MongoRepository Null Pointer Exception I'm a little new to spring and I've been running into a Null Pointer Exception.
I believe the @Autowired is not working on my MongoRepository.
For some reason when I tried some examples it was working. (The commented out code in the run function worked)
This is the error I get:

2016-05-20 02:31:20.877 ERROR 6272 --- [nio-8080-exec-2]
  o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for
  servlet [dispatcherServlet] in context with path [] threw exception
  [Request processing failed; nested exception is
  java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null  at
  com.applesauce.service.CustomerService.addCustomer(CustomerService.java:24)
  ~[classes/:na]

Can you guys take a look and direct me?
Also, please let me know if i'm doing something wrong for best practices.
If you need anymore information, please ask!
com.applesauce.controller
@RestController
@RequestMapping("/customer")
public class CustomerController {

private CustomerService customerService = new CustomerService();

@RequestMapping(value = "/addcustomer", method = RequestMethod.GET)
public Customer addCustomer(@RequestParam("firstName") String fName,
                         @RequestParam("lastName") String lName,
                         @RequestParam("email") String email,
                         @RequestParam("phoneNumber") String phoneNumber,
                         @RequestParam("source") String source){
    return customerService.addCustomer(new Customer(fName,lName,email,phoneNumber,source));
}
}

com.applesauce.repository
@Repository
public interface CustomerRepository extends MongoRepository<Customer, String> {

public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}

com.applesauce.service
@EnableMongoRepositories(basePackages = "com.applesauce.repository")
public class CustomerService {

@Autowired
private CustomerRepository repository;

public Customer addCustomer(Customer customer){

    repository.save(customer);

    return customer;
}
}

A: Xtreme Biker meant, that you should add @Service annotation for your CustomerService, like this:
@EnableMongoRepositories(basePackages = "com.applesauce.repository")
@Service
public class CustomerService {
...
}

Also, you never want to create service using new operator, if you expect Spring to take care about it. In your CustomerController, change initialization line:
private CustomerService customerService = new CustomerService();

to:
@Autowired
private CustomerService customerService;

It must solve NullPointerException.

A: Check you would have created an object of the class which has a @Service annotation (using new). This class should also be autowired instead, where you have autowired your repository bean.

A: I had the same issue and I solved this way (explanation is generic)
Repository.class
@Repository
public interface {...}

Service.class
public class {...}
@Autowired
private Repository repo;

Application.class
@Autowired Service service;
service.method() //does not throws NullPointerException


text:
Q: Long form in React Native with TextInput with absolute position I have a form in my React Native app that is a bit long. Plus I'm using react-native-autocomplete-input which requires absolute positioning on Android.
This makes things tricky. I'm constantly fighting to keep the keyboard not interfere with the form and keep form fields in correct order.
I started with KeyboardAvoidingView but when the user tries to go to the bottom of the form, things get all messed up because of absolute positioning required by the auto complete field.
I wanted to find out what suggestions those who've implemented long forms in React Native could offer.


text:
Q: Replace null values with the most recent value in a time series I have this series (notice the holes in the dates):

Date
Value

2019-12-31
100

2020-01-02
110

2020-01-05
120

2020-01-07
125

2020-01-08
130

And I need to get this one:

Date
Value

2019-12-31
100

2020-01-01
100

2020-01-02
110

2020-01-03
110

2020-01-04
110

2020-01-05
120

2020-01-06
120

2020-01-07
125

2020-01-08
130

Notice that the rows with bold font didn't exist in the first table and the values are forward filled from the most recent value available.
To get this done:

*

*I created a dummy calendar with the List.Dates() function.

*I merged this calendar with the first table obtaining this:

Date
Value

2019-12-31
100

2020-01-01
null

2020-01-02
110

2020-01-03
null

2020-01-04
null

2020-01-05
120

2020-01-06
null

2020-01-07
125

2020-01-08
130

*Then I created a function that took a date as a parameter which filtered the first table and with the function List.Last() took the last non-null value and placed it in the row of the third table instead of the null.

It works quite well, but I find it too slow. For each row the function must be called to scan the table for the most recent value available.
Is there a quicker way to perform this?


text:
Q: With Quartz.Net, how do i find out how many times a trigger has fired I'm using ADOJobStore with my scheduler and in the DB I can see columns that indicate how many times my trigger has fired.  Is there someway to retrieve that data programmatically?  I can't seem to find it as a property on the Trigger.
var triggers = _scheduler.GetTriggersOfJob(jobDetails.Key);

A: You can get this information if the trigger supports it. Following triggers have the TimesTriggered property:

*

*IDailyTimeIntervalTrigger

*ICalendarIntervalTrigger

*ISimpleTrigger

Which can also be inverted to: ICronTrigger does not support this so ITrigger interface does not have the information.
So you need to cast the trigger to some of the above types to get the information.


text:
Q: Criterion for projectively cofibrant diagrams? Let $\mathbf{D}$ be a small category, $\mathbf{Set}$ the category of sets and $\mathbf{sSet}$ the category of simplicial sets with its usual model structure. The category of functors $\mathbf{D}\to \mathbf{sSet}$ (diagrams of shape $\mathbf{D}$) has a model structure (called the projective model structure) in which the weak equivalences and fibrations are the object-wise such and the cofibrations are determined by the left lifting property with respect to the trivial fibrations. We call the the cofibrant objects in this model structure "projectively cofibrant diagrams/functors". This is used for example to calculate homotopy colimits.
My question is about a sufficient condition for a diagram to be projectively cofibrant. There are some results about it on nLab and also in Dugger's paper, specifically in the beginning of section 9, where he defines "free degeneracies". The formulation is a bit more involved than what I would expect so perhaps I am missing something. To be specific, I would like to know if the following is true:

A functor $X:\mathbf{D}\to \mathbf{sSet}$ is projectively cofibrant if for every $n\in\mathbb{N}$, the non-degenerate simplices form a subfunctor of $X_n:\mathbf{D}\to\mathbf{Set}$ and this subfunctor is a coproduct of representables.

Namely, the condition is that the maps in the diagram take non-degenerate simplices to non-degenerate simplices and at every level they form a disjoint union of "free orbits". This differs from Dugger's definition, since he seems to require the existence of subfunctors $N_n\subseteq X_n$ with some properties and he does not say that these are precisely the non-degenrate simplices (are they?). Anyways, any clarification of those matters would be appreciated.


text:
Q: Where to store .net user roles between page requests I've got a web site that implements its own Forms based login, and creates an authentication cookie like this:
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID, DateTime.UtcNow, expiration, isPersistent, userFunctions);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
    cookie.Expires = expiration;
    HttpContext.Current.Response.Cookies.Add(cookie);

The variable "userFunctions" contains a comma-separated list of roles that the user is a member of.
In my Global.asax file I'm retrieving those user functions in the following way:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.User != null)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            if (HttpContext.Current.User.Identity is FormsIdentity)
            {
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;

                string[] roles = id.Ticket.UserData.Split(',');
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
            }
        }
    }
}

All this is working great.  Or it was until I had to change it for a whole new bunch of users.  The problem with the new users is that the "userFunctions" variable can get really long, and is way too long to store in a cookie (that is limited in size to something like 4k).
I would change my code to store the "userFunctions" in session, but session is not available to Application_AuthenticateRequest.  I could possibly store the data in the application cache (maybe in a key/value pair) but I hesitate to do that as the application cache doesn't seem the 'right' place to put this data.
I probably will end up putting it in the application cache, but before I do I thought I'd ask and see if anybody has a better alternative?

A: Given that I cannot use Session to store user roles (as I cannot retrieve them before Authorization has taken place), and I didn't want the expense of making a trip to the database on every page request, I ended up storing the roles in the Application Cache:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.User != null)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            if (HttpContext.Current.User.Identity is FormsIdentity)
            {
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;

                string[] roles;
                string cachedRoles = (string)HttpContext.Current.Cache.Get("UserFunctions" + id.Name.ToLower());
                if (cachedRoles == null)
                {
                    // Reload UserFunctions and add back in to Cache.

                    cachedRoles = [...code to get UserFunctions from database...];

                    HttpContext.Current.Cache.Insert("UserFunctions" + id.Name.ToLower(), cachedRoles, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), System.Web.Caching.CacheItemPriority.NotRemovable, null);

                }

                roles = cachedRoles.Split(',');

                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
            }
        }
    }
}

It seems to work ok (though with limited testing so far).


text:
Q: Prepared statement needed if the user data format was changed? I use JCalendarChooser and user data was in d MMMM yyyy format. Example output is 4 November 2015. Before I SELECT from database I change it to yyyy-MM-dd format. This is my code before SELECT:
                String date1 = null;

                java.util.Date d1 = jDateChooser1.getDate();
                if (d1 == null) {
                    System.out.println("No date specified!");
                } else {
                    DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                    date1 = fmt.format(d1); //jdatechooser
                    // Then select from db
                }

The way I understand about user validation is you need to sanitize all input from user but what if the data format was changed? Do I need to use prepared statements in such case above?
Thanks in advance

A: If there is no other way for input to get from the user to the query except by passing through (and being validated by) the jDateChooser and SimpleDateFormat, then your input is adequately sanitized.
That said, there are other reasons to use a PreparedStatement over a dynamic SQL string. If you run the same query multiple times with different dates, then each dynamic SQL string thus produced will be regarded by the dbms as a new query to be compiled from scratch, while a PreparedStatement will produce a single fill-in-the-blanks execution plan which can be reused without recompilation. This can result in improved performance on an oft-repeated query, which is A Good Thing™.


text:
Q: Why does my
* nav bar with five 20%-width
*s start a new line in a 100% width parent div? New to coding as of a week or so ago, and cannot understand, despite a lot of tinkering, why it will not work. Code is really untidy but a work in progress.
Just as the title states, I would have hoped this would have evenly spaced the 5 li elements across the 100% parent.
NOTE: The 19% width for #other was the only way I had been able to properly align them. Sorry if it confuses you.

* {
    margin: 0px 0px;
    padding: 0px 0px;
    box-sizing: border-box;
}
.navBar li {
    list-style-type: none;
    display: inline-block;
    font-family: Helvetica;
    font-size: 1.7em;
    line-height: 2;
    font-family: 'Anton', sans-serif;
}
.navBar {
    background: #92aad1;
    position: fixed;
    width: 100%;
}
.navBar li {
    position: relative;
    width: 20%;
    text-align: center;
}
.navBar #Other {
    width: 19%;
}
.navBar li:hover {
    background: lightgrey;
}

Home

About

Links

Work

Other

A: You need to get rid of the "whitespace" between each. Basically:

Home

About

Links

Work

Other

or

Home

About

Links

Work

Other

A: I usually use this way to display an inline menu with a defined width.
ul li{
    display:block;
    width:20%;
    float:left;
}

Hope it helps.


text:
Q: PHP8.1-fpm: pdo-mysql installed but not appear on php -m i have install php8.1-fpm and setup it with apache2/FGPI. But after many operation, impossible to "enable pdo-mysql".
i have make this sudo apt-get install php8.1-pdo-mysql
with result
Note, selecting 'php8.1-mysql' instead of 'php8.1-pdo-mysql'
php8.1-mysql is already the newest version (8.1.5-1+b1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded

But, when i do php -m
mysql not appear.
[PHP Modules]
Core
curl
date
dom
filter
gd
gmp
hash
igbinary
imap
intl
json
libxml
mbstring
OAuth
openssl
pcntl
pcre
redis
Reflection
session
SimpleXML
sodium
SPL
standard
xdebug
xml
xmlreader
xmlwriter
xsl
yaml
zip
zlib

[Zend Modules]
Xdebug

When i try to know why, it seem because Pdo is include on php8.1-common, but ... not appear to.
An other action that i have doing is to remove php8.1-mysql and reinstall php8.11-pdo-mysql with sudo apt-get install php8.1-pdo-mysql, the result is
but, nothing on mods-available

EDIT 1
When i look with phpinfo() on a php file to use
php-fpm, i have this result
/etc/php/8.1/fpm/conf.d/15-xml.ini,
/etc/php/8.1/fpm/conf.d/20-curl.ini,
/etc/php/8.1/fpm/conf.d/20-dom.ini,
/etc/php/8.1/fpm/conf.d/20-gd.ini,
/etc/php/8.1/fpm/conf.d/20-gmp.ini,
/etc/php/8.1/fpm/conf.d/20-igbinary.ini,
/etc/php/8.1/fpm/conf.d/20-imap.ini,
/etc/php/8.1/fpm/conf.d/20-intl.ini,
/etc/php/8.1/fpm/conf.d/20-mbstring.ini,
/etc/php/8.1/fpm/conf.d/20-oauth.ini,
/etc/php/8.1/fpm/conf.d/20-redis.ini,
/etc/php/8.1/fpm/conf.d/20-simplexml.ini,
/etc/php/8.1/fpm/conf.d/20-xdebug.ini,
/etc/php/8.1/fpm/conf.d/20-xmlreader.ini,
/etc/php/8.1/fpm/conf.d/20-xmlwriter.ini,
/etc/php/8.1/fpm/conf.d/20-xsl.ini,
/etc/php/8.1/fpm/conf.d/20-yaml.ini,
/etc/php/8.1/fpm/conf.d/20-zip.ini

EDIT2
When i use php8.1-mysql instead of php8.1-pdo-mysql same result because apt automaticly switch on php8.1-mysql when you try to install pdo-mysql.
EDIT3
The command sudo phpenmod pdo_mysql take the result
WARNING: Module pdo_mysql ini file doesn't exist under /etc/php/8.1/mods-available
WARNING: Module pdo_mysql ini file doesn't exist under /etc/php/8.1/mods-available

This is the real problem, that the needed file never been created by sudo apt-get install php8.1-mysql

A: Thx for your comment. I have find the solution in an other post :
https://stackoverflow.com/a/64661113/19034672
I have doing the --purge of all php installed, and reinstall php-fpm, and all is done.


text:
Q: suddenly cannot mount nfs share from Windows 7   I recently reinstalled my file server (moved from fedora to Ubuntu server).
Now I cannot mount my nfs share from Windows 7, mounting from Mac OSX works fine.
In Windows I either keep getting "the semaphore timeout period has expired" or "an unexpected error has occured".
Does Ubuntu need some special magic to allow Windows 7 to mount an nfs share?
This is my exports file
/home/Bing/     192.168.1.*(rw,async,insecure,no_subtree_check)
/home/Bing/mnt/EXTRN2 192.168.1.*(rw,async,insecure,no_subtree_check)
/home/Bing/mnt/EXTRN3 192.168.1.*(rw,async,insecure,no_subtree_check)

A: Ubuntu might defaults to a newer NFS version than your old Fedora did. If Ubuntu already supports NFSv4 by default, then I don't know how Windows 7 handles that one. You might like to try to append nfsvers=3,mountvers=3 flags to your exports lines and see if that fixes your problem.

A: There are actually several programs that implement NFS.  Is your rpc.statd and lockd running when you type in ps aux?  If rpc.statd doesn't run, the connections will not work properly.  Look in the /etc/init.d directory for another script that has "nfs" in it; most likely you'll need to start that script too.

A: Apply the following pseudo-patch to /etc/default/nfs-kernel-server:
-RPCMOUNTDOPTS=--manage-gids
+RPCMOUNTDOPTS=

I encountered the "the semaphore timeout period has expired" problem on Windows 7 while trying to access NFS on Debian Squeeze, so this is probably applicable (due to Debian being upstream for Ubuntu and the proximity of the Squeeze and Lucid release dates), but possibly not.
I could not replicate the problem accessing NFS on (default installs of) RHEL 6 or SLES 11, so upon comparing the running processes related to NFS (ie rpc.*) I noticed the addition of "--manage-gids" to rpc.mountd on Debian Squeeze, retried NFS running rpc.mountd without "--manage-gids" with success, and tracked that argument to /etc/default/nfs-kernel-server.


text:
Q: check input for SQL-Injection with Mybatis I'd like to check my input string for potential SQL-Injection.
Here is my class, method and query:
public class UserNamesQuery {

   public static String getUserNames(Map<String, Object> params) {
       String userNames = (String) params.get("userNames");
       return "SELECT * FROM users WHERE name IN (" + userNames + ") ";
   }

}

Is there a tool or a quick way to validate that userNames is without SQL-Injection?
Notice that I use Mybatis

A: No. There is no way. And no need.
To be frank, there is no such thing like "SQL injection". There is only an exploit of improperly formatted query.
So, instead of hunting down whatever "injections" you have to format your queries properly, by means of using prepared statements.
Any data, depends on context, could be either a potential injection or a harmless chunk of text. So, with whatever filtering function there will be too much false positives. Worse yet, whatever filtering is a "black list" implementation, means it will always be incomplete - it's just impossible to filter out all the codes used to exploit an injection.
On the other hand, prepared statement is a relatively simple solution that will be immune to any type of injection without even knowing them. Just because it won't let the data to interfere with the query.

A: Sanitizing input is not the way to prevent injections like this. Using prepared statements is the way to go.
PreparedStatement ps = connection.prepareStatement("SELECT * FROM users WHERE username IN (?)"); //Add however many ?'s you want, if you have an array you can use a StringBuilder for this to add more ?'s
ps.setString(1, userName);
ResultSet rs = ps.executeQuery();

This will set the ? in the code to your string. The database driver then handles the rest.
If you have multiple values in the IN clause, use a StringBuilder and a loop to add more Questionmarks.
Also notice how the indexing starts with 1 instead of 0.

A: mybatis sql template may be a good choose. FYI:
<sql id="orderTypeSql">
    <trim prefix=" ">
        <if test="orderType=='desc'">desc</if>
    </trim>
</sql>

<sql id="oderColumnSql">
    <trim prefix="order by " suffix="" >
        <choose>
            <when test="orderColumn==null or orderColumn==''"></when>
            <when test="orderColumn=='id'">
                id<include refid="orderTypeSql"/>
            </when>
            <when test="orderColumn=='name'">
                `name`<include refid="orderTypeSql"/>
            </when>
        </choose>
    </trim>
</sql>

<select id="testOrderBy" resultType="User">
    select
    id,
    `name`
    from t_user
    <include refid="oderColumnSql"/>
    limit 0, 10
</select>


text:
Q: Django. Displaying page including text and png image I am having trouble in django generating a page that displays both text and a .png image.
Within views.py a function as per below works fine
    def image_test(request):
        image_file = open("C:\\temp\\test.png",'rb').read()
        return HttpResponse(image_file,mimetype='image/png')

now if i try to create html that will display both text and the image (as below)
    def test(request):
        html = " Hi there.\n\n"
        html += " \n"
        html += " \n"
        return HttpResponse(html)

then only the text displays. However if i save the generated html to a file as per below
     Hi there.

and open that in the browser then it displays both the text and the png file.

A: Why on earth would you want to do any of this? You don't serve image files by reading them from a disk and passing them to an HttpResponse - that's nonsense. You serve files with a webserver, or Django's static.serve during development only. You don't refer to files in generated HTML with the filepath on your local disk. And you don't create HTML by concatenating strings, you use Django's full-featured template language.

A: It's not really a Django issue. When you open a webpage from an external server (ie. not directly from your hard drive, even if the server runs on your local machine) your browser doesn't allow it to reference files on your hard drive.
You need to change the images URL so it references URL on the server, not on your hard disk.
Read about serving static files in Django and about using templates.


text:
Q: Model theory stressing order type of universe. In Appendix B to their Model Theory, Chang and Keisler list some problems and conjectures that, at the time of publication, were unsolved. A few of them take imperative form, for instance:
"Develop a theory of models which stresses the order type of the model $\mathfrak{A} = \langle A, <, \dots\rangle$ rather than the cardinality of the set $A$."
Has anyone worked on this?

A: I don't think many model theorists have worked on this.  Granted, I'm a little unclear what Chang and Keisler were asking here, but here's one possible precisification:
Question: Suppose we are given a (complete?) theory T in a language with a binary relation < such that T proves "< is a strict linear ordering."  Try to develop a theory of the "order-type spectrum" $I(\alpha, T)$, which is defined as the number of nonisomorphic models $M$ of $T$ such that $(M, <^M)$ has order type $\alpha$.
You could start by trying to think about what it means for $T$ to be "$\alpha$-categorical" for some order type $\alpha$, meaning, what are necessary and sufficient conditions for $I(\alpha, T)$ to equal $1$?  (I have no idea whether anybody has investigated this before.)  For example, if $T$ proves that the ordering is dense without endpoints and $\eta$ is the order type of the rationals, then $I(\eta, T) = 1$ if and only if $T$ is $\omega$-categorical, since the complete theory of $(\mathbb{Q}, <)$ itself is $\omega$-categorical.
An immediate complication I see to this project is that I don't know if there is any good analogue of the upward Lowenheim-Skolem theorem.  It seems like it would be difficult to answer the question: "Given a theory $T$, for which infinite order types $\alpha$ is $I(\alpha, T) \neq 0$?"  (The corresponding question for cardinalities of the universe for a $T$ with infinite models is trivial, by Lowenheim-Skolem.)  For example: your theory $T$ could force the order type of any model to not be Dedekind complete (e.g. take the complete theory of an densely-ordered ring with a unary predicate for a proper convex subring).
Are there Morley-like categoricity theorems?  If $T$ is countable, say, and $I(\alpha, T) = 1$ for some uncountable order type $\alpha$, can we conclude that $I(\beta, T) \leq 1$ for every uncountable $\beta$?  Possibly this could be an interesting question; offhand I have no idea what the answer is.
Illustrating the difficulties of this, here's a paper just on the possible order types of a particular theory, PA:
"Order-types of models of Peano arithmetic," by Andrey Bovykin and Richard Kaye, pp. 275-285 of Logic and Algebra, edited by Yi Zhang with a preface by Oleg Belegradek, Contemporary Mathematics 302, AMS.
A different interpretation of the original question would be: given a particular order type $\alpha$, investigate structures with order type $\alpha$.  Along these lines, many model theorists (such as Pillay, van den Dries, Wilkie, and others) have been studying expansions of the ordered field of the real numbers under the rubric of "o-minimal theories," though generally the interest has been in definable sets rather than models per se.  Chris Miller is an example of an o-minimalist who has done a significant amount of research just on structures expanding the field of reals; check out his webpage for some state-of-the-art papers in this area.


text:
Q: Highlight.js doesn't render HTML Essentially I can't get the HTML to render at all.
HTML:

    <link rel="stylesheet" href="/path/to/default.css">

I tried javaScript and it works flawlessly...
Any ideas?
UPDATE:
I inserted the markup in question.

Curabitur gravida vestibulum imperdiet.

Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem. Integer sed mi quis nisl eleifend interdum.

Cras convallis ut turpis vitae facilisis. Morbi eu augue vel quam efficitur rhoncus vitae eget lectus. Cras augue ligula, aliquam ut enim ut, feugiat imperdiet sem.

                        Read More

UPDATE 12-8-2016:
I found a work around but still haven't solved the issue.
Apparently there is a Sublime text plugin called SublimeStringEncode which will Encode your HTML tags.

However as you can see that solution looks messy in the markup and while easy for me to follow, might be hard to 'get' for others who share my CMS...Also I couldn't get a horizontal scroll bar to appear...

A: I did something similar to what you said in your update.  I'm using the WP-Code-Highlight.js for my WP blog.  When trying to format the HTML code, it kept rendering as HTML, rather than only showing the code. Meaning instead of seeing
Hello
 I was seeing a big rendered h1.
The workaround was as you suggested.  I used < and > to make the code render as HTML code that I want to display. For example:

        <h1>hello></h1>

I wish there was a better solution but I have yet to find one.

A: you have to use  for both html & xml syntaxes.


text:
Q: How to remove \n at end of file name When the following bit of code runs, most specifically the last 'else'condition, I get this error: OSError: [Errno 22] Invalid argument: 'My Name\n-Groups.txt'
What should I do so that '\n' isn't included in the file name as I would like it to just be  'My Name-Groups.txt'.
def add_child_to_group():
    file = open("Children.txt", 'r')  # open the Children.txt file
    lineList = file.readlines()
    lineList.sort()
    file.close()
    choice1 = choicebox('Choose a child to enter into a group.', 'Add child to a group. ', choices=lineList)
    if choice1 is None:
        print("You cancelled... returning to the main menu.")
        main()
        return
   else:
        file = open("Groups.txt", 'r')
        lineList = [line.strip() for line in file]
        choice2 = choicebox("Which group would you like to add the child to?", "Choose a group.",
                        choices=lineList)
        file.close()
        if choice2 is None:
            print("You cancelled... returning to the main menu.")
            main()
            return
        else:
            if choice1 in open('%s.txt' % choice2).read():
                child_already_in_group(choice1, choice2)
                return
            else:
                file1 = open('%s.txt' % choice2, 'a')
                file1.write(str(choice1))
                print(str(choice1) + "was added to the " + str(choice2) + " group")
                file1.close()
                file2 = open('%s-Groups.txt' % choice1, 'a')
                file2.write(str(choice2))

A: Something like this can do:
>>> st = 'My Name\n-Groups.txt'
>>> st.replace('\n','')
'My Name-Groups.txt'
>>>

So, in your code, you can make the following change:
file2 = open(('%s-Groups.txt' % choice1).replace('\n',''), 'a')


text:
Q: Problema com condição Estou tentando criar um script que apure se a multa por atraso no pagamento da rescisão é devida.
As condições são as seguintes:
1 - Se o aviso prévio for indenizado ou dispensado (select), e o pagamento foi feito em até 10 dias (date), a multa não é devida.
2 - Se o aviso prévio foi trabalhado ou descontado, e o pagamento foi foi feito após 1 dia do desligamento, a multa é devida.
3 - Nos demais casos não é devida.
Este é o código:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" href="_css/form2.css"/>
    <title></title>

<form method="post" id="Tform" action="multaqss.php">
    Aviso prévio
Como deve ser considerado o aviso prévio?

    <select name="Tavis" id="Cavis">
        <option></option>
        <option value="indenizado">indenizado</option>
        <option value="dispensado">dispensado</option>
        <option value="trabalhado">trabalhado</option>
        <option value="descontado">descontado</option>
    </select>

    Desligamento

    Qual a data do desligamento?

    <input type="date" name="Tdesl" id="Cdesl22" size="6">

    Data do pagamento

    Qual a data em que foi realizado o pagamento?

    <input type="date" id="Cdatapgtos" name="Tdatapagtos">

    <input type="submit" value="enviar">
</form>

<?php

$tavis = $_POST ["Tavis"];
$fimcon = $_POST ["Tdesl"];
$pagtos = $_POST ["Tdatapagtos"];
$multaqss = false;
$prazo = date_diff(date_create($pagtos), date_create($fimcon))->format('%d');

    if ($tavis == "indenizado" || "dispensado" && $prazo > 10){
        $multaqss = true;
    }
    elseif ($tavis == "trabalhado" || "descontado" && $prazo > 1) {
        $multaqss = true;
    }

print "A data de desligamento foi $fimcon" . "
";
print "A data de pagamento foi $pagtos" . "
";
print "A diferença entre o desligamento e o pagamento é de $prazo dia(s)" . "
";
print "O aviso prévio foi $tavis" . "
";

    if ($multaqss == false) {
        echo "A multa não é devida" . "
";
    }
    else {
        echo "A multa é devida." . "
";
    }
?>

O problema é que não importa o que eu faça, ele sempre considera que é devido, mesmo que a data não corresponda.
Um exemplo de saída (errada):

A data de desligamento foi 2015-04-01
A data de pagamento foi 2015-04-05
A diferença entre o desligamento e o pagamento é de 4 dia(s)
O aviso prévio foi indenizado
A multa é devida.

A: Realmente, há um erro na condição. Deve resolver alterando para:
if (($tavis == "indenizado" || $tavis == "dispensado") && $prazo > 10){
    $multaqss = true;
}
elseif (($tavis == "trabalhado" || $tavis == "descontado") && $prazo > 1) {
    $multaqss = true;
}


text:
Q: How to reproduce a browser handshake in c# to a websocket without receiving a 403? I'm building a c# application that connects to a websocket using WebSocket-sharp and I keep receiving a 403 - Forbidden from the server.
I have tried using fiddler to see how the browser handle it differently and I have copied all the local cookies the website is using.
The request:
GET /api/trade/live/Metamorph/lg8jphV HTTP/1.1
User-Agent: websocket-sharp/1.0
Host: www.pathofexile.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: pnjDDw0njbxi4PmLR+A6OA==
Sec-WebSocket-Version: 13
Cookie: POESESSID=<redacted>

The response:
HTTP/1.1 403 Forbidden
Date: Sun, 02 Feb 2020 20:32:32 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d31e2345f42cc565e3bbc5e9a2d0ede691580675552; expires=Tue, 03-Mar-20 20:32:32 GMT; path=/; domain=.pathofexile.com; HttpOnly; SameSite=Lax
X-Rate-Limit-Policy: trade-websocket-request-limit
X-Rate-Limit-Rules: Ip
X-Rate-Limit-Ip: 45:60:60,90:120:3600
X-Rate-Limit-Ip-State: 1:60:0,1:120:0
CF-Cache-Status: DYNAMIC
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 55eeef5a1ec4919e-EWR

Any ideas on what would be the next step in troubleshooting the issue would be greatly appreciated!

A: I've looked at that particular API, and you first have to create a 'search'. That is what your lg8jphV is - the endpoint has to actually exist before you can open it. In my test, for example, my websocket URL is wss://www.pathofexile.com/api/trade/live/Metamorph/Ab3LSL
First post your search to https://www.pathofexile.com/api/trade/search/Metamorph. Your body should look something like this (except with your specific search terms):
{
    "query": {
        "status": {
            "option": "online"
        },
        "stats": [
            {
                "type": "and",
                "filters": []
            }
        ],
        "filters": {
            "type_filters": {
                "disabled": false,
                "filters": {
                    "category": {
                        "option": "weapon.bow"
                    }
                }
            },
            "misc_filters": {
                "disabled": false,
                "filters": {
                    "shaper_item": {
                        "option": "true"
                    }
                }
            }
        }
    },
    "sort": {
        "price": "asc"
    }
}

This creates your actual search object, and you get a response body back like this:
{
    "result": [
        "48c83eb427f369f6ddde8689d7458f6bf5a8380eed114b72b5a7a298651c4d65",
        "6314ac7c88b143b80c777d23cdc12bb9d86e8bb82d8073f659132bf492fa69fe",
        "1c39870f03505acaecd78dc0cc2a498a3a1037cd88b0035e3601e35140b59450",
        "3dc8cf428d842a8be12953c6d2db117e5db4456cb6d3b75f5280ca8fb687c587",
        "9470cc63efbe4ca192103200ad78734784a218c68b9d9ead0be456a98260394f",
        "798ba0699085a63359c459cc89cafbbe28653fe893dfb6a9ba71162fd4d7aa51",
        "dab3edc9c28723decc76ba56eb988c7f245ce15041640dca461124918dafbc90",
        "06da5889c8cbf295ab13e103dfa9e291b3e0caf0256b398ccaec9ddfdb1e56c4",
        "... continues ..."
    ],
    "id": "Ab3LSL",
    "total": 100000,
    "inexact": true
}

You now have a search endpoint via the ID.
Finally, when making the request, you have to set the Origin header or you'll get a 403 Forbidden (you'll have to change the nuget package you're using to https://www.nuget.org/packages/websocket-sharp-customheaders if you want to keep using websocket-sharp). Don't forget your cookie or you'll get 401 Unauthorized
using (ClientWebSocket ws = new ClientWebSocket())
{
    Uri serverUri = new Uri($"wss://www.pathofexile.com/api/trade/live/Metamorph/D4bWwf5");
    //setting headers the way I did below only works because I used reflection to change the IsRequestRestricted bool to false
    ws.Options.SetRequestHeader("Cookie", "__cfduid=d4a76bfa2583a39474272974006edad461580748134; _ga=GA1.2.477754083.1580748162; _gid=GA1.2.2011499591.1580748162; stored_data=1; _sm_au_c=krZJcAOlyMvVNsrvCJ4mJyGIu8S0KVB4Lr7aqcW0VB9UgAAAAa68dX6r0DT/Ta5U0B4NfCgZ2Jm/2q8R651XMxiBtJsM=; cf_clearance=e6964bd6eaed12c405c1b9b8a2b2f08d506b4926-1580761181-0-150; POESESSID=a2c44ee2111904215ccef8c69b2e72b5");
    ws.Options.SetRequestHeader("Origin", "https://www.pathofexile.com");
    ws.ConnectAsync(serverUri, CancellationToken.None).Wait();

    Task.Run(async () =>
    {
        ArraySegment<byte> inbound = new ArraySegment<byte>(new byte[1024]);
        while (ws.State == System.Net.WebSockets.WebSocketState.Open)
        {
            var wsRes = await ws.ReceiveAsync(inbound, CancellationToken.None);
            if (wsRes?.Count > 0)
                Console.WriteLine(Encoding.UTF8.GetString(inbound.Array, 0, wsRes.Count));
        }
    });

    Console.WriteLine("WEB SOCKET OPEN; HIT ENTER TO EXIT");
    Console.ReadLine();
}

You can run the snippet above, just swap out the cookies for your own cookies. This is also just a rough proof of concept using the built in websocket client.
Screenshot of output:


text:
Q: How to create text design I am trying to create this desgin :

Those are dynamics small block of texte from the server.
Any guide line ?
Thanks
Nico

A: You can use Bootstrap Grid system to do this. Hope you know how to load text from the server.
Use
http://www.w3schools.com/Bootstrap/bootstrap_grid_system.asp
to learn about grid system. please refer it and make sure to code to all medium devices, small devices and extra small devices as well because otherwise, it will not display properly in small devices as you expect.
Further use Text and Font CSS styles to achieve the relevant styles.
http://www.w3schools.com/css/css_text.asp
http://www.w3schools.com/css/css_font.asp
https://responsivedesign.is/resources/typography/slab-text
Hope this helps.


text:
Q: iOS Custom UIImagePickerController Camera Crop to Square I'm trying to create a camera like Instagram where the user can see a box and the image would crop to that box. For Some reason the camera doesn't go all the way to the bottom of the screen and cuts off near the end. I'm also wondering how would I go about cropping the image to be 320x320 exactly inside that square?

A: @Anders answer was very close to correct for me on iPhone 5. I made the following modification to add an overlay hardcoded for iPhone 5:
CGRect f = imagePickerController.view.bounds;
f.size.height -= imagePickerController.navigationBar.bounds.size.height;
UIGraphicsBeginImageContext(f.size);
[[UIColor colorWithWhite:0 alpha:.5] set];
UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, 124.0), kCGBlendModeNormal);
UIRectFillUsingBlendMode(CGRectMake(0, 444, f.size.width, 52), kCGBlendModeNormal);
UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f];
overlayIV.image = overlayImage;
overlayIV.alpha = 0.7f;
[imagePickerController setCameraOverlayView:overlayIV];`

I hope this helps someone.

A: Here's the easiest way to do it (without reimplementing UIImagePickerController). First, use an overlay to make the camera field look square. Here's an example for 3.5" screens (you'd need to update it to work for iPhone 5):
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = source;

if (source == UIImagePickerControllerSourceTypeCamera) {
    //Create camera overlay
    CGRect f = imagePickerController.view.bounds;
    f.size.height -= imagePickerController.navigationBar.bounds.size.height;
    CGFloat barHeight = (f.size.height - f.size.width) / 2;
    UIGraphicsBeginImageContext(f.size);
    [[UIColor colorWithWhite:0 alpha:.5] set];
    UIRectFillUsingBlendMode(CGRectMake(0, 0, f.size.width, barHeight), kCGBlendModeNormal);
    UIRectFillUsingBlendMode(CGRectMake(0, f.size.height - barHeight, f.size.width, barHeight), kCGBlendModeNormal);
    UIImage *overlayImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageView *overlayIV = [[UIImageView alloc] initWithFrame:f];
    overlayIV.image = overlayImage;
    [imagePickerController.cameraOverlayView addSubview:overlayIV];
}

imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];

Then, after you get a picture back from the UIImagePickerController, crop it to a square with something like this:
//Crop the image to a square
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width != height) {
    CGFloat newDimension = MIN(width, height);
    CGFloat widthOffset = (width - newDimension) / 2;
    CGFloat heightOffset = (height - newDimension) / 2;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), NO, 0.);
    [image drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
                   blendMode:kCGBlendModeCopy
                       alpha:1.];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

And you're done.


text:
Q: Should I use JavaCV or OpenCV's java library on Android? http://opencv.willowgarage.com/wiki/Android or http://code.google.com/p/javacv/ ?
I am new to computer vision, and want to do something on the phone camera such as matching the current screen to the most similar image in the database.
Both of them are java, what are the differences? Which one should I use?
Thank you so much for helping!

A: JavaCV is a wrapper around some native libraries, including OpenCV.

*

*In any case you are going to use OpenCV, either directly by writing your own wrapper or using OpenCV's Android wrappers or using JavaCV.

*As said JavaCV uses several libs, so it has many more features than only OpenCV. If you need those features than naturally you'd choose JavaCV.


text:
Q: XMLHttpRequest post multipart FormData, file gets added twice I'm making an upload mechanism using XMLHttpRequest and FormData. However when creating a request the file is somehow being added twice, what am I missing here?
I have a class Uploader being responsible for submitting a multipart form and a static object cc being responsible for the actual upload.
The Uploader-class's upload method is called from JS when the single input field dispatches the change event.
The Uploader class looks like the following:
class Uploader {
    constructor(form){
        this._form = form;
        this._files = [];
    }

    _buildFileIndex(){
        const fileInputsEl = this._form.querySelectorAll('input[type="file"]');
        const fileInputs = Array.from(fileInputsEl).map(input => {
            return {
                'name': input.getAttribute('name') || 'undefined',
                'files': input.files
            }
        });

        this._fileInputs = fileInputs;
        return fileInputs;
    }

    _buildFormData(){
        this._formData = new FormData(this._form);
        for(let input of this._fileInputs){
            for(let file of input.files){
                this._formData.append(input.name, file, file.name);
            }
        }

        return this._formData;
    }

    upload(callback){
        this._buildFileIndex();
        this._buildFormData();

        cc.POST('/api/upload', this._formData, res => {
            if(typeof callback === 'function') callback(res);
        });
    }
}

The cc object:
const cc = {
    'serverADDR': function(){return window.location.protocol + '//' + window.location.host},
    'POST': function(endpoint, data, callback, contentType){
        const xhttp = new XMLHttpRequest();
        xhttp.open('POST', cc.serverADDR() + endpoint, true);

        if(contentType) xhttp.setRequestHeader('Content-Type', contentType);

        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if(typeof callback === 'function') callback(this);
            }
        };

        xhttp.send(data);
    }
}

And this is the data sent according to Google Chrome, when selecting only one file in one input:
------WebKitFormBoundaryEDgRU4CNKJQjnIA8
Content-Disposition: form-data; name="media"; filename="Skärmavbild 2017-10-29 kl. 12.16.50.png"
Content-Type: image/png

------WebKitFormBoundaryEDgRU4CNKJQjnIA8
Content-Disposition: form-data; name="media"; filename="Skärmavbild 2017-10-29 kl. 12.16.50.png"
Content-Type: image/png

------WebKitFormBoundaryEDgRU4CNKJQjnIA8--

The submission of the form is made in a page-specific object home:
const home = {
    'el': {
        'inputs': {
            'form': document.querySelector('form'),
            'input': document.querySelector('input')
        }
    },
    'init': function(){
        home.setupForm();
    },
    'setupForm': function(){
        home.el.inputs.input.addEventListener('change', home.upload);
    },
    'upload': function(){
        const uploader = new Uploader(home.el.inputs.form);
        uploader.upload(res => {
            console.log(res);
        });
    }
}

home.init();

...and the form itself is as simple as:
<form method="POST" action="#">
    <input type="file" name="media">
</form>

A: Creating a FormData instance appends the fields of the provided form automatically. All files were therefore added twice before the request was sent.


text:
Q: Object not returning instance variable value For some reason, when I call the method that tells me the object's size, I get nothing. This is my code:
def getSize(name)

    data = Hash.new

    data[:aarakocra] = "medium"

    print "Got size"

    return data[:aarakocra]

end

class Monster

    def initialize(name, statStr, statDex, statCon, statInt, statWis, statCha)
        @name = name
        @statStr = statStr
        @statDex = statDex
        @statCon = statCon
        @statInt = statInt
        @statWis = statWis
        @statCha = statCha
    end

    @size = "medium"

    def displayStats
        return [@statStr, @statDex, @statCon, @statInt, @statWis, @statCha]
    end

    def displaySize
        return @size
    end
end

aarakocra = Monster.new("Aarakocra", 10, 14, 10, 11, 12, 11)

if aarakocra.displaySize == "medium"
    puts "Hello"
else
    puts "Not true"
end

I'm expecting the output to be hello.
If someone could explain what's happening, I'd really appreciate it.

A: @Thrayna seems like you are initializing the instance variable @size outside of the initialize method, try moving the variable inside it. Since it is an instance variable, it gets initialized at object creation (Calling Moster.new) or when calling another method; note, that instance variables are nil by default until you initialize them.


text:
Q: React Native + Redux: How to subscribe to changes in state? I have a component and I want to call a method checking the state whenever it changes. This is my component with a dummy method to demonstrate what I want to do (animate the view offscreen if onboarding.show === false):
export class Onboarding extends Component {

  animateView() {
    // i want to call this method when
    // the state changes
    // something like;
    if (!this.props.onboarding.show) {
      Animated.spring(...);
    }
  }

  render() {
    const { onboarding, finish } = this.props;

    return (
      <Animated.View>
        ...
      </Animated.View>
    );
  }
}

...

export default connect(
  state => {
    return {
      onboarding: state.onboarding,
    };
  },
  dispatch => {
    return {
    };
  }
)(Onboarding);

Is there a way to subscribe to the changes in state?
== UPDATE ==
as requested, here's what my slideOffScreen method does:
  slideOffScreen() {
    Animated.timing(this.state.offsetX, {
      toValue: -Dimensions.get('window').width,
      duration: 350,
      easing: Easing.elastic(),
    }).start();
  }

A: The react-redux connect method wraps the component with a container component that is aware of the store's state changes. Whenever the state changes, connect re-renders the wrapped component (Onboarding in your case).
According to the redux docs:

Technically, a container component is just a React component that uses
  store.subscribe() to read a part of the Redux state tree and supply
  props to a presentational component it renders. You could write a
  container component by hand, but we suggest instead generating
  container components with the React Redux library's connect()
  function, which provides many useful optimizations to prevent
  unnecessary re-renders.

If your component doesn't re-rendered when the state changes, check if you're not mutating the state instead of replacing it. Redux checks if the state changed by shallowly comparing the old state, and the new state (comparing only the references, and not the values).
For example, to add an item to an array, you can't use array.push(item) because that won't create a new array, just mutate the existing one. Instead you'll have to use something like array.concat(item), which does.
To update objects, you can see in the redux docs under handling actios example, you can see that to create a new state:

We don't mutate the state. We create a copy with Object.assign().
  Object.assign(state, { visibilityFilter: action.filter }) is also
  wrong: it will mutate the first argument. You must supply an empty
  object as the first parameter. You can also enable the object spread
  operator proposal to write { ...state, ...newState } instead.

A: Looks like this works:
  componentWillReceiveProps(props) {
    if (!props.onboarding.show) {
      this.slideOffScreen();
    }
  }

not sure if there's a way to do it through the redux API


text:
Q: Applescript w/Keynote. Accessing shapes within a slide I have a templated Keynote file with some slides and all the slides each have 2 shapes in them. I want to be able to say something like, "hey give me shape 2 of slide 2". The purpose of this, is so that i can add text items directly to that shape. below is the code that I have right now.
I am using the latest Keynote 6.5.2 & Yosemite.
  tell application "Keynote"

        activate

        tell document 1

            set anniversary to "Anniversaries"
            set myShape to shape 2 of slide 2
            tell myShape
                set thisTextItem to make new text item with properties {object text:anniversary}
                #log thisTextItem
                tell thisTextItem
                    set the size of its object text to 144
                    set the color of its object text to "blue"
                end tell

            end tell

        end tell

    end tell

I can tell slide 2 by itself and of course i get a big text item for slide 2 with text "Anniversaries" and colored blue but its only slide 2... not within shape 2 of slide 2.
With this code it gives me a pop up error when running the script:
Result:

error "Keynote got an error: Can't make or move that element into that
  container." number -10024

what does this mean? do i not have access to shapes within slides?? Any help/info/examples of setting text within a shape that is within a slide would be beneficial. Thanks!

A: You can set the properties of the text in a shape, you can't insert a text item object in a shape.
tell application "Keynote"
    tell document 1
        tell shape 2 of slide 2
            set object text to "Anniversaries"
            tell object text
                set it's size to 44
                set it's color to {0, 0, 65535} -- blue
            end tell
        end tell
    end tell
end tell


text:
Q: Drupal 7 with Views 7.x-3.5, some fields not showing for Sort I am trying to sort a view by a node field (product weight - which is a decimal), however, that field and various others do not show as fields which I can sort on.
I am hoping there is some simple fix for this, but I have been unable to find the solution.
Why do some fields show in the sort criteria, but others do not? What do I have to do to make it possible to sort by the missing fields?

A: Worked it out.
You have to add an index to the search API...
Once this has been done with the appropriate fields added they should become available to sort.

A: Multi-valued fields don't shows up as sortable in Drupal 7 views.
Go to your field settings->Select no of Values as 1 ->Go to view's format settings and see if Sort option s available->Check Sort->Save the view.


text:
Q: Spring: @NestedConfigurationProperty List in @ConfigurationProperties Hi I am trying to get the following configuration up and running.
@ConfigurationProperties(prefix="my")
public class Config {

    @NestedConfigurationProperty
    private List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>();

    public List<ServerConfiguration> getServers() {
        return this.servers;
    }
}

@ConfigurationProperties(prefix = "server")
public class ServerConfiguration {
    private String name;
    private String description;
}

So, I want to have multiple server configs nested in objects.
I tried setting the properties with the following properties file. I can see that the list is added up by items but the members of the server are never set (name, description)
my.servers[0].name=test
my.servers[0].server.name=test
my.servers[1].name=test
my.servers[1].server.name=test

A: To extend what Maciej said already.
@ConfigurationProperties should be set only on root objects (that is objects that are responsible to handle a given prefix. There is no need to annotated nested objects with it.
@NestedConfigurationProperty is only used by the meta-data generator (to indicate that a property is not a single value but something we should explore to generate additional meta-data. In the case of the List there isn't any finite amount of properties so the meta-data will have to stop at the list.
In any case you need a getter and a setter for each singular property. We don't do field binding and we require a public getter to avoid exposing unnecessary properties in the meta-data.

A: *

*You need to add setters and getters to ServerConfiguration

*You don't need to annotate class with nested properties with @ConfigurationProperties

*There is a mismatch in names between ServerConfiguration.description and property my.servers[X].server.name=test


text:
Q: Kernel, Green function and the functional derivative. I am pretty new to the subject of differential equations and am reading about Green functions and Kernels for the first time. I am more familiar with functional differentiation and am comfortable with the idea that the functional derivative at a point is given by the Dirac delta function.
\begin{equation}
\frac{\delta F}{\delta f(x)}=\delta (x-a)
\end{equation}
With $F=f(a)$. I have noticed that this is very similar to a Green function.
My question is:

Are the above ideas related in a way more than coincidence? In particular functional derivatives, Green functions and Kernels.

My understanding of a Green function is that it is the solution to the inhomogeneous linear ODE while the Kernel is the solution to the homogeneous linear ODE. As you can see it is not extensive!

A: Remark
Given a differential operator $L$ we seek the solution $u$ to the inhomogenous ODE
$$L[u(t)] = f(t)$$
The green function of $L$ is $G(x,t)$ satisfying
$$L[G(x,t)] = \delta(x-t)$$
such that our solution $u(t)$ can be expressed as an integral with kernel $G$:
$$u(t) = \int_C{G(x,t)f(x)dx}$$
Over a suitable domain C.
A fantastic book on such methods of solving ODEs is Brian Davies - Integral Transforms and Their Applications, This is a specialised book and only discusses this topic, but i'm sure you have the prerequisites to follow.
Riley Hobbs - Mathematical Methods for physicists is also on I always go back to. It covers a lot so it is expensive and heavy!