text:
Q: Addthis javascript button/widget adding space to top of webpage If you view this page http://www.herkimer.edu/news/view/community_members_complete_jointly_offered_machine_operator_training_progra/
You'll notice a green bar (screen-shot: http://grab.by/1msh) at the very top. It has something to do w/ the addthis widget you'll see underneath the h1 title.
If you reload the page a couple times, the bar goes away, probably because the script is cached and does not delay, resulting in that extra space at top.
Do you know what I could do to resolve this? Any help is appreciated.

A: I'm assuming that you don't want the DIV to display.  You could add some CSS to the page to hide it.  It has id atffc (and contains a Flash object, but I don't know that it needs to be visible).
#atffc { display: none; }

A: I think in addition to just hiding your extra div you may want to move the  elements to the bottom of your page so they are evaluated after the add_this anchor tag () is created and ready.  That would help with potential timing issues to make sure the element is loaded and ready before their code starts to try to manipulate it.

A: I had the same problem and I downloaded their new code
http://www.addthis.com/web-button-select
I selected "no analytics" and I think they now strip out the flash part when using no analytics. I haven't had the problem again the last time I checked but I'll need more time to confirm this.
You might want to try to do the same

A: A bit late, but try adding this code AFTER the AddThis button code:
<script type="text/javascript">
var addthis_config = {
  data_use_flash: false
}
</script>

Source:
http://www.addthis.com/forum/viewtopic.php?f=4&t=22569&sid=fec603f0cac141b4856eddab92c8e63e&start=10


text:
Q: WrapPanel children order i use WPF and add WrapPanel children in User Control panel.
like that:
SearchPanel sp = new SearchPanel();
sp.Clock = clock;
sp.Name = item.CustomerTwo;
sp.Color = "Purple";
wPanel.Children.Add(sp);

how i organize this added panels

A: The simple answer to this question is that they appear in the order that they are added to the Children collection.
If you were adding them explicitly using XAML they would appear in the same order that they appear in the XAML.
If you were adding them by binding the ItemsSource of the WrapPanel then they would appear in the order that the bound collection presents them.

As for your specific example...
In your linked code, the colour is based on a date indirectly obtained from each "customer" item. To order the WrapPanel based on this, you will need to sort your customer items by that same criteria first.
Unfortunately, the date logic is convoluted (using a DB relation to a Days table and then some awkward date manipulation code). You could use that convoluted date logic in a Comparison function to sort the customer items first. Or you could add a property to the "newSearchPanel" class which you calculate while constructing them and add them to a temp list, which you sort before finally pushing them into the WrapPanel.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't get params from get request - Node JS, Angular I have this angular method that gets features. I only need the features that have the releaseid that I pass with paramters.
getFeatures() {
  this.route.params.subscribe(params => {
    this.featureService.getFeatures(params['releaseid']).subscribe(res => {
      this.features = res;
    })
  });
}

My service (featureService):
getFeatures(releaseId) {
  const uri = 'http://localhost:4000/features';
  return this
          .http
          .get(uri, {params: {releaseId: releaseId}})
          .map(res => {
            return res;
          });
}

My nodejs route
featureRoutes.route('/features').get(function (req, res) {
  console.log(req.body.params);
});

But the req.body.params is undefined.
Any help on this?

A: Try this
Service (featureService):
getFeatures(releaseId) {
    const uri = 'http://localhost:4000/features?releaseId=' + releaseId;
    return this.http.get(uri);
}

Nodejs route:
 featureRoutes.route('/features').get(function (req, res) {
     console.log(req.params); // should contain your releaseId
 });

You should now be able to get the releaseId in your node backend.

A: I found it. in my routes i had to do:
  console.log(req.query.releaseId)


text:
Q: How do I do the Minkowski sum of two sets? I have 2 sets, $X$ and $Y$. How do I find the Minkowski sum of these sets?

A: Another way is with Tuples and Total.
A = {1, 2, 3};
B = {a, b, c};

MinkowskiSum[lis__] := Total[Tuples[{lis}], {2}]

MinkowskiSum[A, B]

{a+1, b+1, c+1, a+2, b+2, c+2, a+3, b+3, c+3}

A1 = {1, 2};
A2 = {a, b};
A3 = {x, y};

MinkowskiSum[A1, A2, A3]

{a+x+1, a+y+1, b+x+1, b+y+1, a+x+2, a+y+2, b+x+2, b+y+2}

A: For example
x = {{1, 0}, {0, 1}, {0, -1}};
y = {{0, 0}, {1, 1}, {1, -1}};

Union @@ Outer[Plus, x, y, 1]

{{0, -1}, {0, 1}, {1, -2}, {1, 0}, {1, 2}, {2, -1}, {2, 1}}

You can use CirclePlus (⊕) (entered as \[CirclePlus] or Escc+Esc) to define your Minkowski sum:
CirclePlus[x__] := Flatten[Union @@ Outer[Plus, x, 1], Length@{x} - 2]

x⊕y

{{0, -1}, {0, 1}, {1, -2}, {1, 0}, {1, 2}, {2, -1}, {2, 1}}

{{1,2}}⊕{{a,b}}⊕{{c,d}}

{{1 + a + c, 2 + b + d}}


text:
Q: How to use QR decomposition of Extreme optimization http://social.msdn.microsoft.com/Forums/vstudio/en-US/7e952c45-2494-4650-aa61-89d5ea21f1f3/how-to-use-qr-decomposition-of-extreme-optimization
How to use QR decomposition of Extreme optimization
No parameterless constructor defined for this object.
let TwelvePalace : float[,] = Array2D.zeroCreate 4 3

TwelvePalace.[0,0] <- 1.0;
TwelvePalace.[0,1] <- 2.0;
TwelvePalace.[0,2] <- 3.0;

TwelvePalace.[1,0] <- 4.0;
TwelvePalace.[1,1] <- 5.0;
TwelvePalace.[1,2] <- 6.0;

TwelvePalace.[2,0] <- 7.0;
TwelvePalace.[2,1] <- 8.0;
TwelvePalace.[2,2] <- 9.0;

TwelvePalace.[3,0] <- 10.0;
TwelvePalace.[3,1] <- 11.0;
TwelvePalace.[3,2] <- 12.0;

let mutable iii = DenseMatrix.Create(TwelvePalace)
let QRProvider : QRDecomposition = iii.GetQRDecomposition()

let Q : DenseMatrix = QRProvider.OrthogonalFactor.ToDenseMatrix() // error here
let R : DenseMatrix = QRProvider.UpperTriangularFactor.ToDenseMatrix()


text:
Q: simple C graphic library for demo a matrix I have been asked to display a pretty big matrix like 200*300. It's kind ugly when i output this to console..
The matrix is changing during an iteration, I have to show this as well.
I wonder if there is a simple tool I can use to display this matrix?
hopefully, I can call it in my C program.
I don't have any graphic programming experience.
Thanks!

A: You could use SDL (libsdl.org) to make a display window and output each character as a pixel on the window.
Here is a test app so you can take a look at how it works:
http://friedspace.com/SDLTest.c

A: I really don't think you want to go into a graphics library for this.  Instead, I would suggest dumping the data to an output file, and handling it from there.
For one, you could just format it to fixed-width fields, and view the text file with a text editor:
000  001  002
099  098  097
...

Or, you could consider dumping it as CSV, and importing it into something like Excel.

A: Try GNUPlot:
OSX Installation:
http://www.miscdebris.net/blog/2009/09/16/install-gnuplot-on-mac-os-x/
Project Homepage:
http://www.gnuplot.info/download.html
I have used it in numerous projects. It is very easy to generate plots. In your case, you could just create a scatter plot, and export it to JPEG in a few simple steps.
If you don't want to have to build and integrate it into your application, you can just send commands via the "system" function to a prebuilt GNUPlot application.
http://www.cplusplus.com/reference/clibrary/cstdlib/system/


text:
Q: Unwanted modification in State variable (Hook), due to manipulation of local variable import React, { useState, useEffect } from "react";

export const Test = () => {
  const [data, setData] = useState([]);
  const file = [{ id: 1, description: "Test Data" }];

  useEffect(() => setData(file), []);

  const manipulateData = (data) => {
    let tempArray = [...data];
    tempArray.map((item) => delete item.id);
  };

  return (
    <>

Testing Data

      {manipulateData(data)}
      {console.log(data)}
    </>
  );
};

I want to make modification to the local variable "tempArray", and the changes shall not reflect in the variable "data"

A: This happens because you are creating a new array, but the objects in that array are not deeply copied. Instead, they represent just a reference to the very same objects as in data.
Because both references are pointing at the same object, if you delete an object property from the tempArray objects, you are actually deleting it from the data objects.
If you want to solve this, you have to destroy the reference by making a deep copy of the objects from the data array.
Here is an example how to do it:
export const Test = () => {
  const [data, setData] = useState([{ id: 1, description: "Test Data" }]);

  const manipulateData = (data) => {
    let tempArray = data.map((item) => {item.description}); //this will create an array with new object, and destroy the reference to the objects of data.
  };

  return (
    <>

Testing Data

      {manipulateData(data)}
      {console.log(data)}
    </>
  );
};

Also, instead of deleting a property, better pick the one that you need.

A: The following code:
let tempArray = [...data];

only shallow copies your data array, meaning that any of the objects inside of tempArray refer to the same objects in memory that are within the data array. This means that when you loop over your objects with .map(), each item refers to an object from data as well, which results in the objects in data changing when you use delete item.id.
Currently, you are using .map() just to loop over your tempArray, this isn't the purpose of .map(). The .map() method returns a new array, and the callback function you pass it should return a new value that you want to map the current value to. This means you can use .map() to create tempArray, by making the callback function return a new object that excludes the id property:
const manipulateData = (data) => {
  const tempArray = data.map(({id, ...rest}) => rest);
  // ... do what you need with `tempArray` ...
};

Above, {id, ...rest} is destructuring assignment syntax, which extracts the id property from the current element, and stores all other properties/values from the current object in rest. This allows you to create a new object that excludes the id property.
As a side note, you shouldn't be calling methods such as console.log() and manipulateData() inside of JSX if they don't return anything meaningful that will be rendered to the screen, instead, you can put these in a useEffect() hook.

A: const [data, setData] = useState([{ id: 1, description: "Test Data" }]);
try this

A: Your way is right in case you are not using a multi-dimensional array, but here you are cloning a multi-dimensional array,
and by using the = operator, it'll assign objects/arrays by reference instead of by value! That means whenever you modify any of the two objects it's going to affect the value in both.
A good way to solve this is by creating a deep clone by doing something like this
    const tempArray = JSON.parse(JSON.stringify([...data]))
    tempArray.map((item) => delete item.id)


text:
Q: combine two pd df by index and column The data looks like this:
df1 =           456089.0  456091.0  456093.0
5428709.0       1.0       1.0       NaN
5428711.0       1.0       1.0       NaN
5428713.0       NaN       NaN       1.0

df2 =           456093.0  456095.0  456097.0
5428711.0       2.0       NaN       NaN
5428713.0       NaN       2.0       NaN
5428715.0       NaN       NaN       2.0

I would like to have this output:
df3 =           456089.0  456091.0  456093.0  456095.0  456097.0
5428709.0       1.0       1.0       NaN       NaN       NaN
5428711.0       1.0       1.0       2.0       NaN       NaN
5428713.0       NaN       NaN       1.0       2.0       NaN
5428715.0       NaN       NaN       NaN       NaN       2.0

I tried several combinations with pd.merge, pd.join, pd.concat but nothing worked the way I want it, since I want to combine the data by index and column.
Does anyone have an idea how to do this? Thanks in advance!

A: Let us try sum with concat
out = pd.concat([df1,df2]).sum(axis=1,level=0,min_count=1).sum(axis=0,level=0,min_count=1)
Out[150]:
           456089.0  456091.0  456093.0  456095.0  456097.0
5428709.0       1.0       1.0       NaN       NaN       NaN
5428711.0       1.0       1.0       2.0       NaN       NaN
5428713.0       NaN       NaN       1.0       2.0       NaN
5428715.0       NaN       NaN       NaN       NaN       2.0


text:
Q: Measure TLB Size Is there a tool that will measure the size of my TLB for me? Or some sort of scripting approach I can take to estimate it?

A: Chris s. has it right, you can probably just check the docs for the processor in question, especially if its an x86 processor. If for some reason you can't do this you can probably calculate it, I believe that lmbench can do this.

A: As the question was about measuring the size of the TLB, not querying it, the tlb test of lmbench may be interesting. lmbench performs a set of micro benchmarks including a test that measures the TLB.


text:
Q: Sql Server - Count occurrences of datetime group by specific interval I have this table with sample data:
MY_TABLE
------------------------------------------
ID    DateVal                other columns
------------------------------------------
1     2017-01-14 11:00:00    ...
2     2017-01-14 11:01:00    ...
3     2017-01-14 11:02:00    ...
4     2017-01-14 11:03:00    ...
5     2017-01-14 11:11:00    ...
6     2017-01-14 11:11:30    ...
7     2017-01-14 11:15:00    ...
8     2017-01-14 11:15:01    ...
9     2017-01-14 11:18:00    ...

I need to have this kind of result:
start               end                 occurrences
-----------------------------------------------------------
2017-01-14 11:00    2017-01-14 11:05    4
2017-01-14 11:05    2017-01-14 11:10    0
2017-01-14 11:10    2017-01-14 11:15    3
2017-01-14 11:15    2017-01-14 11:20    2
...

In specific I need a query that extracts all the occurrences of raws in MY_TABLE in 5 mins range (range value is variable).
Someone could help me?
Best regards,

A: You need to generate the timeframes you want and then left join.  Here is one method:
select v.dt, dateadd(minute, 5, v.dt) as end_dt, count(t.id)
from (values (convert(datetime, '2017-01-14 11:00')),
             (convert(datetime, '2017-01-14 11:05')),
             . . .
     ) v(dt) left join
     my_table t
     on t.dateval >= v.dt and
        t.dateval < dateadd(minute, 5, v.dt)
group by v.dt;

Note:  If you want to do this for a wider range of time, then using a tally table or recursive CTE is handy.

A: If you don't need your start and end to reflect the exact range:
You can use something like DATEDIFF(minute, '2000-01-01', DateVal)/5 as your grouping, then use MIN(DateVal) and MAX(DateVal) for your start and end; but those values will be of the first and last transaction in the interval, not the bounds of the interval.
Alternatively, you can use a recursive CTE to generate the intervals, and then join that to your data:
; WITH intervals AS (
   SELECT CAST('2017-11-01 00:00:00' AS DATETIME) AS `start`
       , CAST ('2017-11-01 00:05:00' AS DATETIME) AS `end`
   UNION ALL
   SELECT DATEADD(minute, 5, `start`) AS, DATEADD(minute, 5, `end`) AS end
   FROM intervals
   WHERE intervals.end < '2017-11-02 00:00:00'
)
SELECT i.`start`, i.`end`, COUNT(t.ID) AS occurrences
FROM intervals AS i
INNER JOIN MY_TABLE AS t ON t.DateVal >= i.`start` AND t.DateVal < i.End
GROUP BY i.`start`, i.`end`
ORDER BY i.`start`, i.`end`
;

Notes:

*

*the literal date values can be adjusted to reflect the actual range you want to query

*If you want intervals without activity to be included, the INNER can be changed to LEFT

*Since your question as stated has overlapping intervals, I went with the assumption that a DateVal on the 5 minute mark belongs to the interval that starts with that value.

A: Let's have a row generator, that generates dates every rangeSize from a startDate:
DECLARE @rangeSize INT = 5;
DECLARE @startDate DATETIME = '2020-01-01 00:00';

WITH RG(D,D2) AS (
   SELECT @startDate AS D, DATEADD(MINUTE, @rangeSize, @startDate) AS D2
   UNION ALL
   SELECT DATEADD(MINUTE, @rangeSize, D), DATEADD(MINUTE, @rangeSize, D2)
   FROM   RG a
   WHERE  D < DATEADD(MINUTE, @rangeSize * 100, @startDate)
)

SELECT D,D2
FROM   RG
OPTION (MAXRECURSION 100);

Now let's hook it up to your data and count the data:
DECLARE @rangeSize INT = 5;
DECLARE @startDate DATETIME = '2020-01-01 00:00';

WITH RG(D,D2) AS (
   SELECT @startDate AS D, DATEADD(MINUTE, @rangeSize, @startDate) AS D2
   UNION ALL
   SELECT DATEADD(MINUTE, @rangeSize, D), DATEADD(MINUTE, @rangeSize, D2)
   FROM   RG a
   WHERE  D < DATEADD(MINUTE, @rangeSize * 100, @startDate)
)

SELECT r.D as StartDate, r.D2 as EndDate, COUNT(m.ID) as Count as EndDate
FROM
  RG r
  LEFT JOIN
  my_table m ON m.dateval > r.D AND m.dateval <= r.D2
GROUP BY r.D, r.D2

OPTION (MAXRECURSION 100);

Note I used > and <= for the range because you seem to classify from e.g 15:01 to 20:00 as a range, whereas it feels more natural to me to have 15:00 to 19:59 as "belonging to the 15-20 range"


text:
Q: Creating a .csv in a Bash Shell Script I am trying to produce a .csv file in a Bash shell script. Please consider this code:
#!/bin/bash

for f1 in *_8_kHz.wav
do
   for f2 in *_8_kHz.wav
   do
      # echo "pesq +8000 $f1 $f2"
      echo -n `pesq +8000 $f1 $f2 | grep Prediction | rev | cut -b1-5 | rev`
   done

   echo
done

This works except, of course, that each line ends with a comma. Here is sample output:
4.500,1.029,1.651,1.475,1.698,1.706,
1.550,4.500,1.477,1.148,1.788,1.478,
1.251,0.958,4.500,1.472,2.091,1.800,
0.961,1.154,1.550,4.500,1.702,1.501,
1.194,0.974,1.356,1.206,4.500,1.626,
0.857,0.960,1.091,1.064,2.012,4.500,

What is the most efficient way to omit those trailing commas?

A: Is the following efficient enough?
echo -n `pesq +8000 $f1 $f2 | grep Prediction | rev | cut -b1-5 | rev` | sed 's/,$//'

It is using sed to remove the last , before the end of the line $.

A: from https://stackoverflow.com/a/18262725/2796606
foo=`pesq +8000 $f1 $f2 | grep Prediction | rev | cut -b1-5 | rev`

echo -n ${foo%?}


text:
Q: How can I pass the argument in vbs I'm a linux guy and new to windows, im trying to create a small vbs script to create bunch of folders.
Im trying to create a mainfolder according to user input and 4 subfolder in it with static names. I somehow got two seperate working scripts for mainfolder and subfolder but I would like to combine them both which means once the mainfolder is created as per user input next it should create  subfolders below that.
Script which creates Mainfolder.vbs as per user input:
strfolder = InputBox("Please enter a name for your new folder:")
set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateFolder "C:\test\" & strfolder

Script which creates subfolders.vbs folders:
Option Explicit

dim wshShell
set wshShell = wscript.CreateObject("WScript.Shell")
DIM fSO

DIM foldername1
DIM foldername2
DIM foldername3
DIM foldername4

foldername1=("subfolder1")
foldername2=("subfolder2")
foldername3=("subfolder3")
foldername4=("subfolder4")

dim folderpath
SET FSO=CreateObject("Scripting.FileSystemObject")

folderpath = "C:\test" & _
             "\" & foldername1
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)

