text:
Q: Calculate camera world position with OpenCV Python I want to calculate my camera's position in world coordinates. This should be fairly easy, but I don't get the results I expect. I believe I've read everything on this topic, but my code isn't working. Here's what I do:
I have a camera looking at an area.
1) I drew a map of the area.
2) I calculated the homography by matching 4 image points to 4 points on my map using cv2.getPerspectiveTransform
3) The H homography transforms every world coordinate to camera coordinate; this is working properly
4) To calculate the camera matrix I followed this:
translation = np.zeros((3,1))
translation[:,0] = homography[:,2]

rotation = np.zeros((3,3))
rotation[:,0] = homography[:,0]
rotation[:,1] = homography[:,1]
rotation[:,2] = np.cross(homography[0:3,0],homography[0:3,1])

cameraMatrix = np.zeros((3,4))
cameraMatrix[:,0:3] = rotation
cameraMatrix[:,3] = homography[:,2]

cameraMatrix = cameraMatrix/cameraMatrix[2][3] #normalize the matrix

5) According to this, the camera's position should be calculated like this:
x,y,z = np.dot(-np.transpose(rotation),translation)

The coordinates I'm getting are totally wrong. The problem should be somewhere in step 4 or 5 I guess. What's wrong with my method?

A: I think I've got it now. The problem was with the method described in step 4. The camera position cannot be calculated from the homography matrix alone. The camera intrinsics matrix is also necessary. So, the correct procedure is the following:
1) draw a map of the area
2) calibrate the camera using the chessboard image with cv2.findChessboardCorners this yields the camera matrix and the distortion coefficients
3) solvePnP with the world coordinates (3D) and image coordinates (2D). The solvePnP returns the object's origo in the camera's coordinate system given the 4 corresponding points and the camera matrix.
4) Now I need to calculate the camera's position in world coordinates. The rotation matrix is: rotM = cv2.Rodrigues(rvec)[0]
5) The x,y,z position of the camera is: cameraPosition = -np.matrix(rotM).T * np.matrix(tvec)


text:
Q: Change font size with Word VBA I would like to change my font size which is not equal to 9 to 9.
But it pops out "Compile Error: Expected Expression".
Sub FindReplaceStyle()

With ActiveDocument.Content.Find
    .ClearFormatting

    With .Font
        .Size <> 9
    End With

    .Format = True

    With .Replacement
        .ClearFormatting
        With .Font
            .Size = 9
        End With
    End With

    .Execute Forward:=True, Replace:=wdReplaceAll, _
        FindText:="", ReplaceWith:=""
End With

End Sub

A: @user2830554 : <> is an conditional operator, so you cannot use it without a conditional statement

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fade in an image by setting opacity I need to fade in an image thats invisible for the first 2 seconds of the animation.
This is what I have rigth now:
     <image x="40%" y="40%" width="30%" height="30%" id="img2"
   opacity="1"

   preserveAspectRatio="xMinYMin meet"
     xlink:href="img/2dugs.jpg" >
     <animate attributeName="opacity"
   attributeType="CSS"
   begin="2s" dur="2s" from="0" to="1"
   repeatCount="1" />

     </image>

With this code the image is visible right at the start of the the animation, which I don't want. If I set  opacity="0" the start is fine: the image is not disolayed for the first 2 seconds , fades in during 2 seconds but at the end gets invisible again.
How do I get an animation that: has the image invisible for the first 2 seconds, then fades in during 2 seconds and then stays visible?

A: Add fill="freeze" to the <animate> tag and make <image ... opacity="0">.


text:
Q: Always setting the text cursor on Textbox I am writing a web page which will have only 1 text box on the page and display the information due to the given data.
Our plan is that, we will use Barcode Scanner or Magnetic Swipe and Touch Screen Monitor for that special page.  When the student card is scanned, it will automatically postback and retrieve the data from the datasource and display on the webpage.  We have built the sample page and managed to make it work with the real data.
The sample data could be a barcode or magnetic swiped data.
Sample Barcode Data - ?300203623;
Sample Magnetic Swiped Data - ;30020362300203622016?

Both input devices (barcode scanner and Magnetic Swipe) append the Enter keycode automatically.  You can disable it if you want.  Since we want to post it back after the scanning/swiping, we prefer to leave the Enter key as it is.
The problem is that when the user accidentally click anywhere on the webpage, the textbox lost the focus and when the card is scanned or swiped again, it doesn't do anything.  Because the text box lost the focus and scanned data are not inserted to the textbox and it doesn't do the post back to the server.

I wrote the javascript to reset the focus on the textbox (id: Reference) whenever it lost the focus.  I can see the console.log lines on the console.  But it's not setting the focus on the textbox.  I tested on FF, Chrome & IE but the same problem.
$('#Reference').focusout(function () {
    console.log('on focusout' + new Date());
    $('#Reference').focus();
});

My first question is how can I re-focus on the textbox whenever it lost the focus.
Secondly, are we doing the right thing?  What if we want to add 'image' or 'link' to touch/click in the future?  Is it going to affect, if we keep forcing the focus to the textbox?
If there is a better way in mind, please feel free to suggest me.

A: With blur instead of focusout it worked for me (used plain javascript, but should work with jquery too):
HTML
<textarea id = 'txt'></textarea>

Javascript
document.getElementById("txt").addEventListener("blur", function(e){ setTimeout(function(){e.target.focus();}, 0); });

http://codepen.io/sergio0983/pen/bBbYzK

A: I just tried your code - it worked in Chrome, but for Firefox i needed to wrap it in a timeout:

$('#input').focusout(function () {
    console.log('on focusout' + new Date());
    setTimeout(function() {
      $('#input').focus();
    });
});

