text:
Q: OpenLayers XYZ example with map proxy script I always wondered if it would be possible to load a map from a public source with a script and display it using OpenLayers. It would also allow to create a map tile cache to allow faster load times.
So my question is how to load maps in OpenLayers using a XYZ source from a script hosted locally?

A: Here is my quick solution for that:
First, I have created a proxy script to load the files for me:
<?php

header('Content-type: image/png');

$x = $_GET['x'];
$y = $_GET['y'];
$z = $_GET['z'];

$urlBegin = 'https://b.tile.openstreetmap.org';
$urlEnd = '.png';

$fullUrl = "$urlBegin/$z/$x/$y$urlEnd";

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $fullUrl,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36'
]);
$content = curl_exec($curl);
curl_close($curl);

echo $content

?>

After that, I have a simple example that loads the maps provided by this proxy script:
<!DOCTYPE html>

<title>XYZ Example</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css">

It is pretty useful if you have trouble loading tiles from an external source, within the browser.


text:
Q: Web socket is not working on my website I'm trying to understand how to use these files which I found on this website so I can learn more about how web-sockets work with PHP. So let's just say I have a website call example.com
what would I have to modify in these files to get this to work on my website call example.com. I been searching for a long time to know how to get this to work here's the original untouch code files from that website.
index.php

        <form name="frmChat" id="frmChat">

            <input type="text" name="chat-user" id="chat-user" placeholder="Name" class="chat-input" required />
            <input type="text" name="chat-message" id="chat-message" placeholder="Message"  class="chat-input chat-message" required />
            <input type="submit" id="btnSend" name="send-chat-message" value="Send" >
        </form>

php-socket.php
<?php
define('HOST_NAME',"localhost");
define('PORT',"8090");
$null = NULL;

require_once("class.chathandler.php");
$chatHandler = new ChatHandler();

$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socketResource, 0, PORT);
socket_listen($socketResource);

$clientSocketArray = array($socketResource);
while (true) {
    $newSocketArray = $clientSocketArray;
    socket_select($newSocketArray, $null, $null, 0, 10);

    if (in_array($socketResource, $newSocketArray)) {
        $newSocket = socket_accept($socketResource);
        $clientSocketArray[] = $newSocket;

        $header = socket_read($newSocket, 1024);
        $chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);

        socket_getpeername($newSocket, $client_ip_address);
        $connectionACK = $chatHandler->newConnectionACK($client_ip_address);

        $chatHandler->send($connectionACK);

        $newSocketIndex = array_search($socketResource, $newSocketArray);
        unset($newSocketArray[$newSocketIndex]);
    }

    foreach ($newSocketArray as $newSocketArrayResource) {
        while(socket_recv($newSocketArrayResource, $socketData, 1024, 0) >= 1){
            $socketMessage = $chatHandler->unseal($socketData);
            $messageObj = json_decode($socketMessage);

            $chat_box_message = $chatHandler->createChatBoxMessage($messageObj->chat_user, $messageObj->chat_message);
            $chatHandler->send($chat_box_message);
            break 2;
        }

        $socketData = @socket_read($newSocketArrayResource, 1024, PHP_NORMAL_READ);
        if ($socketData === false) {
            socket_getpeername($newSocketArrayResource, $client_ip_address);
            $connectionACK = $chatHandler->connectionDisconnectACK($client_ip_address);
            $chatHandler->send($connectionACK);
            $newSocketIndex = array_search($newSocketArrayResource, $clientSocketArray);
            unset($clientSocketArray[$newSocketIndex]);
        }
    }
}
socket_close($socketResource);

class.chathandler.php
<?php
class ChatHandler {
    function send($message) {
        global $clientSocketArray;
        $messageLength = strlen($message);
        foreach($clientSocketArray as $clientSocket)
        {
            @socket_write($clientSocket,$message,$messageLength);
        }
        return true;
    }

    function unseal($socketData) {
        $length = ord($socketData[1]) & 127;
        if($length == 126) {
            $masks = substr($socketData, 4, 4);
            $data = substr($socketData, 8);
        }
        elseif($length == 127) {
            $masks = substr($socketData, 10, 4);
            $data = substr($socketData, 14);
        }
        else {
            $masks = substr($socketData, 2, 4);
            $data = substr($socketData, 6);
        }
        $socketData = "";
        for ($i = 0; $i < strlen($data); ++$i) {
            $socketData .= $data[$i] ^ $masks[$i%4];
        }
        return $socketData;
    }

    function seal($socketData) {
        $b1 = 0x80 | (0x1 & 0x0f);
        $length = strlen($socketData);

        if($length <= 125)
            $header = pack('CC', $b1, $length);
        elseif($length > 125 && $length < 65536)
            $header = pack('CCn', $b1, 126, $length);
        elseif($length >= 65536)
            $header = pack('CCNN', $b1, 127, $length);
        return $header.$socketData;
    }

    function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
        $headers = array();
        $lines = preg_split("/\r\n/", $received_header);
        foreach($lines as $line)
        {
            $line = chop($line);
            if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
            {
                $headers[$matches[1]] = $matches[2];
            }
        }

        $secKey = $headers['Sec-WebSocket-Key'];
        $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host_name\r\n" .
        "WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
        socket_write($client_socket_resource,$buffer,strlen($buffer));
    }

    function newConnectionACK($client_ip_address) {
        $message = 'New client ' . $client_ip_address.' joined';
        $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function connectionDisconnectACK($client_ip_address) {
        $message = 'Client ' . $client_ip_address.' disconnected';
        $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
        $ACK = $this->seal(json_encode($messageArray));
        return $ACK;
    }

    function createChatBoxMessage($chat_user,$chat_box_message) {
        $message = $chat_user . ":
" . $chat_box_message . "
";
        $messageArray = array('message'=>$message,'message_type'=>'chat-box-html');
        $chatMessage = $this->seal(json_encode($messageArray));
        return $chatMessage;
    }
}
?>

I follow the instructions of that website but still it doesn't work even after I modify where it said's ws://localhost:8090/demo/php-socket.php on the index.php file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: html table column sizing I'm trying to create a simple html table (one row to columns). I want one column to overflow with a scroll bar. The problem is that no matter what css setitngs I change the column size changes according to the text, and the scroll bar is horizontally and not vertically.
What needs to be changed in order for my table to be the way I want?
Html code:

            <%@include file="newsData.jsp" %>

                Founded in 1992 as a Finance and Securities Company,
                Imperia Bank converted into a fully fledged commercial bank in January 1996.
                Since then the bank has had a long standing tradition of achieving strong financial performance and carrying out
                expansion strategies while successfully focusing on efficient client service delivery.

                Over the last 20 years, Imperia Bank has achieved a sustained growth in our customer deposit base which is largely attributed to the level of confidence our customers have in the bank and our corporate strategy.
                Currently we have 23 branches in our expanding branch network across major towns and cities.

                Imperial Bank will continue to enhance the existing risk management parameters through the effective use of our newly installed and cutting edge core banking system.
                As part of our growth strategy, we are also continuing to recruit qualified professional staff, and providing appropriate training to our existing human resources to ensure we continue to meet evolving customer demands.

and also (imported from a jsp page):

<%=header %>

<%=newsBody %>

<%=date %>

CSS code:
.homepage_table
{
border: 250;
width: 100%;
height:500px;
margin:auto;
}
.homepage_table td
{
border:solid;

}
#about_td
{
background-image:url('http://www.promenadd.com/en/wp-content/uploads/2013/04/promenadd_grey_background.jpg');
background-repeat:no-repeat;
background-size: 110%;
font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
font-weight:bold;

}
#about_text
{

    padding-right: 50px;
    padding-left: 50px;
    color:steelblue;

}
#Articlesbar
{

 overflow-x: hidden;
overflow-y: scroll;
}

#newsHeader
{
font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
color:steelblue;
font-weight:bold;
font-size: 20px;
padding-right: 10px;
padding-left: 10px;
}

#newsBody
{
font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
color:red;
font-size: 14px;
padding-right: 10px;
padding-left: 10px;
}
#newsDate
{
font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
font-size: 14px;
padding-right: 10px;
padding-left: 10px;
}

A: I put together this fiddle real quick:
DEMO
And I added this CSS to your #about_text ID:
  max-height:200px;
  max-width:700px;
  overflow-y: scroll;

I'm not certain if this is what you want, but I think it seems to do what you are looking for.
You can adjust the width/height as needed and the overflow-y:scroll; is what allows for the scroll bar to appear.

A: I was beaten to the punch but it looks like the poster wants the scrollbar on Articlesbar
So the simple method would be to set a height on that td, add a div inside it and add the scrollbar to that instead.
The structure would be like

here have a fiddle


text:
Q: Fit Path to SVG I have a SVG from fontawesome, but there is space around the path content inside the SVG window.
<svg aria-hidden="true" focusable="false" data-prefix="fab" data-icon="youtube" class="svg-inline--fa fa-youtube fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
<path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path>
</svg>

How would I remove this space and have the path edges touch the SVG window?
CSS preferable but open to other solutions.

A: I haven't found a CSS solution, but you can do it in JavaScript by setting the SVG's view box dimensions to those of the bounding box:

const svg = document.querySelector("svg");
const {x, y, width, height} = svg.getBBox();

svg.setAttribute("viewBox", `${x} ${y} ${width} ${height}`);
body {
  margin: 0;
  padding: 0;
}
<svg aria-hidden="true" focusable="false" class="svg-inline--fa fa-instagram fa-w-14" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
<path
fill="currentColor"
d="M224.1 141c-63.6 0-114.9 51.3-114.9 114.9s51.3 114.9 114.9 114.9S339 319.5 339 255.9 287.7 141 224.1 141zm0 189.6c-41.1 0-74.7-33.5-74.7-74.7s33.5-74.7 74.7-74.7 74.7 33.5 74.7 74.7-33.6 74.7-74.7 74.7zm146.4-194.3c0 14.9-12 26.8-26.8 26.8-14.9 0-26.8-12-26.8-26.8s12-26.8 26.8-26.8 26.8 12 26.8 26.8zm76.1 27.2c-1.7-35.9-9.9-67.7-36.2-93.9-26.2-26.2-58-34.4-93.9-36.2-37-2.1-147.9-2.1-184.9 0-35.8 1.7-67.6 9.9-93.9 36.1s-34.4 58-36.2 93.9c-2.1 37-2.1 147.9 0 184.9 1.7 35.9 9.9 67.7 36.2 93.9s58 34.4 93.9 36.2c37 2.1 147.9 2.1 184.9 0 35.9-1.7 67.7-9.9 93.9-36.2 26.2-26.2 34.4-58 36.2-93.9 2.1-37 2.1-147.8 0-184.8zM398.8 388c-7.8 19.6-22.9 34.7-42.6 42.6-29.5 11.7-99.5 9-132.1 9s-102.7 2.6-132.1-9c-19.6-7.8-34.7-22.9-42.6-42.6-11.7-29.5-9-99.5-9-132.1s-2.6-102.7 9-132.1c7.8-19.6 22.9-34.7 42.6-42.6 29.5-11.7 99.5-9 132.1-9s102.7-2.6 132.1 9c19.6 7.8 34.7 22.9 42.6 42.6 11.7 29.5 9 99.5 9 132.1s2.7 102.7-9 132.1z">
</path>
</svg>