folderpath = "C:\test" & _
             "\" & foldername2
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)

folderpath = "C:\test" & _
             "\" & foldername3
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)

folderpath = "C:\test" & _
             "\" & foldername4
wscript.echo "Creating folder: " & folderpath
FSO.CREATEFOLDER(folderpath)

In short, how can I create a mainfolder as per user input and subfolders with static names?
would like to combine these both and work together as a single script.

A: You can try with this subroutine : SmartCreateFolder(strFolder)

Sub SmartCreateFolder(strFolder)
    With CreateObject("Scripting.FileSystemObject")
        If Not .FolderExists(strFolder) then
            SmartCreateFolder(.getparentfoldername(strFolder))
            .CreateFolder(strFolder)
        End If
    End With
End Sub

The combined whole script can be written like that :
Option Explicit
Const Title = "SmartCreateFolder"
Const Time2Wait = 2
Dim ws,MainFolderPath,MainFolderName,SubFolderPath,Arr_SubFolder_Name,i
Set ws  = CreateObject("wscript.shell")
Arr_SubFolder_Name = Array("subfolder1","subfolder2","subfolder3","subfolder4")

MainfolderName = InputBox(_
"Please enter a name for your new folder :",Title,"Type the name here")
If MainfolderName = "" Then Wscript.Quit(1)

MainFolderPath = "C:\test\" & MainfolderName

For i=LBound(Arr_SubFolder_Name) To UBound(Arr_SubFolder_Name)
    Call SmartCreateFolder(MainFolderPath)
    SubFolderPath = MainFolderPath & "\" & Arr_SubFolder_Name(i)
    Call SmartCreateFolder(SubFolderPath)
Next
ws.run "Explorer " & MainFolderPath
'---------------------------------------------------------------
Sub SmartCreateFolder(strFolder)
    With CreateObject("Scripting.FileSystemObject")
        If Not .FolderExists(strFolder) then
            ws.Popup "Creating folder: " & StrFolder,Time2Wait,_
            Title,vbInformation+vbSystemModal
            SmartCreateFolder(.getparentfoldername(strFolder))
            .CreateFolder(strFolder)
        End If
    End With