$('#form').submit(function( event ) {
  console.log("submit", $("#input").val());
  event.preventDefault();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="text" id="input">
</form>


text:
Q: Check if macro param is defined in optional capture (Declarative Macro Syntax) I am creating a fairly complex macro and can't use the overloading syntax to create my macros.  I am trying to conditionally check if a prop has been defined within an optional capture group or not:
macro_rules! foo {
    (name: $name: ident$(, media: $media: tt)?) => {
        pub struct $name;
        impl $name {
            // how do i use media here and also provide default
            // const MEDIA: &str = IF_DEFINED $media { $media } ELSE { "DEFAULT" };
        }
    };
}

foo! {
    name: Hey,
    media: "hey"
}

foo! {
    name: Hey2
}

Playground Link

A: Within the constraints you mentioned, you can achieve conditional checking by the following workaround:
macro_rules! foo {
    (name: $name: ident$(, media: $media: tt)?) => {

            pub struct $name;

            impl $name {
                const MEDIA: &'static str = [$($media ,)? "DEFAULT"][0];
            }
    };
}

foo! {
    name: Hey,
    media: "hey"
}

foo! {
    name: Hey2
}

fn main() {
    println!("{}", Hey::MEDIA);
    println!("{}", Hey2::MEDIA);
}

Playground Link


text:
Q: Flask blog, only want one user to be able to post I'm creating a blog using Flask and Python and I have a problem. I only want one user to be able to post. In my HTML for post I tried writing
 {% if current_user == default_user1 %}

   .....code for creating a new post....

 {% else %}

Only Admin can create new posts

 {% endif %}

In my database I created the user like this
default_user1 = User(username='Admin',
                         email='default@test.com',
                         profile='Admin',
                         password=hashed_password)
    db.session.add(default_user1)

But when I try to post something while logged in on default_user1 it says "Only Admin can create post". Do you know what I have done wrong?

A: 2 objects in python need not be similar to each other, even if they have the same content
consider the code
class Abc:
    def __init__(self, name):
        self.name = name

a = Abc("Arjun")
b = Abc("Arjun")
print(a == b)

this will print False,
solution :
compare via the username
change
{% if current_user == default_user1 %}
to
{% if current_user.username == "Admin" %}


text:
Q: Keep only the first and the centre part of a string between "_" I have a file with hundreds of lines like:
>hg38_ct_tbrefGene_6787_NM_006820_utr3_8_0_chr1_78641810_f

For only those lines that have the ">" symbol I want to extract the ">" and the "NM_...". In the example above I want to get:
>NM_006820

I'm not sure if this is important but there is also the possibility that some lines share the output (">NM_006820") more than once.
Tried with gsub() but got completely lost.

A: We can use sub to match the > at the start (^) of the string, capture as a group ((..)), followed by characters (.*) followed by _ and then capture the two upper case letters followed by _ and one or more numbers (\\d+).  In the replacement, we use the backreference of the captured groups
sub("^(>).*_([A-Z]{2}_\\d+).*", "\\1\\2", str1)
#[1] ">NM_006820"                           ">NM_006820"
#[3] "Some text without > at the beginning"

If we need to have all the instance of NM_\\d+, then
library(stringr)
v1 <- sapply(str_extract_all(str1, "^>|[A-Z]{2}_\\d+"), function(x)
                         toString(paste0(x[1], x[-1]) ))

i1 <- !grepl("^>", v1)
v1[i1] <- str1[i1]

data
str1 <- c(">hg38_ct_tbrefGene_6787_NM_006820_utr3_8_0_chr1_78641810_f",
     ">hg38_ct_tbrefGene_6787_NM_006820_utr3_NM_006820_8_0_chr1_78641810_f",
   "Some text without > at the beginning")


text:
Q: Inconsistent error due to no time.sleep? I wrote for practice purposes a little Python script in which I calculate all primes to a given value. But I experience some inconsistent errors.
At first here's the code:
import datetime
import time
import threading
class myThread (threading.Thread):
  def __init__(self, threadID, name, threadcounter):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.threadcounter = threadcounter
  def run(self):
    delete_non_primes (self.threadcounter)
print ('This script outputs all primes until the given value. \nWhat value shall be calculated until? ')
maxval = int(input("Please enter the wanted value: "))
print ('Preparing...')
primes = []
primes.append(0)
primes.append(0)
primes.append(2)
i = 3
for i in range (3,maxval+1):
  primes.append(i)
if primes[3]!=3:
  import sys
  sys.exit("An error occured.")
counter = 1
percent = 0
thread1 = myThread(1, "Thread-1 iniated", 0)
thread2 = myThread(2, "Thread-2 iniated", 0)
thread3 = myThread(3, "Thread-3 iniated", 0)
thread4 = myThread(4, "Thread-4 iniated", 0)
thread5 = myThread(5, "Thread-5 iniated", 0)
nr_of_threads = 0
def delete_non_primes ( prime ):
  if prime != 0:
    breaker = prime
    while (breaker < maxval):
      breaker = breaker +1
      if primes[breaker] != 0:
        if primes [prime] != 0:
          if (primes[breaker] % primes[prime]) == 0:
            primes[breaker] = 0
print ("Preparation done.")
print ("Calculating...")
start = datetime.datetime.now()
while (counter < maxval ):
  if counter < maxval:
    counter = counter +1
    thread1 = myThread(1, "Thread-1", counter)
    thread1.start()
  if counter < maxval:
    counter = counter +1
    thread2 = myThread(2, "Thread-2", counter)
    thread2.start()
  if counter < maxval:
    counter = counter +1
    thread3 = myThread(3, "Thread-3", counter)
    thread3.start()
  if counter < maxval:
    counter = counter +1
    thread4 = myThread(4, "Thread-4", counter)
    thread4.start()
  if counter < maxval:
    counter = counter +1
    thread5 = myThread(5, "Thread-5", counter)
    thread5.start()
  thread1.join()
  thread2.join()
  thread3.join()
  thread4.join()
  thread5.join()
#This time.sleep() seems to make the code consistent
  time.sleep(0.05)
  if (counter*100)//maxval > percent:
    percent = (counter*100)//maxval
    print (str(percent) + "%")
end = datetime.datetime.now()
time_needed = end-start
print("\nPrimes to the given max value:")
j = 0
val = 0
while (j <maxval):
  j = j+1
  if primes[j] != 0:
    val = val+1
    if val < 1000000:
      valstr = str(val) + "      "
    if val < 100000:
      valstr = valstr + " "
    if val < 10000:
      valstr = valstr + " "
    if val < 1000:
      valstr = valstr + " "
    if val < 100:
      valstr = valstr + " "
    if val < 10:
      valstr = valstr + " "
    print ( str(valstr) + str(primes[j]))
print ("Time needed for calculation: " + str(time_needed))
print("All primes noted. Script ends.")

The error that occurs sometimes is

"Traceback (most recent call last):
File "python", line 58, in
RuntimeError: can't start new thread"

if I don't use the Time.Sleep(0.05).
It is not always the same thread and if I use it, I receive no error. As there is a lot of calculations in this script, it would be better without this statement.


text:
Q: (arrays) how to move a range of elements to another position i have a dynamic html table, generated with php, with data from mariadb
i need an algorithm (preferently in sql, or in php if not) to re-order the rows and submit... like this (where x = checkbox, o = radiobutton):
range dest data
---------------
.     .    one
x     .    two
x     o    three
x     .    four
.     .    five

[submit move]

the idea is similar to excel> select rows> move+insert rows... first you select a source RANGE (i did with js, just select first, last, and the range selects itself), then you select an insert destination position, then submit... in this example the result will be
one
five
two
three
four

as you can see the selected range [two..four] has advanced to specified position, shifting the overwriten items to space left by the range, preserving the length but just changing indexes... i imagine some sql commands like
UPDATE my_table SET index=index+$diff WHERE index>=$start AND index<=$end;

seems easy but is not so much (for me at least) since there are many different cases with different range lenghts, positions, etc...  i couldn't found any native sql or php function or snippet to do it
please if you have some knowledge or idea about some related algorithm i will be very thankful ... and forgive my bad english xD

A: due the question popularity xD i tried to find an answer myself... and share it with the hope will be useful to somebody, and hopufully motivate someone else to find a better solution
consider this initial set of elements (only indexes shown), and that we want to move elements from 2 to 4 to position 6... we expect a final result
orig  1 2 3 4 5 6 7 8 9
src     2 3 4
dest            6
final 1 5 6 7 8 2 3 4 9

first thing i did was to calculate the source range length, that is 4 -2 = 2
then saved the source range in a temp table, or by marking elements someway, or by writing down unique id's, etc...
until the indexes could simply be duplicated, imagine instead we take away the source range and left a "hole" of "length +1" elements in the list
  2 3 4
  ^ ^ ^
1 . . . 5 6 7 8 9

then the key is to shift the remaining elements to the opposite side "length +1" positions, can be done by substracting "length" to remaining elements
          < < <
1 5 6 7 8 . . . 9

take note the remaining items you shifted is 4, this is the difference between after the last source element and the last destination position... the last destination position is destination + "length" (6 +2 = 8)
in the case the movement is done to the opposite direction (i.e. the source range to their left) all ranges, shifts and operations must be corrected acordingly
now you can set source range to his new position by simply correcting the indices adding "remaining length" (4) to indexes
  > > > > 2 3 4
1 5 6 7 8 . . . 9

be aware destination position can't go outside (first) and (last -"length") positions, i.e. (1 and 7) for this case... and if first source index equals destination the list wouldn't change
so to conclude, there 3 cases with slightly different operations:

*

*move the source range to their right

*move it to same position (do nothing)

*move it to left

now you could post a pseudocode snippet below as a complement :) ...  thanks


text:
Q: Are there Algorithms for generating textures using vector primitives? I'm doing image generation with Canvas, for fun and I'd like to generate textures using canvas alone.  That is I'd like to stay just in canvas and generate paper, stone, sand, wood textures.  I've tried but they tend to remain vector looking.  But, I'm wondering if there are algorithms that I could look at to help me design some textures?

A: I haven't found decent algorithms for "organic" textures.
Good looking vectors are often extremely complex to reflect the complexity of the "real thing".
If you want to experiment:

*

*download a trial version of Adobe Illustrator,

*open a basic texture image,

*run the "trace" procedure which turns the raster image into vector pieces,

*export the vector pieces as canvas drawing commands using a plug-in (eg: http://drawscri.pt/ )

*experiment!


text:
Q: Validate ending letters only I want too validate endings "uu", "ha" and "cross" at the end of the words that users are going to type in... please see "//" in "script" tags of what I mean:)
Here's my html form:
<form name="myForm" action="haha.php" onsubmit="return validateForm()" method="post">

Something:

    <input type="text" name="form" id="box" >
    <input type="submit" value="Submit" id="but" >
</form>

And my java script validation...
function validateForm() {
    if( document.myForm.form.value == "" ) {
        document.getElementById('check').innerHTML = 'Please fill in the form:) ';
        return false;
    }

    //ok so here's an example of what I'm trying to achieve...
    if( document.myForm.form.value == endings "uu" "ha" cross" ) --//please correct- endings "uu" "ha" cross" --    {
        return true;
    }
}

A: Try to use regular expression to test that string ends with one of the given substrings:
if (/(uu|ha|cross)$/.test(document.myForm.form.value)) {
    return true;
}

A: if(submittedValue.slice(-2) == "uu" || submittedValue.slice(-2) ==  "ha" || submittedValue.slice(-5) ==  "cross" )     {
    return true;
}


text:
Q: GDI+ get animated gif loop count always 1 less than it really is? I'm using gdi+ to get animated gif loop count,
when I test the code with gifs made by myself, I found the count is always 1 less than it actually is as played in IE11 and Chrome,
except I set the loop count as 1, it will be 1, it's right,
if I set the loop count as 2,3, and so on, the code get it as 1,2, and so on.
Although the gifs with loop count 1 and 2 are played correctly in IE11 and Chrome,
the code get the same value as 1.
I can't guess if there is anything in gif file expresses it will repeat or not.
After I use command tool gifsicle to list the gif infomation, I found the difference of the loop count 1 and 2 gifs, the loop count 2 gif has a line

loop count 1

while loop count 1 gif has not.
But I don't know what's the code of gdi+ to distinguish the difference.
This is the code:
// new Bitmap
m_pBitmap = new Bitmap(szFilePath);

// get loop count
PropertyItem* pPropLoopCount;
UINT uSize = m_pBitmap->GetPropertyItemSize(PropertyTagLoopCount);
PropertyItem* pPropertyItem = (PropertyItem*)new char[uSize];
Status status = m_pBitmap->GetPropertyItem(PropertyTagLoopCount, uSize, pPropertyItem);
if (Status::Ok != status)
    return false;
m_sLoopCount = *((SHORT*)pPropLoopCount->value);

document of MSDN just said:

For an animated GIF image, the number of times to display the
  animation. A value of 0 specifies that the animation should be
  displayed infinitely.

about PropertyTagLoopCount.
After all, two questions:

*

*Is loop count the code got means actual play times minus 1?

*What's the code of gdi+ to distinguish actual loop count 1 and 2 gifs?

A: I ran into the same issue in C# using GetPropertyItem. I believe GetPropertyItem(20737) always returns a value even if it's missing from the file.
This is how the actual byte data is stored:
http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension
How to decode the application extension block of GIF?
As you can see from this comment, the rules are:

*

*Value 0 in "NETSCAPE2.0" means loop forever.

*Missing "NETSCAPE2.0" block means 0 repetitions = loop once.

*Value 1 in "NETSCAPE2.0" means 1 repetition = 2 loops.

*Value 2 in "NETSCAPE2.0" means 2 repetitions = 3 loops.

The way I solved it was to search for the NETSCAPE bytes and only use the GetPropertyItem value if it exists.
I've got a gist covering these scenarios in C# if it helps at all:
https://gist.github.com/NeilBostrom/8dde778f06e6f337ad73aea6e0152bbc


text:
Q: Find $x$ which satisfies the following equation Find $x$ such that
$\dfrac{6(3x^2-27)8x^2}{4(9-3x)(x^2+3x)} = \dfrac{\tan(x+4)}{\ln(x+\frac{1}{4})}$
I've managed to reduce the left hand side so that
$-12x= \dfrac{\tan(x+4)}{\ln(x+\frac{1}{4})}= \dfrac{\tan(x+4)}{\ln(\frac{4x+1}{4})} = \dfrac{\tan(x+4)}{\ln(4x+1)-\ln(4)}$
But I'm unsure on how to deal with both the $\tan(x+4)$ and $\ln(4x+1)$. I've tried using the maclaurin series expansion for $\tan(\alpha)$ and $\ln(1+\beta)$, with $\alpha=x+4$ and $\beta=4x$ but this just gives an over complicated fraction which I cannot reduce to get a solution for $x$.


text:
Q: Count Characters in Perl I need to count the letter "e" in the string
$x="012ei ke ek ek ";
So far, I've tried with a for-loop:
$l=length($x);

$a=0;
for($i=0;$i<$l;$i++)
{$s=substr($x,$i,1);
if($s=="e")
{$a++;}

print $a;

A: Your code has  some problems. You forgot to close  the for loop brace,
and in Perl == is supposed to compare numbers. Use eq for strings.
It is  also recommended that  you use  warnings and enable  strict mode,
which would  have helped  you debugging  this. In  your case,  since e
would be  treated as 0,  so the other one  char substrings, 1  and 2
would be the only characters not equal to e when compared with ==. A
cleaned up version of your code could be written as:
use warnings;
use strict;

my $x = "012ei ke ek ek ";
my $l = length $x;

my $count = 0;

for(my $i = 0; $i < $l; $i++) {
    my $s = substr($x, $i, 1);
    $count++ if ($s eq "e");
}

print $count;

There are multiple  ways to achieve this.  You could use a  match with a
group,  which if  global returns  all the  occurrences in  list context.
Since you want  the number, take this result in  scalar context. You can
achieve this for example with:
my $count = () = $string =~ /(e)/g;

Or:
my $count = @{[ $string =~ /(e)/g ]}

Another way is  to split the string into characters  and grep those that
are e:
my $count = grep $_ eq 'e', split //, $string;

And probably the most compact is to  use tr which returns the count of
characters in scalar context, although  this does restrict this usage to
counting characters only:
my $count = $string =~ tr/e//;

A: You compare characters with the numeric operator (==) when you should use the string comparison eq.  If you had used the warnings pragma you would have seen that.
You code should have looked like:
#!/usr/bin/env perl
use strict;
use warnings;
my $x = "012ei ke ek ek ";
my $l = length($x);
my $a = 0;
for ( my $i = 0; $i < $l; $i++ ) {
    my $s = substr( $x, $i, 1 );
    if ( $s eq "e" ) {
        $a++;
    }
}
print "$a\n";

Proper indentation and the use of the strict and warnings pragmas will avoid and/or catch unintentional, dumb errors.
A much more Perl-ish (and shorter) way to achieve your answer is:
perl -le '$x="012ei ke ek ek";@count=$x=~m/e/g;print scalar @count'
4

This matches globally and collects all the matches in list context.  The scalar value of the list gives the number of occurrences you seek.
Another way is to use tr
perl -le '$x="012ei ke ek ek";print scalar $x=~tr/e//'
4

A: @sidyll Already mentioned what is the problem in your script and all  of the possible ways, but TIMTOWTDI.
$x="012ei ke ek ek ";
my $count;
$count++ while($x=~/e/g);
print $count;


text: Q: (404)Not Found Error - The requested resource is not available I try to access a web service server with its wsdl address. I mean, I am the client. I used intellij idea to generate the codes. But whenever I try to run my code I get this error. Can this be my fault or do I just need to warn server side?


text:
Q: When running in local ide all outputs are correct but while submitting in codeforces it is throwing error Following is the code which is running as expected in local ide but when i am submitingh the code in codeforces it is displaying that the outputs are wrong.Question is enter link description heredense array
 #include<bits/stdc++.h>
using namespace std;
int main()
{   int t;
    cin>>t;
    while(t--)
    {
    std::vector<int> my;
    int x,i,a,j,bno,sno;
    cin>>x;//enter number of elements
    for(i=0;i<x;i++)
    {
        cin>>a;//enter element
        my.push_back(a);
    }
    for(i=1;i<my.size();i++)
    {
        for(j=i-1;j<my.size();j++)
        {
            bno=(my[j]>my[j+1])?my[j]:my[j+1];
            sno=(my[j]<my[j+1])?my[j]:my[j+1];
            if(bno>(2*sno))
            {
             auto it=my.begin()+j+1;
             my.insert(it,(2*sno));
             break;
            }
        }
    }
    for(i=0;i<my.size();i++)
    {
        if(my.back()==0)
        {
            my.pop_back();
        }
    }
    cout<<(my.size()-x)<<endl;
    }
}

A: Your problem is the following:
#include<bits/stdc++.h>

This is a header-file created by Bjarne Stroustrup(the creator of C++) and is only meant for beginners to use(so that they don't have to pick the headers they need to include).
Simply replace it with:
#include <iostream>
#include <vector>

On a related note: You seem to be a total beginner to c++(e.g. You are using using namespace std;, which is bad practice; google it). You really shouldn't be doing competitive programming. Better start with the basics.


text:
Q: Is there a way to run an R code from an html UI? I've made an application using flask and html which needs to run an R code in the background. The fetching of input and output is handled by flask but I need to run the R code to calculate the output. Is there any function for this?

A: Send the data to Flask (with HTML form or you can also use Javascript AJAX if needed)
then run your R code and get the output like this:(I don't know any thing about R this is an example):
python code:
R_code_resault = os.popen(f'Rcompiler Rfile {arg1} {arg2}').read()
you got arg1&2 from HTML in flask
then render an HTML template and pass the R_code_resault variable to it and then use it in suitable position and place using Jinja


text:
Q: Location of Templates on Netbeans 7.2 MacOSX 10.8.2 Where are the template files created under Tools > Templates located on MacOSX?
As other posts suggested I've checked ~/.netbeans/[version]/config/Templates, but I can only find templates for an older version (7.1.1) here, and not for the 7.2 installed.
the folder ~/.netbeans/7.2/ cannot be found?

A: Found it after using terminal to search for a specific file:
find / -name "temlatefilename*" -print

Version 7.2 locates the Template files at:
~/Library/Application Support/NetBeans/7.2/config/Templates/


text:
Q: Write a migration with reference to a model twice I have a message model (Message) and this models as a userTo and userFrom, so two references to User. How can i write the migration? My user model is User.
Thank you

A: Here's a complete answer to this issue, in case people visiting this question are having a hard time putting everything together (as I was when I first looked into this).
Some parts of the answer take place in your Migrations and some in your Models:
Migrations
class CreateMessages < ActiveRecord::Migration
  create_table :messages do |t|
    def up
      t.references :sender
      t.references :recipient
    end
  end
end

Here you are specifying that there are two columns in this table that will be referred to as :sender and :recipient and which hold references to another table. Rails will actually create columns called 'sender_id' and 'recipient_id' for you. In our case they will each reference rows in the Users table, but we specify that in the models, not in the migrations.
Models
class Message < ActiveRecord::Base
  belongs_to :sender, :class_name => 'User'
  belongs_to :recipient, :class_name => 'User'
end

Here you are creating a property on the Message model named :sender, then specifying that this property will be referencing an instance of the User class. Rails, seeing the "belongs_to", will look for a column in your database called "sender_id", which we defined above, and use that to store the foreign key. Then you're doing the exact same thing for the recipient.
This will allow you to access your Sender and Recipient, both instances of the User model, through an instance of the Message model, like this:
@message.sender.name
@message.recipient.email

Here is your User Model:
class User < ActiveRecord::Base
  has_many :sent_messages, :class_name => 'Message', :foreign_key => 'sender_id'
  has_many :received_messages, :class_name => 'Message', :foreign_key => 'recipient_id'
end

Here you are creating a property on the User Model named :sent_messages, specifying that this property is related to the Message Model, and that the foreign key on the Message model which relates to this property is called 'sender_id'. Then you are doing the same thing for received messages.
This allows you to get all of a users sent or received messages by doing something like this:
@user.sent_messages
@user.received_messages

Doing either of these will return an array of instances of the Message model.

A: In the migration, create two different columns for each kind of user. For example:
add_column :messages, :sender_id, :integer
add_column :messages, :receiver_id, :integer

Then in the model, that's where the logic to map each column to the User class happens:
belongs_to :sender, :class_name => 'User'
belongs_to :receiver, :class_name => 'User'

Of course, use your own words for sender and receiver, but Rails will automatically associate sender to the sender_id column (and the same logic for receiver)
You will then be able to interact with both user user.sender and user.receiver.


text:
Q: Solving a solved Geometric problem in an alternate way. This question (circles, power of point, cross ratios ) has been solved using Steward's theorem. I try to solve it in another way but find myself stuck at some point.

If we let $BC = x, CD = y, DP = z$, the required equality ($CD \cdot BP = BC \cdot DP$) is just $y(x + y + z) = x(z)$ or more simply is $y(x + y) + y(z) = x(z)$.
Interpreted graphically, it is merely an equality of some areas as [pink] + [blue] = [blue] + [brown].
Even more simply put is that we are "required to show [pink] = [brown]".
According to a fact about parallelogram, if we can show that $PSR$ is a straight line, then we are done.
Or alternately, we can assume $PST$ is a straight line cutting the perpendicular erected through $B(C)$ at $T$, can we show that $BT = x$?
How can I continue?


text:
Q: Unity Constructor Injection - Overkill or alternative approach? I'm currently learning about Unity and so far, everything I tried is working fine and as expected. However, what really bugs me is the injection of dependencies into the constructor.
Consider the following service:
public class ReallyComplexService : IReallyComplexService {

    public ReallyComplexService(INeedThisRepo repo1, INeedThisRepo2 repo2, INeedThisRepo3 repo3, IAlsoNeedThisDependency dependencyX, INeedAUnitOfWork uow, INeedCoffeeNow coffee, IShouldBetterAskJonSkeet skeet)
    {
        this.Repo1 = repo1;
        this.Repo2 = repo2;
        this.Repo3 = repo3;
        this.AdditionalDependency = dependencyX;
        this.UnitOfWork = uow;
        this.Coffee = coffee;
        this.JonSkeet = skeet;

        skeet.Ask();
    }

}

Services can get reeeeeally big, especially when they're more than just a service layer for some website that is completely functional with writing stuff into / reading from a database. E.g. a Windows service that serves complex tasks (please record that Videostream from this IP camera and notify me if the camera is offline). This may turns constructors into a completely unreadable wall of code.
Is there an alternative way to satisfy the dependencies of a class?


text:
Q: Error 403 Forbidden when trying to create an Azure Storage Table from Azure Websites I am getting the error below when trying to create a new table in a new Azure storage account from Azure Websites. It works when I try to do it from my local machine. It also works when I use my old Azure storage account.

System.AggregateException was unhandled by user code
  HResult=-2146233088   Message=One or more errors occurred.
  Source=mscorlib   StackTrace:
         at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
         at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
         at System.Threading.Tasks.Task1.get_Result()
         at MyProject.Data.Repositories.MatchRepository..ctor(CloudStorageAccount
  storageAccount) in
  D:\home\site\approot\src\MyProject.Data\Repositories\MatchRepository.cs:line
  15
         at MyProject.Startup.ConfigureStorageRepositoriesAndServices(IServiceCollection
  services, CloudStorageAccount storageAccount) in
  D:\home\site\approot\src\MyProject\Startup.cs:line 98
         at MyProject.Startup.ConfigureServices(IServiceCollection services) in D:\home\site\approot\src\MyProject\Startup.cs:line 86
  InnerException:
         ErrorCode=-2147217005
         HResult=-2147217005
         Message=
     403
  Server failed to authenticate the request. Make
  sure the value of Authorization header is formed correctly including
  the signature.
  Primary
  0d907af5-0002-0117-126c-ea972b000000
        Tue, 08 Sep 2015 19:31:47
  GMT   Tue, 08 Sep 2015 19:31:43
  GMT   Tue, 08 Sep 2015 19:31:47 GMT
AuthenticationFailed
      Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the
  signature. RequestId:0d907af5-0002-0117-126c-ea972b000000
  Time:2015-09-08T19:31:46.4165753Z

      StorageException
      -2146233088
      Unexpected response code, Expected:OK or NotFound, Received:Forbidden
      Microsoft.WindowsAzure.Storage
         at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.<ExecuteAsyncInternal>d__41.MoveNext()</StackTrace>
  </ExceptionInfo> </RequestResult>
         Source=Microsoft.WindowsAzure.Storage
         StackTrace:
              at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.<ExecuteAsyncInternal>d__41.MoveNext()
           --- End of stack trace from previous location where exception was thrown ---
              at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)
              at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)
              at Microsoft.WindowsAzure.Storage.Table.CloudTable.<>c__DisplayClass51_0.<b__0>d.MoveNext()
           --- End of stack trace from previous location where exception was thrown ---
              at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)
              at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)
              at Microsoft.WindowsAzure.Storage.Table.CloudTable.<>c__DisplayClass41_0.<b__0>d.MoveNext()
           --- End of stack trace from previous location where exception was thrown ---
              at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)
              at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)
              at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
              at MyProject.Data.TableRepository.<CreateTableAsync>d__13.MoveNext() in
  D:\home\site\approot\src\MyProject.Data\Common\TableRepository.cs:line
  29
           --- End of stack trace from previous location where exception was thrown ---
              at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)
              at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)
              at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
              at MyProject.Data.Repositories.MatchRepository.d__2.MoveNext()
  in
  D:\home\site\approot\src\MyProject.Data\Repositories\MatchRepository.cs:line
  20
         InnerException:
              HResult=-2146233088
              Message=Unexpected response code, Expected:OK or NotFound, Received:Forbidden
              Source=Microsoft.WindowsAzure.Storage
              StackTrace:
                   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.d__4`1.MoveNext()
              InnerException:

A: It seems that you are using your manage keys in a wrong way.
web.config:
<configuration>
    <appSettings>
        <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=storagesample;AccountKey=nYV0gln9fT7bvY+rxu2iWAEyzPNITGkhM88J8HUoyofpK7C8fHcZc2kIZp6cKgYRUM74lHI84L50Iau1+9hPjB==" />
    </appSettings>
</configuration>

c# code:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.AppSettings["StorageConnectionString"]);

source:
https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-tables/


text:
Q: Terminal errors with npm -install on mac These are the errors I see when I run npm install, tried a bunch of things by search the error, but so far none has worked, sorry I don't have much more details other than:
*
MAC OS Monterey 12.5
node v8.17.0
npm default 8.11.0 bu ran as nvm use 16*
terminal error


text:
Q: How do I branch if message.properties-code exists I want to branch if a message-property-code does exist or not.
<g:if test="${message(code: 'default.code.foo')}">
  true
</g:if><g:else>
 false
</g:else>

should answer true if there a message property named default.code.foo and false if not.
It fails because it answers the code if there is no property for it.

A: Can't you supply a default that's a blank string?
<g:if test="${message(code: 'default.code.foo', default:'')}">
  true
</g:if><g:else>
 false
</g:else>

This will equate to false under Groovy's truth

A: Then why don't you just test if the String returned is the code itself?
<g:if test="${message(code: 'default.code.foo') == 'default.code.foo'}">
  true
</g:if><g:else>
 false
</g:else>

If you need to do this in several places and want to make the code a bit more concise, then put this logic in a tag lib.
class MsgTagLib {
    static namespace = 'msg'

    def messageSource

    private static final NO_ARGS = [].toArray();

    def exists = {attrs ->

        try {
            messageSource.getMessage(attrs.code, NO_ARGS, Locale.default)
            out << true
        } catch (NoSuchMessageException e) {
            out << false
        }
    }
}

You could then call this in a GSP using:
<msg:exists code="default.code.foo"/>

Note

*

*The tag lib above is 100% untested, beware!

*The exists tag in it's form above doesn't support parameterized messages


text:
Q: array sort alphabetic order into dropdown javascript I have a empty dropdown list and a array however i want to display my array in my dropdown list in alphabetic order. How can i achieve this ?
<select id="dropdown">
</select>

var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];

A: var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];

array.sort(function(val1 , val2){
  return val1.localeCompare(val2);
});

console.log(array); // ["engraved", "flask", "frames", "jewelerybox", "stickers", "treats", "vintage"]


text:
Q: what does class_mode parameter in Keras image_gen.flow_from_directory() signify? train_image_gen = image_gen.flow_from_directory('/Users/harshpanwar/Desktop/Folder/train',
                                               target_size=image_shape[:2],
                                               batch_size=batch_size,
                                               class_mode='binary')

In the above code snippet what does class_mode='binary' signify. I think it is for the number of categories of images. I am using this code for training a image recognition classifier in Keras to classify between 2 different categories like dog and cat. So if class_mode='binary' is for signifying two categories how do we make it for three or more?

A: class_mode: One of "categorical", "binary", "sparse", "input", or None. Default: "categorical". Determines the type of label arrays that are returned: - "categorical" will be 2D one-hot encoded labels, - "binary" will be 1D binary labels, "sparse" will be 1D integer labels, - "input" will be images identical to input images (mainly used to work with autoencoders). - If None, no labels are returned (the generator will only yield batches of image data, which is useful to use with model.predict_generator()). Please note that in case of class_mode None, the data still needs to reside in a subdirectory of directory for it to work correctly.

A: Say you have N classes in your dataset. If you have 4 labels, dog (index 0), cat (1), donkey (2) and human (3), N would be 4.
Class modes:

*

*"categorical": 2D output (aka. list of numbers of length N), [0, 0, 1, 0], which is a one-hot encoding (only one number is 1/ "hot") representing the donkey. This is for mutually exclusive labels. A dog cannot be a cat, a human is not a dog.

*"binary": 1D output (aka. 1 number), which is either 0, 1, 2, 3 ... N. It is called this because it is binary if there are only two classes (IMHO this is a bad reason), source. I suggest using "binary" just for single label classification, because it documents-in-code, your intention.

*"sparse": After digging in the code, this is the same as "binary". The logic is done with elif self.class_mode in {'binary', 'sparse'}:, and the class_mode is not used after that. I suggest using "sparse" for multilabel classification though, again because it documents-in-code, your intention.

*"input": The label is literally the image again. So the label for an image of the dog, is the same dog picture array. If I knew more about autoencoders I might have been able to explain further.

*None: No labels, therefore not useful for training, but for inference/ prediction.

The TensorFlow documentation is here but I think it should go into more depth for class_mode:

One of "categorical", "binary", "sparse", "input", or None. Default: "categorical". Determines the type of label arrays that are returned: - "categorical" will be 2D one-hot encoded labels, - "binary" will be 1D binary labels, "sparse" will be 1D integer labels, - "input" will be images identical to input images (mainly used to work with autoencoders). - If None, no labels are returned (the generator will only yield batches of image data, which is useful to use with model.predict()). Please note that in case of class_mode None, the data still needs to reside in a subdirectory of directory for it to work correctly.

Sparse is the same as binary?:
As you can see in my search results, sparse is only checked twice (line 2 and 4 in search results). I believe the intention of "sparse" is for multi-label classification, and "binary" is designed for single-label classification (Hot-dog vs. No hotdog), but currently there is no difference, since the behaviour is the same:


text:
Q: How can I use web-deploy on github actions? I have my domain and my hosting through one.com and I'm tired of moving individual files through filezilla and wanted to automate that process using github actions.
I guess I'll start out by saying I'm completely new to this and this is my first time trying to setup an action. Basically what I want is to just push the code to my github repo and then it gets build and sent to my host. Kinda like how it is with Netlify.
I stumbled upon this https://github.com/SamKirkland/web-deploy which should do the trick. I've seen tutorials using this method on youtube, but I guess they have a different provider than I do making it easier.
This is what information I have to go off of and I hope it will be enough to set it up:
Host: ssh.one-example.com
Username: one-example.com
Password: the one you chose for SSH in your Control Panel
Port: 22
and this is what I put in the yml file:
on:
  push:
    branches:
      - main
name: Publish Website
jobs:
  web-deploy:
    name:  Deploy Website Every Commit
    runs-on: ubuntu-latest
    steps:
      - name:  Get Latest Code
        uses: actions/checkout@v3

      - name:  Sync Files
        uses: SamKirkland/web-deploy@v1
        with:
          target-server: ${{ secrets.ftp_host }}
          remote-user: ${{ secrets.ftp_username }}
          private-ssh-key: ${{ secrets.ftp_password }}
          destination-path: ~/destinationFolder/

I've tried having the target server both be ssh.one-example.com (obviously using my own here) and I've tried one-example.com@ssh.one-example.com
But I'm ending up with the following error when the action is running:
Error: Error: The process '/usr/bin/rsync' failed with exit code 255

So safe to say I'm a little lost and would like some guidance on how to make it work. Is it what I'm typing that's the issue, is it the host? And if so how do I fix it?
Any help is much appreciated.

A: Try an SSH action first, to see if you actually can open an SSH session. This is just for testing the connection: try and execute on the remote server a trivial command (ls, or pwd)
Then, regarding your current original action, check the error messages before your "The process '/usr/bin/rsync' failed with exit code 255".
See as an example of previous error messages SamKirkland/web-deploy issue 5 (not yet resolved).


text:
Q: Why `python main.py\` (different with `python main.py`) executable on Windows? # a.py, with `import b` version.
print("# With `import b`")
import sys, b
print(sys.path)

# a.py, without `import b` version.
print("# Without `import b`")
import sys
print(sys.path)

# b.py
print('b.py executed')

When I execute python a.py(With import b version), import b works well but python a.py\ not.
I run it on Windows 11. I guess this happen's only on Windows, not linux.
When I check system path using sys.path, python a.py\ contains:
(currentDir)/a.py, not (currentDir)
I wonder why python main.py\ is executable on Windows. And I guess it could induce some bugs for python-based programs.
click here to view what is going here on image

A: On Windows, backslash is the path separator, thus python a.py\ tries to run a directory named "a.py" as a module (ie. it looks for a.py\__main__.py). In your case, Python will error with a message that looks something like this:
can't open file 'c:\some\path\here\a.py\': [Errno 22] Invalid argument

because "a.py" is actually a file, so attempting to treat it as a directory fails.


text:
Q: Passing values from one function to another with React navigation 5 I would like to pass the value "Hello" from App.js to screen1.js. Snack: https://snack.expo.io/@mobshed/passing-data-between-functions
Thank you for your help!
App.js
import React, { useState, useEffect, Component } from "react";
import MyScreen from './screen1'

export default function Root() {
    return <MyScreen show="Hello" />;
}

screen1.js
import { NavigationContainer } from "@react-navigation/native";
import {
  createStackNavigator
} from "@react-navigation/stack";
const Stack = createStackNavigator();

function screenPage ({show}) {
  alert(show)
  return (<View style={{ justifyContent: "center", flex: 1}}><Text>Hello world</Text></View>)
}

export default function Root({ navigation }) {
  return (
    <NavigationContainer>
    <Stack.Navigator
      screenOptions={{
        headerTitleAlign: "center",
        gestureEnabled: false,
        gestureDirection: "horizontal"
      }}
    >
      <Stack.Screen
        options={{
          headerShown: false
        }}
        name="screenPage"
        component={screenPage}
      />
    </Stack.Navigator>
     </NavigationContainer>
  );
}

A: in screen1.js:
import { NavigationContainer } from "@react-navigation/native";
import {
  createStackNavigator
} from "@react-navigation/stack";
const Stack = createStackNavigator();

function screenPage ({route}) {
  const {show} = route.params;
  alert(show);
  return (<View style={{ justifyContent: "center", flex: 1}}><Text>Hello world</Text></View>)
}

export default function Root({ navigation, show }) {
  return (
    <NavigationContainer>
    <Stack.Navigator
      screenOptions={{
        headerTitleAlign: "center",
        gestureEnabled: false,
        gestureDirection: "horizontal"
      }}
    >
      <Stack.Screen
        options={{
          headerShown: false
        }}
        name="screenPage"
        component={screenPage}
        initialParams={{show: show}}
      />
    </Stack.Navigator>
     </NavigationContainer>
  );
}

Another way, you can pass params something like this:
<Button
        title="Done"
        onPress={() => {
          // Pass params back to screenPage
          navigation.navigate('screenPage', { show: "hello" });
        }}
      />

A: OK, found it! Thanks Khanh for putting me on the right path earlier before you deleted your answer
import { NavigationContainer } from "@react-navigation/native";
import {
  createStackNavigator
} from "@react-navigation/stack";
const Stack = createStackNavigator();

function screenPage ({route}) {
  alert(route.params.user)
  return (<View style={{ justifyContent: "center", flex: 1}}><Text>Hello world</Text></View>)
}

export default function Root({ navigation, show}) {
  return (
    <NavigationContainer>
    <Stack.Navigator
      screenOptions={{
        headerTitleAlign: "center",
        gestureEnabled: false,
        gestureDirection: "horizontal"
      }}
    >
      <Stack.Screen
        options={{
          headerShown: false
        }}
        name="screenPage"
        component={screenPage}
        initialParams={{ user: show }}
      />
    </Stack.Navigator>
     </NavigationContainer>
  );
}


text:
Q: Micro services and PubSub: how to make sure a service consumes the right events I have a microservices architecture for an app.
I have a service S1 that can fetch data and store it somewhere. Then 2 services, S2 and S3, both running very different ML tasks.
When S2 or S3 need data, they publish a message to the PubSub on a topic called fetch_request.
The service that fetches data continiously pulls from this topic, fetches the data. When it finishes a task, it publishes a message on a topic called "fetch_done" to let the service that made the request know that the data has been fetched.
My question is: how to make sure S2 and S3 don't consume messages from "fetch_done" that they were not supposed to consume ?
I thought about solutions but I'm not sure:

*

*may be when trying to pull from "fetch_done" I could add a filter to only pull message if they contain a UUID that I would have written in the initial request message ? This way, you can only pull a message if you know the ID. Of course the service that fetches data will then need to put the id in the response.

*Kinda the same idea, but may be just add the name of the requesting service in the initial request instead of an id ? The problem with this one is that eventually, a service could impersonate another service if I'm correct, and as I probably won't be the sole developer of every service in the app, I think the UUID is a better idea.

*Something obvious I completely missed ?

A: There is several patterns that you can implement. IMO it's better to have 1 subscription per service. Like that, the S1 post a message in a topic and the message is duplicated in each subscription.
Now, you can:

*

*Put an attributes in the message send by S2/S3 and received by S1. According to this attribute, S1 post in the topic for S2 or in the topic for S3. I don't really like this solution because there is too much responsibility on the S1 service side

*Put an attributes in the message send by S2/S3 and received by S1. This time, the S1 simply mirror the attribute in the message sent in response in the only one topic. When you create the S2 and S3 subscription, you add a filter to received only the message with the corresponding attribute. Like this, for example, only the message for S2 are filtered and delivered in the S2 subscription.

*Put an attributes in the message send by S2/S3 and received by S1. This information is mirrored in the body or in the attribute of the messages by the S1 service when it's posted. No filter on the PubSub subscription, the S2 and S3 service received all the message and checks on their side if the message is for them (and continue the processing) or not (and trash the message -> Ack correctly but do nothing).

In any case, because the communication is async you need a element to distinguish the correct receiver of the messages. The 2nd solution, with the pubsub filter is the most efficient (I think).


text:
Q: Why is Tomcat 7 on 32 Bit CPU/OS/Java so much slower than on 64 Bit?                         Raspberry Pi3   Raspberry Pi3   Odroid C2       Odroid XU4
                        1,20 GHz        1,20 GHz        1,5 GHz         2,0 GHz
                        Debian 32 Bit   SuSE 64 Bit     Ubuntu 64 Bit   Ubuntu 32 Bit
Start Apache Tomcat     04:30,00        00:29,06        00:27,45        04:08,39
1. page (1. request)    00:50,00        00:03,91        00:03,66        00:24,75
1. page (2. request)    00:03,30        00:00,79        00:00,77        00:02,39

I'm working on an IoT kind of project and needed to test if some web frontend implemented in Java using Tomcat as web server is "fast enough" on our possible hardware. We need to choose between Raspberry Pi3, Odroid C2 and Odroid XU4. Pi3 and C2 both have a 64 Bit CPU with slightly different performance according to their specs, XU4 has a 32 Bit CPU only and should be faster as the other two in theory as well. The important thing is that Pi3 is by default running a 32 Bit OS even if it has a 64 Bit CPU, the XU4 is running 32 Bit as well, but the C2 is running a 64 Bit OS incl. 64 Bit Java etc.
Comparing all those devices in default settings we found that the C2 was significantly faster than the other both. It was 4+ minutes vs. ~30 seconds for a restart of Tomcat with some test application of ours. Additionally, tools like htop showed that most of the runtime all cores of the C2 were used, whereas Pi3 and XU4 were mostly only able to put one core under load. That great performance difference was the same after Tomcat has loaded and we were able to browse through our test app: It was ~1,5 seconds vs. 4 to 5,5 seconds for just browsing some page with some CSS/JS.
While the default OS for the Pi3 is 32 Bit only, we were able to successfully install a special 64 Bit SuSE distribution. And guess what happened? The performance was much closer now to what we saw on the C2 already, almost the same for many tests, even though the Pi3 is clocked at only 1,2 vs. 1,5 GHz of the C2. Especially interesting was that now all cores of the Pi3 were under load most of the time as well, so overall behaviour was very much like the C2 now.
So by only switching to 64 Bit OS, Java etc. we saw that dramatically improvement in performance. Everything else was the same, same test app, Tomcat etc., nothing overclocked, no other storage or else. How can that be? What is responsible for that dramatic improvement?
With a 64 Bit OS we see that all cores of the devices are more under load compared to 32 Bit. But why should the Linux kernel scheduler care about if it's running on 32 or 64 Bit this much?
And if it doesn't and the difference comes from Java, why/how that? Shouldn't a 32 Bit and 64 Bit JVM perform almost identically in such a simple test? Shouldn't both especially put almost the same load on cores and not behave that different? The architecture of the OS shouldn't have any effect on how many threads are used inside the JVM, that is mostly under control of Tomcat and our test app and therefore didn't change. According to what I've read about performance of 32 vs. 64 Bit Java, the difference should be negligible in my use case. Additionally, other users with a better performance of a 64 Bit JVM don't seem to have a factor of 4 to 5 like I'm seeing and the differences on CPU load of individual cores aren't explained as well.
Our test is not I/O bound, we don't allocate much memory or work with many threads or such, it's almost strictly CPU, only compiling Java classes and publishing HTML, CSS and JS. But we see very different load on the cores depending on 32/64 Bit and very different performance results.
One of my colleagues said he read somewhere that Java is internally working with 64 Bit values only and that therefore on a 32 Bit CPU/OS more cycles are needed to process the same thing. I guess his source doesn't mean really everything, but only references/pointers to memory like for objects. But I can't believe that a 32 Bit JVM is internally really using 64 Bit pointers for no reason, especially if even optimizations like compressed oops exist. But might be an explanation, so any ideas on that?
If it's of any interest, the packages on the 32 Bit OS all had "armhf" as architecture, compared to "arm64" on the 64 Bit ones. I thought that might have influence on how Java was built, maybe really using 64 Bit pointers for some weird reason?
Java was OpenJDK 8 always, same architecture like OS and as current as the package manager of the OS provides. Pi3 with SuSE had 1.8_144, UB provided 1.8_131 for both 32 Bit and 64 Bit installations, all were server VMs. Additionally, the Linux Kernel was different e.g. Pi3 with SuSE vs. C2 and XU 4 with UB: Pi3 had some current 4.x, C2 some old 3.14 and XU 4 some current 4.9 as well.
So, any ideas on where the difference comes from? Thanks!

A: You've told you installed OpenJDK 8 from the standard package.
There has never been an optimized build of OpenJDK 8 for ARM 32 (at least on Debian and Ubuntu). The default package is built from "Zero" port which does not even have a JIT compiler.
root@localhost:~# java -server -version
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-1~bpo8+1-b11)
OpenJDK Zero VM (build 25.131-b11, interpreted mode)
        ^^^^^^^                    ^^^^^^^^^^^^^^^^

Try to install Oracle JDK manually from Java SE downloads page.
It has an optimized HotSpot JVM inside. And it indeed works much faster.
root@localhost:~# /usr/java/jdk1.8.0_131/bin/java -server -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) Server VM (build 25.131-b11, mixed mode)
     ^^^^^^^^^^^^^^^^^^^^^                    ^^^^^^^^^^

On the contrast, Aarch64 port of HotSpot JVM has been a part of OpenJDK for a long time. So, on a 64-bit OS the default OpenJDK package comes with HotSpot JVM that includes an optimizing JIT compiler.


text:
Q: ASIHTTPRequest and NSOperations - Is there any other way to implement Multithreading? Apart from  ASIHTTPRequest and using NSOperations what other ways are there to implement Multithreading? Please provide a link if there are any other ways to implement multithreading.
Also can we implement multithreading for AudioStreaming to retrieve from url..

A: Take a look at this method:
[NSThread detachNewThreadSelector:@selector(entryPointMethodForSecondThread) toTarget:objectWhereEntryPMethodDeclarated withObject:nil];

Note that you must create an autorelease pool for it in 'entry point method'.
The details check in the specification of NSThread.


text:
Q: drag and drop - how to simplify the droppable part? i have created the drag and drop work. Here i can place the drag content into particular area, but i have create each droppable function for draggable item. i need to simplify that.
$(document).ready(function() {
    $(".list").draggable({
    helper: 'clone',
    cursor: 'hand',
    revert: true,
    drag: function(ev, ui) {
        dragId = $(this).attr('id');
     }
    });

    $("#td1").droppable({
      accept: '#1',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td2").droppable({
      accept: '#1',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td3").droppable({
      accept: '#2',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td4").droppable({
      accept: '#2',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td5").droppable({
      accept: '#3',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td6").droppable({
      accept: '#3',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td7").droppable({
      accept: '#4',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

    $("#td8").droppable({
      accept: '#4',
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });

 });

This is my work: http://jsfiddle.net/thilakar/u7TnA/
Please help me out.
Thanks

A: You can define a function like below. Look at demo here.
function drop(selector, a) {
   $(selector).droppable({
      accept: a,
      activeClass: 'drop-active',
      hoverClass: 'dropareahover',
      drop: function(event, ui) {
        var targetId = $(this).attr("id");
        $("#" + targetId).each(function() {
            $(this).append(ui.draggable.text());
        });
      }
    });
}

$(document).ready(function() {
    $(".list").draggable({
    helper: 'clone',
    cursor: 'hand',
    revert: true,
    drag: function(ev, ui) {
        dragId = $(this).attr('id');
     }
    });

    drop("#td1", '#1');
    drop("#td2", '#1');
    drop("#td3", '#2');
    drop("#td4", '#2');
    drop("#td5", '#3');
    drop("#td6", '#3');
    drop("#td7", '#4');
    drop("#td8", '#4');
 });

EDIT
More compact sultion using arrays below. Live deme here.
function drop2(teacher, subjects) {
    $.each(subjects, function(index, subject) {
       $(subject).droppable({
          accept: teacher,
          activeClass: 'drop-active',
          hoverClass: 'dropareahover',
          drop: function(event, ui) {
            var targetId = $(this).attr("id");
            $("#" + targetId).each(function() {
                $(this).append(ui.draggable.text());
            });
          }
        });
    });
}

$(document).ready(function() {
    $(".list").draggable({
    helper: 'clone',
    cursor: 'hand',
    revert: true,
    drag: function(ev, ui) {
        dragId = $(this).attr('id');
     }
    });

    drop2('#1',['#td1', '#td2']);
    drop2('#2',['#td3', '#td4']);
    drop2('#3',['#td5', '#td6']);
    drop2('#4',['#td7', '#td8']);

 });


text:
Q: How to prove $M(x)$ is continuous? $f $ is continuous in $[a, b]$.
Show that $ M(x) = \sup\{f(y) : y ∈ [a, x]\}$ is continuous in $[a, b]$
I tried yo think in it as a constant function but this seems  not true

A: Hint
$M$ is indeed not a constant map. As $f$ is continuous on the compact $[a,x]$ it attains its maximum at a point $x_0 \in [a,x]$. Then separate the cases $x_0=x$ or not.

A: Choose any $\epsilon > 0$.
We know there is a $\delta > 0$ such that for any $u,v \in [a,b]$ with $|u - v| \leq \delta$ then $|f(u) - f(v)| \leq \epsilon.$
Choose any $x,y \in [a,b]$ and with $|x - y| \leq \delta$ we will show $|M(x) - M(y)| \leq \epsilon$. This will show $M()$ is uniformly continuous and we are done.
If $x = y$ there is nothing to prove, otherwise wlog assume $x < y$.
Note that for any $t \in [x,y]$ we have $|t - x| \leq \delta$, in particular
$|f(t) - f(x)| \leq \epsilon$.
This implies $f(t) \leq f(x) + \epsilon \leq M(x) + \epsilon$ for all $t \in [x,y]$.
Clearly $f(t) \leq  M(x) \leq M(x) + \epsilon$ for all $x \in [a,x]$.
Combining the above two observations we get
$f(t) \leq M(x) + \epsilon$ for all $t \in [a,y]$.
Taking supremums we have $M(x) \leq M(y) \leq M(x) + \epsilon$,
i.e., $|M(y) - M(x)| \leq \epsilon$ and we are done.


text:
Q: What is the best way to add APM to NuxtJS project What is the right way to configure/enable an Elastic APM agent in a Nuxtjs project?
I referred this documentation for a custom NodeJS app. The key takeaway was:

It's important that the agent is started before you require any other
modules in your Node.js application - i.e. before http and before your
router etc.

I added the following snippet in nuxt.config.js, but the APM agent is not started or working. I do not see any errors in the app logs.
var apm = require('elastic-apm-node').start({
  serviceName: 'nuxt-app',
  serverUrl: 'http://ELK_APM_SERVER:8200'
})

Is there any other way to do this?

A: We managed to get this working using a custom Nuxt module which explicitly requires the Node modules to instrument after it has initiated the APM module.
modules/elastic-apm.js:
    const apm = require('elastic-apm-node');
    const defu = require('defu');

    module.exports = function() {
      this.nuxt.hook('ready', async(nuxt) => {
        const runtimeConfig = defu(nuxt.options.privateRuntimeConfig, nuxt.options.publicRuntimeConfig);
        const config = (runtimeConfig.elastic && runtimeConfig.elastic.apm) || {};

        if (!config.serverUrl) {
          return;
        }

        if (!apm.isStarted())  {
          await apm.start(config);

          // Now explicitly require the modules we want APM to hook into, as otherwise
          // they would not be instrumented.
          //
          // Docs: https://www.elastic.co/guide/en/apm/agent/nodejs/master/custom-stack.html
          // Modules: https://github.com/elastic/apm-agent-nodejs/tree/master/lib/instrumentation/modules
          require('http');
          require('http2');
          require('https');
        }
      });
    }

nuxt.config.js:
    module.exports = {
      // Must be in modules, not buildModules
      modules: ['~/modules/elastic-apm'],

      publicRuntimeConfig: {
        elastic: {
          apm: {
            serverUrl: process.env.ELASTIC_APM_SERVER_URL,
            serviceName: 'my-nuxt-app',
            usePathAsTransactionName: true // prevent "GET unknown route" transactions
          }
        }
      }
    };

A: All the answers are outdated and from beginning incorrect (17.02.2022)
To make it work follow these steps:
1.) Create a nodeApm.js in your root dir with the following content:
const nodeApm = require('elastic-apm-node')

if (!nodeApm.isStarted()) {
    nodeApm.start()
}

2.) Use environment variables to store your config. For example:
ELASTIC_APM_SERVICE_NAME=NUXT_PRODUCTION
ELASTIC_APM_SECRET_TOKEN=yoursecrettokenhere

3.) Edit your package.json
"scripts": {
    // if you want apm also on dev to test, add it also here
    "dev": "node -r ./nodeApm.js node_modules/nuxt/bin/nuxt",
    ...
    "start": "node -r ./nodeApm.js node_modules/nuxt/bin/nuxt start",
...

! Be awere that in ~2022 the node_modules bin folder has lost the "." in the directory name
! In all othere anwsers people forget the start parameter at the end
"start": "node -r ./nodeApm.js node_modules/nuxt/bin/nuxt start",

A: Based on what I've seen it looks like there isn't a "right" way to do this with the stock nuxt command line application.   The problem seems to be that while nuxt.config.js is the first time a user has a chance to add some javascript, that the nuxt command line application bootstraps the Node's HTTP frameworks before this config file is required.  This means the elastic agent (or any APM agent) doesn't have a chance to hook into the modules.
The current recommendations from the Nuxt team appears to be

*

*Invoke nuxt manually via -r
     {
       "scripts": {
         "start": "node -r elastic-apm-node node_modules/nuxt/.bin/nuxt"
       }
     }

*Skip nuxt and use NuxtJS programmatically as a middleware in your framework of choice
     const { loadNuxt } = require('nuxt')
     const nuxtPromise = loadNuxt('start')
     app.use((req, res) => { nuxtPromise.then(nuxt => nuxt.render(req, res)) })

A: Based on Alan Storm answer (from Nuxt team) I made it work but with a little modification:

*

*I created a file named nodeApm.js where I added the following code:
const nodeApm = require('elastic-apm-node')

if (!nodeApm.isStarted()) { ... // configuration magic }

*In script sections I added:
"start": "node -r ./nodeApm.js node_modules/nuxt/.bin/nuxt"


text:
Q: ajax php file upload and php page failed to retrieve the file HTML:
<form id="imageform" method="post" enctype="multipart/form-data" >
    Upload image <input type="file" name="photoimg" id="photoimg" />
</form>

JavaScript:
$('#photoimg').change(function() {
    $("#preview").html('');
    $("#preview").html('');

    var data = new FormData();
    jQuery.each($('#photoimg')[0].files, function(i, file) {
        data.append('file-' + i, file);
    });

    $.ajax({
        url: 'ajaximage.php',
        data: data,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data) {}
    });
});

PHP:
print_r($_FILES);

Need help to resolve this issue.

A: You can not upload files via AJAX. You can use this ajax form plugin
Example


text:
Q: How to get last 7 days data if from and to date is null? I want to get all records from a table between two dates. If both the "from" and "to" dates are null then I want to fetch data of last seven days. I have written below query which is successfully giving data between two dates. How can I get last seven days of data default if both dates are null ?
SELECT
     COUNT(*), d.dd_value
FROM audit_transaction t,
     audit_master m,
     dd_type_details d
WHERE t.audit_id = m.audit_id
    AND d.dd_id = m.process
    AND m.activity_id = 9
    AND t.iscompleted = 'completed'
    AND audit_start_time BETWEEN '10/01/2018'::timestamp AND '10/17/2018'::timestamp
GROUP BY d.dd_value

A: You can use conditional WHERE clauses to achieve that.
If the timestamp is null it'll skip the clause on the right. Causing your query to only search the timestamps when you have one.
AND (v_start_date IS NULL AND v_end_date IS NULL) OR audit_start_time BETWEEN v_start_date AND v_end_date

Run an additional check to do the opposite, i.e. Only skip when it's null.
AND (NOT (v_start_date IS NULL AND v_end_date IS NULL)) OR audit_start_time BETWEEN now() AND now() - INTERVAL '7 days'

Edit: Assumed some variables from the context of a stored procedure, v_start_date and v_end_date must be timestamps.

A:
Use below query.

SELECT now(), now() - INTERVAL '7 days';

A: Use COALESCE to check for the null value and now() - INTERVAL '7 days' to get your desired results.


text:
Q: Laravel 5.1 - Service Provider unresolvable dependency I want to use the Youtube wrapper service provider from alaouy and I'm getting the following error.

Unresolvable dependency resolving [Parameter #0 [  $key ]] in class Alaouy\Youtube\Youtube

This is my code inside the controller:
use Alaouy\Youtube\Youtube;

class UrlController extends Controller
{
    public function search(Request $request, Youtube $yt)
    {
        $yt->parseVIdFromURL($request->input('url'));
    }

    ....

In the register method you can see how he access the config file, that code appears in his API
$this->publishes(array(__DIR__ . '/../../config/youtube.php' => config_path('youtube.php')));
    $this->app->bindShared('youtube', function () {
        return $this->app->make('Alaouy\Youtube\Youtube', [config('youtube.KEY')]);
    });

"php artisan vendor:publish" - has been executed

A: Solution is to use Facades.
use Youtube;

public function search(Request $request)
{
    Youtube::parseVidFromURL($request->input('url'));
}

Thanks to a forum member from: Laracast


text:
Q: Unable to create DataCacheFactory instance in debug
*

*I'm working on web project that will run on Windows Azure Web role;

*In the cloud, there will be 2 instances of the role;

*I'm using co-located named cache (In-Role Cache) spread between 2 role instances;

*Locally, I debug with single instance;

*In the cloud, cache client is created successfully and work fluently;

*When debug locally, I am unable to create instance of DataCacheFactory, because when the constructor is called, the program flow "stops" and doesn't continue to the following statement. There is no exception!

That's the code where I'm creating Factory and cache client:
var cacheFactoryConfig = new DataCacheFactoryConfiguration
        {
            ChannelOpenTimeout = TimeSpan.FromMinutes(2),
            TransportProperties = {ReceiveTimeout = TimeSpan.FromSeconds(45)}
        };
        DataCacheFactory cacheFactory;
        try
        {
            cacheFactory = new DataCacheFactory(cacheFactoryConfig);// <--stops here
        }
        catch (Exception e)
        {
            Trace.WriteLine(string.Format("--> Message-> {0}; --> Stack Trace->{1}", e.Message, e.StackTrace));
            throw;
        }
cacheClient = cacheFactory.GetDefaultCache();

Service configuration:

Cache client and server configuration in web.config

I would give any additional information if such is requested in order to resolve the problem shortly.
------EDIT 1------------------
Due to related post Making Windows Azure Caching Work in Compute Emulator I have to add some info:

*

*Operating sistem -> Windows 7 Professional

*IDE -> Visual Studio 2013 Ultimate Update 4

*Windows Azure Caching package 2.4.0.0

*Windows Azure SDK Version 2.4

I don't have Windows Server AppFabric installed, so I'm going for it!

A: After few days of investigation, I managed to solve the issue and successfully create instance of DataCacheFactory and DataCache and so on. The problem is described and solved in the following 2 posts:
https://social.msdn.microsoft.com/Forums/azure/en-US/8580689a-a1a1-4db7-bba9-f42c1a90e0db/windows-azure-webrole-caching-preview-hangs-makes-the-emulator-stuck-in-deploy-loop?forum=windowsazuredevelopment
http://blog.elastacloud.com/2012/06/09/using-the-windows-azure-cache-preview-with-sdk-1-7/

*

*In my case, I had Microsoft Server AppFabric installed, so I removed it.

*Just in case, I removed all available Windows Azure SDKs (2.4 was installed) and
all old nuget packages related to Azure Caching.

*I did verify that all assemblies are removed from GAC too.

*After "cleaning" I install again latest Azure SDK available which is 2.5. http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-in-role/
I would like to point out, that windows Event Viewer helped a lot. In Windows Azure logs I found an error that was happening when I start the web role with Azure Emulator. Error was thrown by CacheInstaller.exe -> MissingMethodExceprion with message:

Method not found:
  'Microsoft.ApplicationServer.Caching.ClusterConfigElement


text:
Q: How to crate a package create a package that can update the VP9 Video Extensions library on all computers I want to create a package that can update the VP9 Video Extensions library on all Computers.
it has to be deployed in SCCM.
Any help is appreciated.
Thanks in advance!!!
Tried creating Script but not working.


text:
Q: Weird vector filtering in R. Please explain When running the below commands
x <- c(1:10)
x

y <- c(1:35)
y

res <- y [x <= 5]
res

The result looks like this:
 [1]  1  2  3  4  5  6  7  8  9 10
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26 27 28 29 30 31 32 33 34 35
 [1]  1  2  3  4  5 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35

Could you explain how the numbers 16:20 and 25:30 got filtered out?
Also refer me to a resource where i can learn more about this.

A: The logical vector is getting recycled to the length of 'y' as one of them is of length greater than the other.  If we replicate, it would give the same output as the OP's case
rep(x <= 5, length.out = length(y))
#[1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE
#[23]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

y[rep(x <= 5, length.out = length(y))]
#[1]  1  2  3  4  5 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35

y[x <= 5]
#[1]  1  2  3  4  5 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35


text:
Q: autogenerating ".uuid" files in linux directory OS - Debian Stable
I downloaded fonts from a website (that seemed legitimate to me) and transferred the contents to /usr/share/fonts/directory. There's a .uuid file being generated for every directory with a string like this as its sole content:
f25e9432-c6f1-4bbe-a33c-89289a8d17f1
This file regenerates right after I delete it. Is this a malicious program? Is this indexing by the OS itself or is it something like fc-cache running in the background? What could be the cause of this?

A: This has nothing to do with the fact that you've downloaded your own fonts. This is simply just fontconfigdoing it's job. It very well could just be the cached data created. Only rather, the binary data is being converted into a uuid string/unique ID.
So, I would say no. I do not believe this to be the cause of anything malicious. Nor are any of these occurrences a result from you downloading fonts from your web browser.


text:
Q: Run-Time code tracking in Fortran I have a big fortran 77 program. when running under certain constants it runs fine. but, when I change that constants it stoped.
I can not find where is the problem in the code.
Is there any specific software to make a checking for the program during running?? I mean a kind of tracking ......
Thanks in Advance
Ghazooo

A: The advice you have already been given, about learning how to use a debugger, is good advice.  There are better debuggers than GDB, but if you don't have any of them GDB is OK.
However, before you dive into the entrails of the program with GDB stop and think.  You say that changing some constants stops the program.  What exactly do you mean ?  Do you mean that if you change what Fortran calls PARAMETERs in the source code, recompile and try to run the program fails ?  Or do you mean that if you provide certain values as input the program runs and fails ?
What error messages does the compiler or run-time system provide when the program fails ?  How far into its execution does the program fail ?
I guess you have already studied these aspects of the program, but if you haven't you should do so.  You should still start learning how to use a debugger but they have a justified reputation, in general, of not being very easy to use.  That's partly because not many of us use them frequently enough to become fluent with them.

A: I would recommend Fortran debugging with GDB. GDB is well integrated in various Linux IDE's. If you use the Intel Fortran compiler, intel also distributes a debugger.


text:
Q: How can I overlay a colour and a pattern? Is there any way I can add a pattern onto a colored cell through conditional formatting such that the color of the cell remains visible?
I am trying to do a sort of Gantt chart, where the different colours represent different people:

When I activate a cell I want to highlight the selected row and column with a pattern. I have managed to create that functionality, however, when a pattern shows, the colour disappears.
In below I move the cursor one cell up. The corresponding row gets a pattern, but the red colour disappears. If I move the cursor one cell up and to the left, the same happens with the yellow colour.

I've tried below VBA code, and the result is the same: when the pattern shows, the colour disappears.
LR = Cells(Rows.Count, 1).End(xlUp).Row

Set PatternRng = Range("A6" & ":" & "GM" & Sheets("Source").Range("I1").Value)
PatternRng.Interior.Pattern = xlPatternNone

If ((ActiveCell.Row >= 7) And (ActiveCell.column <= 194) And (ActiveCell.Row <= LR)) Then
    If (ActiveCell.column > 1) Then
       Set PatternRng = Range("A6:A" & LR).Offset(, ActiveCell.column - 1)
       PatternRng.Interior.Pattern = xlPatternGray25
       PatternRng.Interior.PatternColor = RGB(191, 191, 191)
    End If

    Set PatternRng = Range("A6:GM6").Offset(ActiveCell.Row - 6, 0)
    PatternRng.Interior.Pattern = xlPatternGray25
    PatternRng.Interior.PatternColor = RGB(191, 191, 191)

    Sheets("Source").Range("I2").Value = (ActiveCell.column - 1)
    Sheets("Source").Range("I3").Value = (ActiveCell.Row - 6)
End If


text:
Q: Increasing height of one div to reduce the height of other div? I'm using https://mattlewis92.github.io/angular-resizable-element/demo/ in order to make my bottom element resizable only on my top border. Above i have a table which i made also resizable but only the bottom border. The issue is i want the tables bottom border to reduce or its height reduces from the bottom side when i increase the height of the element which is below. I'm having a hard time figuring this out.
This is my first post on stackoverflow sorry if i did something wrong or if i missed something.
https://stackblitz.com/edit/angular-k2beg1
I've tried using ElementRef, [style.height] and the events provided by the plugin above.

style: object = {};
styleTable: object = {};
tableHeight: any;

validate(event: ResizeEvent): boolean {
   return true;
 }

onResizeEnd(event: ResizeEvent): void {
   this.style = {
     position: 'fixed',
     left: `${event.rectangle.left}px`,
     width: `${event.rectangle.width}px`,
     top: `${event.rectangle.top}px`,
     height: `${event.rectangle.height}px`
   };
 }

resizing(event) {
   this.styleTable = {
     left: `${event.rectangle.left}px`,
     width: `${event.rectangle.width}px`,
     top: `${event.rectangle.top}px`,
     height: `${event.rectangle.height--}px`
   }
 }

A: Try using this -

Hello.component.ts

/* tslint:disable:max-inline-declarations */
import { Component } from '@angular/core';
import { ResizeEvent } from 'angular-resizable-element';

@Component({
  selector: 'mwl-demo',
  styles: [
    `
      .rectangle {
        position: relative;
        top: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 300px;
        height: 150px;
        background-color: #fd4140;
        border: solid 1px #121621;
        color: #121621;
        margin: auto;
      }
      .resize-handle-top,
      .resize-handle-bottom {
        position: absolute;
        height: 5px;
        cursor: row-resize;
        width: 100%;
      }
      .resize-handle-top {
        top: 0;
      }
      .resize-handle-bottom {
        bottom: 0;
      }
      .resize-handle-left,
      .resize-handle-right {
        position: absolute;
        height: 100%;
        cursor: col-resize;
        width: 5px;
      }
      .resize-handle-left {
        left: 0;
      }
      .resize-handle-right {
        right: 0;
      }
    `
  ],
  template: `

  `
})
export class HelloComponent {
  public style: object = {};

  validate(event: ResizeEvent): boolean {
    const MIN_DIMENSIONS_PX: number = 50;
    if (
      event.rectangle.width &&
      event.rectangle.height &&
      (event.rectangle.width < MIN_DIMENSIONS_PX ||
        event.rectangle.height < MIN_DIMENSIONS_PX)
    ) {
      return false;
    }
    return true;
  }

  onResizeEnd(event: ResizeEvent): void {
    this.style = {
      position: 'fixed',
      left: `${event.rectangle.left}px`,
      top: `${event.rectangle.top}px`,
      width: `${event.rectangle.width}px`,
      height: `${event.rectangle.height}px`
    };
  }
}


text:
Q: Usage of "yet" and "but" I want to convey "Something is important. But it is hard to achieve". Can I use "yet" as in the following sentence?

It is an important yet non-trivial task.

Also, can I use "yet" to connect sentences with opposite meanings? For example,

This book is very well-written, yet few people know about it.

A: You cannot use yet in your first example. You need AND.
Alternatively, change the order and use but.

It is a non-trivial but important task.

6. used for introducing a word or idea that is surprising after what has just been mentioned

*

*They had plenty of time, yet she felt there was almost none.

*The novel is 800 pages long, yet it reads more quickly than many shorter books.

*He looks cheerful yet somehow sad at the same time.
https://www.macmillandictionary.com/dictionary/british/yet

Your second example is an example of correct usage

This book is very well-written, yet few people know about it.


text:
Q: In XPages mobile app, how to avoid appending resetContent=false/true after pressing Done? I've a mobile page developed with ExtLib mobile controls:
http://hostname/mydb.nsf/MobileTest.xsp
The page consists of two appPages (i.e. a "mainPage" appPage & a "subPage" appPage).
Click on an entry in the mainPage will move to the subPage. Click on the "Done" button in the subPage will move back to the mainPage. After moving back to the mainPage, the resulting URL will automatically change to: http://hostname/mydb.nsf/MobileTest.xsp#mainPage&resetContent=false
When this happened, if I press the browser's refresh button on my iPhone, instead of showing the mainPage, a grey blank page will be displayed. Then, if I manually remove &resetContent=false from the URL and press the refresh button again, the mainPage will be displayed properly.
So, is there any way to suppress appending &resetContent=false (or true) after clicking on a Done button?

A: I have found the cause of this and have put a fix into the ExtLib, it will be in the next release. I don't know when that will be at the minute but will update when I know

A: See answer:
http://www.openntf.org/internal/home.nsf/response.xsp?action=openDocument&documentId=0B41430C59FA242C862579D50034D72A


text:
Q: Multi-Context InMemory Database Is it possible to have an InMemory database (ASP.NET Core) that is shared across multiple DbContexts? It seems that each DbContext type keeps its own database, even when the same database name is specified in UseInMemoryDatabase.

A: The same name is enough. If your instances of DbContext do not 'see' the same in memory DB, it seems they use ones with different names. Make sure your DbContext is created once for the same name.
EF Core 2.0 even re-uses in memory databases with the same name:

In-memory databases must be named
The global unnamed in-memory database has been removed and instead all in-memory databases must be named. For example:

optionsBuilder.UseInMemoryDatabase("MyDatabase");

This creates/uses a
  database with the name "MyDatabase". If UseInMemoryDatabase is called again with the same name, then the same in-memory database will be used, allowing it to be shared by multiple context instances.

A: Beside the same database name, the model must also be the same.
This means that in case of an own implementation of IModelCacheKeyFactory, it's Create-Method must return "equal" objects.

A: This is possible nowadays, but indeed passing just the name is not enough if you use different context types. I'm using .net core 2.2 and had the exact same issue. My code now is now like this:
I create a InMemoryDatabaseRoot object like this in class level
//using Microsoft.EntityFrameworkCore.Storage;
private static readonly InMemoryDatabaseRoot InMemoryDatabaseRoot = new InMemoryDatabaseRoot();

When I add the db contextes I pass the root instance
services.AddDbContext<MyContext>(options =>
{
    options.UseInMemoryDatabase("MyContext", InMemoryDatabaseRoot);
    options.UseInternalServiceProvider(serviceProvider);
 });

 services.AddDbContext<MySecondContext>(options =>
 {
    options.UseInMemoryDatabase("MyContext", InMemoryDatabaseRoot);
    options.UseInternalServiceProvider(serviceProvider);
  });

I found it in a discussion here: https://github.com/aspnet/EntityFrameworkCore/issues/9613#issuecomment-430722420


text:
Q: DatagridView column size I want to resize some columns on form load programmatically. Here's my code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim resetBtn = New Button With {.Text = "S", .Width = 20}
    dtp.Name = "dtp"
    dtp.Width = 80

    'TODO: This line of code loads data into the 'MakbuzDataSet.makbuzT' table. You can move, or remove it, as needed.
    Me.MakbuzTTableAdapter.Fill(Me.MakbuzDataSet.makbuzT)

    MakbuzTDataGridView.Dock = DockStyle.Bottom

    Me.SavePending = True

    AddHandler dtp.ValueChanged, AddressOf DateTimePicker1_ValueChanged
    FillByTest08ToolStrip.Items.Add(New ToolStripControlHost(dtp))

    FillByTest08ToolStrip.Items.Add(New ToolStripControlHost(resetBtn))

    Button1.Visible = False
    FillByTest08ToolStrip.Margin = New Padding(150, 150, 150, 150)
    FillByTest08ToolStrip.Dock = DockStyle.Top
    MakbuzTDataGridView.Dock = DockStyle.Fill
    MakbuzTDataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
    MakbuzTDataGridView.ColumnHeadersHeight = 75
    MakbuzTDataGridView.EnableHeadersVisualStyles = True

    AddHandler resetBtn.Click, AddressOf onresetBtnClick

    MakbuzTDataGridView.CurrentCell = MakbuzTDataGridView(0, 0)
    MakbuzTDataGridView.TabIndex = 0

    MakbuzVars = Utils.Load(Of Info)("ayarlar.xml")
    MakbuzTDataGridView.Columns(1).Width = 150

End Sub

I'm using Visual Studio 2012. How can I resize a column?


text:
Q: It is possible to pass variable Ref cursor of an Oracle stored procedure when called from SQL Server I have a problem calling an Oracle stored procedure from SQL Server.
Another system, send me a stored procedure that I need to call, it is not possible to change it, but I am trying to call it from SQL Server.
I created a linked server in SQL Server to Oracle, I have run select queries and if I can retrieve data, the RPC properties are enabled
EXECUTE ('begin SP_DETAILS(P_QUALIFIER,P_PORTFOLIO,P_DATE); end;', null, null, null) AT Operadora;

Mens. 7213, Nivel 16, Estado 1, Línea 4
The attempt by the provider to pass remote stored procedure parameters to remote server 'Operadora'  failed. Verify that the number of parameters, the order, and the values passed are correct.
The parameters that the stored procedure receives in Oracle are the following, but I have problem assigning the REF CURSOR, the rest of the parameters are null
create or replace PROCEDURE SP_DETAILS ( P_DS_MODEL_PORTF_DET_C IN OUT SYS_REFCURSOR,
 P_QUALIFIER IN VARCHAR2,
 P_PORTFOLIO     IN     VARCHAR2,
 P_DATE     IN     TIMESTAMP )

Thanks

A: You can access an Oracle REF CURSOR via .NET. If you really need to do this from SQL Server you will have to use the CLR.


text:
Q: Правильно ли я работаю с массивом Json? Я получаю с сервера массив данных в формате Json. Вот как я его вытаскиваю из ответа сервера:
JsonArray filter1 = response.body().getFilters().getAsJsonArray("prof");

дальше вот что я получаю в логах если выведу переменную filter1:
[{"count":1,"name":"name1","id":13392},{"count":2,"name":"name2","id":13408},{"count":3,"name":"name3","id":13466}]

дальше мне нужно получить каждую переменную по отдельности и я пишу такие строки:
for (int i = 0; i < filter1.size(); i++) {
JsonElement object = filter1.get(i);
Log.w("MY_TAG", String.valueOf(object));
}

в логах я получаю такое:
{"count":1,"name":"name1","id":13392}
{"count":2,"name":"name2","id":13408}
{"count":3,"name":"name3","id":13466}

вроде бы как получаю каждую переменную по отдельности и это то что нужно. Дальше я планирую перенести все в массив и тд. Но вот возник вопрос - правильно ли я сделал? Буду благодарен за критику и полезные советы.

A: добавьте Gson в Gradle
dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

Добавьте класс-описание:
class Item{
    int count;
    String name;
    int id;
}

Пример:
String jsonOutput = "[{\"count\":1,\"name\":\"name1\",\"id\":13392},{\"count\":2,\"name\":\"name2\",\"id\":13408},{\"count\":3,\"name\":\"name3\",\"id\":13466}]";

Type listType = new TypeToken<List<Item>>(){}.getType();

List<Item> items = new Gson().fromJson(jsonOutput, listType);

for (Item item : items){
    Log.i("Log",item.name);
}

Если вы получаете данные через retrofit2, то будет еще проще см.: https://stackoverflow.com/a/42029755/10965132


text:
Q: Laravel - 1066 Not unique table/alias on a relationship I'm trying to create a simple relationship between tables :
- attribute_type -
    id
    name

- category -
    id
    name
    description

So I created a pivot table to link them :
- attribute_type_category -
    attribute_type_id
    category_id

There is the model relationships :
On AttributeType.php
public function category() {
    return $this->belongsToMany('App\AttributeTypeCategory', 'attribute_type_category', 'attribute_type_id', 'category_id');
}

On AttributeTypeCategory.php
public function category() {
    return $this->belongsToMany('App\Category');
}

All seems to be fine, but I get the following error :

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique
  table/alias: 'attribute_type_category' (SQL: select
  attribute_type_category.*,
  attribute_type_category.attribute_type_id as
  pivot_attribute_type_id, attribute_type_category.category_id as
  pivot_category_id from attribute_type_category inner join
  attribute_type_category on attribute_type_category.id =
  attribute_type_category.category_id where
  attribute_type_category.attribute_type_id = 1)

Do you have any idea ?
Thank you !

A: when you want to create simple many to many relation between two tables
like attribute_type and category,
you should create three tables using migrations as you did

*

*attribute_type -
id
name

*category -
id
name
description

*attribute_type_category -
attribute_type_id
category_id
then you will create two classes (attribute_type and category) no need to create third one for the relation.
and in attribute_type you should define method for the category relation
public function category() {
return $this->belongsToMany('App\Category');}

and in category class:
public function attributeType() {
 return $this->belongsToMany('App\AttributeType');}

and then you can access the categories of any attribute_type by using ->categories and you can access the attributeTypes of any category by using ->attributeTypes
you should follow laravel official documentation to learn  more about relations
https://laravel.com/docs/5.4/eloquent-relationships


text:
Q: Building Boost 1.59 with Intel C++ Compiler 15.0 in Centos 7 I am trying to build Boost 1.59 with Intel C++ Compiler 15.0 in Centos 7. I am using the below command.
./bootstrap.sh --without-libraries=mpi,python
./b2 toolset=intel-15.0 address-model=64 cxxflags="-std=c++11" --layout=versioned link=static variant=debug,release

I got the below error in building Boost.Log. Could you please help? I tried to compile with GCC 4.8 and it works. Is it a bug in Intel C++ Compiler?
intel-linux.compile.c++ bin.v2/libs/log/build/intel-linux-15.0/debug/link-static/log-api-unix/threading-multi/default_filter_factory.o
./boost/fusion/algorithm/query/detail/find_if.hpp(208): internal error: assertion failed at: "shared/cfe/edgcpfe/lower_il.c", line 18968

              return recursive_call(iter, found());
              ^

compilation aborted for libs/log/src/default_filter_factory.cpp (code 4)

"icpc" -c -xc++ -O0 -g -w1 -inline-level=0 -pthread -m64 -fvisibility=hidden -std=c++11 -wd177,780,2196,1782,193,304,981,1418,411,734,279 -DBOOST_ALL_NO_LIB=1 -DBOOST_CHRONO_STATIC_LINK=1 -DBOOST_FILESYSTEM_STATIC_LINK=1 -DBOOST_LOG_SETUP_BUILDING_THE_LIB=1 -DBOOST_LOG_USE_AVX2 -DBOOST_LOG_USE_NATIVE_SYSLOG -DBOOST_LOG_USE_SSSE3 -DBOOST_LOG_WITHOUT_EVENT_LOG -DBOOST_SPIRIT_USE_PHOENIX_V3=1 -DBOOST_SYSTEM_NO_DEPRECATED -DBOOST_SYSTEM_STATIC_LINK=1 -DBOOST_THREAD_BUILD_LIB=1 -DBOOST_THREAD_DONT_USE_CHRONO=1 -DBOOST_THREAD_POSIX -DBOOST_THREAD_USE_LIB=1 -DDATE_TIME_INLINE -D_GNU_SOURCE=1 -D_XOPEN_SOURCE=600 -I"."   -c -o "bin.v2/libs/log/build/intel-linux-15.0/debug/link-static/log-api-unix/threading-multi/default_filter_factory.o" "libs/log/src/default_filter_factory.cpp"

...failed intel-linux.compile.c++ bin.v2/libs/log/build/intel-linux-15.0/debug/link-static/log-api-unix/threading-multi/default_filter_factory.o...
intel-linux.compile.c++ bin.v2/libs/log/build/intel-linux-15.0/debug/link-static/log-api-unix/threading-multi/matches_relation_factory.o
./boost/fusion/algorithm/query/detail/find_if.hpp(208): internal error: assertion failed at: "shared/cfe/edgcpfe/lower_il.c", line 18968

              return recursive_call(iter, found());
              ^

compilation aborted for libs/log/src/matches_relation_factory.cpp (code 4)


text:
Q: environments fail to align with surroundings In the following examples, neither the alignment parameter t nor b works(please see the attached figure). Why and how to make environment align with its surroundings.
Codes:
\documentclass{article}
\usepackage{listings}
\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newbox\mybox
\savebox\mybox{\parbox{3in}{%
  \begin{itemize}
  \item 1\item 2\item 3\item 4\item 5
  \end{itemize}
}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Exp 1. Aligned by t:\par
\begin{minipage}[t]{2in}
  \begin{lstlisting}[]
      ab
      cd
      ef
  \end{lstlisting}
\end{minipage}
\vrule\
\parbox[t]{3in}{\usebox\mybox}
\par\bigskip
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Exp 2. Aligned by b:\par
\begin{minipage}[b]{2in}
    \begin{lstlisting}[]
      ab
      cd
      ef
  \end{lstlisting}
  \end{minipage}
\vrule\
\parbox[b]{3in}{\usebox\mybox}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\end{document}