text:
Q: Trouble in installing GCP Profiler agent in Docker I am trying to install the GCP Profiler agent for my app which runs in GKE, following instructions here: https://cloud.google.com/profiler/docs/profiling-java
I can't get past this error. Can someone help?

Could not find agent library /opt/cprof/profiler_java_agent.so in
  absolute path, with error: Error relocating
  /opt/cprof/profiler_java_agent.so: __pthread_key_create: initial-exec
  TLS resolves to dynamic definition in
  /opt/cprof/profiler_java_agent.so

This is the Dockerfile
FROM openjdk:8-jdk-alpine
RUN apk update && apk add --no-cache gcompat
RUN apk update && apk add --no-cache libc6-compat

WORKDIR /app

# The application's jar file
ARG JAR_FILE=target/example-svc-*.jar

# Add the application's jar to the container
ADD ${JAR_FILE} example-svc.jar

EXPOSE 5050

RUN mkdir -p /opt/cprof && \
  wget -q -O- https://storage.googleapis.com/cloud-profiler/java/latest/profiler_java_agent.tar.gz \
  | tar xzv -C /opt/cprof

ENTRYPOINT ["java", \
    "-agentpath:/opt/cprof/profiler_java_agent.so=-cprof_service=example-svc,-cprof_service_version=0.0.1-SNAPSHOT", \
    "-jar", "/app/example-svc.jar"]

A: The problem appears to be the base version of the container image you are working from.  Looking at your Dockerfile, you are starting from:
openjdk:8-jdk-alpine

Digging into the docs of this, we find:

The main caveat to note is that it does use musl libc instead of glibc
  and friends, so certain software might run into issues depending on
  the depth of their libc requirements.

(Reference: openjdk)
Now if we look at the Google docs found here, we find the following requirement defined:

Supported operating systems:

*

*Linux versions whose standard C library is implemented with glibc.

... and this appears to be a conflict.  Please try with an alternate version of an openjdk image that is not based on alpine.


text:
Q: How to display count for different values sharing the same prefix? I am trying to count number of times particular sequence occurs. Say a column - 'testC' in a table - 'testT' as characters such as 'DS-PP', 'WQ-PP', 'FF-PP', 'DS-PP', 'DS-PP', 'FF-PP'
I want the result to be like
DS-PP - 3
FF-PP - 2
WQ-PP - 1

how can I achieve that. So far I have got
SELECT count(testC) from testT where testC like '%-PP%' group by testC

This gives me the count But doesnt say for which. I need to add something in select to get the DS-PP and so on
Note: testC column can have anything (it is a text field) say - 'DP-PP was here.' I want it to show just DP-PP not the whole sentence is that possible.
Check this
http://sqlfiddle.com/#!2/f0c29/1

A: didnt you miss WHERE testC clause ? AND you missed to select testC also.
    SELECT testC, count(testC) from testT WHERE testC like '%-PP%' group by testC

DEMO HERE
for your second suggestion .you can locate -PP first and then substract characters like that :
 select substr(TestC, locate('-pp', TestC) - 2, 5) as testc, count(*)
 from testT
 where locate('-pp', TestC) > 2
 group by substr(TestC, locate('-pp', TestC) - 2, 5)

DEMO HERE

A: You need to add the TestC in the select:
SELECT TestC, count(testC)
from testT
where testC like '%-PP%'
group by testC

EDIT:
Definitely a much more reasonable question.
select substr(TestC, locate('-pp', TestC) - 2, 5), count(*)
from testT
where locate('-pp', TestC) > 2
group by substr(TestC, locate('-pp', TestC) - 2, 5)

This assumes that you want the two characters before the '-pp'.  It filters out any rows where '-pp' starts on the first or second character.


text:
Q: ParseUser.setEmail() does not work with "some kind of Strings"? I'm trying to set the email in a user obtained from Facebook SDK. If I set the email with any string like this:
user.setEmail("whatever@whwhwh.com");
user.saveInBackground();

It works, no problem... it appears in Parse's Data Browser...
If I try to do what I need to do(see code below), then it doesn't work, I've checked the String value and it's ok, it is the needed email....I've tried different things.. no luck.. Please help, thanks.
user.setEmail(user.getProperty("email").toString());
user.saveInBackground();

A: Make sure the email being supplied is not used by any other user. This is because an email must be unique.
When calling saveInBackground, it will actually not throw any exception if one does occur. So in your case, if the email is a duplicate, the email won't get saved and no exception is thrown.
To catch an exception with saveInBackground, you can use the SaveCallback.
user.saveInBackground(new SaveCallback() {
  public void done(ParseException e) {
    if (e == null) {
      // No exception
    } else {
      // Exception occured
    }
  }
});

For a list of exceptions you can refer to ParseException.


text:
Q: Symlink Sublime Text 2 Settings - Other Machines (Windows) I got my Sublime Text 2 Settings to symlink from dropbox on my first machine (laptop). I am now trying to get my second machine to read those setttings using the instructions at
https://packagecontrol.io/docs/syncing#dropbox-windows
I am mostly having trouble with this command
cmd /c mklink /D User $env:userprofile\Dropbox\Sublime\User
I am running
cmd /c mklink /D User c:\Users\Ross Dallaire\Dropbox\Sublime\User
and getting
The syntax of the command is incorrect.


text:
Q: How do I divide one row in a DataFrame with all other rows in another df? I have two DataFrames, df1 and df2. I want to divide each row in one df with the row in my other df. When I try this by myself, I only get NaN values.
df1 has one row and three columns, and looks likes this:
    0         1         2
0 -0.001506  0.000357 -0.002386

I want to divide each row in my other DataFrame, df2, that looks like this:
0   1   2
-0.008225100913712424   0.002488360440698889    -0.008225100913712424
-0.0012552065743555163  0.002048857368006418    -0.0001238320387255687
-0.0009167397808822475  0.001411666779150167    -0.0007873838608803974
-0.0005182164342202311  0.0016391411125882271   0.001532118153346973
-0.002096707101822415   0.00020798435058289044  -0.0020292527178495945
-0.0006015392658972329  0.0006577578888782298   0.00011805910826012678
-8.441050516860837e-05  0.0009791618599572782   0.0009791618599572782
-0.000343184413801656   0.00046695584173006566  -0.00024754285585693037
-0.0003435148893994322  0.0010474388430867787   0.0009629679686444792
-0.0014786804752094929  0.0022067330755990433   0.0022067330755990433

Desired output:
4,46    6,96    3,45
-0,17   5,73    0,05
-0,39   3,95    0,33
-0,66   4,59    -0,64
0,39    0,58    0,85
-0,60   1,84    -0,05
-0,94   2,74    -0,41
-0,77   1,31    0,10
-0,77   2,93    -0,40

A: Just do:
df2.div(df1.iloc[0])

Or
df2.div(df1.values)

Output (your output seems incorrect: -0.008225 / -0.001506 = 5.46):
          0         1         2
0  5.461554  6.970197  3.447234
1  0.833471  5.739096  0.051899
2  0.608725  3.954249  0.330002
3  0.344101  4.591432 -0.642128
4  1.392236  0.582589  0.850483
5  0.399428  1.842459 -0.049480
6  0.056049  2.742750 -0.410378
7  0.227878  1.308000  0.103748
8  0.228098  2.934002 -0.403591
9  0.981860  6.181325 -0.924867

A: Try
df2[:] = df2.values/df1.values
df2
Out[170]:
          0         1         2
0  5.461554  6.970197  3.447234
1  0.833471  5.739096  0.051899
2  0.608725  3.954249  0.330002
3  0.344101  4.591432 -0.642128
4  1.392236  0.582589  0.850483
5  0.399428  1.842459 -0.049480
6  0.056049  2.742750 -0.410378
7  0.227878  1.308000  0.103748
8  0.228098  2.934002 -0.403591
9  0.981860  6.181325 -0.924867


text:
Q: Performance Problems - Large DLLs and Large Namespaces This is sort of the next step of the LINQ to DB2 question I asked here.
Following zb_z's answer, I poked around a bit with the code for DB_Linq and have managed to add working DB2 support.  (It's still in its infancy now, not ready to be contributed back to the project yet.)  The proof of concept worked great, it was pretty exciting actually.  However, I've run into another hiccup along the way.
As it turns out, our DB2 database is big.  8,306 tables big.  So the code that was generated turned out to be over 5.2 million lines of code.  In one file.  Needless to say, Visual Studio didn't much care for it :)
So I further modified the generator to spit out each table class into its own file.  This left me with 8,307 files (the data context and one for each table, which extend the data context with table properties).  Visual Studio still didn't like it, understandably, so I wrapped up the code generation and compilation in a script and just run that to output a DLL for my projects to use.
A 36 MB DLL.
Now, searching around a bit on performance led me to this SO question (which itself references this one) and I've followed the answers and the links and see what they're saying.  So this leads me to wonder if its perhaps the existence of over 8,000 classes within the same namespace that's the culprit of noticeable performance issues.
My test for performance was to write a little console app that initializes the data context, grabs the data with LINQ, prints out a row count, grabs the data with classic ADO, and prints out another row count.  Each statement includes a time stamp.  Adding more queries to test, etc. always results in the same performance.  The LINQ code takes several seconds to run, while the ADO fills the dataset in the blink of an eye.
So I guess this ends up being a somewhat open-ended (and long-winded, sorry about that) question.  Does anybody have any ideas on speeding up performance here?  Anything simple to tweak, or design considerations I could apply?
EDIT
A few things to note:

*

*If I restrict the code generation to a subset of tables (say, 200) then it runs much faster.

*Stepping through in the debugger, the length of time is spent on the line var foo = from t in bank1.TMX9800F where t.T9ADDEP > 0 select t.T9ADDEP and when I expand the property in the debugger to enumerate the results (or let it go to the next line which does a .Count()) then that part takes no time at all.