End Sub
'---------------------------------------------------------------


text:
Q: Intuition behind splitting sums into sub sums At 11:15 of this video, Michael Penn takes this sum,
$$ \sum_{i=1}^{n} \sum_{j=1}^{i}  \frac{1}{ \alpha_j \alpha_{i-j} }$$
And splits into three sums,
$j=i-j$ , $ j<i-j$ and $j>i-j$
but I  don't understand, what's the intuition behind this? Like, what exactly is the procedure behind putting constraints on indexs to split the sums into sub sums?
Looking for explanations based on using a concrete example how inserting restriction on it helps us make subsums?

A: Let's consider a simpler case:
You have $$a^2+b^2+c^2+2ab+2bc+2ca-2ab-2bc-2ca$$
You may write it as $$\sum_{i\in\{a,b,c\}}\sum_{j\in\{a,b,c\}}{ij}-2\sum_{i,j\in\{a,b,c\}, i<j}{ij}$$.
This is just a fancy way of writing the top equation but it makes the thing less obvious to see the difference is just the $i=j$ cases. What the video is saying, is that the left summation and the right summation has difference for those $i=j$ cases.

A: If I have the sum
$$\text{apple} +\text{lion} +\text{banana} +\text{England} +\text{Brazil} +\text{donkey} +\text{Australia} +\text{China} +\text{bear} $$
I can rewrite it like
$$(\text{apple} +\text{banana}) +(\text{England} +\text{Brazil} +\text{Australia} +\text{China})+(\text{donkey}  +\text{bear} +\text{lion})$$
Rather than summing among all these strange things together, I prefer to put the fruit-things together, the country-things together, and the animal-things together (hoping maybe that the three sub-sums will be easier to handle).


text:
Q: How to set member type in Doxygen for PHP code? I'm trying to document PHP class members with Doxygen (I'm not using PHPDocs because the project involves COCOA programming, so I can use the same tool for both parts).
/**
 * This is brief description.
 *
 * This is detailed description.
 */
 private $foo;

This code gets the documentation done right, but I would like to include in the docs the type the var should handle.
I tried to use \var and  \property, but then Doxigen does not generate the doc for the var.
 //THIS IS NOT WORKING!
 /**
 * This is brief description.
 *
 * This is detailed description.
 * \var int
 */
 private $foo;

I have seen this post:
Doxygen: how to describe class member variables in php?
Seems that \var is not working in Doxyegn, but the post is a bit old and maybe there is something I can do now.

A: I have follow the bug comments of this feature:
https://bugzilla.gnome.org/show_bug.cgi?id=626105.
In comment number 6 a solution is proposed, adding the var name after the type.
class Mine {
   /**
    * Definition of variable
    * @var string $var
    */
   private $var = array();
}

This is working for me.

A: Simple workaround which generates acceptable results is to add this input filter:
INPUT_FILTER = "sed -e 's/@var\s/@see /'"

Or even better to define an alias:
ALIASES += "var=@see"

It simply replaces @var command with @see command. It is not perfect, but it is very simple and relatively bulletproof.
Small disadvantage is that the type is somewhere in the description instead of the heading. On the other side, if only few properties has type defined, it makes documentation more consistent (headings look the same).

A: @type works for me:
    /** @type string[] */
    private $csvData;

    /**
     * command line parameters
     * @type string[]
     */

    private $parameters;


text:
Q: Starting SWT widget from HttpServlet For some weird reason I need to open swt dialog from a servlet. Is this even possible?
Currently I have this but getting "Invalid thread access error". So far I am doing this.
        Thread th=new Thread(new Runnable(){

        @Override
        public void run() {
            Shell shell = new Shell();
            FileDialog dialog=new FileDialog(shell);
            dialog.setText("Enter a filename");
            dialog.setFilterPath("c:\\");
            String selected=dialog.open();
            log.error(selected);
            shell.dispose();

        }

    });
    th.start();

Any ideas?

A: I don't want to know the weird reason, at the same time I can't warn you about the problems you may run into while opening a SWT window in a Servlet but the problem is you are accessing SWT widgets from a Native Thread which won't work.

You can access SWT only on UI Thread.

Also you are not blocking the UI Thread.
PFB the code which solves your problem
Thread th = new Thread(new Runnable()
    {

        @Override
        public void run()
        {
            Display.getDefault().syncExec(new Runnable()
            {
                @Override
                public void run()
                {
                    Display display = Display.getDefault();
                    Shell shell = new Shell(display);
                    FileDialog dialog=new FileDialog(shell);
                    dialog.setText("Enter a filename");
                    dialog.setFilterPath("c:\\");
                    String selected=dialog.open();
                    log.error(selected);
                    while (!shell.isDisposed())
                    {
                        if (!display.readAndDispatch())
                            display.sleep();
                    }

                }

            });
        }
    });

    th.start();


text:
Q: Add script tag to React component without using props or context in NextJS I want to add a library to my React component as a script tag. I'm doing this currently by calling an API in an _app.tsx file then accessing the value in a _document.tsx file. Within _document.tsx I add the script tag to the document head by passing it to a custom component.
My ultimate goal is to remove it from NEXT_DATA (I'm working on a SSR Next JS app).
Any ideas? I've looked into using window, but have not had success there.
Note: Updated question for clairty.

A: You can use the Next.js Head tag from anywhere in your app to achieve loading a script.
For example:
    import Head from 'next/head';

    function MyLibraryLoader() {
        return (
            <Head>
                <script src="..." type="text/javascript" />
            </Head>
        )
    }

More about the Head tag can be found here:
https://nextjs.org/docs/api-reference/next/head


text:
Q: google chrome ajax call doesn't show arabic characters in js concole i am using ajax for data in arabic characters and everything works good , i can store arabic characters to database and i can retrieve arabic characters from database and prints it to the screem and everything works good , but my problem is that when i check javascripte concole on google chrome to check the retriveing data i can't show arabic characters , but the prints as this (this is just example and not all data)
["\u0645\u062f\u064a\u0646\u0629","\u0645\u062f\u064a\u0646\u0629 \u062a\u0627\u0631\u064a\u062e\u064a\u0651\u0629","\u0634\u062e\u0635\u064a\u0651\]

i mean like this

A: When using JSON, strings are in UTF-8, and special characters are encoded as \u followed by 4 hexadecimal characters.
In your case, if you try to decode that string -- for example, with the first item of your array :
>>> str = "\u0645\u062f\u064a\u0646\u0629";
"مدينة"

I don't read arabic, but this looks like arabic to me :-)
Even if the JSON doesn't look good, it's not what matters : the important thing is that you get your original data back, once the JSON is decoded ; and, here, it seems you'll do.

To get the original, decoded, string in the browser's console (for debugging purposes, I suppose), you should be able to use the same JS library you are using in your application (if any), or the JSON.parse() function (I just tested this in Firefox's console, actually) :
>>> JSON.parse('"\u0645\u062f\u064a\u0646\u0629"');
"مدينة"

Of course, you'll have to write some code to actually output that decoded-value to the browser's console (be it "by hand" or when getting the JSON back from your server) ; but since the browser's console it a debugging tool it seems OK.
By default, the console, as a debugging tool, outputs the raw JSON string it gets from the server -- and, with JSON, special characters are encoded, there is nothing you can do about it (except decode the JSON string and display it yourself, if you need to)

If you want to output the decoded string to the console each time you get a result from your server, you'll have to call JSON.parse() each time you get a result from your server ; and then output it, probably using console.log().
Don't forget to remove that debugging code before distributing your application / uploading it to your production server, though.


text:
Q: I cannot display text using array and import method
I don't know what is happening but no text is displaying. Please help if I have implemented the wrong way or things have been changed. Below is the code for my CategoriesScreen.js
import React from'react';
import {View, Text, FlatList, StyleSheet} from 'react-native';

import { CATEGORIES } from '../data/dummy-data';
const renderGridItem =itemData => {
return (
<View style ={styles.gridItem}>
<Text>{itemData.item.title}</Text>
</View>
); //item in line 9 would be the item defined with this function
};

const CategoriesScreen = props =>{
   return(
    <FlatList
    data={CATEGORIES}
    renderItem={renderGridItem}
     numColumns={2} // numColumn is function that set no of columns - grid view
     />
   );
};

const styles = StyleSheet.create({
screen:{
    flex:1,
    justifyContent:'center',
    alignItems:'center'
},
gridItem:{
    flex:1,  //it can get as much space as it can get
    margin:15,
    height:150
}
});

export default CategoriesScreen;

Below would be my code for dummy-data.js
//just a dummy data
import Category from '../models/category';

export const CATEGORIES = [
  new Category('c1', 'Italian', '#f5428d'),
  new Category('c2', 'Quick & Easy', '#f54242'),
  new Category('c3', 'Hamburgers', '#f5a442'),
  new Category('c4', 'German', '#f5d142'),
  new Category('c5', 'Light & Lovely', '#368dff'),
  new Category('c6', 'Exotic', '#41d95d'),
  new Category('c7', 'Breakfast', '#9eecff'),
  new Category('c8', 'Asian', '#b9ffb0'),
  new Category('c9', 'French', '#ffc7ff'),
  new Category('c10', 'Summer', '#47fced')
];

And below is my category.js
// I will set how my data is shaped in this app in this file

class Category {

constructor(id, tittle, color) {
this.id = id;        // with help of this property i will store all data
this.tittle= tittle;  //in this right side constructor (...) has been called
this.color= color;     //this all features belongs to javascript
}
}

export default Category;

Any help and suggestions would be really appreciated. Thank You.

A: Change this:
<Text>{itemData.item.title}</Text>

To this:
<Text>{itemData.item.tittle}</Text>

Because in your constructor, you call it tittle. Alternatively, you can rename tittle to title. I also don't think you need item, you can just do itemData.tittle I think.


text:
Q: How to run RequireJS optimizer via Sublime Text 2 Build System My build config looks like this.
{
  "cmd": ["node r.js -o app.build.js"],
  "working_dir": "$project_path"
}

The Sublime error log looks like this:
[Errno 2] No such file or directory
[cmd:  [u'node r.js -o app.build.js']]
[dir:  /Users/janjarfalk/Desktop/Projects/Template]
[path: /Users/janjarfalk/Desktop/Projects/Template]
[Finished]

And the Sublime console looks like this:
Running node r.js -o app.build.js

If I run "node r.js -o app.build.js" in "/Users/janjarfalk/Desktop/Projects/Template" in the Terminal it works.
What am I doing wrong?

A: The ST2 docs show the cmd value should be the same command but split into an array of strings, so in your config it would look like ["node", "r.js", "-o", "app.build.js"]

A: Here is my build
Step to build working
step 1 : install node for cmd
of course you will need node js to complie the r.js
step 2 : create a project
menu --> project --> save
step 3 : create r.js build file
Save path just outside of the project folder so that it dont get mix up with project files
i do a .../build/app.build.js
where the build folder also contain r.js
step 4 : create a build plugin for sublime text
Menu --> Tools --> Build system --> new build system
{
    "cmd": ["node", "r.js", "-o", "app.build.js"],
    "working_dir" : "${project_path:${folder}}/../build"
}

save as RJS.sublime-build
Note that i use ${project_path:${folder}} instead of a absolute path so that i dont have to create a new buildtool for each project just keep the same relative path


text:
Q: Scroll to child Recyclerview item in Nested Recyclerview Context
I have a nested Recyclerview like the following sketch shows you:

In the drawing you can see a RecyclerView, which in turn holds one RecyclerView each as item.
Question
My question now is: How can I get the outer, parent Recyclerview scroll to a position of one of the child RecyclerViews. In the drawing I marked you Content pos 5 as my target position for example the Child RecyclerView 2.
What I already found out
One approach I've been thinking about was using scrollToPositionWithOffset(position, offset) on the parent RecyclerView, then just scroll to the position of the child RecyclerView 2 and then have the offset as the size of the list of items in the Child RecyclerView. But how can I get the size when the view isn't even inflated?
I would be very happy if one of you could give me some help that also ran into this problem of scrolling to a position of the child RecyclerView in such a nested Recyclerview.


text:
Q: Understanding Android App RAM Usage My app uses a service which I start in the main activity's onCreate() method. When I first launch the app on my tablet, and view what's running in Settings/Apps/Running, it shows my service running and consuming 11MB of RAM.
Now, if I cycle the activity's life cycle 20 times by rotating the device, and go back into Settings/Apps/Running, it shows that I'm now using 29MB of RAM.
At first I thought this must be due to a memory leaks, but after taking heap dumps before and after cycling the activity's life cycle, I don't appear to be leaking any objects. Below is a screenshot from MAT, where the column titled Objects #0 lists instances of my objects before cycling, and column titled Objects #1 lists instances of my objects after cycling.

and for all objects

There don't appear to be any obvious memory leaks, and yet I can't understand why the RAM usage in Settings/Apps/Running increases after each orientation/lifecycle. Am I missing something here? Why is my RAM usage apparently increasing, when I don't appear to have any memory leaks?
Update
The reason my app was consuming more RAM on each orientation change was the result of creating custom fonts from assets. I had created a custom TypefacedTextView (can be seen as an object in the screenshots above) that appears to have been reloading the fonts into memory each time the view was created. Removing the TypefacedTextViews has fixed the problem. The problem was made clearly apparent using the adb tool with command shell dumpsys meminfo my.package.com which listed my abundant font Asset Allocations.

A: There's a short blog post which, I believe, holds a lot of information nonetheless. You can find it here.
In it you find an intereseting explanation of what can/will happen if you manage your Activity's references wrongly:
private static Drawable sBackground;

@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);

  TextView label = new TextView(this);
  label.setText("Leaks are bad");

  if (sBackground == null) {
    sBackground = getDrawable(R.drawable.large_bitmap);
  }
  label.setBackgroundDrawable(sBackground);

  setContentView(label);
}

This code is very fast and also very wrong; it leaks the first
  activity created upon the first screen orientation change. When a
  Drawable is attached to a view, the view is set as a callback on the
  drawable. In the code snippet above, this means the drawable has a
  reference to the TextView which itself has a reference to the activity
  (the Context) which in turns has references to pretty much anything
  (depending on your code.)

Since you're talking about memory leaks on orientation changes, you may very well be making the mistakes the author details in his post.


text:
Q: How to replace the new page to existing URL? I am using the WordPress and I created one page few months back. Now, I just created new page and wanted to use the existing page URL. But, it doenst works.
Existing Page URL is: www.techno.com/pricing
I renamed the existing page to www.techno.com/pricingOld and used the above URL to new page.
Problem is , when I use the  www.puthuvan.com/pricing it redirects to www.puthuvan.com/pricingOld
How to solve this?
Thanks.

A: I think this issue is being caused by wordpress auto completing URLs. They should disable this protocol, people sometimes add pages to sites that they do not necessary want the public to know are there. Even if someone types a url incorrectly, wordpress will modify the url and redirect to what page it think the user wants to go to. This makes it a lot easier for the public to access unlisted pages on wordpress sites.
to prevent this add the below php code to functions.php
//stop wp auto completing url
function remove_redirect_guess_404_permalink( $redirect_url ) {
    if ( is_404() )
        return false;
    return $redirect_url;
}
add_filter( 'redirect_canonical', 'remove_redirect_guess_404_permalink' );


text:
Q: How periodicaly evaluate the Performance of Models in TF-Slim? I am trying to use DensNet for regression problem with TF-Slim. My data contains 60000 jpeg images with 37 float labels for each image. I divided my data into three different tfrecords files of a train set (60%), a validation set (20%) and a test set (20%).
I need to evaluate validation set during training loop and make a plot like image.
In TF-Slim documentation they just explain train loop and evaluation loop separately. I can just evaluate validation or test set after training loop finished. While as I said I need to evaluate during training.
I tried to use slim.evaluation.evaluation_loop function instead of slim.evaluation.evaluate_once. But it doesn't help.
slim.evaluation.evaluation_loop(
    master=FLAGS.master,
    checkpoint_dir=checkpoint_path,
    logdir=FLAGS.eval_dir,
    num_evals=num_batches,
    eval_op=list(names_to_updates.values()) + print_ops,
    variables_to_restore=variables_to_restore,
    summary_op = tf.summary.merge(summary_ops),
    eval_interval_secs = eval_interval_secs )

I tried evaluation.evaluate_repeatedly as well.
from tensorflow.contrib.training.python.training import evaluation

evaluation.evaluate_repeatedly(
    master=FLAGS.master,
    checkpoint_dir=checkpoint_path,
    eval_ops=list(names_to_updates.values()) + print_ops,
    eval_interval_secs = eval_interval_secs )

In both of these functions, they just read the latest available checkpoint from checkpoint_dir and apparently waiting for the next one, however when the new checkpoints are generated, they don't perform at all.
I use Python 2.7.13 and Tensorflow 1.3.0 on CPU.
Any help will be highly appreciated.

A: Using evaluate_once works just fine with bash script using sleep. Appears that Tensorboard is capable plotting multiple single runs from given eval_dir...
So I use something like:
#!/bin/bash
set -e

# Paths to model and evaluation results
TRAIN_DIR=~/pDL/tensorflow/model/mobilenet_v1_1_224_rp-v1/run0004
TEST_DIR=${TRAIN_DIR}/eval

# Where the dataset is saved to.
DATASET_DIR=/mnt/data/tensorflow/data

# Run evaluation (using slim.evaluation.evaluate_once)
CONTINUE=1

while [ "$CONTINUE" -ne 0 ]
do

python eval_image_classifier.py \
  --checkpoint_path=${TRAIN_DIR} \
  --eval_dir=${TEST_DIR} \
  --dataset_name=master_db \
  --preprocessing_name=preprocess224 \
  --dataset_split_name=valid \
  --dataset_dir=${DATASET_DIR} \
  --model_name=mobilenet_v1 \
  --patch_size=64

echo "sleeping for next run"
sleep 600
done

A: This appear to be issue of setting the checkpoint_path properly as addressed here:
https://github.com/tensorflow/tensorflow/issues/13769
Where the answer is by Ellie68 setting:
if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
   if tf.train.latest_checkpoint(FLAGS.checkpoint_path):
       checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
   else:
       checkpoint_path = FLAGS.checkpoint_path


text:
Q: Python- Can't get form data to transfer to python from HTML using flask I am trying to activated an output using a button click on a HTML page. But it's currently not giving me any errors but just isn't working. I'm new to Python and HTML so maybe I'm missing something. I've lost countless hours trying to search for a solution but have found nothing.

<meta name="viewport" content="width=device-width">

<form action="/" method="post" id="garageform">
<input ="post" id="garagecode" name="garagecode" type="text "pattern="[0-9]*" value="12345678" STYLE="background-color:white;">
</form>
<button width="90%" onclick="document.forms['garageform'].submit();">Submit</button>

Click for Log File

# Call flask function, template function and request function
from flask import Flask, render_template, request
print('Test')

# Import sys, datetime and time
import sys
import datetime
import time

# Imports the GPIO library for use
import RPi.GPIO as GPIO

# Turns off warning for GPIO in use
GPIO.setwarnings(False)

# Sets the GPIO use as board numbers
GPIO.setmode(GPIO.BOARD)