EDIT
I can't post the entire generated DLLs, but here's the code for the test app:
static void Main(string[] args)
        {
            Console.WriteLine(string.Format("{0}: Process Started", DateTime.Now.ToLongTimeString()));

            // Initialize your data contexts
            var bank1 = new BNKPRD01(new iDB2Connection(ConfigurationManager.ConnectionStrings["DB2"].ConnectionString));
            var bank6 = new BNKPRD06(new iDB2Connection(ConfigurationManager.ConnectionStrings["DB2"].ConnectionString));
            Console.WriteLine(string.Format("{0}: Data contexts initialized", DateTime.Now.ToLongTimeString()));

            var foo = from t in bank1.TMX9800F where t.T9ADDEP > 0 select t; // <- runs slow
            Console.WriteLine(string.Format("{0}: {1} records found in BNKPRD01 test table", DateTime.Now.ToLongTimeString(), foo.Count().ToString()));

            var baz = from t in bank6.TMX9800F where t.T9ADDEP > 0 select t; // <- runs slow
            Console.WriteLine(string.Format("{0}: {1} records found in BNKPRD06 test table", DateTime.Now.ToLongTimeString(), baz.Count().ToString()));

            var ds = new DataSet();
            using (var conn = new iDB2Connection(ConfigurationManager.ConnectionStrings["DB2"].ConnectionString))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM BNKPRD01.TMX9800F WHERE T9ADDEP > 0";
                    new IBM.Data.DB2.iSeries.iDB2DataAdapter(cmd).Fill(ds);
                }
            }
            Console.WriteLine(string.Format("{0}: {1} records found in BNKPRD01 test table", DateTime.Now.ToLongTimeString(), ds.Tables[0].Rows.Count.ToString()));

            ds = new DataSet();
            using (var conn = new iDB2Connection(ConfigurationManager.ConnectionStrings["DB2"].ConnectionString))
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM BNKPRD06.TMX9800F WHERE T9ADDEP > 0";
                    new IBM.Data.DB2.iSeries.iDB2DataAdapter(cmd).Fill(ds);
                }
            }
            Console.WriteLine(string.Format("{0}: {1} records found in BNKPRD06 test table", DateTime.Now.ToLongTimeString(), ds.Tables[0].Rows.Count.ToString()));

            Console.WriteLine("Press return to exit.");
            Console.ReadLine();
        }

Maybe I'm missing something obvious or there's something about LINQ I didn't grok?
EDIT
Upon discussion with Jon and Brian below, I've stepped further into the DB_Linq code that gets called when the LINQ query is created and came across the long step:
public override IEnumerable<MetaTable> GetTables()
        {
            const BindingFlags scope = BindingFlags.GetField |
                BindingFlags.GetProperty | BindingFlags.Static |
                BindingFlags.Instance | BindingFlags.NonPublic |
                BindingFlags.Public;
            var seen = new HashSet<Type>();
            foreach (var info in _ContextType.GetMembers(scope))
            {
                // Only look for Fields & Properties.
                if (info.MemberType != MemberTypes.Field && info.MemberType != MemberTypes.Property)
                    continue;
                Type memberType = info.GetMemberType();

                if (memberType == null || !memberType.IsGenericType ||
                        memberType.GetGenericTypeDefinition() != typeof(Table<>))
                    continue;
                var tableType = memberType.GetGenericArguments()[0];
                if (tableType.IsGenericParameter)
                    continue;
                if (seen.Contains(tableType))
                    continue;
                seen.Add(tableType);

                MetaTable metaTable;
                if (_Tables.TryGetValue(tableType, out metaTable))
                  yield return metaTable;
                else
                  yield return AddTableType(tableType);
            }
        }

That loop iterates 16,718 times.

A: Posting the console app would really help.
Having many classes in a namespace and in an assembly will slow down compilation and there will be a one-time hit of JITting for each method in each type... but I wouldn't expect it to slow down LINQ queries.
You should check what SQL is actually being generated from your LINQ queries. I would expect the problem to lie there.

A: I just created a small test project with 10.000 classes in a namespace and while there's a noticeable overhead when loading/jitting the assembly I wouldn't say that it is particularly slow. So it is probably not the number of classes itself that's the reason for the bad performance you're seeing.
I'm Jon here, it would be helpful with more info on your test app.


text:
Q: Passing char* to a function in combination with memcpy usually a basic question, but maybe I am just too stupid. I try to pass an char * as output trought the parameter of a function. Inside the function I create a temporary char * which I want to memcpy to the address I've passed. Here is the code:
#define BLOCKSIZE=1024
int myFunction(char *s, char **out) {
  int i = strlen(s);
  *out = (char *)malloc(BLOCKSIZE);
  char tmp[BLOCKSIZE];

  strcpy(tmp, s);
  tmp[++i] = 0x0f;

  for(int i=strlen(s);i < BLOCKSIZE; i++) {
    tmp[i] = 0xcc;
  }

  memcpy(*out, tmp, BLOCKSIZE);

  return 0;
}

int main() {
  char *s = "Hello World";
  char *o = (char *)malloc(BLOCKSIZE);

  myFunction(s, &o);

}

The problem is, the stack gets corrupted after it jumps out of the function myFunction..
Is there another way to do it?
Thank you in advance!
Best,
Update: Problem solved
The for loop part i < BLOCKSIZE must be changed to i < (BLOCKSIZE - 1).

A: Your first problem is that you malloc twice, before and in the function. The malloc outside the call (second line of main) is leaked.
The second problem (and this tells me you didn't even compile the code) is that you use i before defining it.


text:
Q: Docker out of space when running bundle install I'm trying to build an image for my app, FROM ruby:2.2.1, my app folder sums up about 200 mb compressed.
I'm receiving a "Your disk is full" when running bundle install. It's also takes too much time to create the compressed context. However runing a df on /var/ shows more than 1TB available, this however is not what bother me.
My question is, can I ignore everything using an * in .dockerignore and then add my root project folder as a volume using docker-compose? does this sounds like a good idea?
I've also think in:

*

*Move the Dockerfile to a subfolder (but I think i'm not able to add a parent folder as volume using docker compose

*Do a git clone in the Dockerfile, but as I already have the files on my computer this sounds like a dumb step.

*Should I just figure out how to add more disk space to the docker container? But I still dont like the time that it takes to create the context.

A: Note, your question doesn't match your title or first half of your post, I'll answer what you've asked.

My question is, can I ignore everything using an * in .dockerignore and then add my root project folder as a volume using docker-compose? does this sounds like a good idea?

You can add your project with a volume in docker-compose, but you lose much of the portability (your image will be incomplete if anyone else tries to use it without your volume data). You also lose the ability to do any compilation steps and may increase your container startup time as it pulls in dependencies. Lastly, if you run out of space on build, there's a good chance you'll run out of space on a run unless your volume data is a significant portion of your container size.

If I ignore a file on .dockerignore can I use COPY on that file from Dockerfile?

No, you can't use COPY or ADD on any file that's excluded in the push to the docker daemon via .dockerignore.


text:
Q: Why is urlparse.urlenparse works inconsistent? When netloc is empty urlparse.urlunparse is inconsistent:
>>> urlparse.urlunparse(('http','','test_path', None, None, None))
'http:///test_path'
>>> urlparse.urlunparse(('ftp','','test_path', None, None, None))
'ftp:///test_path'
>>> urlparse.urlunparse(('ssh','','test_path', None, None, None))
'ssh:test_path'

Is it a bug or a feature?
I would expect urlunparse to behave always, as in first example, even if scheme is not recognized.

A: The data tuple you are passing to urlunparse has the following components:
scheme, netloc, url, query, fragment = data

When there is no netloc, and the scheme is not in uses_netloc, the url is
    url = scheme + ':' + url

That is the way urlunparse (which calls urlunsplit) is defined:
def urlunsplit(data):
    ...
    scheme, netloc, url, query, fragment = data
    if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
        if url and url[:1] != '/': url = '/' + url
        url = '//' + (netloc or '') + url
    if scheme:
        url = scheme + ':' + url

Note that 'ssh' is not in uses_netloc:
uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet',
               'imap', 'wais', 'file', 'mms', 'https', 'shttp',
               'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '',
               'svn', 'svn+ssh', 'sftp','nfs','git', 'git+ssh']

You do get a url that begins with ssh:// if you supply a netloc:
In [140]: urlparse.urlunparse(('ssh','netloc','test_path', None, None, None))
Out[140]: 'ssh://netloc/test_path'


text:
Q: JavaScript - Run callback after all fetch requests to finish in multiple for loops - errored or not I'm writing a little proof of concept thing, which downloads all my HTML assets via fetch(). Currently, I query all the tags with a compatible asset and run it through a for loop for each asset type. What I need to do is run a callback function after all the requests in the loops have finished. I tried await but it downloads each asset one by one. How can I do this?
const scripts = document.querySelectorAll("script");
const links = document.querySelectorAll("link");
const images = document.querySelectorAll("img");
for (const script of scripts) {
    (async (s) => {
        const doIgnore = s.getAttribute("data-ignoreload");
        if (doIgnore) return;
        const src = s.getAttribute("data-src");
        if (!src) {
            console.error("Script does not have a data-src prop.");
            return;
        }
        fetch(src)
            .then(x => x.text())
            .then(r => {
                const newScript = document.createElement("script");
                newScript.innerHTML = r;
                document.body.appendChild(newScript);
            })
            .catch(err => {
                console.error(`Error loading script with src ${src}: ${err}`);
            });
    })(script);
}
for (const link of links) {
    (async (l) => {
        const doIgnore = l.getAttribute("data-ignoreload");
        if (doIgnore) return;
        const rel = l.getAttribute("rel");
        if (!(rel == "stylesheet")) {
            return;
        }
        const href = l.getAttribute("data-href");
        if (!href) {
            console.error("Stylesheet does not have a data-href prop.");
            return;
        }
        fetch(href)
            .then(x => x.text())
            .then(r => {
                const newStyle = document.createElement("style");
                newStyle.innerHTML = r;
                document.head.append(newStyle);
            })
            .catch(err => {
                console.error(`Error loading stylesheet with href ${href}: ${err}`);
            });
    })(link);
}
for (const image of images) {
    (async (i) => {
        const doIgnore = i.getAttribute("data-ignoreload");
        if (doIgnore) return;
        const src = i.getAttribute("data-src");
        if (!src) {
            console.error("Image does not have a data-src prop.");
            return;
        }
        fetch(src)
            .then(x => x.blob())
            .then(r => {
                const url = URL.createObjectURL(r);
                i.setAttribute("src", url);
            })
            .catch(err => {
                console.error(`Error loading image ${src}: ${err}`);
            });
    })(image);
}

A: Push all of your promises into an array, and then use Promise.allSettled(promises).then((results) => {})
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
Example:
const promises = images.map(async (image) => {
    // do some async work
    return fetch(whatever); // don't .catch this

})

Promise.allSettled(promises).then((results) => {
  // results is a result of errors or successes
})


text:
Q: Convert Sage List of list of list to R list of list of list I have a sage list of list of list that is the result of some function applied over an R list of list of list (converted to sage format)
The code goes like this:
%r
my_r_list<-load("my_r_list.RData")

for d in range(D):
    for s in range(S):
        for c in range(C):
            my_sage_list[d][s][c] = ("my_r_list")[[d+1]][[s+1]][[c+1]]._sage_()
            output_my_sage_list[d][s][c] = some_function(my_sage_list[d][s][c])

I would like to convert output_my_sage_list back into an R list so as to save it into an .RData file
Documentation on interface Sage with R is mainly about going from R to Sage but not the other way around.This question concerns converting a sagemath matrix to R matrix using r.matrix()' so i tried using 'r.list()' but with no luck. I also tried the simpleoutput_my_r_list = r(output_my_sage_list)which gives no error but the output is not correct as doingoutput_my_r_list[0][0]` doesn't give the last level of list but directly some values.
A reproducible code (bypassing the R to Sage part) would be:
    output_d = [[] for _ in range(9)]
    for d in range(9):
        output_s = [[] for _ in range(4)]
        output_d[d] = output_s
        for s in range(4):
            output_c = [[] for _ in range(2)]
            output_s[s] = output_c
            for k in range(2):
                res = random()
                output_c[k] = res

I would like to convert output_d to an R list

A: The key here is your statement

I also tried the simple output_my_r_list = r(output_my_sage_list) which gives no error but the output is not correct as doing output_my_r_list[0][0] doesn't give the last level of list but directly some values.

Sage actually documents that it will make the list just one concatenated list, or more properly an R vector:
    sage: x = r([10.4,5.6,3.1,6.4,21.7]); x
    [1] 10.4  5.6  3.1  6.4 21.7

The following assignment creates a vector $y$ with 11 entries which
consists of two copies of $x$ with a 0 in between::

    sage: y = r([x,0,x]); y
    [1] 10.4  5.6  3.1  6.4 21.7  0.0 10.4  5.6  3.1  6.4 21.7

This is directly modeled upon R usage, and presumably (via some nesting procedure) even just comes from it:
The further assignment

> y <- c(x, 0, x)

would create a vector y with 11 entries consisting of two copies of
with a zero in the middle place.

So your beef is not exactly with Sage, but R, as (somehow) Sage gets the 'right' thing here.  Sage does this because  here it says
def _left_list_delim(self):
    return "c("

and then the R behavior follows as this is done recursively and it makes a vector of vectors.
A hack around this would be to return "list(" there.  Another hack would be to try to use r.eval("list(something)") but I didn't experience a lot of success with this.
It would be nice to find a way to deal with this more easily, of course, and in the return direction Sage attempts to take nested R stuff and keep it nested (with what success, I don't know).


text:
Q: Select value not selected in Angularjs I have this html markup:

  Property {{$index + 1}} ({{prop.AddressLine1}})

       <select ng-model="prop.Grade" class="form-control" ng-options="opt.name for opt in propGradings track by opt.id">                                                                       <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>     </select>

This static array to fill in the dropdown:
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];

I'm able to load the items in the dropdown, but I'm not able to preselect the correct value based on the prop.Grade value.
HTML Output:

Any idea what am I doing wrong?

A: When selecting options from a dropdown, type matters for binding purposes. When using ng-options, you can use as to bind something to the model as a non-string value. In your case, you may want to bind to the integer value of the id.
Syntax: select as label for value in array
> select: The value that gets bound to ng-model
> label: What value visibly shows up in the dropdown
> value: Current item in array
> array: Data source for generating the options
Example of binding to an integer value:

var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
  $scope.props = [{Grade: 1}];
  $scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];

});

  Binding with an integer value:

    Property {{$index + 1}} ({{prop.AddressLine1}})

      <select ng-model="prop.Grade" class="form-control" ng-options="opt.id as opt.name for opt in propGradings">
        <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
      </select>