# Setup of the I/O's
GPIO.setup(7, GPIO.OUT)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(5, GPIO.OUT)
GPIO.setup(40, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(38, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(8, GPIO.OUT)

app = Flask(__name__)

# Create route to page on flask server
@app.route('/', methods=['POST','GET'])
def index():
    if GPIO.input(40) == GPIO.HIGH:
        name1=('\n Door fully closed ' + str(datetime.datetime.now()))
        GPIO.output(5, 0)
        name = name1
        return render_template('index.html', name=name)

    if GPIO.input(40) == GPIO.LOW and GPIO.input(38) == GPIO.LOW:
        name1=('\n Door in transition' + str(datetime.datetime.now()))
        GPIO.output(5, 1)
        output = request.form.to_dict()
        name =name1
        return render_template('index.html', name=name)

    if GPIO.input(38) == GPIO.HIGH:
        name1=('\n Door fully open ' + str(datetime.datetime.now()))
        GPIO.output(3, 1)
        output = request.form.to_dict()
        name =name1
        return render_template('index.html', name=name)

@app.route('/', methods=['GET', 'POST'])
def Garage():
    name = request.form['garagecode']
    if name == '12345678':
        GPIO.output(8, 0)
        time.sleep(1)

if __name__ == '__main__':
    app.run(debug=True, host='192.168.10.141')

The page loads but the input doesn't register back in Python.


text:
Q: Using bit shifting to guess UTF-8 encoding I am writing a program like file(1) that can guess if a text file contains ascii character, ISO-8859-1 characters, or UTF-8.
Ive already programmed it to guess ascii and ISO, only UTF-8 remains. My problem is I am supposed to be using bit-shifting, and while I know the very basics of bit-shifting, I am having trouble figuring it out how to use it for guessing UTF-8 characters.
I am of course not asking for a solution, but if someone could push me in the right direction, I would be pleased!
I am writing in C.

A: Any solution to this is going to be heuristic-based. But in general, UTF-8 has the following byte sequences (available in man utf8):
0x00000000 - 0x0000007F:
    0xxxxxxx
0x00000080 - 0x000007FF:
    110xxxxx 10xxxxxx
0x00000800 - 0x0000FFFF:
    1110xxxx 10xxxxxx 10xxxxxx
0x00010000 - 0x001FFFFF:
    11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

So your heuristic can look a few bytes ahead, and see if the bytes follow one of four patterns (UTF-8 in theory supports byte sequences stretching to six characters, but in practice only uses four):

*

*0* (you'll have to be careful to distinguish this from regular ASCII files)

*110*, 10*

*1110*, 10*, 10*

*11110*, 10*, 10*, 10*

Checking for these is easy:
To check if a unsigned char a fits one of these patterns, run:

*

*For 10* - the most frequent pattern - use (a >> 6) == 0x2.

*For 0* - use (a >> 7) == 0x0.

*For 110* - use (a >> 5) == 0x6.

*For 1110* - use (a >> 4) == 0xe.

*For 11110* - use (a >> 3) == 0x1e.

All we're doing is shifting the bits to the right and checking if they're equal to the bits in the UTF-8 byte sequences.


text:
Q: while loop not working for blackjack I am basically creating a simple blackjack game using python. I was trying to do a while loop by asking the player if they want to draw a card or no. However, it is not working, can someone help to figure out? Thanks!
The error is the while loop is not generating the draw_cards function if I put 'Y' or printing the message and break out of the loop if I put 'N'
import random
def draw_cards(): #this is a function to draw a card from the deck
  ranks =(2,3,4,5,6,7,8,9,10,'J','Q','K','A')
  suits =('Club','Dice','Heart','Spade')
  card = random.choice(suits) + ' ' +str(random.choice(ranks))
  return [card]

def stay_hit(): #this is to decide if the player wants to draw a card
  while True:
    playerinput=input('would you like to draw one more card? Y or
    N').upper
    if playerinput == 'Y':
        return draw_cards()
        continue
    elif playerinput == 'N':
        print('Ok, please show your cards')
        break

A: Your code works with some minor modifications:
import random
def draw_cards(): #this is a function to draw a card from the deck
  ranks =(2,3,4,5,6,7,8,9,10,'J','Q','K','A')
  suits =('Club','Dice','Heart','Spade')
  card = random.choice(suits) + ' ' +str(random.choice(ranks))
  return [card]

def stay_hit(): #this is to decide if the player wants to draw a card
  while True:
    playerinput=input('would you like to draw one more card? Y or N').upper()
    if playerinput == 'Y':
        print(draw_cards())
        continue
    elif playerinput == 'N':
        print('Ok, please show your cards')
        break

stay_hit()


text:
Q: не получается поднять текст при помощи css Вот код:

.blue_bg {
  background: url('Fon.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.upp_quete {
  margin: 0em 0em 20em 0em;
}

.quete p {
  text-transform: uppercase;
  font-weight: bold;
  line-height: 1.7em;
  color: #FFFFFF;
  font-size: 1em;
}

.Utug {
  padding: 0em 0em 0em 45em;
}

утюг Braun TS 345

Утюг с пароувлажнением для непревзойденного результата

cглажения даже мелких деталей одежды.

Глубоко проникающий пар разглаживает самые трудные участки ткани.

Безупречный результат быстро и просто.

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

A: Можно сделать так:

.blue_bg {
  background: url('Fon.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.upp_quete {
  margin: 0em 0em 20em 0em;
}

.quete p {
  text-transform: uppercase;
  font-weight: bold;
  line-height: 1.7em;
  color: #000000;
  font-size: 1em;

  margin: 0;
  /*     ^^^
   *     Обнуляем отступы
   */
}

.img-link {

  float: right;
  /*     ^^^^^
   *     Выравниваем по правой стороне
   */
}

утюг Braun TS 345

Утюг с пароувлажнением для непревзойденного результата

cглажения даже мелких деталей одежды.

Глубоко проникающий пар разглаживает самые трудные участки ткани.

Безупречный результат быстро и просто.


text:
Q: WCF: How can I send data while gracefully closing a connection? I've got a WCF service that offers a Login method. A client is required to call this method (due to it being the only IsInitiating=true). This method should return a string that describes the success of the call in any case. If the login failed, the connection should be closed.
The issue is with the timing of the close. I'd like to send the return value, then immediately close the connection.
string Login (string name, string pass)
{
    if (name != pass) {
        OperationContext.Current.Channel.Close ();
        return "fail";
    }
    else {
        return "yay";
    }
}

The MSDN states that calling Close on the channel

causes an ICommunicationObject to
  gracefully transition from the Opened
  state to the Closed state. The Close
  method allows any unfinished work to
  be completed before returning. For
  example, finish sending any buffered
  messages).

This did not work for me (or my understanding is wrong), as the close is executed immediately - WCF does not wait for the Login method to finish executing and return a string but closes the connection earlier.
Therefore I assume that calling Close does not wait for the running method to finish. Now, how can I still return a value, then close?
In my desperation I tried the following, but it is hardly a serious solution.
new Thread (() => {
    Thread.Sleep (100);
    OperationContext.Current.Channel.Close ();
}).Start ();

A: When the documentation says "gracefully", it's really talking about when you invoke ICommunicationObject.Close from the client side.  On the service side, if you try to close the channel while the client is still waiting for a response, you're going to have a bad time.
The client will get confused, not bothering to acknowledge the close, then the server will time out of its Close attempt, which in your case is happening on a worker thread, and unhandled exceptions on worker threads are not good for your service's health or your own sanity.
What you really want isn't a graceful connection close at all, you want to forcibly disconnect clients that fail to log in successfully.  In order to do that, you have to register an event handler for when the operation is completed, after the response is sent:
public string Login(string name, string pass)
{
    if (name != pass)
    {
        OperationContext.Current.OperationCompleted += LoginFailed;
        return "fail";
    }
    return "yay";
}

private void LoginFailed(object sender, EventArgs e)
{
    OperationContext.Current.Channel.Abort();
}

This will do what I'm pretty sure you want - send "fail" back to the client, clean up everything that needs to be cleaned up, and then disconnect the client, preventing any further activity on the session.
Incidentally, I don't know how close this is to the real service code, but it's a little redundant to have a "Login" method on the service when you can just use WCF's built in service credential system.

A: Why do you want to close the connection server side? I understand u want to clean up any resources as soon as possible. However why not manage this by using the available throttling (instance modes and such) and timeout options that WCF provides?


text:
Q: Why does a Node.js heapdump shows compiled code? Hi first time at investigating memory leak in a Node.js application.  By reading thru a heapdump snapshot in Chrome Profiler, I see that there is an entry for (compiled code), see attached.  I thought Javascript is not compiled, unlike Java.  Can anyone shed some lights?

Further, unlike JProfiler and with the way the code was written (without a formal constructor), it is very hard to find the leak, and so far the info the snapshot provides is not quite useful, I have searched for sometime and so far not too much useful info on reading these snapshots, any suggestions?
Thanks!

A: (compiled code) indeed refers to the code generated by V8's JIT compiler. All JavaScript VMs employed by browsers today are using tiered adaptive JIT compilation - it wouldn't be possible to achieve good performance otherwise. In fact V8 never had an interpreter at all.

A: That refers to host objects that are implemented in C++, such as the DOM, or the JS built-in functions.


text:
Q: Macports issue setting up RVM Just setting up rails and RVM on a new laptop and i'm getting this error when running
Error running 'requirements_osx_port_update_system ruby-2.0.0-p247',
please read /Users/#####/.rvm/log/1380821805_ruby-2.0.0-p247/update_system.log
Requirements installation failed with status: 1.

When running this
sudo rvm install ruby

Which produces this code.
[2013-10-03 13:36:45] requirements_osx_port_update_system
requirements_osx_port_update_system ()
{
    __rvm_try_sudo port -dv selfupdate || return $?
}
current path: /Users/matthewpetitt
command(2): requirements_osx_port_update_system ruby-2.0.0-p247
DEBUG: Copying /Users/matthewpetitt/Library/Preferences/com.apple.dt.Xcode.plist to                 /opt/local/var/macports/home/Library/Preferences
DEBUG: MacPorts sources location:     /opt/local/var/macports/sources/rsync.macports.org/release/tarballs
--->  Updating MacPorts base sources using rsync
rsync: failed to connect to rsync.macports.org: Operation timed out (60)
rsync error: error in socket IO (code 10) at /SourceCache/rsync/rsync-    42/rsync/clientserver.c(105) [receiver=2.6.9]
Command failed: /usr/bin/rsync -rtzv --delete-after     rsync://rsync.macports.org/release/tarballs/base.tar     /opt/local/var/macports/sources/rsync.macports.org/release/tarballs
Exit code: 10
DEBUG: Error synchronizing MacPorts sources: command execution failed
    while executing
"macports::selfupdate [array get global_options] base_updated"
Error: Error synchronizing MacPorts sources: command execution failed
To report a bug, follow the instructions in the guide:
    http://guide.macports.org/#project.tickets
Error: /Users/matthewpetitt/.rvm/bin/port: port selfupdate failed: Error synchronizing     MacPorts sources: command execution failed

I already have Xcode and Xcode command line tools installed. Anyone fixed something like this before.

A: Realized that it was just some network configuration at work that must have been blocking the ports. Check your network permissions or try a different network.

A: You need to make sure this command can be run first:
sudo port -dv selfupdate

This can be temporary network problem - if it is not follow the displayed instructions.


text:
Q: ColoredTextBox in UML C# I want to design and implement a class that represents a ColoredBox which also has a title. The color for the title bar should be also defined as a data member in the class.
The first thing i want todo is to write this as a UML design. I have written this:
ColoredTextBox // Class name
-------------- //Datafields

*

*x,y: int  //variables to declair the positions of the box

*Title: string

-------------- // Methods

*

*DrawBox ()

So, i have written down x and y ints to find the box positions, a string to give it a title and a method for drawinf the actual box. Is there anything else i have missed?

A: you don't appear to have any place to store the actual colour - or foreground/background colour depending how you are planning on doing it

A: Objects & Classes can be represented in a very conceptual way,
or more concrete, tool related way.
In this case, its a very specific implementation:
........................
..+------------------+..
..|  ColoredTextBox  |..
..+------------------+..
..| int: X           |..
..| int: Y           |..
..| string: Title    |..
..| Color: Backcolor |..
..+------------------+..
..| void: DrawBox(); |..
..+------------------+..
........................

Don't forget to add the return type for methods.
Cheers.


text:
Q: Proved by defining the boundary (delta and epsilon) I would be happy if anyone could give me a detailed answer. I was unable to express Delta using Epsilon.
My thought was (I will use keyboard keys) |x-a| = |x -(- 7)| = |x + 7| <delta | 3x +20 -1 | = |x + 7 + 2x + 12| < |x + 7| + 2| x + 6| I now have an expression | x + 7 | Which is smaller than Delta, but how do I reduce 2|x+ 6|
\begin{equation*} \lim_{x \rightarrow -7} |3x + 20|=1 \end{equation*}

A: Let $\epsilon>0$. By the reverse triagle inequality we have:
$||3x+20|-1|=||3x+20|-|-1||\leq |(3x+20)-(-1)|=|3x+21|=3|x+7|$
So now let $\delta=\frac{\epsilon}{3}$. If $|x-(-7)|=|x+7|<\delta$ then we get:
$||3x+20|-1|\leq 3|x+7|< 3\delta=3\frac{\epsilon}{3}=\epsilon$


text:
Q: Replacing particular value in hashtable I have declared a hashmap in javascript
formdata["id"]={"1","2","3",...}
formdata["value"]={"one","two","three",....}

Now, I want to update value for id=3, (value="three") to (value="four").
Is there any way to do this in javascript?

A: First, I think you must understand the difference between javascript and jquery. Very briefly, javascript: the language, jquery: a framework over the language.
So that's a javascript question and must be resolved in javascript.
Also your definition is bad, the array must be defined so:
formdata["id"]=[1,2,3,...];
formdata["value"]=["one","two","three",....];

A way based on your formdata var:
var index = formdata["id"].indexOf("3");
var value = formdata["value"][index];

Another way to define the structure like a "real dictionary":
var formdata = {
    "1": "one",
    "2": "two",
    "3": "three",
    ...
};
var value = formdata["3"];

// Update value:
formdata["3"] = "three_2";

// Add value:
formdata["4"] = "four";

// Remove value
delete formdata["3"]


text:
Q: Unable to build docker image with sasl python module I am trying to build a docker image containing Python 2 on my mac (High Sierra). Here is the docker file. (build command: docker build -t integration_test .)
FROM python:2

WORKDIR /usr/src/app

COPY requirements.txt ./

RUN pip install -r requirements.txt

COPY . .

CMD [ "nosetests" ]

Here are the contents of the requirements.txt
nose
pyhive
thrift
sasl
thrift_sasl
python-dateutil
future
six>=1.7.2

When I try to build the docker image, I get the following error.
Failed building wheel for sasl
  Running setup.py clean for sasl
  Running setup.py bdist_wheel for thrift-sasl: started
  Running setup.py bdist_wheel for thrift-sasl: finished with status 'done'
  Stored in directory: /root/.cache/pip/wheels/c8/3a/34/1d82df3d652788fc211c245d51dde857a58e603695ea41d93d
  Running setup.py bdist_wheel for future: started
  Running setup.py bdist_wheel for future: finished with status 'done'
  Stored in directory: /root/.cache/pip/wheels/bf/c9/a3/c538d90ef17cf7823fa51fc701a7a7a910a80f6a405bf15b1a
Successfully built pyhive thrift thrift-sasl future
Failed to build sasl
Installing collected packages: nose, future, six, python-dateutil, pyhive, thrift, sasl, thrift-sasl
  Running setup.py install for sasl: started
    Running setup.py install for sasl: finished with status 'error'
    Complete output from command /usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-Dd4Z7v/sasl/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-_rw4YI/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/sasl
    copying sasl/__init__.py -> build/lib.linux-x86_64-2.7/sasl
    running egg_info
    writing requirements to sasl.egg-info/requires.txt
    writing sasl.egg-info/PKG-INFO
    writing top-level names to sasl.egg-info/top_level.txt
    writing dependency_links to sasl.egg-info/dependency_links.txt
    reading manifest file 'sasl.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'sasl.egg-info/SOURCES.txt'
    copying sasl/saslwrapper.cpp -> build/lib.linux-x86_64-2.7/sasl
    copying sasl/saslwrapper.h -> build/lib.linux-x86_64-2.7/sasl
    copying sasl/saslwrapper.pyx -> build/lib.linux-x86_64-2.7/sasl
    running build_ext
    building 'sasl.saslwrapper' extension
    creating build/temp.linux-x86_64-2.7
    creating build/temp.linux-x86_64-2.7/sasl
    gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isasl -I/usr/local/include/python2.7 -c sasl/saslwrapper.cpp -o build/temp.linux-x86_64-2.7/sasl/saslwrapper.o
    cc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++
    In file included from sasl/saslwrapper.cpp:254:0:
    sasl/saslwrapper.h:22:23: fatal error: sasl/sasl.h: No such file or directory
     #include <sasl/sasl.h>
                           ^
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/local/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-Dd4Z7v/sasl/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-_rw4YI/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-Dd4Z7v/sasl/
The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1

I have seen a similar problem here It talks about installing the dependent library on host OS. I wanted to know how this can be done on docker image/container.
Has anyone faced this problem before? Any suggestions on how to solve this?

A: You need to install libsasl2-dev to your Docker image.
In its simplest form, add the following line to your Dockerfile before pip install:
RUN apt-get update && apt-get install libsasl2-dev

A:  RUN apt-get update && apt-get install gcc g++ libsasl2-dev -y
if anyone's build fail due to GCC missing.
Airflow is using a slim python image without gcc.


text:
Q: PowerShell script - distinguish between 3 command outcomes Can anyone tell me why I'm always get the same output result?
$syslocal = Get-WmiObject -Class Win32_UserAccount -Filter "localaccount=true" |
            where {$_.Disabled -eq $False}
if ($syslocal -eq "") {
    Write-Host "Syslocal Enabled"
    exit 0
} else {
    Write-Host "No Syslocal"
    exit 0
}

It just needs to see if a account syslocal exist and if it's enabled or not
with 3 outcomes:

*

*write host: syslocal does not exist, exit 0

*write host: syslocal exist, but is disabled, exit 0

*write host: syslocal exist and is enabled, exit 1010

But all outcomes are the same.

A: If your Get-WmiObject | Where-Object statement finds a match the variable $syslocal will contain a list of WMI objects. If the statement doesn't find a match (i.e. no local accounts exist or all of them are disabled) the variable will be empty. Neither an empty value nor an array of objects equal the empty string, so your check will always evaluate to $false.
Also, for a 3-way check you need to actually check 3 ways.
Change your code to something like this and it should do what you expect.
$syslocal = Get-WmiObject -Class Win32_UserAccount -Filter 'localaccount=true'

if ($syslocal) {
    if ($syslocal | Where-Object {-not $_.Disabled}) {
        Write-Host 'Enabled local accounts exist.'
        exit 1010
    } else {
        Write-Host 'Local accounts exist, but are disabled.'
    }
} else {
    Write-Host 'No local accounts.'
}
exit 0

A: this line is wrong:
if ($syslocal -eq "")

If it exist it's still not equal to ""
this should be:
if ($syslocal)

More details already explained on Ansgar Wiechers Answer...

A: Well there's this as well.
$syslocal = Get-WmiObject -Class win32_useraccount -filter "localaccount=true"
Foreach($account in $syslocal){
    If ($syslocal) {
        if($account.Disabled -eq $true) {
            Write-Host "$($account.name) is currently Disabled"
        } Else {
            Write-Host "$($account.name) is currently Enabled"
        }
    } Else {
        Write-host "Just no..."
    }
}


text:
Q: cupy performs task for 48ms vs numpy for 4ms - why and how to fix it? I try to use cupy to perform task on GPU - here is a code:
# on CPU
x_cpu = np.array([1, 2, 3])
%timeit l2_cpu = np.linalg.norm(x_cpu)

# on GPU
x_gpu = cp.array([1, 2, 3])
%timeit l2_gpu = cp.linalg.norm(x_gpu)

here is the output:
4 µs ± 18 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
48.7 µs ± 86.4 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) ```

Question:
My question is - why in my case cupy works slowly than NumPy? I expected that the CuPy will work quicker than NumPy. What did I do wrong and maybe somebody can advise me how to fix it?
Environment:

*

*OS: Ubuntu 20.04

*Video:

 > nvidia-smi
 Wed Sep 15 22:11:36 2021
 +-----------------------------------------------------------------------------+
 | NVIDIA-SMI 470.57.02    Driver Version: 470.57.02    CUDA Version: 11.4     |
 |-------------------------------+----------------------+----------------------+
 | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
 | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
 |                               |                      |               MIG M. |
 |===============================+======================+======================|
 |   0  NVIDIA GeForce ...  Off  | 00000000:01:00.0 Off |                  N/A |
 | 41%   33C    P8     1W / 260W |    184MiB / 11019MiB |      0%      Default |
 |                               |                      |                  N/A |
 +-------------------------------+----------------------+----------------------+

 +-----------------------------------------------------------------------------+
 | Processes:                                                                  |
 |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
 |        ID   ID                                                   Usage      |
 |=============================================================================|
 |    0   N/A  N/A    627367      C   ...conda3/envs/t1/bin/python      181MiB |
 +-----------------------------------------------------------------------------+

Also, I use puthon3.8 and I have installed:

*

*cupy                  8.3.0

*cupy-cuda114          9.4.0

*cudatoolkit           10.1.243             h6bb024c_0
and so on.

UPDATED
I used array with 1023272 items also - here is a result:

*

*175 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

*579 µs ± 97.1 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Also, I checked GPU utilization using nvidia-smi and I can confirm - GPU was involved in calculation

A: You are measuring 4-8 GB/s data copying performance from the cupy test. Norm is normalization so its most probably a short reduction to find max element in matrix and dividing all elements by this value. This has little computation per byte transferred through pcie.
If you really want to compare compute performances, you may do something like matrix-matrix multiplication and with big enough matrix sizes like 2048x2048 x 2048x2048.
In your current test, numpy bottlenecked by ram bandwidth while cupy is bottlenecked by pcie bandwidth. You could open a profiler for cuda and see exact compute time of kernel and use that (should be faster than cpu already).
In first test, there are only 3 elements so first test numpy result is probably function call overhead of python. Then, the cupy result must be the kernel launch overhead and python function overhead and an extra overhead from calling data copying function. Even just kernel launching in cuda costs 10-20 microseconds for an empty kernel function.


text:
Q: how to send object from jquery to aspnet webapi controller? I tried to send object as json  to controller in post method but it's raise error.
what's to do?(attatched this relvant code):
    public class user
    {
        public string username;
        public string password;
    }
    // POST: api/User
    public void Post(user u)
    {
        if (!database_layer.create_user(u.username, u.password))
        { throw new HttpResponseException(HttpStatusCode.BadRequest); }
    }

A: If your data is to be send as JSON you need to serialize it before it is send. Replace data:user with
data: JSON.stringify(user)

See one of the following already asked questions:

*

*Send JSON data via POST (ajax) and receive json response from Controller (MVC)

*Send JSON data with jQuery

*jQuery ajax, how to send JSON instead of QueryString


text:
Q: Python - Extract/access information from json via Kraken API I'm trying to understand how to work with the json returns I am getting from de Kraken API.
This is my code:
resp = kraken_request("/0/private/TradeBalance", {
    "nonce": str(int(10000*time.time())),
    "asset": "USD"
}, api_key, api_sec)

print("TradeBalance: " + str(resp.json()))

resp = kraken_request("/0/private/OpenOrders", {
    "nonce": str(int(10000*time.time())),
    "asset": "USD"
}, api_key, api_sec)
print()
print("OpenOrders: " + str(resp.json())

This is my json return (edited so it is no real data):
{"error":[],"result":{"open":{"ABCDE-AWSCG-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683580.8848298,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.70000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.70000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-AHKEK-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683548.8137474,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.60000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.60000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-POQX7-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683517.207053,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.50000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.50000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-UADOV-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683490.4299977,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.40000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.40000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-ABCDE-2JGH3M":{"refid":null,"userref":0,"status":"open","opentm":1666646615.668582,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.30000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.30000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fciq"},"ABCDE-623OO-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666646572.9639573,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.20000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.20000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fciq"},"ABCDE-4EHBG-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666646537.55891,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.10000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.10000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fciq"},"ABCDE-SPHMF-ABCDE":{"refid":null,"link_id":"ABCDE-YWJVW-ABCDE","userref":0,"status":"open","opentm":1666646453.770994,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"7.99900","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 7.99900","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-RVWQO-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1663311467.0131989,"starttm":0,"expiretm":0,"descr":{"pair":"ETHWUSD","type":"sell","ordertype":"limit","price":"1000.000","price2":"0","leverage":"none","order":"sell 357.00000000 ETHWUSD @ limit 1000.000","close":""},"vol":"357.00000000","vol_exec":"0.00000000","cost":"0.0000000","fee":"0.0000000","price":"0.0000000","stopprice":"0.0000000","limitprice":"0.0000000","misc":"","oflags":"fcib"}}}}

Now I can't work out how to work with this json, I'd like to go through it and deal with each of the items, like "ABCDE-AWSCG-ABCDE" and  "ABCDE-POQX7-ABCDE" etc., with for each all of it's underlying information, I have no idea how to do this. Please note, I do not know the item names like "ABCDE-AWSCG-ABCDE" beforehand.

A: You should use pandas. You can see all the data in a table. This is much easier than working with a json.
import pandas as pd
import numpy as np
null=np.nan

returned_json={"error":[],"result":{"open":{"ABCDE-AWSCG-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683580.8848298,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.70000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.70000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-AHKEK-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683548.8137474,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.60000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.60000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-POQX7-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683517.207053,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.50000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.50000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-UADOV-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666683490.4299977,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.40000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.40000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-ABCDE-2JGH3M":{"refid":null,"userref":0,"status":"open","opentm":1666646615.668582,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.30000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.30000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fciq"},"ABCDE-623OO-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666646572.9639573,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.20000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.20000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fciq"},"ABCDE-4EHBG-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1666646537.55891,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"8.10000","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 8.10000","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fciq"},"ABCDE-SPHMF-ABCDE":{"refid":null,"link_id":"ABCDE-YWJVW-ABCDE","userref":0,"status":"open","opentm":1666646453.770994,"starttm":0,"expiretm":0,"descr":{"pair":"LINKEUR","type":"sell","ordertype":"limit","price":"7.99900","price2":"0","leverage":"none","order":"sell 1.00000000 LINKEUR @ limit 7.99900","close":""},"vol":"1.00000000","vol_exec":"0.00000000","cost":"0.000000","fee":"0.000000","price":"0.000000","stopprice":"0.000000","limitprice":"0.000000","misc":"","oflags":"fcib"},"ABCDE-RVWQO-ABCDE":{"refid":null,"userref":0,"status":"open","opentm":1663311467.0131989,"starttm":0,"expiretm":0,"descr":{"pair":"ETHWUSD","type":"sell","ordertype":"limit","price":"1000.000","price2":"0","leverage":"none","order":"sell 357.00000000 ETHWUSD @ limit 1000.000","close":""},"vol":"357.00000000","vol_exec":"0.00000000","cost":"0.0000000","fee":"0.0000000","price":"0.0000000","stopprice":"0.0000000","limitprice":"0.0000000","misc":"","oflags":"fcib"}}}}

df=pd.DataFrame(returned_json['result'])['open'].apply(pd.Series).rename(columns={'price':'price_main'})
df=df.join(df['descr'].apply(pd.Series))
print(df)
'''
                      refid userref status             opentm     starttm   expiretm    descr   vol vol_exec    cost    fee price_main  stopprice   limitprice  misc    oflags  link_id pair    type    ordertype   price   price2  leverage    order   close
ABCDE-4EHBG-ABCDE       0   open    1666646537.55891    0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.10000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.10000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fciq        LINKEUR sell    limit   8.10000 0   none    sell 1.00000000 LINKEUR @ limit 8.10000
ABCDE-623OO-ABCDE       0   open    1666646572.9639573  0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.20000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.20000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fciq        LINKEUR sell    limit   8.20000 0   none    sell 1.00000000 LINKEUR @ limit 8.20000
ABCDE-ABCDE-2JGH3M      0   open    1666646615.668582   0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.30000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.30000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fciq        LINKEUR sell    limit   8.30000 0   none    sell 1.00000000 LINKEUR @ limit 8.30000
ABCDE-AHKEK-ABCDE       0   open    1666683548.8137474  0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.60000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.60000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fcib        LINKEUR sell    limit   8.60000 0   none    sell 1.00000000 LINKEUR @ limit 8.60000
ABCDE-AWSCG-ABCDE       0   open    1666683580.8848298  0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.70000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.70000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fcib        LINKEUR sell    limit   8.70000 0   none    sell 1.00000000 LINKEUR @ limit 8.70000
ABCDE-POQX7-ABCDE       0   open    1666683517.207053   0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.50000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.50000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fcib        LINKEUR sell    limit   8.50000 0   none    sell 1.00000000 LINKEUR @ limit 8.50000
ABCDE-RVWQO-ABCDE       0   open    1663311467.0131989  0   0   {'pair': 'ETHWUSD', 'type': 'sell', 'ordertype': 'limit', 'price': '1000.000', 'price2': '0', 'leverage': 'none', 'order': 'sell 357.00000000 ETHWUSD @ limit 1000.000', 'close': ''}   357.00000000    0.00000000  0.0000000   0.0000000   0.0000000   0.0000000   0.0000000       fcib        ETHWUSD sell    limit   1000.000    0   none    sell 357.00000000 ETHWUSD @ limit 1000.000
ABCDE-SPHMF-ABCDE       0   open    1666646453.770994   0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '7.99900', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 7.99900', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fcib    ABCDE-YWJVW-ABCDE   LINKEUR sell    limit   7.99900 0   none    sell 1.00000000 LINKEUR @ limit 7.99900
ABCDE-UADOV-ABCDE       0   open    1666683490.4299977  0   0   {'pair': 'LINKEUR', 'type': 'sell', 'ordertype': 'limit', 'price': '8.40000', 'price2': '0', 'leverage': 'none', 'order': 'sell 1.00000000 LINKEUR @ limit 8.40000', 'close': ''}   1.00000000  0.00000000  0.000000    0.000000    0.000000    0.000000    0.000000        fcib        LINKEUR sell    limit   8.40000 0   none    sell 1.00000000 LINKEUR @ limit 8.40000

'''


text:
Q: numpy.core._exceptions.MemoryError: Unable to allocate 10.3 GiB for an array with shape (138494, 10000) and data type float64 def train(self):
        self.P = np.random.rand(self.nr_users, self.K)/self.K
        self.Q = np.random.rand(self.nr_events, self.K)/self.K
        self.b_u = np.zeros(self.nr_users, dtype='uint8')
        self.b_m = np.zeros(self.nr_events, dtype='uint8')
        self.b = np.uint8(np.mean(self.R[np.where(self.R != 0)]))

numpy.core._exceptions.MemoryError: Unable to allocate 10.3 GiB for an array with shape (138494, 10000) and data type float64
Unable to get rid of this error. Tried the .astype=('uint8') does not work. My python is running on 64-bit so wondering why I am facing this issue.
How do I add dtype='uint8' in a np.random.rand variable?_


text:
Q: The ContextMenu and the sublevels I am able to create a ContextMenu with a level and a first sublevel. I was trying to add more sublevels but I can't. I searched the Internet for a long time to find some examples, but nothing. In my example, how should I modify the code to add the 'Brenda' option in the second sublevel? Please look at the picture. Thanks.

def contextMenuEvent(self,event):

    menu = QMenu(self)

    Option1 = menu.addAction("Paul")

    Option2 = QMenu("Richard")
    Option2_1 = Option2.addAction("Frida")
    Option2_2 = Option2.addAction("Susan")
    menu.addMenu(Option2)

    Option3 = menu.addAction("Thomas")

    action = menu.exec_(self.mapToGlobal(event.pos()))
    if action == Option1:
        print("Paul")
    elif action == Option2_1:
        print("Frida")
    elif action == Option2_2:
        print("Susan")
    elif action == Option3:
        print("Thomas")

A: Shouldn't this be how to achieve a third menu layer?
def contextMenuEvent(self,event):

    menu = QMenu(self)

    Option1 = menu.addAction("Paul")

    Option2 = QMenu("Richard")
    Option2_1 = Option2.addAction("Frida")
    Option2_2 = QMenu("Susan") # define a new menu, not an action
    Option2_2_1 = Option2_2.addAction("Brenda") # add sub menu item
    Option2.addMenu(Option2_2) # add menu to Option2 menu
    menu.addMenu(Option2)

    Option3 = menu.addAction("Thomas")

    action = menu.exec_(self.mapToGlobal(event.pos()))
    if action == Option1:
        print("Paul")
    elif action == Option2_1:
        print("Frida")
    elif action == Option2_2:
        print("Susan")
    elif action == Option3:
        print("Thomas")


text:
Q: Eigen cast with auto return type - Less efficient than explicit return type? When casting a vector integers (i.e. Eigen::VectorXi) to a vector of doubles, and then operating on that vector of doubles, the generated assembly is dramatically different if the return type of the cast is auto.
In other words, using:
    Eigen::VectorXi int_vec(3);
    int_vec << 1, 2, 3;

    Eigen::VectorXd dbl_vec = int_vec.cast<double>();

Compared to:
    Eigen::VectorXi int_vec(3);
    int_vec << 1, 2, 3;

    auto dbl_vec = int_vec.cast<double>();

Here are two examples on godbolt:
VectorXd return type: https://godbolt.org/z/0FLC4r
auto return type: https://godbolt.org/z/MGxCaL
What are the ramifications of using auto for the return here? I thought it would be more efficient by avoiding a copy, but now I'm not sure.

A: Indeed, in your code in the question you avoid a copy (indeed, until dbl_vec is used, it's essentially a noop). However, in the code on godbolt, you traverse the original int_vec  and evaluate dbl_vec at least twice, possibly thrice:
max + std::log((dbl_vec.array() - max)
^^^             ^^^^^^^           ^^^

I'm not sure if the two calls to max are collapsed into a temporary or not. I'd hope so.
In any case, kmdreko is right and you should avoid using auto with Eigen unless you know exactly what you're doing. In this case, the auto is an expression template that does not get evaluated until used. If you use it more than once, then it gets evaluated more than once. If the evaluation is expensive, then the savings from not using a copy are lost (with interest) to the additional evaluation times.


text:
Q: Why do airboats roll into turns? I have read this question and the answers left me with almost the same question about airboats:
Assuming that an airboat CoM is below the center of the horizontal thrust provided by the rudder. Along with some resistance on the hull from the water this should (in my mind) create a torque rolling the top of the boat towards the outside of the turn, however the opposite appears to happen, why?
I can think of a few of reasons why this might be:

*

*My assumption is incorrect that the CoM is below the turning force (is that why the drivers are always seated so high)?

*The driver compensates by using the torque of the motor or by counter-steering.

*There is a force with a significant upward component acting on the outside-side of the hull. However I find it difficult to get my mind around how this would instigate the roll in the case of a 90$\unicode{xb0}$ chine i.e. a simple rectangular hull cross section. (which many airboats seem to have).

A: It shouldn't be the general solution, but for some of the boats it can be that your assumption about the boat's Center of Mass is not verified.
Many of these boats are known for being top heavy, with not only the seats, but also the engine and propeller often mounted high on the boat.
Besides, the rudder plates are sometimes mounted low behind the propeller, which means the center of horizontal thrust will be rather low.

A: I think your last guess (about the forces on the hull) might be the reason for what you see.
A massive object wants to go in a straight line unless there is a force acting on it.  Let's look at the case of you turning a boat to the right.  In this case, the net force acting on the boat must be acting to the right.  On an airboat you do this by initially deflecting the airstream to the right.  This causes a reaction force on the boat in the left-ward direction.  But didn't we just say that in order to turn the boat to the right, the net force on the boat must be to the right, and not the left?
Well, let's look at what happens.  The deflected airstream pushes the back of the boat towards the left, which causes the front of the boat to rotate towards the right.  Inertia of the boat wants to keep it moving in a straight line, but now you have to think about what the water is doing.  When the front of the boat is tilted to the right, then as the boat tries to move in a straight line, it will push a lot of water towards the left.  This deflected water exerts a reaction force on the boat pointing to the right.  This is the force that causes the boat to move towards the right.
But you are not only deflecting water to the left, but you are also deflecting a lot of water downward, which pushes upward on the outside of the hull and causes the boat to be tilted into the curve.


text:
Q: accessing objects outside of function inner scope in event call, and when do objects get cleaned up I'm trying to create a utility method which will attach to the $destroy event of the $scope$ of AngularJS, so  that it automatically cleans up the handler and avoid memory leaks.  Below is some sample code for this utility method called attachEventToRootscopeAndRegisterUnbind(), and is in TypeScript however should be quite similar to JavaScript.
class EventToUnRegister {
    public $scope: ng.IScope;
    public unbindHandler: Function;
    public eventName: string;
    public logger: Core.ILog;

    public onScopeDestroy() {
        this.logger.debug("EventToUnRegister:onScopeDestroy",`Scope destroyed, unbinding event '${this.eventName}'`);
        this.unbindHandler();

        //remove references
        this.logger = null;
        this.unbindHandler = null;
        this.$scope = null;
        this.eventName = null;

    }

}

    attachEventToRootscopeAndRegisterUnbind($scope: ng.IScope, eventName: string, listener: (event: angular.IAngularEvent, ...args: any[]) => any) {
        var eventToUnRegister = new EventToUnRegister();
        eventToUnRegister.$scope = $scope;
        eventToUnRegister.logger = this.logger;
        eventToUnRegister.unbindHandler = this.$rootScope.$on(eventName, listener);
        eventToUnRegister.eventName = eventName;
        $scope.$on("$destroy", () => {
            eventToUnRegister.onScopeDestroy();  //<-- IS IT AN ISSUE TO ACCESS THIS HERE?
            eventToUnRegister = null; //remove reference to make sure it is cleaned up
        });
    }

My issues are:

*

*Are there any issues with accessing eventToUnRegister from the $scope.$on event handler?

*Would there still be any form of memory leaks this way?

The original issue is that from a controller you attach to an event on the $rootscope for any reason.  Ideally, this is not done but sometimes it is needed. Then, since $rootscope never is destroyed, the controller will live on forever due to the event.  I'm trying to create this utility method to fix this.

A: Looks perfectly valid to me and as long as there is no chain of related events fired within the $destroy I don't see any problem. Besides you don't need to nullify everything so explicitly. If the reference to the containing object is out of scope (and none of it's child properties have somehow a reference back), the object is garbage collected.


text:
Q: Limiting one appointment per user I'm trying to make it so users are only able to schedule one appointment. Here I am modifying the save method. What I am trying to figure out is how to see if that user already has an appointment.
def save(self, *args, **kwargs):
    if Appointment.objects.filter(owner=user_pk).exists() and not self.pk:
        # if you'll not check for self.pk
        # then error will also raised in update of exists model
        raise ValidationError('You have already scheduled an appointment.')
    return super(Appointment, self).save(*args, **kwargs)

In my views.py I already have something that will raise an error if an appointment with that user already exists. But i'm thinking this is not enough and that there should be something at the model level.
appointments = Appointment.objects.filter(owner=request.user)
    if appointments.exists():
        raise PermissionDenied('You have already scheduled an appointment.')

A: Rather than having your view handle that logic,I would change the database relation to a OneToOneField.  Have the field be nullable, and therefore you can rely on your django's db module to maintain relational integrity with this field
As described in the source code:
A OneToOneField is essentially the same as a ForeignKey, with the exception
that it always carries a "unique" constraint with it and the reverse
relation always returns the object pointed to (since there will only ever
be one), rather than returning a list.

A: The self object has the owner attribute set to the current user, so you can use self.owner to access it:
def save(self, *args, **kwargs):
    if Appointment.objects.filter(owner=self.owner).exists() and not self.pk:
    ...


text:
Q: Properties of trees I need to show that the three following statements are equivalent:

*

*$G$ is a tree.

*Every closed walk in a connected graph $G$ uses all of its edges at least twice

*Every closed walk in a connected graph $G$ uses at least one of its edges at least twice.

I've been able to show that $1 \implies 3$ and $3 \implies 1$. It's easy to show that $2 \implies 3$, however I can't quite figure out how to show that $3 \implies 2$ or $1 \implies 2$ to complete the equivalences.
I've been mainly trying to prove $1 \implies 2$. It would be easy if all walks were made up of two paths: $u, \ldots, v, \ldots, u$. Since there's only one path between $u$ and $v$ in a tree, each edge would have to be traversed twice. But a walk could be constructed out of a lot more than two paths like my example ($u, \ldots, v, \ldots, w, \ldots x, \ldots, y, \ldots, z, \ldots u$), so I'm a little confused about how to proceed.
I would appreciate a push in the right direction.

A: Hint for $1 \implies 2$: if there is a closed walk which does not use all of its edges at least twice, we can find a leaf (and an edge connected to that leaf) that is visited only once. The only possibility is that you started the walk from that leaf, but this leads to a contradiction with the fact that the walk was closed, because you can never reach the start.
Notice that these three aren't equivalent for infinite trees.

A: Continuing the argument I had in the question:
If a closed walk has the form $uv$-path, $vu$-path, it's obvious to see that every edge is traversed twice.
If a closed walk has the form $uv$-path, $vw$-path, $wu$-path, then there are two cases:
Case 1: The $uv$-path is disjoint from the $vw$-path.
$\implies$ The $wu$-path will have to travel through $v$ $\implies uv$-path, $vw$-path, $wu$-path $\equiv uv$-path, $vw$-path, $wv$-path, $vu$-path.
Case 2: The $uv$-path is not disjoint from the $vw$-path.
Let $x$ be the last vertex that the $uv$-path and the $vw$-path have in common. Now we have $uv$-path, $vw$-path, $wu$-path $\equiv ux$-path, $xv$-path, $vx$-path, $xw$-path, $wx$-path, $xu$-path.
In either case, we have to traverse each edge twice.
It's possible to extend this to any number of vertices to show that it holds in general.


text:
Q: Why do we pass the reference arg into the function creating the list_head_insert function in C++? Here are some codes for creating a Linked list by inserting the elements in the head.But I don't know why we use the reference variable for the arg since we need to use the malloc function to assign a address to c .
typedef struct lnode{
    int data;
    struct lnode* next;
}lnode;

void createlistF(lnode* &c,int a[],int n)
{
    c=(lnode*)malloc(sizeof(lnode));
    c->next=NULL;
    lnode *s;
    for (int i=0;i<n;++i)
    {
        s=(lnode*)malloc(sizeof(lnode));
        s->data=a[i];
        s->next=c->next;
        c->next=s;
    }
}

I mean,why not to write like this?

typedef struct lnode{
    int data;
    struct lnode* next;
}lnode;

lnode* createlistF(int a[],int n)
{
    lnode *c;
    c=(lnode*)malloc(sizeof(lnode));
    c->next=NULL;
    lnode *s;
    for (int i=0;i<n;++i)
    {
        s=(lnode*)malloc(sizeof(lnode));
        s->data=a[i];
        s->next=c->next;
        c->next=s;
    }
    return c;
}

I would appreciate it if you could help me understand this thing.Thank you!


text:
Q: How to debug multi-threaded code in GDB? I am trying to debug multi-threaded program with one thread that waits input from user. When I put a breakpoint at some function of other thread and run app, it switches into same breakpoint and then immediately at input thread, so app waits input from user and I can't do any command in gdb. I simply need see all stack before invoking same function. I can't make bt command in

A: Does thread apply all bt answer your question?

A: You can add commands to a breakpoint, see the manual. Something like this:
(gdb) break some_func
Breakpoint 2 at ...
(gdb) commands 2
Type commands for breakpoint(s) 2, one per line.
End with a line saying just "end".
>thread apply all bt full
>end
(gdb) cont
Continuing.
Breakpoint 2, ...
Thread 1 (Thread 0x....
...

Edit 0:
Oh, I'm guessing you get gdb printing this on you:
---Type <return> to continue, or q <return> to quit---

Just do the following before you do run (you can also stick this into .gdbinit file):
(gdb) set pagination off