Example of binding to a string value:

var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
  $scope.props = [{Grade: "1"}];
  $scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];

});

  Binding with a string value:

    Property {{$index + 1}} ({{prop.AddressLine1}})

      <select ng-model="prop.Grade" class="form-control" ng-options="opt.name as opt.name for opt in propGradings">
        <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
      </select>


text:
Q: find a Möbius transformation between the unit disc to $\{|\operatorname{im}(z)|<1\}$ find a Möbius transformation between the unit disc to $\bigl\{|\operatorname{im}(z)|<1\bigr\}$ that satisfies: $f(0)=0,\; |f'(0|)>0$.
My try: I tried to plug all this condition and got:
$\frac{ax}{cx+d}$ and that a and d must have the same sign, but nothing else.


text:
Q: override onbackPressed() by another's activity default I have 2 activities.
MyMain
MySecond I call MySecond activity in MyMain activity. And what i want, that when pressing back button in MySecond activity, it doesn't return to MyMain activity, but return to the screen where MyMain activity was called. I found a way to ovverride it, so it just opens home screen by this:
 @Override
 public void onBackPressed() {
      Intent setIntent = new Intent(Intent.ACTION_MAIN);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(setIntent);
        return;
 }

A: You may want to try this:
@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

That will move not only the current activity but all activities in your task (which would be your app) to the back of the activity stack. It should then return you to wherever you were before your MyMain activity started.


text:
Q: Image of linear system I found the determinant and null space of the matrix in previous exercises, but I am having trouble understanding how to find the image of following matrix.
"Given the matrix
$$A_{a} =
 \begin{pmatrix}
  a & 1 & 1 \\
  a & 0 & a \\
  0 & 1 & a
 \end{pmatrix}$$
for $a\in \mathbb{R}$, determine the image
$$B(A_{a})=\{y\in \mathbb{R}^3 \mid A_ax=y\;,\;x\in \mathbb{R}^3 \}"$$
To me, it seems the equation $A_ax=y$ have so many unknowns; a, x and y?
Solutions and hints are very welcome.

A: The image is spanned by $A(e_1)=ae_1+ae_2$, $A(e_2)=e_1+e_3$ and $A(e_3)=e_1+ae_2+ae_3$ according to the matrix $A$. Here $e_1,e_2,e_3$ is a basis of $\mathbb{R}^3$, and $a\in \mathbb{R}$. For $a\neq 0, \frac{1}{2}$ the image is $\mathbb{R}^3$, because $\det(A)=a(1-2a)$, so that $A$ is a surjective linear map.

A: If the determinant is differen from zero, it means that the the matrix has three eigenvalues (different from zero) with independent eigenvectors. You have to concentrate then on the values $a$ that make the determinant equal to zero. In this case it is useful to determine the eigenvectors and to see if their eigenvalue is different from zero or not. If the eigenvector is asociated with an eigenvalue different from zero, it is included in the image of the matrix. In the oposite case, the eigenvector is not included in the image of the matrix. I hope this answer to be useful for you

A: A general method is with Gaussian elimination. We can do
\begin{align}
\begin{pmatrix}
  a & 1 & 1 \\
  a & 0 & a \\
  0 & 1 & a
\end{pmatrix}
&\to
\begin{pmatrix}
  a & 1 & 1 \\
  0 & -1 & a-1 \\
  0 & 1 & a
\end{pmatrix} && R_2\gets R_2-R_1
\\
&\to
\begin{pmatrix}
  a & 1 & 1 \\
  0 & -1 & a-1 \\
  0 & 0 & 2a-1
\end{pmatrix} && R_3\gets R_3+R_2
\\
\end{align}

*

*If $a\ne0$ and $a\ne 1/2$, the rank of the matrix is $3$, so the image is $\mathbb{R}^3$.

*If $a=1/2$, the rank is $2$ and the image is generated by the first two columns of the matrix, so a basis consists of
$$
\begin{pmatrix}1/2 \\ 1/2 \\ 0\end{pmatrix},
\qquad
\begin{pmatrix}1 \\ 0 \\ 1\end{pmatrix}
$$

*If $a=0$, the rank is $2$ and the image is generated by the last two columns of the matrix, so a basis consist of
$$
\begin{pmatrix}1 \\ 0 \\ 1\end{pmatrix},
\qquad
\begin{pmatrix}1 \\ 0 \\0\end{pmatrix}
$$

A: You want to find $\{Ax: x \in \mathbb{R}^3\}$.  First note that $Ax$ is a linear combination of the columns of $A$, where the coefficients of this combination are the components of $x$.  So the question is: what is the subspace obtained from all possible linear combinations of the columns of $A$?
Observe from the lower-left 2 by 2 submatrix that if $a$ is nonzero, then the last two rows are linearly independent.  Looking at the second column and first column, we see that the only way the first row is a linear combination of the second and third rows is if it is equal to their sum, in which case (by the entries in the third column) $2a=1$, or $a=1/2$.
Thus, if $a \ne 0$ and $a \ne 1/2$, the matrix has rank 3. In this case, $A$ is invertible and so is a bijective map from $\mathbb{R}^3$ to itself.  The image $\{Ax: x \in \mathbb{R}^3\}$ is then all of $\mathbb{R}^3$.
If $a=0$, then the matrix $A$ is equal to $\left(\begin{array}{ccc} 0 & 1 & 1 \\ 0 & 0 & 0 \\ 0 & 1 & 0\end{array}\right)$.  The column space of $A$ is then equal to the set of all linear combinations of the vectors $(0,0,1)^T$ and $(1,0,0)^T$.
If $a=1/2$, the matrix $A$ is equal to $\left(\begin{array}{ccc} 1/2 & 1 & 1 \\ 1/2 & 0 & 1/2 \\ 0 & 1 & 1/2\end{array}\right)$.   The third column is equal to the sum of the first column and half the second column. So the third column can be ignored, since the column space is the span of the first two columns of $A$. Thus, the column space is the subspace spanned by $(1,1,0)^T$ and $(1,0,1)^T$.


text:
Q: monkey patching at the npm package level? I'd like to extend the npm package "truffle", but currently in version 4 (and version 5), "truffle" doesn't have a plugin extension mechanism.
So the broad question is how to "monkey patch" that. One possiblity would be to list the truffle package as a dependancy and then run some shell commands like "patch" to modify truffle which is generally installed in node_modules.
Does npm have a way where I could run such shell commands after node dependencies are successfuly installed?
Any other suggestions? (Another method might be monkey patching at the nodejs level, but I think that will be more cumbersome.)
EDIT
The postinstall field of scripts in the package.json may be what I am looking for.

A: In the end we used patch-package


text:
Q: Read JSON array from websocket data feed ReactJS - TypeError: Cannot read property '0' of undefined
this.ws.onmessage = e => {
  var tbox = JSON.parse(e.data);
  this.setState({
  user : this.state.usernames.concat(tbox.data[0].user),
  messages : this.state.messages.concat(tbox.data[0].message)
})
console.log(tbox.data[0].user + ': ' + tbox.data[0].html);

I'm trying to parse, setState and display data in realtime (in a Ant Design List component) from a public websocket api.
I managed to get thus far but if someone can better help me steer in the right direction, that would be much appreciated!

const URL = 'wss://www.bitmex.com/realtime?subscribe=chat:1'

const data = [
  {
    user: 'buythediplosers',
    message: 'im over here waiting for nothing lol',
    time: '4:20 AM', /*TODO: let the user set their timezone*/
  },
];

class Trollbox extends Component {
  constructor(props) {
    super(props);
    this.state = {
        usernames: [],
        messages: [],
        timestamps: [],
    }
  }

  ws = new WebSocket(URL)

  componentDidMount() {
    this.ws.onopen = () => {
      console.log('connected')
    }

    this.ws.onmessage = e => {
      var tbox = JSON.parse(e.data);
      this.setState({
        user : this.state.usernames.concat(tbox.data[0].user),
        messages : this.state.messages.concat(tbox.data[0].message)
      })
      console.log(tbox.data[0].user + ': ' + tbox.data[0].html);
    }

    this.ws.onclose = () => {
      console.log('disconnected')
      this.setState({
        ws: new WebSocket(URL),
      })
    }
  }

  render() {
    return (

          <List
            itemLayout="horizontal"
            dataSource={data}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  description={

                        {item.user}: {item.message} {item.time}

                  }
                />
              </List.Item>
            )}
          />

...

console.log(tbox.data[0].user + ': ' + tbox.data[0].html);

shows me what I want to see in the console, which is a step forward for me:

   console.log(this.state.usernames + ': ' + this.state.messages);

though, this bunches it all up unlike the previous line while still giving me an error:

EDIT: JSON sample:
{
   "table":"chat",
   "action":"insert",
   "keys":[
      "id"
   ],
   "data":[
      {
         "channelID":1,
         "date":"2019-11-27T07:20:30.862Z",
         "fromBot":false,
         "html":"Keepitreal: ok bruh\n",
         "id":43087881,
         "message":"Keepitreal: ok bruh",
         "user":"cryxix"
      }
   ],
   "filterKey":"channelID"
}

A: Looking at the images you provided in your comments, this one:

Shows that the first 3 responses you are getting are different than the ones you are expecting, and don't have key called user in it, hence why you are getting that error. You can skip over it by adding a conditional like:
if(tbox.data){
      this.setState({
        user : this.state.usernames.concat(tbox.data[0].user),
        messages : this.state.messages.concat(tbox.data[0].message)
      })
}

In regards to your second question,

though, this bunches it all up unlike the previous line while still giving me an error:

This is because you are posting the entirety of your this.state.usernames which is repeatedly growing larger as an array. If you want to post it that way, you have to loop through the state and log each one separately.

A: "this.ws.onmessage" handles every message from the other endpoint, so you have to make sure your code can handle every case that could happen.
first time json without tbox.data comes, tbox.data is undefined, so you have the error "Cannot read property '0' of undefined".
second time the error is "Cannot read property 'user' of undefined", so tbox.data is not undefined but tbox.data[0] is undefined. I think tbox.data is a empty array(data : []).
if you want to use tbox.data[0].user, check tbox.data[0]  is not undefined.
try
if(tbox.data && tbox.data.length > 0){ .....}


text:
Q: Hyperlinked sectionnames in fancyheader I am trying to create a header that consist of chaptername and sectionname (chaptername:sectionname) both of them a hyperlink to chapter and section respectively. I am using Hungarian language so there are many accented word, and - as I gathered - hyperref do not support accented links and after all, section names can be the same in different chapters so I need to get some unique names. So I generate a unique ASCII section name (see \Section) and in \sectionmark I concatenated it with the name of the section and in \fancyhead I try to separate them again and using them in a \hyperlink command, but so far I failed. Here is the brief (not working) code example:
\documentclass[pdftex,a4paper,12pt,oneside]{book}%

\usepackage[latin2]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[magyar]{babel}
\usepackage{fancyhdr}
\usepackage{xstring}
\usepackage{hyperref}
\usepackage{bookmark}

\hypersetup{colorlinks,                               linkcolor=blue!80,filecolor=Orange,urlcolor=red!60,citecolor=magenta,
              linktoc=all,
            hypertexnames=false,
            unicode=true,
            bookmarksnumbered=false,
        pdfmenubar=true,%
          pdftoolbar=true
         }

\newcommand{\chapterlinkname}{}
\newcommand{\setchapterlinkname}[1]{\renewcommand{\chapterlinkname}{#1}}
\newcommand{\chapterlink}[1]{\setchapterlinkname{lnk:chap#1}\hypertarget{\chapterlinkname}{}}
\newcommand{\Chapter}[2]{\newpage\chapterlink{#2} \chapter{#1}}

\newcommand{\sectionlinkname}{}
\newcommand{\setsectionlinkname}[1]{\renewcommand{\sectionlinkname}{#1}}
\newcommand{\sectionlink}[1]{\setsectionlinkname{\chapterlinkname:sec#1}\hypertarget{\sectionlinkname}{}}
\newcommand{\Section}[2]{\sectionlink{#2}\section{#1}}

\newcommand{\seclink}{}
\newcommand{\secname}{}
\newcommand{\mystrsplit}[4]{
  \renewcommand{#3}{\StrBefore{#1}{#2}}
  \renewcommand{#4}{\StrBehind{#1}{#2}}
}

%------------------

\begin{document}

\pagestyle{fancy}
\fancyhf{}
\renewcommand{\chaptermark}[1]{\markboth{##1}{}}
\renewcommand{\sectionmark}[1]{\markright{\sectionlinkname,##1}}

\fancyhead[LO,RE]{\mystrsplit{\rightmark}{,}{\seclink}{\secname} \hyperlink{\chapterlinkname}{\bfseries\leftmark} : \hyperlink{\seclink}{\bfseries\secname}}

\fancyhead[LE,RO]{\bfseries\thepage}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\addtolength{\headheight}{2.5pt}
\fancypagestyle{plain}{\fancyhead{}\renewcommand{\headrulewidth}{0pt}}

\Chapter{Állóképek}{Allokepek}

\Section{Tükörkép}{Tukorkep}

\newpage

\Section{Sírkőgyártó}{Sirkogyarto}

\end{document}

I am using MiKTeX 2.9 with TeXnicCenter.

A: The following example first fixes a compatibility problem between hyperref and
magyar. Both redefine \refstepcounter. Then \@currentHref is available that contains
the name of the anchor used in hyperref's \refstepcounter. Then the titles of
the chapters or sections do not need to be used as target or label name.
\documentclass[pdftex,a4paper,12pt,oneside]{book}%

\usepackage[latin2]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{fancyhdr}

\usepackage[magyar]{babel}
% magyar.ldf redefines \refstepcounter in \extrasmagyar
% and overwrites hyperref's definition.
% The following hacks work around this by
% restoring hyperref's definition that will
% then call magyar.ldf's version.
\begingroup
  \extrasmagyar
  \global\let\MagyarRefstepcounter\refstepcounter
\endgroup
\let\refstepcounter\MagyarRefstepcounter
\usepackage{hyperref}
\let\HyperrefRefstepcounter\refstepcounter
\addto\extrasmagyar{%
  \let\refstepcounter\HyperrefRefstepcounter
}
\usepackage{bookmark}

\hypersetup{colorlinks,
            linkcolor=blue!80,filecolor=Orange,
            urlcolor=red!60,citecolor=magenta,
            linktoc=all,
            hypertexnames=false,
            unicode=true,
            bookmarksnumbered=false,
        pdfmenubar=true,%
          pdftoolbar=true
         }

\begin{document}

\pagestyle{fancy}
\fancyhf{}

% \@currentHref contains the anchor name
\makeatletter
\renewcommand{\chaptermark}[1]{%
  \markboth{\protect\hyperlink\@currentHref}{\thechapter. #1}}{}%
}
\renewcommand{\sectionmark}[1]{%
  \markright{\protect\hyperlink{\@currentHref}{\thesection. #1}}%
}

\fancyhead[LO,RE]{{\bfseries\leftmark} : {\bfseries\rightmark}}

\fancyhead[LE,RO]{\bfseries\thepage}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\addtolength{\headheight}{2.5pt}
\fancypagestyle{plain}{\fancyhead{}\renewcommand{\headrulewidth}{0pt}}

\chapter{Állóképek}

\section{Tükörkép}

\newpage

\section{Sírkogyártó}

\end{document}


text:
Q: How to convert a string into a readable view From some database i get string, it looks like this
[5] => Array
    (
        [0] => 6
        [body] =>  ÉÓËÒÅÎÎÅ ÔÅÂÅ ÖÅÌÁÀ ã×ÅÔÏ×, ÌÀÂ×É É ËÒÁÓÏÔÙ!
    )

How to convert this string into a readable view using php?
I'm use PDO type connection with option "SET NAMES utf8", maybe I need to change this option?

Using phpmyadmin i see this table decription
table description
and browse
table view

A: Lazy solution: set names to latin1 (or don't set it at all, as it's set by default).
It will return you results in original cp1251, which you can convert in any other encoding using iconv() or mb_convert_encoding().
Complex but proper solution: set the right encoding for the table columns. It have to be cp1251, not latin1. For this, you have to re-create tables using CHARACTER SET=1251 in table definition and then re-filling tables back with data.
After that everything will be back in order:

*

*phpmyadmin will show your data  correctly

*you will be able to set names to utf8 and get data in this encoding

*(most important part) WHERE and ORDER BY operators will stop driving you crazy.


text:
Q: pyqt : resize qdockwidget in maya

I've made a tool for Maya. And I used QDockWidget within QMainWindow for entire UI composition. As you and I know, I can "saveState" and "restoreState" to retain QToolBar, QDockWidget, and so on.
I don't know the reason, but in Maya I can't "restoreState" the actual state. It can restore all of the state for QToolBar, QDockWidget except the size of QDockWidget. So I want to try to resize QDockWidget programmatically. Is there any way to do that?

A: Try reimplementing the sizeHint for the top-level content widget of the dock-widget:
class MyWidget(QtGui.QWidget):
    _sizehint = None

    def setSizeHint(self, width, height):
        self._sizehint = QtCore.QSize(width, height)

    def sizeHint(self):
        if self._sizehint is not None:
            return self._sizehint
        return super(MyWidget, self).sizeHint()

UPDATE
Here's a simple demo that shows one way to implement this:
from PyQt4 import QtGui, QtCore

class DockContents(QtGui.QWidget):
    _sizehint = None

    def setSizeHint(self, width, height):
        self._sizehint = QtCore.QSize(width, height)

    def sizeHint(self):
        print('sizeHint:', self._sizehint)
        if self._sizehint is not None:
            return self._sizehint
        return super(MyWidget, self).sizeHint()

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.setCentralWidget(QtGui.QTextEdit(self))

        self.dock = QtGui.QDockWidget('Tool Widget', self)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)

        contents = DockContents(self)
        contents.setSizeHint(400, 100)
        layout = QtGui.QVBoxLayout(contents)
        layout.setContentsMargins(0, 0, 0, 0)
        self.toolwidget = QtGui.QListWidget(self)
        layout.addWidget(self.toolwidget)

        self.dock.setWidget(contents)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 600, 400)
    window.show()
    sys.exit(app.exec_())


text:
Q: AttributeError: type object 'sklearn.manifold._barnes_hut_tsne.array' has no attribute '__reduce_cython__' I'm trying to run a code in Python to import Kmeans using sklearn. However, when I try to import, I get this error message:

AttributeError: type object 'sklearn.manifold._barnes_hut_tsne.array' has no attribute 'reduce_cython'

sklearn is installed with all the necessary packages. I'm unsure as to what the problem might be. Here is part of the code from my work involving the import:
from sklearn.cluster import KMeans
num_clusters = 8
km = KMeans(n_clusters=num_clusters)
%time km.fit(tfidf_matrix)
clusters = km.labels_.tolist()

even if I put from sklearn.cluster import KMeans all by itself, I get the same error, so the error is coming from that line of code alone. Any help would be appreciated.
NOTE: I am using Jupyter Notebook and yes, I have installed any and all necessary packages as well as updated sklearn.

A: Just uninstalled scipy and installed it again and restarted
the kernel and then run the code.
It worked for me.
Basically it is due to the Kernel restart issue.


text:
Q: twig thumbnail - set relative offset I'm using OctoberCMS and my thumbnail gallery is generated this way:

The offset value will "overshoot" the picture, if the picture format is 1:1.
I'm looking for a way to get the very top of every image size, like the css property
background-position: 0% 0%;

Do you have any ideas?
Here's a picture, where you can see that twig "overshoots" in the top row:
Example

A: For this, you can use background-image property of CSS and with background-image property you can use background-position property.
For background-position property, you have more options here.

Note: For using backgrond-image property you have to use auto mode in thumbnail generator function.

If you have defined any link on that image you can use background-image property on the link and give inline CSS on it, like below

or Instead of  tag, You can use any HTML tags like
  and give CSS Properties(particular height and width) for that
 and manage your view.
Try this, and tell me your reviews.


text:
Q: Opening a date picker automatically when a page loads I'm writing a mobile app based on html, css and javascript. I need to open a date picker automatically when a page loads in mobile. How can I do it?

A: You need to wait for onload event and then call the open function for you date picker. Without knowing about whether you use jQuery or some other framework for date picker, it is hard to give more concrete instructions.
For jQuery it looks something like this
$( document ).ready(function() {
    // Open date picker
});

In case of not using jQuery and vanilla JS instead, refer to here
document.onload = function() {
    // Open date picker
};

A: You should be able to trigger it using jQuery's ready event. Judging from your tags, this should work. .datepicker-element is the selector for the element with the datepicker.
$( document ).ready(function() {
    $('.datepicker-element').datepicker( "show" );
});


text:
Q: How to Avro Binary encode the JSON String using Apache Avro? I am trying to avro binary encode my JSON String. Below is my JSON String and I have created a simple method which will do the conversion but I am not sure whether the way I am doing is correct or not?
public static void main(String args[]) throws Exception{
try{
    Schema schema = new Parser().parse((TestExample.class.getResourceAsStream("/3233.avsc")));
    String json="{"+
        "  \"location\" : {"+
        "    \"devices\":["+
        "      {"+
        "        \"did\":\"9abd09-439bcd-629a8f\","+
        "        \"dt\":\"browser\","+
        "        \"usl\":{"+
        "          \"pos\":{"+
        "            \"source\":\"GPS\","+
        "            \"lat\":90.0,"+
        "            \"long\":101.0,"+
        "            \"acc\":100"+
        "          },"+
        "          \"addSource\":\"LL\","+
        "          \"add\":["+
        "            {"+
        "              \"val\":\"2123\","+
        "              \"type\" : \"NUM\""+
        "            },"+
        "            {"+
        "              \"val\":\"Harris ST\","+
        "              \"type\" : \"ST\""+
        "            }"+
        "          ],"+
        "          \"ei\":{"+
        "            \"ibm\":true,"+
        "            \"sr\":10,"+
        "            \"ienz\":true,"+
        "            \"enz\":100,"+
        "            \"enr\":10"+
        "          },"+
        "          \"lm\":1390598086120"+
        "        }"+
        "      }"+
        "    ],"+
        "    \"ver\" : \"1.0\""+
        "  }"+
        "}";

    byte[] avroByteArray = fromJsonToAvro(json,schema);

} catch (Exception ex) {
    // log an exception
}

Below method will convert my JSON String to Avro Binary encoded -
private static byte[] fromJsonToAvro(String json, Schema schema) throws Exception {

    InputStream input = new ByteArrayInputStream(json.getBytes());
    DataInputStream din = new DataInputStream(input);

    Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);

    DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
    Object datum = reader.read(null, decoder);

    GenericDatumWriter<Object>  w = new GenericDatumWriter<Object>(schema);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    Encoder e = EncoderFactory.get().binaryEncoder(outputStream, null);

    w.write(datum, e);
    e.flush();

    return outputStream.toByteArray();
}

Can anyone take a look and let me know whether the way I am trying to avro binary my JSON String is correct or not?

A: I think OP is correct. This will write Avro records themselves without the schema that would be present if this were an Avro data file.
Here's a couple examples within Avro itself (useful if you are working with files.
    • From JSON to Avro: DataFileWriteTool
    • From Avro to JSON: DataFileReadTool
Here's a complete example going both ways.
@Grapes([
    @Grab(group='org.apache.avro', module='avro', version='1.7.7')
])

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.io.JsonEncoder;

String schema = '''{
  "type":"record",
  "namespace":"foo",
  "name":"Person",
  "fields":[
    {
      "name":"name",
      "type":"string"
    },
    {
      "name":"age",
      "type":"int"
    }
  ]
}'''
String json = "{" +
  "\"name\":\"Frank\"," +
  "\"age\":47" +
"}"

assert avroToJson(jsonToAvro(json, schema), schema) == json

public static byte[] jsonToAvro(String json, String schemaStr) throws IOException {
    InputStream input = null;
    GenericDatumWriter<GenericRecord> writer = null;
    Encoder encoder = null;
    ByteArrayOutputStream output = null;
    try {
        Schema schema = new Schema.Parser().parse(schemaStr);
        DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema);
        input = new ByteArrayInputStream(json.getBytes());
        output = new ByteArrayOutputStream();
        DataInputStream din = new DataInputStream(input);
        writer = new GenericDatumWriter<GenericRecord>(schema);
        Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
        encoder = EncoderFactory.get().binaryEncoder(output, null);
        GenericRecord datum;
        while (true) {
            try {
                datum = reader.read(null, decoder);
            } catch (EOFException eofe) {
                break;
            }
            writer.write(datum, encoder);
        }
        encoder.flush();
        return output.toByteArray();
    } finally {
        try { input.close(); } catch (Exception e) { }
    }
}

public static String avroToJson(byte[] avro, String schemaStr) throws IOException {
    boolean pretty = false;
    GenericDatumReader<GenericRecord> reader = null;
    JsonEncoder encoder = null;
    ByteArrayOutputStream output = null;
    try {
        Schema schema = new Schema.Parser().parse(schemaStr);
        reader = new GenericDatumReader<GenericRecord>(schema);
        InputStream input = new ByteArrayInputStream(avro);
        output = new ByteArrayOutputStream();
        DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);
        encoder = EncoderFactory.get().jsonEncoder(schema, output, pretty);
        Decoder decoder = DecoderFactory.get().binaryDecoder(input, null);
        GenericRecord datum;
        while (true) {
            try {
                datum = reader.read(null, decoder);
            } catch (EOFException eofe) {
                break;
            }
            writer.write(datum, encoder);
        }
        encoder.flush();
        output.flush();
        return new String(output.toByteArray());
    } finally {
        try { if (output != null) output.close(); } catch (Exception e) { }
    }
}

For the sake of completeness, here's an example if you were working with streams (Avro calls these container files) instead of records.  Note that when you go back from JSON to Avro, you don't need to pass the schema.  This is because it is present in the stream.
@Grapes([
    @Grab(group='org.apache.avro', module='avro', version='1.7.7')
])

// writes Avro as a http://avro.apache.org/docs/current/spec.html#Object+Container+Files rather than a sequence of records

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.io.JsonEncoder;

String schema = '''{
  "type":"record",
  "namespace":"foo",
  "name":"Person",
  "fields":[
    {
      "name":"name",
      "type":"string"
    },
    {
      "name":"age",
      "type":"int"
    }
  ]
}'''
String json = "{" +
  "\"name\":\"Frank\"," +
  "\"age\":47" +
"}"

assert avroToJson(jsonToAvro(json, schema)) == json

public static byte[] jsonToAvro(String json, String schemaStr) throws IOException {
    InputStream input = null;
    DataFileWriter<GenericRecord> writer = null;
    Encoder encoder = null;
    ByteArrayOutputStream output = null;
    try {
        Schema schema = new Schema.Parser().parse(schemaStr);
        DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema);
        input = new ByteArrayInputStream(json.getBytes());
        output = new ByteArrayOutputStream();
        DataInputStream din = new DataInputStream(input);
        writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>());
        writer.create(schema, output);
        Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
        GenericRecord datum;
        while (true) {
            try {
                datum = reader.read(null, decoder);
            } catch (EOFException eofe) {
                break;
            }
            writer.append(datum);
        }
        writer.flush();
        return output.toByteArray();
    } finally {
        try { input.close(); } catch (Exception e) { }
    }
}

public static String avroToJson(byte[] avro) throws IOException {
    boolean pretty = false;
    GenericDatumReader<GenericRecord> reader = null;
    JsonEncoder encoder = null;
    ByteArrayOutputStream output = null;
    try {
        reader = new GenericDatumReader<GenericRecord>();
        InputStream input = new ByteArrayInputStream(avro);
        DataFileStream<GenericRecord> streamReader = new DataFileStream<GenericRecord>(input, reader);
        output = new ByteArrayOutputStream();
        Schema schema = streamReader.getSchema();
        DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);
        encoder = EncoderFactory.get().jsonEncoder(schema, output, pretty);
        for (GenericRecord datum : streamReader) {
            writer.write(datum, encoder);
        }
        encoder.flush();
        output.flush();
        return new String(output.toByteArray());
    } finally {
        try { if (output != null) output.close(); } catch (Exception e) { }
    }
}

A: You can use the avro-tools to convert the json file({input_file}.json) to avro file({output_file}.avro) when you know the schema({schema_file}.avsc) of the json file. Just like below:
java -jar the/path/of/avro-tools-1.8.1.jar fromjson {input_file}.json   --schema-file {schema_file}.avsc > {output_file}.avro

By the way, the contents of {schema_file}.avsc file is as belows:
{"type": "record",
 "name": "User",
  "fields": [
      {"name": "name", "type": "string"},
      {"name": "favorite_number",  "type": ["int", "null"]},
      {"name": "favorite_color", "type": ["string", "null"]}
  ]
 }

Download avro-tools-1.8.1
Download others avro-tools

A: To add to Keegan's answer, this discussion is likely useful:
http://mail-archives.apache.org/mod_mbox/avro-user/201209.mbox/%3CCALEq1Z8s1sfaAVB7YE2rpZ=v3q1V_h7Vm39h0HsOzxJ+qfQRSg@mail.gmail.com%3E
The gist is that there is a special Json schema and you can use JsonReader/Writer to get to and from that. The Json schema you should use is defined here:
https://github.com/apache/avro/blob/trunk/share/schemas/org/apache/avro/data/Json.avsc


text:
Q: I want to load a webpage with custom CSS styles every time it is loaded For example, I want some method to open FIFA website with enlarged font and resized table, I don't want to do this every single time.. It should be applied only on this webpage
I used a js code, but I cant set it for always.
This is a use case for RPA


text:
Q: Non-decreasing Hilbert Function In commutative algebra, people care about the Hilbert function of the associated graded ring is non-decreasing. As far as I know, motivation came from Sally's question in 1978 which is one dimensional Cohen-Macaulay ring with a small embedding dimension that has a non-decreasing Hilbert function or not.
But, I still don't get what is the advantage of having a non-decreasing Hilbert function, why people so care about it?
And what is the geometric difference between non-decreasing and decreasing functions?


text:
Q: MLCP load compressed xml files and skip xml files with a specific xml tag I am trying to load xml gzip files and I am breaking the input xml to multiple xml records.. But is there a way in mlcp to ignore a record while loading if a particular xml tag or xml value is present. If not what are my other options ?
Following is my options that I am using now to load the gzip xml file and break to individual records
import
-host
xxxxx
-port
xxxx
-username
xxxx
-password
xxxx
-batch_size
1
-input_compressed
true
-input_compression_codec
gzip
-input_file_type
aggregates
-output_collections
wos
-output_permissions
rest-reader,read,rest-writer,update
-output_uri_prefix
/wos/
-output_uri_suffix
.xml
-aggregate_record_element
REC
-aggregate_record_namespace
http://xxxx.yyyy.com
-uri_id
UID

A: I can only think of using an MLCP transform (-transform_module e.a.) in which you conditionally pass through the $content map:map. Return empty sequence if you want to have a particular aggregate fragment suppressed.
HTH!


text:
Q: useEffect not running at all when navigating to page with React Router App.js:
import React, { Fragment } from "react";
import Header from "./components/Header";
import PostList from "./components/PostList";
import Post from "./components/Post";
import TagList from "./components/TagList";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

const App = () => {
  return (
    <Fragment>
      <Router>

        <Switch>
          <Route exact path="/" component={PostList} />
          <Route path="/tags" component={TagList} />
          <Route path="/posts/:id" component={Post} />
        </Switch>
      </Router>
    </Fragment>
  );
};

export default App;

Post.js:
import React, { useEffect, useState } from "react";
import Tag from "./Tag";
import { useParams } from "react-router-dom";
import axios from "axios";

const Post = () => {
  const { id } = useParams();
  const [post, setPost] = useState({});

  useEffect(() => {
    const fetchPost = async () => {
      try {
        const res = await axios.get(`/api/posts/${id}`);

        setPost(res.data);
      } catch (err) {
        console.error(err);
      }
    };
    fetchPost();
  }, []);

  return (

{post.title}

{post.text}

        {post.tags.map((tag) => (
          <Tag key={tag._id} tag={tag} />
        ))}

  );
};

export default Post;

I'm trying to get the skeleton for a simple blog site up and running but I'm having issues with the Post component. When navigating to a specific post with the route '/posts/:id' the useEffect that's supposed to grab the post from my API doesn't seem to run, and inevitably I end up with a 'post.tags is undefined' error. Everything else is working correctly - API responds as expected to requests from Postman and 'useParams' is grabbing the post id from the URL just fine - it's just that the useEffect isn't running at all (console.logs aren't showing up either).
I've had no issues doing things this way in previous projects - in fact the useEffect in the TagList component is virtually identical and the /tags route works as expected, so I'm not sure what I'm missing?

A: useEffect runs only at first render, and then at any other render IF the dependencies specified have changed. Since you added there an empty array, those never change.
If you want useEffect to run again when the post id has changed, you need to add id as a dependency for useEffect.
useEffect(() => {
  ....
}, [id, setPost]);

also, your post.tags will still be undefined, because the data comes after the component has finished rendering so you should actually check before that return if you have post data and if you don't have post data, to return null or a loading skeleton.


text:
Q: Cassandra UDT: error: unpack requires a string argument of length 4 Using [cqlsh 5.0.1 | Cassandra 2.1.5.469 | DSE 4.7.0 | CQL spec 3.2.0 | Native protocol v3]
and the C# 2.5 driver, I'm trying to represent user settings as a UDT.
The following is defined in a *.cql script:
CREATE TYPE GeneralSettings (
    last_changed        timestamp,
    last_tokaned        timestamp,
    tokan               text,
    emails              list<text>,
);

CREATE TABLE users (
    id                  timeuuid,
    name                text,
    general_settings    frozen<GeneralSettings>,

    PRIMARY KEY (id)
);

The following is defined in my C# code:
public class UserGeneralSettings
{
    public DateTimeOffset? LastChanged { get; set; }
    public DateTimeOffset? LastTokened { get; set; }
    public string Token { get; set; }
    public IEnumerable<string> Emails { get; set; }
}

session.UserDefinedTypes.Define(
            UdtMap.For<UserGeneralSettings>().Map(s => s.LastChanged, "last_changed")
                                             .Map(s => s.LastTokened, "last_tokaned")
                                             .Map(s => s.Token, "tokan")
                                             .Map(s => s.Emails, "emails")
        );

For<User>()
        .TableName("users")
        .PartitionKey(e => e.Id)
        .Column(e => e.Id, cm => cm.WithName("id"))
        .Column(e => e.Name, cm => cm.WithName("name"))
        .Column(e => e.GeneralSettings, cm => cm.WithName("general_settings"));

I'm trying to insert the following data as a new user record, using the IMapper interface:
newUser.GeneralSettings = new UserGeneralSettings
        {
            Emails = new [] { "test@provider.com" },
            LastChanged = DateTimeOffset.UtcNow,
            LastTokened = DateTimeOffset.UtcNow,
            Token = "abcd-efg-hijk-lmnop-qrst-uvw-xyz",
        };

But even though the insertion goes smoothly, it looks like it is corrupting my users table because I can't select anything from that table using cqlsh.
The error that I'm getting is:
Traceback (most recent call last):
File "/usr/share/dse/resources/cassandra/bin/cqlsh", line 1056, in perform_simple_statement rows = self.session.execute(statement, trace=self.tracing_enabled)
File "/usr/share/dse/resources/cassandra/bin/../lib/cassandra-driver-internal-only-2.5.1.zip/cassandra-driver-2.5.1/cassandra/cluster.py", line 1405, in execute result = future.result(timeout)
File "/usr/share/dse/resources/cassandra/bin/../lib/cassandra-driver-internal-only-2.5.1.zip/cassandra-driver-2.5.1/cassandra/cluster.py", line 2976, in result raise self._final_exception
error: unpack requires a string argument of length 4
Does anyone know what causes this error?
Is this a bug?

A: This sounds a lot like CASSANDRA-7656.  Although, that was supposed to have been fixed in one of the later 2.1 release candidates.  Are any of the values you are inserting null?
My theory as to what is happening here, is that Cassandra matches a timestamp with a C# DateTimeOffset.  And that is not the same as a DateTimeOffset? (nullable).
Change your UserGeneralSettings class to use DateTimeOffset for your timesstamps and not a nullable type (DateTimeOffset?).  Then truncate your table and try your insert again.


text:
Q: How do I resolve a conflict between my Anaconda environment and Opencv cv2? I am trying to run a Python script in my terminal that uses the cv2 library and I am getting the following error message.  It appears that there is a conflict between two instances of RunLoopModeTracker in my Anaconda environment.  I have uninstalled and reinstalled Anaconda and the same thing happens.

objc[80110]: Class RunLoopModeTracker is implemented in both
/Users/satyadoraisamy/opt/anaconda3/lib/python3.7/site-packages/cv2/.dylibs/QtCore
(0x1079527f0) and
/Users/satyadoraisamy/opt/anaconda3/lib/libQt5Core.5.9.7.dylib
(0x11b86ba80). One of the two will be used. Which one is undefined.
You might be loading two sets of Qt binaries into the same process.
Check that all plugins are compiled against the right Qt binaries.
Export DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries
are being loaded.

Any idea how to solve this (or specify which of the two instances I want to use)?
Thanks.


text:
Q: How to create calculations in alerts? I am creating an interactive game and am very new to programming.  I was wondering how exactly to increment a variable and then put it into an alert box. I want to find the calculation of foodCaught and foodWasted and display it in an alert box at the end of my game. Also how do I make it so it is on a timer and at the end of this timer the alert box with foodCaught and foodWasted appears?
$(document).ready(function(){
    var cnv = $("#myCanvas")[0];
    var ctx = cnv.getContext("2d");
    var catcherX = ctx.canvas.width/2;
    var catcherY = ctx.canvas.height - 100; // set the initial location of the catcher's y position
    var numFoods = 5;
    var catcherSpeed = 30;
    var foodCaught = 0;
    var foodWasted = 0;

    function Food(){ // the name of the constructor usually begins with a captial letter
        this.radius = 30;

        this.x = Math.floor(Math.random()*ctx.canvas.width);
        this.y = 0 - this.radius;
        this.speed = 1+ Math.floor(Math.random()*5);
        var imageToUse = new Image();
        this.width = 50; // default values
        this.height = 50; // default values

        var randomNum = Math.floor(Math.random()*2); // create a random number to choose the image
        if(randomNum == 0){

            imageToUse.src = "corn.png";
            this.width = 27; // width of corn.png
            this.height = 100; // height of corn.png

        } else if(randomNum == 1){
            imageToUse.src = "straw.png"
            this.width = 83; // width of straw.png
            this.height = 100; // height of straw.png
        }

        this.moveFood = function(){

            if(this.y > ctx.canvas.height){
                this.x =  Math.floor(Math.random()*ctx.canvas.width);
                this.y = 0;
                footWasted += 1;
            }

            this.y += this.speed; // add speed to location
        }

        this.drawFood = function() {
            ctx.drawImage(imageToUse, this.x, this.y);
        }

        this.intersectFood = function(targetX, targetY, targetR) {

            if(this.x + this.width > targetX && this.x < targetX + targetR && this.y + this.height > targetY && this.y < targetY + targetR){
                foodCaught += 1;
                return true;
            }

            /*
            var distanceX = this.x - targetX;
            var distanceY = this.y - targetY;
            var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);

            if(distance < targetR + this.radius){
                return true;
            }
             */
        }
    }
    // create an Array of Foods
    var FoodArray = new Array();
    for(var i=0; i<numFoods; i++) {
        FoodArray[i] = new Food();
    }

    // get mouse Postion

    $(document).keydown(function(e){ // attach the event to the entire document

        switch(e.keyCode){
            case 37:    // left
                catcherX-= catcherSpeed;
                break;
            case 39:    // right
                catcherX+= catcherSpeed;
                break;
        }

    });

    var interval = setInterval(gameLoop,10); // call draw every 10 milliseconds
    var counter = 0;

    function gameLoop(){
        ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles
        for(var i=0; i < FoodArray.length; i++) {
            FoodArray[i].moveFood();
            FoodArray[i].drawFood();
            if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){
                FoodArray.splice(i,1);
                 console.log(i);
            }
        }

        // draw catcher
        ctx.beginPath();
        ctx.fillStyle="#119933";
        ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true);
        ctx.closePath();
        ctx.fill();

A: Updated Answer
After your game has ended, do:
  alert("foodCaught = " + foodCaught + "<br>foodWasted = "  + foodWasted);

Just make sure that this alert is withing the scope of foodCaught and foodWasted variables.
EDIT:
Your game is actually never ending. The setInterval that you keeps calling gameLoop() every 10 milliseconds, ENDLESSLY!
To keep a track of foodCaught and foodWasted variables, add a console.log() statement at the end of gameLoop() function as shown in the code below:
function gameLoop(){
    ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles
    for(var i=0; i < FoodArray.length; i++) {
        FoodArray[i].moveFood();
        FoodArray[i].drawFood();
        if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){
            FoodArray.splice(i,1);
            //console.log(i);
        }
    }

    // draw catcher
    ctx.beginPath();
    ctx.fillStyle="#119933";
    ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true);
    ctx.closePath();
    ctx.fill();

    console.log("foodCaught = " + foodCaught + "\nfoodWasted = " + foodWasted);

}

With this, you will get the values of foodCaught and foodWasted variables everytime the gameLoop function is called.
If you are unaware of how to use the console, checkout this post.
EDIT2:
I have an idea about ending this game. In the updated code below, I have set the game to run for 10 seconds (just as an example so you can change it quickly) using setTimeout(). You have change it to any duration that you want. In setTimeout(), I am also alerting the values that you need.
Here is the updated Javascript/jQuery code:
$(document).ready(function(){
    var cnv = $("#myCanvas")[0];
    var ctx = cnv.getContext("2d");
    var catcherX = ctx.canvas.width/2;
    var catcherY = ctx.canvas.height - 100; // set the initial location of the catcher's y position
    var numFoods = 5;
    var catcherSpeed = 30;
    var foodCaught = 0;
    var foodWasted = 0;

    function Food(){ // the name of the constructor usually begins with a captial letter
        this.radius = 30;

        this.x = Math.floor(Math.random()*ctx.canvas.width);
        this.y = 0 - this.radius;
        this.speed = 1+ Math.floor(Math.random()*5);
        var imageToUse = new Image();
        this.width = 50; // default values
        this.height = 50; // default values

        var randomNum = Math.floor(Math.random()*2); // create a random number to choose the image
        if(randomNum == 0){

            imageToUse.src = "corn.png";
            this.width = 27; // width of corn.png
            this.height = 100; // height of corn.png

        } else if(randomNum == 1){
            imageToUse.src = "straw.png"
            this.width = 83; // width of straw.png
            this.height = 100; // height of straw.png
        }

        this.moveFood = function(){

            if(this.y > ctx.canvas.height){
                this.x =  Math.floor(Math.random()*ctx.canvas.width);
                this.y = 0;
                foodWasted += 1;
            }

            this.y += this.speed; // add speed to location

        }

        this.drawFood = function() {
            ctx.drawImage(imageToUse, this.x, this.y);
        }

        this.intersectFood = function(targetX, targetY, targetR) {

            if(this.x + this.width > targetX && this.x < targetX + targetR && this.y + this.height > targetY && this.y < targetY + targetR){
                foodCaught += 1;
                return true;
            }
            /*

            var distanceX = this.x - targetX;
            var distanceY = this.y - targetY;
            var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);

            if(distance < targetR + this.radius){
                return true;
             }
             */

        }

    }

    function gameLoop(){
        ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); //clears previous circles
        for(var i=0; i < FoodArray.length; i++) {
            FoodArray[i].moveFood();
            FoodArray[i].drawFood();
            if(FoodArray[i].intersectFood(catcherX, catcherY, 15)){
                FoodArray.splice(i,1);
            }
        }

        // draw catcher
        ctx.beginPath();
        ctx.fillStyle="#119933";
        ctx.arc(catcherX,catcherY,15,0,Math.PI*2,true);
        ctx.closePath();
        ctx.fill();

    }

    $(document).keydown(function(e){ // attach the event to the entire document

        switch(e.keyCode){
            case 37:    // left
                catcherX-= catcherSpeed;
                break;
            case 39:    // right
                catcherX+= catcherSpeed;
                break;
        }

    });

    // create an Array of Foods
    var FoodArray = new Array();
    for(var i=0; i<numFoods; i++) {
        FoodArray[i] = new Food();
    }

    var interval = setInterval(gameLoop,10); // call draw every 10 milliseconds

    setTimeout(function(){
        clearInterval(interval);
        alert("Time UP!\n\nfoodCaught = " + foodCaught + "\nfoodWasted = " + foodWasted);
    }, 10000);

});


text:
Q: How can I cache data that I already requested and access it from the store using React and Redux Toolkit How can I get data from the store using React Redux Toolkit and get a cached version if I already requested it?
I need to request multiple users for example user1, user2, and user3. If I make a request for user1 after it has already been requested then I do not want to fetch user1 from the API again.  Instead it should give me the info of the user1 from the store.
How can I do this in React with a Redux Toolkit slice?

A: Edit: This answer predates the release of RTK Query which has made this task much easier!  RTK Query automatically handles caching and much more.  Check out the docs for how to set it up.
Keep reading if you are interested in understanding more about some of the concepts at play.

Tools
Redux Toolkit can help with this but we need to combine various "tools" in the toolkit.

*

*createEntityAdapter allows us to store and select entities like a user object in a structured way based on a unique ID.

*createAsyncThunk will create the thunk action that fetches data from the API.

*createSlice or createReducer creates our reducer.

React vs. Redux
We are going to create a useUser custom React hook to load a user by id.
We will need to use separate hooks in our hooks/components for reading the data (useSelector) and initiating a fetch (useDispatch).  Storing the user state will always be the job of Redux.  Beyond that, there is some leeway in terms of whether we handle certain logic in React or in Redux.
We could look at the selected value of user in the custom hook and only dispatch the requestUser action if user is undefined.  Or we could dispatch requestUser all the time and have the requestUser thunk check to see if it needs to do the fetch using the condition setting of createAsyncThunk.
Basic Approach
Our naïve approach just checks if the user already exists in the state.  We don't know if any other requests for this user are already pending.
Let's assume that you have some function which takes an id and fetches the user:
const fetchUser = async (userId) => {
    const res = await axios.get(`https://jsonplaceholder.typicode.com/users/${userId}`);
    return res.data;
};

We create a userAdapter helper:
const userAdapter = createEntityAdapter();

// needs to know the location of this slice in the state
export const userSelectors = userAdapter.getSelectors((state) => state.users);

export const { selectById: selectUserById } = userSelectors;

We create a requestUser thunk action creator that only executes the fetch if the user is not already loaded:
export const requestUser = createAsyncThunk("user/fetchById",
  // call some API function
  async (userId) => {
    return await fetchUser(userId);
  }, {
    // return false to cancel
    condition: (userId, { getState }) => {
        const existing = selectUserById(getState(), userId);
        return !existing;
    }
  }
);

We can use createSlice to create the reducer.  The userAdapter helps us update the state.
const userSlice = createSlice({
    name: "users",
    initialState: userAdapter.getInitialState(),
    reducers: {
    // we don't need this, but you could add other actions here
    },
    extraReducers: (builder) => {
        builder.addCase(requestUser.fulfilled, (state, action) => {
            userAdapter.upsertOne(state, action.payload);
        });
    }
});
export const userReducer = userSlice.reducer;

But since our reducers property is empty, we could just as well use createReducer:
export const userReducer = createReducer(
    userAdapter.getInitialState(),
    (builder) => {
        builder.addCase(requestUser.fulfilled, (state, action) => {
            userAdapter.upsertOne(state, action.payload);
        });
    }
)

Our React hook returns the value from the selector, but also triggers a dispatch with a useEffect:
export const useUser = (userId: EntityId): User | undefined => {
  // initiate the fetch inside a useEffect
  const dispatch = useDispatch();
  useEffect(
    () => {
      dispatch(requestUser(userId));
    },
    // runs once per hook or if userId changes
    [dispatch, userId]
  );

  // get the value from the selector
  return useSelector((state) => selectUserById(state, userId));
};

isLoading
The previous approach ignored the fetch if the user was already loaded, but what about if it is already loading?  We could have multiple fetches for the same user occurring simultaneously.
Our state needs to store the fetch status of each user in order to fix this problem.  In the docs example we can see that they store a keyed object of statuses alongside the user entities (you could also store the status as part of the entity).
We need to add an empty status dictionary as a property on our initialState:
const initialState = {
  ...userAdapter.getInitialState(),
  status: {}
};

We need to update the status in response to all three requestUser actions.  We can get the userId that the thunk was called with by looking at the meta.arg property of the action:
export const userReducer = createReducer(
  initialState,
  (builder) => {
    builder.addCase(requestUser.pending, (state, action) => {
      state.status[action.meta.arg] = 'pending';
    });
    builder.addCase(requestUser.fulfilled, (state, action) => {
      state.status[action.meta.arg] = 'fulfilled';
      userAdapter.upsertOne(state, action.payload);
    });
    builder.addCase(requestUser.rejected, (state, action) => {
      state.status[action.meta.arg] = 'rejected';
    });
  }
);

We can select a status from the state by id:
export const selectUserStatusById = (state, userId) => state.users.status[userId];

Our thunk should look at the status when determining if it should fetch from the API.  We do not want to load if it is already 'pending' or 'fulfilled'. We will load if it is 'rejected' or undefined:
export const requestUser = createAsyncThunk("user/fetchById",
    // call some API function
    async (userId) => {
        return await fetchUser(userId);
    }, {
        // return false to cancel
        condition: (userId, { getState }) => {
            const status = selectUserStatusById(getState(), userId);
            return status !== "fulfilled" && status !== "pending";
        }
    }
);