text:
Q: padding is invalid and cannot be removed ERROR firing at cs.FlushFinalBlock() line I am trying to use the Rijndael method to encrypt and decrypt data. It encrypts fine but when I try to decrypt it it gives padding is invalid and cannot be removed  at the line cs.FlushFinalBlock(); in the private static byte[] DecryptString(byte[] cipherData, byte[] Key, byte[] IV) method. I tried many sources like

*

*RijndaelManaged "Padding is invalid and cannot be removed" that only occurs when decrypting in production

*Stopping decryption before EOF throws exception: Padding is invalid and cannot be removed

*http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0fa69204-3bba-48a9-9bdc-32a12b0da4a0
I know this is a common question and might be even a duplicate.  I searched onlne from the morning and came up with  no solutions. following is my code.
    //clearText -> the string to be encrypted
    //passowrd -> encryption key
    public string EncryptString(string clearText, string Password)
    {
        // First we need to turn the input string into a byte array.
        byte[] clearBytes =
            Encoding.Unicode.GetBytes(clearText);

        // Then, we need to turn the password into Key and IV
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        var pdb = new PasswordDeriveBytes(Password,
                                          new byte[]
                                              {
                                                  0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                  0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
                                              });

        // Now get the key/IV and do the encryption using the
        // function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes.
        byte[] encryptedData = EncryptString(clearBytes,
                                             pdb.GetBytes(32), pdb.GetBytes(16));

        // Now we need to turn the resulting byte array into a string.
        // A common mistake would be to use an Encoding class for that.
        //It does not work because not all byte values can be
        // represented by characters.
        // We are going to be using Base64 encoding that is designed
        //exactly for what we are trying to do.
        return Convert.ToBase64String(encryptedData);
    }
    //cipherText -> the string to be decrypted
    //passowrd -> decryption key
    public string DecryptString(string cipherText, string Password)
    {
        // First we need to turn the input string into a byte array.
        // We presume that Base64 encoding was used
        byte[] cipherBytes = Convert.FromBase64String(cipherText);

        // Then, we need to turn the password into Key and IV
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        var pdb = new PasswordDeriveBytes(Password,
                                          new byte[]
                                              {
                                                  0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
                                                  0x64, 0x76, 0x65, 0x64, 0x65, 0x76
                                              });

        // Now get the key/IV and do the decryption using
        // the function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first
        // getting 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by
        // default 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes.
        byte[] decryptedData = DecryptString(cipherBytes,
                                             pdb.GetBytes(32), pdb.GetBytes(16));

        // Now we need to turn the resulting byte array into a string.
        // A common mistake would be to use an Encoding class for that.
        // It does not work
        // because not all byte values can be represented by characters.
        // We are going to be using Base64 encoding that is
        // designed exactly for what we are trying to do.
        return Encoding.Unicode.GetString(decryptedData);
    }

    // Encrypt a byte array into a byte array using a key and an IV
    private static byte[] EncryptString(byte[] clearData, byte[] Key, byte[] IV)
    {
        // Create a MemoryStream to accept the encrypted bytes
        var ms = new MemoryStream();

        // Create a symmetric algorithm.
        // We are going to use Rijndael because it is strong and
        // available on all platforms.
        // You can use other algorithms, to do so substitute the
        // next line with something like
        //      TripleDES alg = TripleDES.Create();
        Rijndael alg = Rijndael.Create();

        // Now set the key and the IV.
        // We need the IV (Initialization Vector) because
        // the algorithm is operating in its default
        // mode called CBC (Cipher Block Chaining).
        // The IV is XORed with the first block (8 byte)
        // of the data before it is encrypted, and then each
        // encrypted block is XORed with the
        // following block of plaintext.
        // This is done to make encryption more secure.

        // There is also a mode called ECB which does not need an IV,
        // but it is much less secure.
        alg.Key = Key;
        alg.IV = IV;

        // Create a CryptoStream through which we are going to be
        // pumping our data.
        // CryptoStreamMode.Write means that we are going to be
        // writing data to the stream and the output will be written
        // in the MemoryStream we have provided.
        var cs = new CryptoStream(ms,
                                  alg.CreateEncryptor(), CryptoStreamMode.Write);

        // Write the data and make it do the encryption
        cs.Write(clearData, 0, clearData.Length);

        // Close the crypto stream (or do FlushFinalBlock).
        // This will tell it that we have done our encryption and
        // there is no more data coming in,
        // and it is now a good time to apply the padding and
        // finalize the encryption process.
        cs.FlushFinalBlock();

        // Now get the encrypted data from the MemoryStream.
        // Some people make a mistake of using GetBuffer() here,
        // which is not the right way.
        byte[] encryptedData = ms.ToArray();

        return encryptedData;
    }

    private static byte[] DecryptString(byte[] cipherData,
                                        byte[] Key, byte[] IV)
    {
        // Create a MemoryStream that is going to accept the
        // decrypted bytes
        var ms = new MemoryStream();

        // Create a symmetric algorithm.
        // We are going to use Rijndael because it is strong and
        // available on all platforms.
        // You can use other algorithms, to do so substitute the next
        // line with something like
        //     TripleDES alg = TripleDES.Create();
        Rijndael alg = Rijndael.Create();

        // Now set the key and the IV.
        // We need the IV (Initialization Vector) because the algorithm
        // is operating in its default
        // mode called CBC (Cipher Block Chaining). The IV is XORed with
        // the first block (8 byte)
        // of the data after it is decrypted, and then each decrypted
        // block is XORed with the previous
        // cipher block. This is done to make encryption more secure.
        // There is also a mode called ECB which does not need an IV,
        // but it is much less secure.
        alg.Key = Key;
        alg.IV = IV;

        // Create a CryptoStream through which we are going to be
        // pumping our data.
        // CryptoStreamMode.Write means that we are going to be
        // writing data to the stream
        // and the output will be written in the MemoryStream
        // we have provided.
        var cs = new CryptoStream(ms,
                                  alg.CreateDecryptor(), CryptoStreamMode.Write);

        // Write the data and make it do the decryption
        cs.Write(cipherData, 0, cipherData.Length);

        // Close the crypto stream (or do FlushFinalBlock).
        // This will tell it that we have done our decryption
        // and there is no more data coming in,
        // and it is now a good time to remove the padding
        // and finalize the decryption process.
        cs.FlushFinalBlock();

        // Now get the decrypted data from the MemoryStream.
        // Some people make a mistake of using GetBuffer() here,
        // which is not the right way.
        byte[] decryptedData = ms.ToArray();

        return decryptedData;
    }

Thank you very much :)
PS : i grabbed this code from online and edited a bit to suit my program

A: You need to get past the exception so you can diagnose what is going on.  In order to do that, you need to set the decryption side only to expect no padding.  That will let it accept anything.  Once you have done that, you can have a look at what is emerging from your decryption and start diagnosing faults.  Note that this is not a solution, it is a way to ignore the exception.  Whatever is causing the exception is still there.
Have a look at what emerges.  Is is all garbage?  Is it part garbage and part the original plaintext?  If it is mixed, where does the garbage appear: at the start, at the end, both, in the middle somewhere?  Tell us what you see and we can point you to probable causes of the problems.
When everything is working, set both encryption and decryption to PKCS#7 padding.  Do not leave the no padding in place.


text:
Q: Clojure - using map recursively If I have a list, I can use map to apply a function to each item of the list.
(map sqrt (list 1 4 9))

(1 2 3)

I can also use map in front of a list of lists:
(map count (list (list 1 2 3) (list 4 5)))

(4 5)

Now is there a way to apply sqrt to each number in the list of lists? I want to start from
(list (list 1 4 9) (list 16 25))

and obtain
((1 2 3)(4 5))

However, the following does not seem to work,
(map (map sqrt) (list (list 1 4 9) (list 16 25)))

nor the following.
(map (fn [x] (map sqrt x)) (list (list 1 4 9) (list 16 25)))

Why? (And how do I solve this?)

A: Your second to last version "nearly" works.  Clojure has no automatic
currying, so (map sqrt) is not partial application, but (map sqrt)
returns a transducer, which takes one argument and returns a function
with three different arities - so running your code there will give you
back a function for each list of numbers.
To make that work, you can use partial:
user=> (map (partial map sqrt) (list (list 1 4 9) (list 16 25)))
((1 2 3) (4 5))

And of course there is the obligatory specter answer:
user=> (transform [ALL ALL] sqrt '((1 4 9)(16 25)))
((1 2 3) (4 5))

A: You can write recursive function for this task:
(defn deep-map [f seq1]
  (cond (empty? seq1) nil
        (sequential? (first seq1))
        (cons (deep-map f (first seq1))
              (deep-map f (rest seq1)))
        :else (cons (f (first seq1))
                    (deep-map f (rest seq1)))))

Example:
(deep-map #(Math/sqrt %) '((1 4 9) (16 25 36)))
=> ((1.0 2.0 3.0) (4.0 5.0 6.0))

Or you can use clojure.walk and function postwalk:
(clojure.walk/postwalk
  #(if (number? %) (Math/sqrt %) %)
  '((1 4 9) (16 25 36)))

=> ((1.0 2.0 3.0) (4.0 5.0 6.0))

A: The function map is closely related to the function for, which I think is sometimes easier to use.  Here is how I would solve this problem:
  (let [matrix [[1 4 9]
                [16 25]]
        result (vec (for [row matrix]
                      (vec (for [num row]
                             (Math/sqrt num)))))]
    result)

with result:
result =>
    [[1.0 2.0 3.0]
     [4.0 5.0]]

If you remove the two (vec ...) bits, you'll see the same result but for normally returns a lazy sequence.

A: @MartinPuda's answer is right.
The tail call recursive version is here:
(defn map* [f sq & {:keys [acc] :or {acc '()}}]
  (cond (empty? sq) (vec (reverse acc))
        (sequential? (first sq)) (map* f
                                       (rest sq)
                                       :acc (cons (map* f (first sq)) acc))
        :else (map* f (rest sq) :acc (cons (f (first sq)) acc))))

By tradition in lisp, such recursively into the nested structure going functions are fnname* (marked by an asterisk at the end).
acc accumulates the result nested tree which is constructed by cons.
In your case this would be:
(map* Math/sqrt (list (list 1 4 9) (list 16 25)))

Test with:
(map* (partial + 1) '[1 2 [3 4 [5] 6] 7 [8 [9]]])

;; => [2 3 [4 5 [6] 7] 8 [9 [10]]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: PNG image rotation component Can anyone help me in finding a component or SDK that rotates PNG images quickly whilst retaining transparency?

A: The original author of the PNGImage component (the basis of the Delphi native component) had a forum where he, and others, posted code snippets on how to do things using the PNGImage component.
Before the forum was taken down I grabbed a copy of all of the code snippets and placed them on the CodeGear Code Central website.
Most if not all of these work with native PNG images and do maintain the Alpha channel.
Here is the complete list of examples included in the package:
Smooth rotates a PNG object
Resizes a TPNGObject using a smooth algorithm
Slice one PNG into several smaller ones
Saves an image as either a bitmap or a png.
Sample chunk descendant
Read all tEXt-Chunks and write values into a TStrings object
Display a message box with information extracted from the PNG File
Finds and cuts a block from a PNG image
This method converts the png into a jpeg object
This method converts the png into a bmp object
Overlay one PNG over another
This makes the image half transparent
Flips a png image vertically and saves back
Draws a png image over the desktop

Here is the link: CodeCentral PNG Methods
EDIT
Here is a highly optimized version of a RotatePNG function.
It still, technically, goes pixel by pixel but it uses a number of techniques, such as scanlines, pointer math and storage of image dimensions to achieve a decent speed increase.
I used a 2550x3300 pixel image (~5MB) for testing and by using semi-rough, but totally (non)scientific calculations (counting in my head) I came up with the following metrics:
the old routine (mentioned above):~7 seconds
the new routine (code below):~1.5 seconds
I can't strictly take credit for this.  The code originally came from from EFG's website  and I decided to try my hand at converting one of those routines to rotate PNG images instead of bitmaps.
I'm sure anyone who knows more about this type of thing will take a look at the code and offer up some suggestions to tweak more speed out of it.
procedure RotatePNG(
        const PNGOriginal:TPNGImage;//input PNG
        out   PNGRotated:TPNGImage; //output PNG
    Const Angle : double);
{
  (c) har*GIS L.L.C., 1999
    You are free to use this in any way, but please retain this comment block.
    Please email questions to jim@har-gis.com .
    Doc & Updates: http://www.efg2.com/Lab/ImageProcessing/RotateScanline.htm
    and http://www.efg2.com/Lab/Library/Delphi/Graphics/JimHargis_RotateBitMap.zip
}
{
  Modified by R.J.Mills, 2012 -
    - Use pointer arithmetic instead of type sub-scripting for faster pixels.
    - Converted to rotate PNG images June 2012.
}

Type
  TRGBTripleArray = array [0..32767] of TRGBTriple; //allow integer subscript
  pRGBTripleArray = ^TRGBTripleArray;

VAR
  wPng : TPngImage;
  theta:Double;  // rotn angle in radians counterclockwise in windows
  cosTheta       :  Single;   {in windows}
  sinTheta       :  Single;
  i              :  INTEGER;
  iOriginal      :  INTEGER;
  iPrime         :  INTEGER;
  j              :  INTEGER;
  jOriginal      :  INTEGER;
  jPrime         :  INTEGER;
  NewWidth,NewHeight:INTEGER;
  nBytes: Integer;//no. bytes per pixelformat
  Oht,Owi,Rht,Rwi: Integer;//Original and Rotated subscripts to bottom/right
  RowSizeRot : integer;
  RowSizeOrg : integer;
  AlphaSizeRot : integer;
  AlphaSizeOrg : integer;
  RowStartPtr : Pointer;
  AlphaStartPtr : Pointer;

  RowRotatedT: pRGBtripleArray; //3 bytes
  AlphaRowT: pByteArray;    //1 byte
  AlphaRotatedT : pByteArray;   //1 byte

  TransparentT: TRGBTriple;

{=======================================}
 function Mod360( const angle:Double ):Double;
 begin
   result := frac( angle/360 )*360;
   if result < 0 then
     result := result+360;
 end;
{=======================================}

begin
  Theta := -(2*pi* Mod360(angle))/360;
  sinTheta := SIN( theta );
  cosTheta := COS( theta );

    NewWidth  := ABS( ROUND( PNGOriginal.Height*sinTheta) ) + ABS( ROUND( PNGOriginal.Width*cosTheta ) );
    NewHeight := ABS( ROUND( PNGOriginal.Width*sinTheta ) ) + ABS( ROUND( PNGOriginal.Height*cosTheta) );

  if ( ABS(theta)*MAX( PNGOriginal.width,PNGOriginal.height ) ) > 1 then
  begin//non-zero rotation

    wPng := TPngImage.createblank(PNGOriginal.Header.ColorType, 8, NewWidth, NewHeight);
    try

    //local constants for loop, each was hit at least width*height times   1/8/00
      Rwi := NewWidth - 1; //right column index
      Rht := NewHeight - 1;//bottom row index
      Owi := PNGOriginal.Width - 1;    //transp color column index
      Oht := PNGOriginal.Height - 1;   //transp color row  index

      RowRotatedT := wPng.Scanline[ Rht ] ;

      RowStartPtr := PNGOriginal.Scanline[ 0 ];
      RowSizeRot := Integer(wPng.ScanLine[1])-Integer(wPng.ScanLine[0]);
      RowSizeOrg := Integer(PNGOriginal.ScanLine[1])-Integer(PNGOriginal.ScanLine[0]);

      TransparentT := pRGBtripleArray( PNGOriginal.Scanline[ Oht ] )[0];

      if PNGOriginal.Header.ColorType in [COLOR_RGBALPHA] then
      begin
        AlphaRowT := PNGOriginal.AlphaScanline[ Oht ];
        AlphaStartPtr := PNGOriginal.AlphaScanline[ 0 ];
        AlphaRotatedT := wPng.AlphaScanline[ Rht ];
        AlphaSizeRot := Integer(wPng.AlphaScanline[1])-Integer(wPng.AlphaScanline[0]);
        AlphaSizeOrg := Integer(PNGOriginal.AlphaScanline[1])-Integer(PNGOriginal.AlphaScanline[0]);
      end
      else
      begin
        AlphaRowT := nil;
        AlphaStartPtr := nil;
        AlphaRotatedT := nil;
        AlphaSizeRot := 0;
        AlphaSizeOrg := 0;
      end;

      for j := Rht downto 0 DO   //1/8/00
      begin //for j
        jPrime := 2*j - NewHeight + 1 ;
        for i := Rwi downto 0 DO   //1/8/00
        begin //for i
          iPrime := 2*i - NewWidth   + 1;
          iOriginal := ( ROUND( iPrime*CosTheta - jPrime*sinTheta ) + Owi ) div 2;

          if ( iOriginal >= 0 ) and ( iOriginal <= Owi ) then
          begin //inside
            jOriginal := ( ROUND( iPrime*sinTheta + jPrime*cosTheta ) + Oht ) div 2 ;
            if ( jOriginal >= 0 ) and ( jOriginal <= Oht ) then
            begin    //1/8/00
              RowRotatedT[i] := pRGBTripleArray(Integer(RowStartPtr) + (jOriginal * RowSizeOrg))[iOriginal];
              if assigned(AlphaRotatedT) then
                AlphaRotatedT[i] := pByteArray(Integer(AlphaStartPtr) + (jOriginal * AlphaSizeOrg))[iOriginal];
            end
            else
            begin //set Transparent
              if Assigned(AlphaRotatedT) then
                AlphaRotatedT[i] := 0;
              RowRotatedT[i] := TransparentT;
            end;
          end //inside
          else
          begin //Set Transpaarent;
            if Assigned(AlphaRotatedT) then
              AlphaRotatedT[i] := 0;
            RowRotatedT[i] := TransparentT;
          end;
        end; //for i
        Dec(Integer(RowRotatedT), RowSizeRot) ;
        if assigned(AlphaRotatedT) then
          Dec(Integer(AlphaRotatedT), AlphaSizeRot) ;
      end;//for j
      PNGRotated.Assign(wPng);
    finally
      wPng.Free;
    end;
  end //non-zero rotation
  else
  begin //Zero rotation
    if PNGRotated <> PNGOriginal then
      PNGRotated.Assign(PNGOriginal);
  end;
end; {RotatePNG}


text:
Q: autotools and python setup.py I have a project written mostly in c++ that includes a few helper scripts written in python. For the moment, the scripts contain variables substituted by the autotools:
#!@PYTHON@
# -*- coding: utf-8 -*-
...

try:
    datapath = os.environ['DATA_PATH']
except KeyError:
    datapath = '@pkgdatadir@'

And here is an extract of Makefile.am:
BUILT_SOURCES = script.py
nodist_python_PYTHON = script.py
CLEANFILES = $(python_PYTHON)
EXTRA_DIST = script.py.in

do_subst = sed -e 's,[@]PYTHON[@],$(PYTHON),g'\
           -e 's,[@]pkgdatadir[@],$(pkgdatadir),g'

script.py: script.py.in
    $(do_subst) < $< > $@
chmod +x $@

These scripts have also a few module dependencies which would probably be better handled by a setup.py script.
So what is the best way to mix the autotools and the python distutils tools? Should I rely entirely on the autotools? Otherwise how can I integrate the launching of setup.py in the Makefile.am?

A: I'd use autoconf to setup script.py instead of 'make' as you've shown. Something like:
AC_CONFIG_FILES([script.py], [chmod +x script.py])

before AC_OUTPUT in configure.ac should do it.


text:
Q: parsing a list and creating columns in excel I have a large list in which I need to identify on Titles and URLs each section in the list may have more information that I'm not concerned with.  The list looks like Column B in the picture.  I'm looking to make it into two columns like E & F.
Any ideas?

A: The simple/messy way to do this would be:
Paste this formula in column C
 =IF(ISNUMBER(SEARCH("item",A1)),A1,IF(ISNUMBER(SEARCH(".com",A1)),A1,""))

Then copy paste the result as values into a new sheet, remove duplicates (aka spaces). Then apply filters/copy paste to get the desired format.


text:
Q: Merging presentations into single presentation I'm using GemBox.Presentation and I need to merge multiple PPTX files, combine them into a single PPTX file.
I tried this:
PresentationDocument presentation1 = PresentationDocument.Load("PowerPoint1.pptx");
PresentationDocument presentation2 = PresentationDocument.Load("PowerPoint2.pptx");

foreach (Slide slide2 in presentation2.Slides)
    presentation1.Slides.Add(slide2);

But I get the following error:

Item is already contained in some collection. Remove it from that collection first.
  Parameter name: item

How can I merge several presentations into one presentation?

A: Use one of the AddCopy methods instead of Add.
In other words, try this:
var presentation1 = PresentationDocument.Load("PowerPoint1.pptx");
var presentation2 = PresentationDocument.Load("PowerPoint2.pptx");

// Merge "PowerPoint2.pptx" file into "PowerPoint1.pptx" file.
var context = CloneContext.Create(presentation2, presentation1);
foreach (var slide in presentation2.Slides)
    presentation1.Slides.AddClone(slide, context);

// Save resulting "Merged PowerPoints.pptx" file.
presentation1.Save("Merged PowerPoints.pptx");

Also, you can refer to Cloning example.


text:
Q: My PDO Prepared Statement is not working with a fetchALL and Limit I am trying to get some products from my database with a prepared PDO statements. The formula worked well if I included the variable inside the SQL but of course this is really bad practice.
Working formula:

protected function getSomeProducts($somequantity){
        $sql = "SELECT * FROM products ORDER by ID DESC LIMIT $somequantity";

        $stmt = $this->connect()->query($sql);
        $result = $stmt->fetchAll();
        return $result;

My approach to the prepared statement:
protected function getSomeProducts($somequantity){
        $sql = "SELECT * FROM products ORDER by ID DESC LIMIT ?";

        $stmt = $this->connect()->prepare($sql);
        $stmt->execute([$somequantity]);
        $result = $stmt->fetchAll();

        return $result;

    }

This is the error message I get:
Fatal error
: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''6'' at line 1.
Any idea what Im doing wrong could be?

A: replace the below line
$stmt->execute([$somequantity]);

with
$stmt->bindParam(1, $somequantity, PDO::PARAM_INT);
$stmt->execute();


text:
Q: SAX Parser support in Apache Pig I am working on a UDF to process XML files on the Hadoop cluster. I am using PIG to load the XML files and then I use my UDF to flatten the structure of the XML data.
My current implementation is with DOM parser and I didn't have to include the DOM parser jars along with my udf jar. I am planning to shift this implementation from DOM parser to SAX parser.
Does the hadoop/pig framework provide those jars for SAX parsers out of the box or I need to have them included along with my udf jar?

A: My bad. I started working on the SAX Parser. And they just come right along with it.


text:
Q: Implementing Map Rotation in ArcGIS for Android? I am trying to rotate the map as the orientation of the device is changed. What I want is the map should always point towards the north regardless of the orientation of the device.
Like Suppose, If I gradually rotate my device to x degrees, The map should accordingly rotate to -x degrees keeping the map facing in the same direction as it was earlier.


text:
Q: Jquery Array multiple items I want to get a list of items in a page and push them into an array:
$('#softwareUpdates article').each(function(index) {
   productList.push({
      class: $(this).attr("class"),
      text: $(this).attr("su_title")
   });
});

HOWEVER I want to avoid multiple items, so when I current check the productList array I have:
  Item 1, Item1, Item 2, Item 3, Item 3, Item 4

What I would like to have is:
  Item 1, Item 2, Item 3, Item 4

A: I pulled the following code from http://hackingon.net/post/Handy-Javascript-array-Extensions-e28093-distinct().aspx.
Array.prototype.distinct = function() {
  var derivedArray = [];
  for (var i = 0; i < this.length; i += 1) {
    if (!derivedArray.contains(this[i])) {
      derivedArray.push(this[i])
    }
  }
  return derivedArray;
};

There are also javascript libraries equivalent to .NET's Linq.  Any of those should work.  Here's one: http://jsinq.codeplex.com/


text:
Q: TWebBrowser - возможна ли смена движка с IE, на какой-нибудь другой? Возникла мысль написать Desktop-приложения со своих всяких разных web-скриптов, аля "курс валют на рабочий стол" или "погода за окном". Но в своих web-приложениях я использовал много CSS3, который явно не поддерживается IE. (У меня установлен IE ver.8).
Так вот, хотелось бы не заставлять пользователя из-за маленькой программки с двумя циферками обновлять целый Web-браузер от корпорации Microsoft, а на стороне разработчика подменить движок в компонент TWebBrowser, чтобы он рендерил HTML, как нормальные браузеры. Т.е. чтобы ПО не зависело от IE.
Возможно ли такое?  Или же потребуется поиск и установка альтернативы для TWebBrowser?

A: Как уже писали ранее, TWebBrowser можно запустить в режиме совместимости одной из версий IE. Тут можно посмотреть какие ключи в реестре нужно прописать, чтобы включить соответствующий режим.

A: На другой движок боюсь что нет, разве что только на другую версию.
А так можно скачать дополнение библиотек с новым элементом браузера на другом движке.


text:
Q: Why does javascript bind() not bind property by itself? I am trying to understand javascript bind method. I have read this other SO post about bind method and learned a great deal. One of the posts linked to javascripture where I played around with bind.
To my understanding, and according to mozilla's site, bind "creates a new function that 'binds' this to the bound object."
var Button = function(content) {
  this.content = content; //stores content into this.content property
};

Button.prototype.click = function() { //adds click method
  console.log(this.content + ' clicked');
}

var myButton = new Button('OK');
console.log(myButton.content);        //OK
myButton.click();                     //OK clicked

var looseClick = myButton.click;
console.log(looseClick.content);      //undefined
looseClick();                         //undefined clicked

var notLooseClick = myButton.click.bind(myButton);
console.log(notLooseClick.content);   //undefined
notLooseClick();                      //OK clicked

My confusion is the last var, notLooseClick. I don't understand why notLooseClick.content returns undefined while notLooseClick(); returns 'OK clicked'. I had expected 'OK' to be bound to notLooseClick.content.
How can I bind notLooseClick so when I call notLooseClick.content, it is bound to Button's this.content, so when I type notLooseClick.content it returns 'OK'? Why does bind() behave this way?

A: You are misunderstanding what Function.bind does. It makes sure that when a function is called, this will be whatever you pass in. It does not copy any properties of the object to the function that you've bound.
var Button = function(content) {
  this.content = content; //stores content into this.content property
};

Button.prototype.click = function() { //adds click method
  console.log(this.content + ' clicked');
}

var okButton = new Button('OK');

// This calls click using okButton as its `this`
okButton.click();

var looseClick = okButton.click;
// This calls the same click function without specifying a `this`
// It will be window or null if on strict mode
looseClick();

// Here you are saying:
// No matter how this function is called, it will always use okButton as its `this`
var boundClick = okButton.click.bind(okButton);
boundClick();

You seem to be under the impression that the bind function would make your function inherit properties from the object that you bind it to. But that is not what it does, it binds the this within the call.
var notLooseClick = myButton.click.bind(myButton);
// It's undefined, you didn't copy properties of myButton to notLooseCLick
console.log(notLooseClick.content);   //undefined
// Here it works because you've set `this` in calls to notLooseClick to be myButton
notLooseClick();


text:
Q: Mouse gets stuck when switching screens Hi I have the latest amd drivers, and 3 monitors setup. When moving the mouse from one screen to another it seems like it gets stuck, and I have to keep moving it for it to finally switch, its really odd, does anybody know a quick fix?
Example:
(the black is the other screen and the pattern is the other screen)
If I move the mouse fast enough it dosen't seems to happen.

A: See identical question: How do I disable mouse magnet on middle edge with multi monitors?
System Settings - Displays. Uncheck the box that says "Sticky edges".


text:
Q: How to remap 'Shift & Up/Down arrow keys' to type actual up & down arrows? I do a lot of typing in Evernote and I really need an 'up arrow' and 'down arrow' instead of typing 'increasing' or 'decreasing'... Ideally pressing Shift and 'Up arrow' would be the best way to get an upward arrow. I've downloaded and tried using KeyRemap4Macbook but I can't work out how to get the up or down arrows.

A: KeyRemap4MacBook currently can't insert arbitrary text. For something like this, I'd recommend using DefaultKeyBinding.dict.
Create ~/Library/KeyBindings/DefaultKeyBinding.dict and enter
{ "$\Uf700" = (insertText:, "↑"); "$\Uf701" = (insertText:, "↓"); }

$ = shift, \Uf700 = up, \Uf701 = down, insertText: will insert a string at the current cursor location
Quit and reopen applications for the change to take effect


text:
Q: Determine OS type in docker I want to download an sdk depending on the OS type my docker image is running on. How can I write the below pseudo code in docker script
RUN variable x = getOS()
if [ "$x" = "Darwin" ]; then
     RUN wget -q http://xxx/android-ndk-xxxx-darwin-x86_64.bin
else
     RUN wget -q http://xxx/android-ndk-xxxx-linux-x86_64.bin

A: Use the uname command.
x=$(uname)

On a darwin system, it should output Darwin.
In your dockerfile, the RUN command then could look like this:
RUN [ "$(uname)" = Darwin ] && system=darwin || system=linux; \
    wget -q http://xxx/android-ndk-xxxx-${system}-x86_64.bin

Or like this (in order to support arbitrary systems):
RUN system=$(uname); \
    wget -q http://xxx/android-ndk-xxxx-${system,}-x86_64.bin


text:
Q: Why does Common.Logging in NuGet use .NET Portable? I am using:

*

*MonoDevelop 7.1

*.NET Framework 4.6.2

*Mono 5.0.1.1 (2017-02/5077205 Thu May 25 09:16:53 UTC 2017) (64-bit)

*No PCL or profiles (to my knowledge)

*msbuild 15.2.0.0 (Thu May 11 17:28:41 UTC 2017)

<NoStdLib> is not specified; that is, it's left at its default.
<TargetFrameworkVersion> is set to v4.6.2.
When I build in the IDE, I see no warnings or errors. However, when I build the solution with
msbuild /v:detailed my.sln

I see a few of these messages:
  Dependency "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea77
98e, Retargetable=Yes".
      Could not resolve this reference. Could not locate the assembly "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

Browsing through the Mono files, all of the following assemblies match the above version and key:
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile102/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile19/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile225/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile5/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile92/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile47/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile14/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile24/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile328/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile6/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile158/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile255/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile37/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile240/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile136/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile147/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile42/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile344/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/Profile/Profile336/mscorlib.dll
/usr/lib/mono/xbuild-frameworks/.NETPortable/v4.0/mscorlib.dll

Other mscorlib assemblies either have the wrong version, or have the key token b77a5c561934e089 instead of 7cec85d7bea7798e.
My questions are:

*

*Why is my solution attempting to make a reference to a portable .NET?

*Is there an assembly reference tree tool I can use to find out what the referring culprit is?

*Why is it that this is a non-fatal error, and doesn't even appear in the IDE build output at all?

*Should I make a manual reference to one of these assemblies? If so, which profile?

*If I do not make a reference to one of these assemblies, what are the consequences?

*Does the fact that all of my assemblies are strong-name-signed affect the importance of resolving this error?

Thanks in advance.
Edit:
Using monodis --assemblyref, I see that the problem is Common.Logging:
Common.Logging.dll
AssemblyRef Table
...
4: Version=2.0.5.0
        Name=mscorlib
        Flags=0x00000100
        Public Key:
0x00000000: 7C EC 85 D7 BE A7 79 8E

./Common.Logging.Core.dll
AssemblyRef Table
...
1: Version=2.0.5.0
        Name=mscorlib
        Flags=0x00000100
        Public Key:
0x00000000: 7C EC 85 D7 BE A7 79 8E

./Common.Logging.NLog41.dll
AssemblyRef Table
...
6: Version=2.0.5.0
        Name=mscorlib
        Flags=0x00000100
        Public Key:
0x00000000: 7C EC 85 D7 BE A7 79 8E

This, despite my packages.config specifically asking for .NET 4.62:
  <package id="Common.Logging" version="3.3.1" targetFramework="net462" />
  <package id="Common.Logging.Core" version="3.3.1" targetFramework="net462" />
  <package id="Common.Logging.NLog41" version="3.3.1" targetFramework="net462" />

So I guess this is a bug in Common.Logging?


text:
Q: Casimir effect and negative mass The Casimir effect causes a limited number of wave functions, causing fewer particles between plates than outside and this could be considered as a negative mass. Then, if we have a technology good enough so that the total energy of the system is negative, will the system have acceleration towards the opposite direction of a force applied to this system?

A: It's a good question, and the simple answer is that we don't know.
I would repeat Anna's comment that virtual particles are a calculational device and do not really exist, so you need to be careful when talking about there being fewer virtual particles between the plates. However it is definitely true that the vacuum energy density is lower between the plates than it is outside them. That is, after all, what causes the Casimir force.
The problem is that we don't know how vacuum energy gravitates, or indeed if it does. If we do a naive calculation of how much gravitational force we expect from the vacuum energy we get a ridiculous number, so clearly the naive calculation doesn't work. We have to conclude we don't understand how the vacuum energy behaves, and therefore we don't understand how the reduced vacuum energy between the plates behaves.
It is possible the region between the plates does behave as a negative mass, though the end result would simply be that the total mass of the two plates plus the space between them was slightly less than the mass of the two plates alone. And we see this sort of thing routinely as the mass of any bound system is slightly less than the mass of its parts. This is what causes the mass deficit in nuclei.


text:
Q: How do I split and merge this dataflow pipeline? I am trying to create a dataflow using tpl with the following form:
                    -> LoadDataBlock1 -> ProcessDataBlock1 ->
GetInputPathsBlock  -> LoadDataBlock2 -> ProcessDataBlock2 -> MergeDataBlock -> SaveDataBlock
                    -> LoadDataBlock3 -> ProcessDataBlock3 ->
                    ...
                    -> LoadDataBlockN -> ProcessDataBlockN ->

The idea is, that GetInputPathsBlock is a block, which finds the paths to the input data that is to be loaded, and then sends the path to each LoadDataBlock. The LoadDataBlocks are all identical (except that they have each recieved a unique inputPath string from GetInputPaths). The loaded data is then sent to the ProcessDataBlock, which does some simple processing. Then the data from each ProcessDataBlockis sent to MergeDataBlock, which merges it and sends it to SaveDataBlock, which then saves it to a file.
Think of it as a dataflow that needs to run for each month. First the path is found for the data for each day. Each day's data is loaded and processed, and then merged together for the entire month and saved. Each month can be run parallelly, data for each day in a month can be loaded parallelly and processed parallelly (after the individual day data has been loaded), and once everything for the month has been loaded and processed, it can be merged and saved.
What I tried
As far as I can tell TransformManyBlock<TInput,string> can be used to do the splitting (GetInputPathsBlock), and can be linked to a normal TransformBlock<string,InputData> (LoadDataBlock), and from there to another TransformBlock<InputData,ProcessedData> (ProcessDataBlock), but I don't know how to then merge it back to a single block.
What I looked at
I found this answer, which uses TransformManyBlock to go from an IEnumerable<item> to item, but I don't fully understand it, and I can't link a TransformBlock<InputData,ProcessedData> (ProcessDataBlock) to a
TransformBlock<IEnumerable<ProcessedData>>,ProcessedData>, so I don't know how to use it.
I have also seen answers like this, which suggests using JoinBlock, but the number of input files N varies, and the files are all loaded in the same way anyway.
There is also this answer, which seems to do what I want, but I don't fully understand it, and I don't know how the setup with the dictionary would be transferred to my case.
How do I split and merge my dataflow?

*

*Is there a block type I am missing

*Can I somehow use TransformManyBlock twice?

*Does tpl make sense for the split/merge or is there a simpler async/await way?

A: I would use a nested block to avoid splitting my monthly data and then having to merge them again. Here is an example of two nested TransformBlocks that process all days of the year 2020:
var monthlyBlock = new TransformBlock<int, List<string>>(async (month) =>
{
    var dailyBlock = new TransformBlock<int, string>(async (day) =>
    {
        await Task.Delay(100); // Simulate async work
        return day.ToString();
    }, new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 4 });

    foreach (var day in Enumerable.Range(1, DateTime.DaysInMonth(2020, month)))
        await dailyBlock.SendAsync(day);
    dailyBlock.Complete();

    var dailyResults = await dailyBlock.ToListAsync();
    return dailyResults;
}, new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 1 });

foreach (var month in Enumerable.Range(1, 12))
    await monthlyBlock.SendAsync(month);
monthlyBlock.Complete();

For collecting the daily results of the inner block I used the extension method ToListAsync that is shown below:
public static async Task<List<T>> ToListAsync<T>(this IReceivableSourceBlock<T> block,
    CancellationToken cancellationToken = default)
{
    var list = new List<T>();
    while (await block.OutputAvailableAsync(cancellationToken).ConfigureAwait(false))
    {
        while (block.TryReceive(out var item))
        {
            list.Add(item);
        }
    }
    await block.Completion.ConfigureAwait(false); // Propagate possible exception
    return list;
}

A: The answers to your questions are: no, you don't need another block type, yes, you can use TransformManyBlock twice, and yes, it does make sense.  I wrote some code to prove it, which is at the bottom, and some notes on how it works, which are after that.
The code uses a split then merge pipeline as you describe.  As for the bit you were struggling with:  merging the data for individual files back together can be done by adding processed items to a list as they become available.  Then we only pass the list on to the next block if it has the expected final number of items.   This can be done with a fairly simple TransformMany block returning zero or one items.  This block can't be parallelized because the list isn't threadsafe.
Once you've got a pipeline like this you can test the parallelization and ordering by just using the options passed to the blocks.  The code below sets parallelization to unbounded for every block it can, and lets the DataFlow code sort it out.  On my machine it maxes out all the cores/logical processors and is CPU-bound, which is what we want.  Ordering is enabled, but turning that off doesn't make much difference: again, we are CPU-bound.
Finally I have to say this is a very cool tech, but you can actually solve this problem much more simply using PLINQ, where it's just a few lines of code to get something just as fast.  The big drawback is that you can't easily incrementally add fast-arriving messages to a pipeline if you do that: PLINQ is better-suited to one big batch process.  However PLINQ may be a better solution for your usecase.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks.Dataflow;

namespace ParallelDataFlow
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program().Run();
            Console.ReadLine();
        }

        private void Run()
        {
            Stopwatch s = new Stopwatch();
            s.Start();

            // Can  experiment with parallelization of blocks by changing MaxDegreeOfParallelism
            var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded };
            var getInputPathsBlock = new TransformManyBlock<(int, int), WorkItem>(date => GetWorkItemWithInputPath(date), options);
            var loadDataBlock = new TransformBlock<WorkItem, WorkItem>(workItem => LoadDataIntoWorkItem(workItem), options);
            var processDataBlock = new TransformBlock<WorkItem, WorkItem>(workItem => ProcessDataForWorkItem(workItem), options);
            var waitForProcessedDataBlock = new TransformManyBlock<WorkItem, List<WorkItem>>(workItem => WaitForWorkItems(workItem));  // Can't parallelize this block
            var mergeDataBlock = new TransformBlock<List<WorkItem>, List<WorkItem>>(list => MergeWorkItemData(list), options);
            var saveDataBlock = new ActionBlock<List<WorkItem>>(list => SaveWorkItemData(list), options);

            var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
            getInputPathsBlock.LinkTo(loadDataBlock, linkOptions);
            loadDataBlock.LinkTo(processDataBlock, linkOptions);
            processDataBlock.LinkTo(waitForProcessedDataBlock, linkOptions);
            waitForProcessedDataBlock.LinkTo(mergeDataBlock, linkOptions);
            mergeDataBlock.LinkTo(saveDataBlock, linkOptions);

            // We post individual tuples of (year, month) to our pipeline, as many as we want
            getInputPathsBlock.Post((1903, 2));  // Post one month and date
            var dates = from y in Enumerable.Range(2015, 5) from m in Enumerable.Range(1, 12) select (y, m);
            foreach (var date in dates) getInputPathsBlock.Post(date);  // Post a big sequence

            getInputPathsBlock.Complete();
            saveDataBlock.Completion.Wait();
            s.Stop();
            Console.WriteLine($"Completed in {s.ElapsedMilliseconds}ms on {ThreadAndTime()}");
        }

        private IEnumerable<WorkItem> GetWorkItemWithInputPath((int year, int month) date)
        {
            List<WorkItem> processedWorkItems = new List<WorkItem>();  // Will store merged results
            return GetInputPaths(date.year, date.month).Select(
                path => new WorkItem
                {
                    Year = date.year,
                    Month = date.month,
                    FilePath = path,
                    ProcessedWorkItems = processedWorkItems
                });
        }

        // Get filepaths of form e.g. Files/20191101.txt  These aren't real files, they just show how it could work.
        private IEnumerable<string> GetInputPaths(int year, int month) =>
            Enumerable.Range(0, GetNumberOfFiles(year, month)).Select(i => $@"Files/{year}{Pad(month)}{Pad(i + 1)}.txt");

        private int GetNumberOfFiles(int year, int month) => DateTime.DaysInMonth(year, month);

        private WorkItem LoadDataIntoWorkItem(WorkItem workItem) {
            workItem.RawData = LoadData(workItem.FilePath);
            return workItem;
        }

        // Simulate loading by just concatenating to path: in real code this could open a real file and return the contents
        private string LoadData(string path) => "This is content from file " + path;

        private WorkItem ProcessDataForWorkItem(WorkItem workItem)
        {
            workItem.ProcessedData = ProcessData(workItem.RawData);
            return workItem;
        }

        private string ProcessData(string contents)
        {
            Thread.SpinWait(11000000); // Use 11,000,000 for ~50ms on Windows .NET Framework.  1,100,000 on Windows .NET Core.
            return $"Results of processing file with contents '{contents}' on {ThreadAndTime()}";
        }

        // Adds a processed WorkItem to its ProcessedWorkItems list.  Then checks if the list has as many processed WorkItems as we
        // expect to see overall.  If so the list is returned to the next block, if not we return an empty array, which passes nothing on.
        // This isn't threadsafe for the list, so has to be called with MaxDegreeOfParallelization = 1
        private IEnumerable<List<WorkItem>> WaitForWorkItems(WorkItem workItem)
        {
            List<WorkItem> itemList = workItem.ProcessedWorkItems;
            itemList.Add(workItem);
            return itemList.Count == GetNumberOfFiles(workItem.Year, workItem.Month) ? new[] { itemList } : new List<WorkItem>[0];
        }

        private List<WorkItem> MergeWorkItemData(List<WorkItem> processedWorkItems)
        {
            string finalContents = "";
            foreach (WorkItem workItem in processedWorkItems)
            {
                finalContents = MergeData(finalContents, workItem.ProcessedData);
            }
            // Should really create a new data structure and return that, but let's cheat a bit
            processedWorkItems[0].MergedData = finalContents;
            return processedWorkItems;
        }

        // Just concatenate the output strings, separated by newlines, to merge our data
        private string MergeData(string output1, string output2) => output1 != "" ? output1 + "\n" + output2 : output2;

        private void SaveWorkItemData(List<WorkItem> workItems)
        {
            WorkItem result = workItems[0];
            SaveData(result.MergedData, result.Year, result.Month);
            // Code to show it's worked...
            Console.WriteLine($"Saved data block for {DateToString((result.Year, result.Month))} on {ThreadAndTime()}." +
                              $"  File contents:\n{result.MergedData}\n");
        }
        private void SaveData(string finalContents, int year, int month)
        {
            // Actually save, although don't really need to in this test code
            new DirectoryInfo("Results").Create();
            File.WriteAllText(Path.Combine("Results", $"results{year}{Pad(month)}.txt"), finalContents);
        }

        // Helper methods
        private string DateToString((int year, int month) date) => date.year + Pad(date.month);
        private string Pad(int number) => number < 10 ? "0" + number : number.ToString();
        private string ThreadAndTime() => $"thread {Pad(Thread.CurrentThread.ManagedThreadId)} at {DateTime.Now.ToString("hh:mm:ss.fff")}";
    }

    public class WorkItem
    {
        public int Year { get; set; }
        public int Month { get; set; }
        public string FilePath { get; set; }
        public string RawData { get; set; }
        public string ProcessedData { get; set; }
        public List<WorkItem> ProcessedWorkItems { get; set; }
        public string MergedData { get; set; }
    }
}

This code passes a WorkItem object from each block to the next and enriches it at each stage.  It then creates a final list with all the WorkItems for a month in it, before running an aggregation process on that and saving the results.
This code is based on dummy methods for each stage using the names you use.  These don't do much but hopefully demonstrate the solution.  For example LoadData is handed a file path and just adds some text to it and passes the string on, but obviously it could load a real file and pass the contents string on if there actually was a file on disk.
Similarly to simulate doing work in ProcessData we do a Thread.SpinWait and then again just add some text to the string.  This is where the delay comes from, so change the number if you want it to run faster or slower.  The code was written on the .NET Framework, but it runs on Core 3.0, and on Ubuntu and OSX.  The only difference is that a SpinWait cycle can be significantly longer or shorter, so you may want to play with the delay.
Note that we could have merged in the waitForProcessedDataBlock and had exactly the pipeline you were asking for.  It just would have been a bit more confusing
The code does create files on disk at the end, but also dumps the results to the screen, so it doesn't really need to.
If you set parallelization to 1 you'll find it slows down by about the amount you'd expect.  My Windows machine is four-core and it's slightly worse than four times slower.


text:
Q: what do i need to do to develope an iphone\android app in vs2010? we are a .net team that devleoped a full app in c# with web services and services that support it. we now want to develope a Mobile app (Android\Iphone) that will look similiar to the original to allow mobile use of it.
we thought about MonoTouch instead of trying to learn Objective-c and to try to develope a cross platform mobile app.
is anyone tried developing a mobile app in vs 2010 in MonoTouch? is there a simple add in for it? is it possible?

A: Important caveat: both of these tools are in pain - since the vendor fired the dev team (read the "Fighting for Your Right to Party" paragraph). Hopefully soon to be replaced by Xamarin.
MonoDroid does exactly that for android development. For iPhone, you need to be on a mac, and it runs inside MonoDevelop - but ultimately the code is pretty similar.
I would expect any Xamarin tools be have similar architecture.

A: There is a GitHub project to allow you to use Visual Studio to code everything except the UI.
https://github.com/follesoe/VSMonoTouch
Also, he has a very good tutorial on doing cross platform mobile dev
https://github.com/follesoe/FlightsNorway/tree/workshop

A: According to the MonoTouch roadmap, they plan to make it possible to use MonoTouch in VisualStudio. You still need a mac, though. You can't get around that.
I guess Android would be easier. There is no platform dependency there


text:
Q: Apache: Include Virtual SSI not working for CGI script I have the following Server Side Includes within an .html file called test.html...
<!--#include virtual="/cgi-bin/myScript.cgi"-->

<!--#include virtual="/includes/myFile.html"-->

When I view test.html live in my browser, myFile.html is being inserted/rendered just fine, however myScript.cgi is giving me

[an error occurred while processing this directive]

*

*From the browser address bar, /cgi-bin/myScript.cgi is rendering output just fine, proving the file exists at the path and the permissions are correct (755).

*The SSI handlers are set correctly as myFile.html is included just fine, proving the page is being parsed.
So if SSI is working and myScript.cgi is working, why isn't #include virtual working on this script?
As a side-note, this is on a cPanel hosting account and I have many other accounts (sites) at the server at the same hosting company with the same configuration.  The others are all working as expected.

*

*cPanel Version: 11.30.6 (build 3)

*Apache version: 2.2.17

*Architecture: x86_64

*Operating system: linux

*Perl version: 5.8.8

*Kernel version: 2.6.18-194.32.1.el5

*cPanel Pro: 1.0 (RC1)

The script simply returns the year from today's date as formatted text.  The output is preceded by Content-type: text/html\n\n and it's not a new Perl script.  It's working on the other accounts.

A: My hosting company escalated the issue to cPanel, and to my embarrassment, it ended up being a setting in my .htaccess file that was missing after all.
The account that was working had this line, where the broken account, did not...
Options All -Indexes

All, by default, includes what the hosting company added in order to get it working...
Options +Includes +ExecCGI

Without +ExecCGI, it breaks as I described in my original posting.

A: Good troubleshooting in discovering that your SSIs work.
You have localized the problem to the CGI subsystem.
First of all, you need to make sure that you have set this in your .htaccess file:
Options ExecCGI

If your problem persists, you will need to look at your error log to find out the reason:

This error message is the same as a 500 error (which is generally what you get with errors in .htaccess itself) so the logs are where you will find the descriptive error message.

cPanel allows you to see your error logs.
They are your best friend.
In the error log section, cPanel will show you your client IP address that you are looking for - at the top.  This is the IP address assigned by your ISP.
Modern versions of cPanel (like the one I use at Bluehost, Nov 2017), highlight the entries from your client, so the hack attempts don't distract you.  If you don't have highlighting then use the Ctrl-F (Find) function of your browser to locate entries coming from you.

See the end of this answer for an example of all the hacking attempts they deal with.  It is worth every penny to let them handle it rather than to try to run your own server out in the wild.

ANSWER:  I believe your use of <!--#Include for CGI is the problem.
Most modern Apache servers need you to use:
<!--#exec cgi="/cgi-bin/myScript.cgi" -->

instead of simply including the script.
==> Be sure your HTML file has a .shtm or .shtml extension.

Note that all /cgi-bin/ files need to have 755 permissions. - that means RWX for Owner and RX for Group & Public
chmod 755 /cgi-bin/*

===> Never give 777 permissions to them or to the .htaccess file, or else someone from outside can easily alter them.

This shows is why it is good to use a hosting service instead of running your own server.
Sample log output of hacking attempts, mostly blocked by RBL:


text:
Q: Minio or S3 simple web browser? I am using minio to store files in front of my app
My users told me that the browser is very limited : they cannot preview/edit the files directly (given that they upload small text files and images, this seems ok for the requirement)
My instinct tells me that this is by design, the minio goal is not to provide this tool.
So I start looking for alternatives, however everything I've looked at is either dead or client-side (destop) or too complex.
Does someone knows a web app that is more or less like the minio web browser with a preview on the right (and the capacity to edit the file when it is a .txt|.md|.json|.yaml|...)

A: Up to now (I searched for) there is no free good web browser even as good as minio browser itself.
But for accessing files and be able to modify them you (or your clients) can mount a bucket or a whole partition on their OS and then work with it like a regular file.

*

*pretty easy to upload files (just drag and drop)

*pretty easy to make bucket (just create directory)

*etc

In fact it will be a real-time active mirror.
And you can do it by using :

*

*rclone

*FUSE

*

*Windows win-fsp

*Linux you will have it by default

And Linux it is simple, on Windows you can run:
rclone mount s3w:/windows/ E: --vfs-cache-mode full --dir-cache-time 0m5s

which means mount windows bucket on s3w (=alias) for S3c locally in a partition with E: with full access and every 5 seconds make sure it is refreshed.
screenshot
On a Windows server I have mounted /windows bucket.


text:
Q: Unit Test a FileStreamResult I'm working on a ASP.NET Core 2.1 Api controller that returns a FileStreamResult. My business layer returns a MemoryStream object that has been rewound to the start position. What I am trying to do is write a unit test that checks if the expected MemoryStream is return from the method. However, when I attempt this, the test method just hangs. I'm using Automapper, NSubstitute and Xunit for mapping, mocking, and testing respectively.

        //Action Method
        [Route("Excel")]
        [HttpPost]
        [ProducesResponseType(typeof(string), 200)]
        public ActionResult CreateExcelExport([FromBody]ExportRequestApiModel exportRequest)
        {
            try
            {
                var records = _mapper.Map<IEnumerable<ExportRecord>>(exportRequest.Records);
                var result = _excelFileManager.GenerateFile(records, "sheet 1", 1);

                return new FileStreamResult(result,
                    new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                {
                    FileDownloadName = "export.xlsx"
                };
            }
            catch (Exception ex)
            {

                if (!(ex is BusinessException))
                    _logger?.LogError(LoggingEvents.GeneralException, ex, ex.Message);

                return StatusCode(StatusCodes.Status500InternalServerError);

            }
        }

        //Action Method test.
        [Fact]
        public void CanCreateExportFile()
        {
            //Arrange
            var exportRequestApiModel = new ExportRequestApiModel()
            {
                Records = new List<ExportRecordApiModel>() { }
            };
            var exportRecords = new List<ExportRecord>
            {
                new ExportRecord()
            };
            _mapper.Map<IEnumerable<ExportRecord>>(exportRequestApiModel.Records)
                .Returns(exportRecords);

            _excelFileManager.GenerateFile(exportRecords, "sheet 1", 1)
                .Returns(new MemoryStream(){Position = 0});
            //Act
            var result = (ObjectResult) _controller.CreateExcelExport(exportRequestApiModel);
            //Assert
            Assert.Equal(StatusCodes.Status200OK, result.StatusCode);
            Assert.IsType<FileStream>(result.Value);
        }


text:
Q: Scraping using rvest through multiple pages I'm trying to figure out how to adapt the code below to scrape through the 100+ pages of search results. I've looked through other SO questions and it looks like 'purrr' might be the best library to use but I've struggled to make any of the suggestions work. The url of change.org seems to vary through "&offset=10", "&offset=20".
Any suggestions or other SO questions that I've missed would be much appreciated.
library(rvest)

#Specifying the url for website to be scraped
url <- 'https://www.change.org/search?q=PPE'

#Reading the HTML code from the website
webpage <- read_html(url)

#Using CSS selectors to scrape HEADING & convert to text
title_data <- html_nodes(webpage,'.xs-mbs') %>%
  html_text(trim = TRUE)

#Using CSS selectors to scrape DATE & convert to text / nb. trim =true
date_data <- html_nodes(webpage,'.symbol-clock+ span') %>%
  html_text(trim = TRUE)
#Remove "Created" (not sure how to remove leading whitespace!!)
date_data <- gsub("Created","",date_data)

#Using CSS selectors to scrape SUPPORTER NUMBERS & convert to text
supporters_data <- html_nodes(webpage,'.symbol-supporters+ span') %>%
  html_text(trim = TRUE)
#remove SPACE & 'supporters'
supporters_data<-gsub(" supporters","",supporters_data)

#Using CSS selectors to scrape PETITION TO/ADDRESSEE & convert to text
addressee_data <- html_nodes(webpage,'.xs-mbn .type-s') %>%
  html_text(trim = TRUE)
#remove "Petition to"
addressee_data<-gsub("Petition to ","",addressee_data)

#Using CSS selectors to scrape LOCATION & convert to text
location_data <- html_nodes(webpage,'.plxxs') %>%
  html_text(trim = TRUE)

#Combining all the lists to form a data frame
change_df<-data.frame(Title = title_data, Addressee = addressee_data, Date = date_data,
                      Supporters = supporters_data)

A: You can use a functional approach here - that is, building up a helper function that will allow you to scrape all the pages by just applying the same function to a vector of urls. Here's a little function that replicates your code:
scrape_change_page <- function(url)
{
  webpage  <- xml2::read_html(url)

  get_text <- function(css)
  {
    vec <- rvest::html_text(rvest::html_nodes(webpage, css), trim = TRUE)
    if(length(vec) < 10) c(vec, rep("", 10 - length(vec))) else vec
  }

  dplyr::tibble(
         title_data      = get_text('.xs-mbs'),
         date_data       = gsub("Created", "", get_text('.symbol-clock+ span')),
         supporters_data = gsub(" supporters", "", get_text('.symbol-supporters+ span')),
         addressee_data  = gsub("Petition to ", "", get_text('.xs-mbn .type-s')),
         location_data   = get_text('.plxxs')
         )
}

So if we test it on your url, we get a nice data frame (here it's actually shown as a tibble just for formatting purposes:
url <- 'https://www.change.org/search?q=PPE'

scrape_change_page(url)
#> # A tibble: 10 x 5
#>    title_data      date_data  supporters_data addressee_data      location_data
#>    <chr>           <chr>      <chr>           <chr>               <chr>
#>  1 PPE FOR INDIAN~  22 Mar 2~ 31,521          Government of Indi~ India
#>  2 Personal prote~  27 Mar 2~ 992,282         Matthew Hancock MP~ Liverpool, EN~
#>  3 Government mus~  3 May 20~ 208,747         UK Government       London, ENG, ~
#>  4 PPE for NHS st~  19 Mar 2~ 48,536          Matt Hancock        Woking, ENG, ~
#>  5 URGENT NEED fo~  28 Mar 2~ 36,773          Boris Johnson, Mat~ Hebburn, ENG,~
#>  6 PPE for all fr~  1 Apr 20~ 12,963          Public Health Engl~ Hartlepool, E~
#>  7 Appropriate PP~  29 Mar 2~ 4,996           Government          United Kingdom
#>  8 PPE for all Tf~  8 Apr 20~ 11,850          Transport For Lond~ Ilford, ENG, ~
#>  9 Mandate PPE fo~  22 Apr 2~ 11,068          Kay Ivey, Michael ~ Anoka, MN, US
#> 10 Effective PPE ~  28 Mar 2~ 24,588          Ministry of Health  Christchurch,~

Now, if we want to get multiple pages into a single data frame, we generate a vector of urls that we want and lapply this function to get a list of data frames, which we then rbind into one large data frame. It seems there are 191 pages to scrape here, so I will just do 5 for the sake of the example:
n_pages <- 5
urls    <- paste0(url, "&offset=", 10 * (seq(n_pages) - 1)
result  <- do.call(rbind, lapply(urls, scrape_change_page))

result
#> # A tibble: 50 x 5
#>    title_data      date_data  supporters_data addressee_data      location_data
#>    <chr>           <chr>      <chr>           <chr>               <chr>
#>  1 PPE FOR INDIAN~  22 Mar 2~ 31,521          Government of Indi~ India
#>  2 Government mus~  3 May 20~ 208,747         UK Government       London, ENG, ~
#>  3 Personal prote~  27 Mar 2~ 992,282         Matthew Hancock MP~ Liverpool, EN~
#>  4 PPE for NHS st~  19 Mar 2~ 48,536          Matt Hancock        Woking, ENG, ~
#>  5 PPE for all fr~  1 Apr 20~ 12,963          Public Health Engl~ Hartlepool, E~
#>  6 Appropriate PP~  29 Mar 2~ 4,996           Government          United Kingdom
#>  7 URGENT NEED fo~  28 Mar 2~ 36,773          Boris Johnson, Mat~ Hebburn, ENG,~
#>  8 PPE for all Tf~  8 Apr 20~ 11,850          Transport For Lond~ Ilford, ENG, ~
#>  9 Mandate PPE fo~  22 Apr 2~ 11,068          Kay Ivey, Michael ~ Anoka, MN, US
#> 10 Effective PPE ~  28 Mar 2~ 24,588          Ministry of Health  Christchurch,~
#> # ... with 40 more rows

And you can see result has 50 rows (10 from each page)
Created on 2020-07-08 by the reprex package (v0.3.0)


text:
Q: set display by role programmatically in Drupal 7 I want to display this text link,
Click here to register.
 in the body of a larger block of text on a page and but I want the link to show up when some is logged in. I want to use php conditional to show this other link when someone is instead anonymous on the site,

You need to login before you can register. Please Click here to login.

I want a code like:
<?php
if user=="logged-in";
    echo "Click here to register.";
    else echo "Click here to login."
?>

I know I must not have written perfect php but I do not have problems with the php, what I need is the Drupal syntax for if user == "logged-in" and if user == "not-logged-in".
I do not want to use a block and start setting visibility by role. I want to use code as described.
Thanks.

A: See the docs
You want something like this. Both of your link descriptions need some work though. What you'd most likely want to do is display both the register and the login link to anonymous users.
<?php
 if (user_is_logged_in()){
   //user is logged in
 }
 else{
   //user is not logged in
 }
?>


text:
Q: semi continuity I've read about semi continuity on set valued-maps from topological space and real functions.
Given $X$ and $Y$ are two topological spaces and set valued function
$$F:X\to \mathcal{P}(Y).$$
Function $F$ is said to be upper semi continuous to $x\in X$ if for every open set containing $F(x)$, there exists $U\in\mathcal{U}(x)$ such that
$$F(U)=\displaystyle \cup\{F(u):u\in U\}\subseteq V.$$
Meanwhile, in real-valued functions, $f$ is upper semi continuous to $x\in X$ if for every $k>f(x)$, there is a neighbourhood $V$ of $x$ such that $k>f(y)$ for every $y\in V$.
If we consider set of real numbers as topological space, why two definitions above doesn't look similar?

A: They are actually similar at a higher level. $\Bbb R$ has a subbase consisting of two types of sets: upper sets $U(a) =\{x \in \Bbb R: x > a\}$, and lower sets $L(a)= \{x \in \Bbb R: x < a\}$, where $a \in \Bbb R$. This holds in fact in all ordered topological spaces by the definition of the order topology.
Now $\{L(a),R(a): a \in \Bbb R\}$ generates the topology on $\Bbb R$ and in fact only the upper sets (plus $\{\emptyset, \Bbb R\}$) already form a topology on $\Bbb R$ (not a very nice one, only $T_0$ but not $T_1$ but it's sometimes used) and likewise for only the lower sets, and the usual topology is the supremum of these two weak topologies in the poset of all topologies on $\Bbb R$.
Now $f:X \to \Bbb R$ is upper semicontinuous (also as you state the definition) iff $f^{-1}[U(a)]$ is open in $X$ for all $a \in \Bbb R$. So it's continuity for the upper sets only. So quite literally semicontinuous: only the upper sets behave nicely under $f^{-1}$, hence upper semicontinuous. You could also say $f$ is continuous for the upper-topology on $\Bbb R$.
You can also check that lower semicontinuous functions are those that have $f^{-1}[L(a)]$ always open, and this explains their name. Also clear right away is that a function that is both upper and lower semicontinuous is continuous. Then openness of all inverse images of subbasic elements are open etc.
The same can be said for $\mathcal{P}(Y)$. This too has a standard topology that has a subbase that consists of two types of sets:
$[U]= \{F \in \mathcal{P}(Y): F \cap U \neq \emptyset\}$, where $U$ varies over all non-empty open subsets of $Y$ ("hit"-sets, because they have to "hit" $U$) and
$\langle U \rangle = \{F \in \mathcal{P}(Y): F \subseteq U\}$, where $U$ runs over the same sets ("miss"-sets as these are sets that "miss" (are disjoint from) $Y\setminus U$). All these types of sets together define a subbase for the Vietoris topology, which is normally restricted to the subspace of all closed (or compact even) non-empty sets of $Y$, to make it more nicely behaved, and is the major example of hit-and-miss topologies on power sets (here we have to hit open sets and miss closed sets, but other variants have been considered).
A set-values $F: X \to \mathcal{P}(Y)$ is upper semicontinuous if $F^{-1}[\langle V \rangle]=\{x \in X: F(x) \subseteq V\}$ is open in $X$ for all $V \subseteq Y$ open and non-empty. Again, continuity for half of the topology's subbase. It makes sense to call this the "upper" half as $\langle V \rangle$ are all sets upper bounded by $V$, as it were.
It's straightforward to check that it coincides with your definition (you take $x \in F^{-1}[\langle V \rangle]$ and the condition verifies it's an interior point of that set).
You can hopefully guess what a lower semi-continuous set-valued function must be, and check it against other statements of the definition.
You can also check that if $f:X \to \Bbb R$ is seen as a set valued function, e.g. by   $F(x) = \{(-\infty,f(x)]\} \in \mathcal{P}(\Bbb R)$ then usc-ness of $F$ comes down to usc-ness of $f$ and vice versa (please check that, but it seems OK).
So actually, the definitions are similar: it's continuity wrt a half of a standard subbase of the codomain.


text:
Q: Checking uniform continuity I want to show that $x^2\sin \frac {1}{x}$ is not uniformly continuous on $(0,\infty)$. I tried to find sequences $(x_n),(y_n)$ in $(0,\infty)$ such that $|x_n-y_n|\to 0$ but $|f(x_n)-f(y_n)|$ does not go to $0$. Please help.

A: For $f(x) = x^2 \sin(1/x)$ we have
$$f'(x) = 2x \sin(1/x) - \cos(1/x).$$
For $ x \in (0,\infty)$ we have
$$|f'(x)| \leqslant 2|x\sin(1/x)| + |\cos(1/x)| \leqslant 3.$$
Since the derivative is bounded the function is uniformly continuous on $(0,\infty).$
Note that $|x\sin(1/x)| \leqslant 1$ for $x \in (0,\infty)$.  On $[1,\infty)$ we have $0 < 1/x \leqslant 1$ and $|x \sin(1/x)| = \frac{\sin(1/x)}{1/x} \leqslant 1$ since $\frac{sin y}{y} \uparrow 1$ as $y \to 0+$. On $(0,1)$ we have $|x \sin(1/x)| \leqslant 1$ since $|x \sin(1/x)| \to 0$ as $x \to 0$.


text:
Q: Mysql query returns duplicate results for each record I am not a sql guru but I have three tables that I added a foreign key to each (maybe thats where the problem is)
|---------------------|    |---------------------|   |---------------------|
|   DISTINCT_DEALER   |    |  DISTINCT_CUSTOMER  |   |    CUSTOMER_SALES   |
|---------------------|    |---------------------|   |---------------------|
|      d_id   (pk)    |    |       d_id          |   |        d_id         |
|---------------------|    |---------------------|   |---------------------|
|    dealer_address   |    |     dealer_name     |   |   customer_number   |
|---------------------|    |---------------------|   |---------------------|
|    dealer_city      |    |   customer_number   |   |    total_sales      |
|---------------------|    |---------------------|   |---------------------|
|    dealer_state     |    |    customer_name    |
|---------------------|    |---------------------|
|    dealer_zip       |    |    customer_email   |
|---------------------|    |---------------------|

I have a FK for distinct_customers d_id ref on distinct_dealer d_id and a FK on customer sales on d_id referencing distinct_dealer d_id.
when I run this query below, it returns every record duplicate 54 times (number of total records for that one d_id.
select d.d_id, d.dealer_name, cs.total_sales from dship d
join cs_sales cs on d.d_id = cs.d_id order by d.d_id

It looks like its returning a record for each d_id, can someone see what I am doing wrong?

A: I think you want aggregation:
select d.d_id, d.dealer_name,
       sum(cs.total_sales)
from dship d join
     cs_sales cs
     on d.d_id = cs.d_id
group by d.d_id;


text:
Q: Algorithm to find relations between polynomials Let $p_1,\ldots,p_k\in\mathbb{C}[x_1,\ldots,x_n]$ be polynomials. Is there an algorithm to compute the ideal of relations between them?
More precisely, to find a set of generators for the kernel of the ring homomorphism
$$\mathbb{C}[y_1,\ldots,y_k]\to \mathbb{C}[x_1,\ldots,x_n],\quad y_i\mapsto p_i(x_1,\ldots,x_n).$$
(This enables us to compute $\mathbb{C}[p_1,\ldots,p_k]$).
Example: Consider
$$x_1x_2,x_3x_4,x_1x_3,x_2x_4\in\mathbb{C}[x_1,x_2,x_3,x_4].$$
One obvious relation between them is
$$(x_1x_2)(x_3x_4)=(x_1x_3)(x_2x_4).$$
Thus, if
$$\varphi:\mathbb{C}[y_1,y_2,y_3,y_4]\to\mathbb{C}[x_1,x_2,x_3,x_4]$$
is the homomorphism defined by
$$y_1\mapsto x_1x_2,\quad y_2\mapsto x_3x_4,\quad y_3\mapsto x_1x_3,\quad y_4\mapsto x_2x_4,$$
then $y_1y_2-y_3y_4\in\ker \varphi$. It is easy to see that $\ker\varphi$ is in fact generated by $y_1y_2-y_3y_4$, so
$$\mathbb{C}[x_1x_2,x_3x_4,x_1x_3,x_2x_4]\cong\mathbb{C}[y_1,y_2,y_3,y_3]/(y_1y_2-y_3y_4).$$

A: You can do this using elimination. Among other places, this is explained in this blog post.
The input is a list $(f_1,...,f_r)$ of polynomials in $R = k[x_1,...,x_n]$. Adjoin $r$ new variables, giving $S = k[x_1,...,x_n,y_1,...,y_r]$. Define the ideal
$$ I = (y_1-f_1, ..., y_r-f_r) $$
of $S$ and notice that $I$ is precisely the kernel of the $R$-algebra morphism
$$ \psi\colon\; S \to R,\; y_i \mapsto f_i \,\text. $$
Eliminate the $x$-variables from $I$, for instance by computing a Gröbner basis with respect to a suitable ordering, to get
$$ I \cap k[y_1,...,y_r] \,\text. $$
This set is an ideal of $T=k[y_1,...,y_r]$ which contains precisely the polynomial relations you are looking for.
Proof: The morphism $\varphi\colon\; T\to R,\; y_i\mapsto f_i$ factors as $T \overset\iota\hookrightarrow S \overset\psi\twoheadrightarrow R$, hence $\ker\varphi = \iota^{-1}(\ker\psi) = \iota^{-1}(I) = I \cap T$.

In SageMath, your example can be solved as follows:
sage: R.<x1,x2,x3,x4> = QQ[]
sage: fs = Sequence([x1*x2, x3*x4, x1*x3, x2*x4])
sage: fs.algebraic_dependence()
Ideal (T0*T1 - T2*T3) of Multivariate Polynomial Ring in T0, T1, T2, T3 over Rational Field


text:
Q: Placing an ellipse on a canvas programmatically on a Windows 8 store app I've been successful at placing an ellipse on a canvas, but it shows up at the top left corner of it despite my trying different methods of moving it. In this attempt, I am trying to move it to the center of the canvas, but I would like to be able to move it anywhere in the canvas.
private Ellipse drawEllipse(Canvas aCanvas)
{
   Ellipse newEllipse= new Ellipse();
   newEllipse.Width = 40;
   newEllipse.Height = 40;
   newEllipse.Fill = new SolidColorBrush(Colors.Aquamarine);
   aCanvas.Children.Add(lEllipse);
   newEllipse.SetValue(Canvas.LeftProperty, aCanvas.ActualWidth / 2.0);
   newEllipse.SetValue(Canvas.TopProperty, aCanvas.ActualHeight / 2.0);

   return newEllipse;
}

A: Try this:
Canvas.SetLeft(newEllipse, aCanvas.ActualWidth/2.0);
Canvas.SetTop(newEllipse, aCanvas.ActualHeight/2.0);

I didn't try it, but it worked for me all the time.
Edit: Ahh and you should probably first add the ellipse to the canvas before moving the ellipse around.


text:
Q: Git pull request etiquette for repo author - broken style, unrelated changes, partial fixes I got my first pull request on GitHub. https://github.com/Ark-kun/Piranha/pull/1
The change is very small and easy to understand.
Unfortunately, I'm a bit too perfectionistic. I see 3 problems with this pull request:

*

*Broken style (tabs instead of spaces; missing curly braces)

*The pull request has two not quite related fixes - it fixed a NullReferenceException and fixes the libraries path for Mac OS X.

*While this request fixes the path for Mac OS X, it doesn't fix it for Linux.

What should I do?

*

*Ask the PR author to fix the issues.

*Just port and fix the code myself and close the PR without accepting it.

*Checkout the PR branch, fix the style and code, merge the fixed branch. (possibly squashing the commits)

*Something else.

A: (1) and (3) are both reasonable options (though I wouldn't squash the other author's commit if you chose #3).
I'd avoid (2) as it omits attribution - chances are you want to encourage people to submit improvements to your project, and attribution is important in that regard.

A: First option in my opinion is better than others, because making repository public and having pull requests are supposed to help you with your project, so it's good to give credit to people who are trying to help. Hiding their contribution by just porting code and rejecting PR won't encourage them to do more. So I'd definitely avoid option 2.
Secondly, fixing code by yourself will be waste of your time. I know, it's just a few keyboard shortcuts to fix indentation, but if you let people contribute code, which doesn't match your standards (which are very important to have in a public project, and in general too, of course), you're going to have a lot of fixing in the future.
Github has a lot of options to bring programming society together, and it's really easy to post comments to PR or even lines of code. So when you interact with your contributor, you make him a better programmer, and also his next PRs will be better (hopefully :) ), so it's in your interest. Sometimes really interesting discussions are started in those comments, so it might be learning experience for both of you.
Of course, if the fix is really small, you can pick third "action" and make amends yourself, but I'd contact your contributor about the fixes anyway.


text:
Q: Ошибка табуляции Начал изучать программирование ботов на платформе vk api, но столкнулся с проблемой. Сидел 2 часа, но так и не смог решить
    import vk_api
from vk_api import VkUpload
from vk_api.longpoll import VkLongPoll, VkEventType

def main():
    session = requests.Session()

    login, password = 'login', 'password'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth(token_only=True)
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vk = vk_session.get_api()

    longpoll = VkLongPoll(vk_session)

    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
            if event.text == 'Работай':
                if event.from_user:
                    vk.messages.send( #Если написали в ЛС
                        user_id=event.user_id,
                        message='какой-то текст'
                    )

                elif event.from_chat: #Если написали в беседе
                    vk.messages.send(
                        chat_id=event.chat_id,
                        message='какой-то текст'
                    )

if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
                                                                           ^
TabError: inconsistent use of tabs and spaces in indentation

A: У тебя для отступов используются табы и пробелы в перемешку, загугли команду для твоего редактора что бы заменить табы на пробемы, большинство редакторов умеют.
В виме например :retab


text:
Q: C++ FLTK restting components I have a 5 choice components, for example
Fl_Choice* mySideChoice;
mySideChoice = new Fl_Choice(aX, aY, aWidth, aHeight, "Side");

This is part of a multi-step process.  At the end of process, I want to reset all the components so the user can do it again.  I'm having difficulty.  When the widgit is created, the text is blank, and the user needs to pick something for it to call the callback.  Its very obvious the user they need to click in there and select a value.
I was hoping to "reset it" with this code:
mySideChoice->hide();
mySideChoice->value(0);

Doesn't work, just picks the first value when I show the widgit again.
I tried this messy code just trying get somewhere:
Fl::delete_widget(mySideChoice);
Fl::do_widget_deletion();
Fl::check();
Fl::flush();
Sleep(1000);
mySideChoice = new Fl_Choice(aX, aY, aWidth, aHeight, "Side");
Fl::check();
Fl::flush();

Doesnt work, even when totally recreating the widgit.  The widgit does not reappear on the window at all...
Help! Any ideas?
Thanks!!

A: Ha!  so dumb
mySideChoice->value(-1);


text:
Q: Different icon of the nearest marker to current location in Leaflet I'm working with Leaflet and JavaScript for the first time, so I feel a bit lost here. I have an app that displays user's location and a couple of points of interest from a GeoJSON on a map. The points have a popup bound to them that displays information when clicked.
Now I would like the marker for the closest POI to the user be different than the other markers. I have also managed to find the closest point using L.GeometryUtil.
//GEOJSON LAYER
//----------
function onEachFeature(feature, layer){
    if (feature.properties && feature.properties.name) {
        layer.bindPopup(feature.properties.name);
    }
}

var geojsonLayer = L.geoJSON(pivovary, {
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {icon: beerMarker})},
    onEachFeature: onEachFeature
}).addTo(map);

//USER LOCATION
//----------
var closestpt = null
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e){
    L.marker(e.latlng, {icon: youAreHereMarker}).addTo(map),
    closestpt = L.GeometryUtil.closestLayer(map, geojsonLayer.getLayers(), e.latlng).latlng
}

map.on('locationfound', onLocationFound)

I tried to add a new marker at the closestpt coordinates in onLocationFound, but then I am just placing a new marker on top of one that is already there and I cannot use the popup that is bound to my geojsonLayer anyway.
Is there a way to render the markers after I find the closest point?

A: You could do it by adding markers to layer group and later looking for closest marker in the group, something like this:
var markerGroupLayer = L.layerGroup();

var geojsonLayer = L.geoJSON(pivovary, {
    pointToLayer: function (feature, latlng) {
        var marker = L.marker(latlng, {icon: beerMarker});
        markerGroupLayer.addLayer(marker);
        return marker;},
    onEachFeature: onEachFeature
}).addTo(map);

var closestMarker = null;
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e){
    L.marker(e.latlng, {icon: youAreHereMarker}).addTo(map),
    closestMarker = L.GeometryUtil.closestLayer(map, markerGroupLayer.getLayers(), e.latlng);
    closestMarker.setIcon(closestMarkerIcon);
}

I haven't tried it, but it should work. What is still missing is logic of changing icon of previous closest marker to default icon and handling of case where several markers are at equal closest distance.


text:
Q: exponent formula in Ruby without using default operator How can use methods to calculate exponent without using ** operator. Suppose method name calculate(a,b) where a is base and b is exponent value.
The value of a and b can be positive or negative integers, decimals, etc.
Thanks

A: Would Math.exp(b * Math.log(a)) suit your needs?  Note that while this works for non-integer a and b, it requires a > 0.  It is also subject to the finite precision limitations of floating point arithmetic.

With the restriction that b is integer, the following recursive solution works and is O(log b), i.e., asymptotically faster than repeated multiplication:
def calculate(a, b)
  return 1.0 / calculate(a, -b) if b < 0
  if b == 0
    1
  elsif b.even?
    calculate(a * a, b / 2)
  else
    a * calculate(a, b - 1)
  end
end

The value of a can be integer or have decimals, and positive or negative.
If you're worried about precision issues, you could also change the return statement to return Rational(1, calculate(a, -b)) if b < 0.

A: quite the same solution as Wand maker suggested, with different syntax for creating the Array :
Array.new(b, a).reduce(&:*)

Another solution using an enumerator (should be faster) :
b.times.reduce(1) { |r| r * a }

b.times returns an enumerator yielding the values 0 to b - 1 (resulting in b values)
the use of reduce with a block is best explained from its docs : http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-reduce

A: How about:
def calculate(a,b)
  b.times.reduce(1) { |acc, _| acc * a }
end

I think it's easy to read and it displays the exponent definition clearly.


text:
Q: Validate CSV file in angularJs I have a csv file which contains two columns store_id and store_name.When the user uploads a csv file I need to validate the file i.e check if first column is Integer(store_id) and second column is String(store_name).Can you help how to read and retrieve the content and validate the file?
Thanks

A: document.getElementById('csvUpload').onchange = function(){
        var file = this.files[0];
        var storeId = [],storeName = [],line,flag = 1;
        var reader = new FileReader();
        reader.onload = function(progressEvent){
            var lines = this.result.split('\n');
            for(var iterator = 0; iterator < lines.length-1; iterator++){
                line = lines[iterator].split(',');
                storeId.push(line[0]);
                storeName.push(line[1]);
            }
            var result = !storeId.some(isNaN);
            for(var iterator = 0; iterator < storeName.length; iterator++) {
                console.log(typeof storeName[iterator]);
                if(typeof storeName[iterator] !== "string"){
                    flag = 0;
                    break;
                }
            }
            if(result === false || flag === 0) {
                var alert = mdDialog.alert({
                    textContent: 'Please select a valid csv file',
                    ok: 'Close'
                });
                mdDialog.show( alert );
            }
        };
        reader.readAsText(file);
    }

A: Try this code
my csv file
    store_id,store_name
01,"First point"
02,"Second point"
03,"Third point"

var demo = angular.module('demo', []);
demo.controller('loadData', function($scope,$rootScope,$http){
   $scope.uploadData = function() {
    var uploaded=$scope.fileContent;
  $scope.processData(uploaded);
   };
    $scope.processData = function(allData) {
  var filteredData = allData.split(/\r\n|\n/);
  var headers = filteredData[0].split(',');
  var final = [];

  for ( var i = 0; i < filteredData.length; i++) {

  if (!filteredData[i]=="") {

   var data = filteredData[i+1].split(',');

   if (isNaN(data[0])==false && isNaN(data[1])==true) {
    final.push(data);
    console.log("Valid CSV");
   }
   else{
    console.log("Not Valid CSV");
   }
  }
  }
  $scope.data = final;
 };
});
demo.directive('fileReader', function() {
  return {
    scope: {
      fileReader:"="
    },
    link: function(scope, element) {
      $(element).on('change', function(changeEvent) {
        var files = changeEvent.target.files;
        if (files.length) {
          var r = new FileReader();
          r.onload = function(e) {
              var contents = e.target.result;
              scope.$apply(function () {
                scope.fileReader = contents;
              });
          };
          r.readAsText(files[0]);
        }
      });
    }
  };
});

   <input type="file" file-reader="fileContent" />
   <button ng-click='uploadData($event)' >upload</button>

{{fileContent}}

    {{ y }}

A: you may try this component
https://www.import-javascript-angular-xlsx-csv-validator.com/
it validates that and more


text:
Q: How to remotely retrieve a java thread dump JVisualVM connects to a Java process over JMX and can produce a thread dump through the click of a button. I'd like to add a similar feature to my own application so that it can request thread dumps from remote services.
Which MBeans do I need to interrogate to get this information? and how?

A: You can use the ThreadMXBean management interface.
This FullThreadDump class demonstrates the capability to get a full thread dump and also detect deadlock remotely using JMX.

A: You can use MBean with name "java.lang:type=Threading". It's interface is described here.
In order to get thread dump you first need to use getAllThreadIds method and then loop through all retrieved ids and call getThreadInfo method for each of them.


text:
Q: Form submit to iframe on new page I have a form which submits to an iframe, This works fine if you are on a page with the iframe.
I want to be able to have the form on any page and when submit is pressed load a page and send the submit to the iframe
e.g.

*

*On page "article.php" and press submit

*Open page "results.php" and

*Send post data from form clicked in "article.php" to iframe "DataHere" on "results.php"

Thanks in advance

A: You could try detecting if the frame exists when the form is submitted and if it does not, reload the whole page and generate the iFrame.
If you need a hand checkout http://www.java-scripts.net/javascripts/Check-Frames-Page-Script.phtml

A: If you are able to comfortably sanitize your initial POST data to avoid XSS, you could create an intermediate page for your iframe destination that does your POST for you:

*

*On page article.php with <form action="results.php">, press submit.

*results.php validates that the input isn't XSS, and renders with a <iframe src="negotiator.php?my=form&data=here"></iframe>

*negotiator.php takes the query string arguments (and runs the same sanitizing as results.php) and POSTs them to your intended url.

*Your results will load in the iframe.

It's pretty important that you make sure your input isn't insane. If your form requires arbitrary text, punctuation, and special characters, this is not safe for you.


text:
Q: How to recover tuleap aministration project I've deleted the Administration project on Tuleap.
Therefore I lost the Admin menu on the upper right.
How can I recover the Administration project?
Thank you in advance

A: I solved the problem by executing the following script in MySQL Tuleap Database:
update groups set status = 'A' where group_id='1';

insert into user_group(user_id,group_id, admin_flags, bug_flags, forum_flags, project_flags, patch_flags, support_flags, file_flags, wiki_flags, svn_flags, news_flags) values(101, 1, 'A', 2, 2, 2, 2, 2, 2, 2, 2,2 );


text:
Q: Unable to verify the first certificate - kibana/elasticsearch I'm trying to configure xpack for elasticsearch/kibana, I've activated the trial license for elasticsearch, configured xpack for kibana/elasticsearch and also I've generated ca.crt, node1-elk.crt, node1-elk.key and also kibana.key , kibana.crt  and if I'm testing with curl towards the elasticsearch using the kibana user and password and also the ca.crt it's working like a charm, if I'm trying to access kibana from the GUI says that the "Server is not ready yet" and the logs show that " unable to verify the first certificate" :
{"type":"log","@timestamp":"2021-11-16T04:41:09-05:00","tags":["error","savedobjects-service"],"pid":13250,"message":"Unable to retrieve version information from Elasticsearch nodes. unable to verify the first certificate"}
My configuration:
kibana.yml
server.name: "my-kibana"
server.host: "0.0.0.0"
elasticsearch.hosts: ["https://0.0.0.0:9200"]
server.ssl.enabled: true
server.ssl.certificate: /etc/kibana/certs/kibana.crt
server.ssl.key: /etc/kibana/certs/kibana.key
server.ssl.certificateAuthorities: ["/etc/kibana/certs/ca.crt"]
elasticsearch.username: "kibana_system"
elasticsearch.password: "kibana"

elasticsearch.yml
node.name: node1
network.host: 0.0.0.0
discovery.seed_hosts: [ "0.0.0.0" ]
cluster.initial_master_nodes: ["node1"]
xpack.security.enabled: true
xpack.security.http.ssl.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.http.ssl.key: /etc/elasticsearch/certs/node1.key
xpack.security.http.ssl.certificate: /etc/elasticsearch/certs/node1.crt
xpack.security.http.ssl.certificate_authorities: [ "/etc/elasticsearch/certs/ca.crt" ]
xpack.security.transport.ssl.key: /etc/elasticsearch/certs/node1.key
xpack.security.transport.ssl.certificate: /etc/elasticsearch/certs/node1.crt
xpack.security.transport.ssl.certificate_authorities: [ "/etc/elasticsearch/certs/ca.crt" ]

curl testing:
[root@localhost kibana]#  curl -XGET https://0.0.0.0:9200/_cat/nodes?v -u kibana_system:kibana  --cacert /etc/elasticsearch/certs/ca.crt
ip              heap.percent ram.percent cpu load_1m load_5m load_15m node.role   master name
192.168.100.102           23          97   3    0.00    0.02     0.08 cdfhilmrstw *      node1

I don't know what to do more here:
[root@localhost kibana]#  curl -XGET https://0.0.0.0:9200/_license -u kibana_system:kibana  --cacert /etc/elasticsearch/certs/ca.crt
{
  "license" : {
    "status" : "active",
    "uid" : "872f0ad0-723e-43c8-b346-f43e2707d3de",
    "type" : "trial",
    "issue_date" : "2021-11-08T18:26:15.422Z",
    "issue_date_in_millis" : 1636395975422,
    "expiry_date" : "2021-12-08T18:26:15.422Z",
    "expiry_date_in_millis" : 1638987975422,
    "max_nodes" : 1000,
    "issued_to" : "elasticsearch",
    "issuer" : "elasticsearch",
    "start_date_in_millis" : -1
  }
}

Thank you for your help


text:
Q: jQuery unexpected identifier using $(this) for mousemove I'm trying to get a parallax effect on one element with:
jQuery(document).ready(function($){
    $('#Parallax').mousemove(
            function(e){
            /* Work out mouse position */
            var offset = $(this).offset();
            var xPos = e.pageX - offset.left;
            var yPos = e.pageY - offset.top;

            /* Get percentage positions */
            var mouseXPercent = Math.round(xPos / $(this).width() * 100);
            var mouseYPercent = Math.round(yPos / $(this).height() * 100);

            /* Position Each Layer */
            $(this).children('img').each(
                    function(){
                            var diffX = $('#Parallax').width() - $(this).width();
                            var diffY = $('#Parallax').height() - $(this).height();

                            var myX = diffX * (mouseXPercent / 100);
                            var myY = diffY * (mouseYPercent / 100);
                            var cssObj = {
                                    'left': myX + 'px',
                                    'top': myY + 'px'
                            }
                            $(this).animate({left: myX, top: myY},{duration: 50, queue: false, easing: 'linear'});

                    }
            );

            }
    );
});

However, I keep getting the following error:

Uncaught Syntax error: Unexpected Identifier for line 5 "var offset = $(this).offset();".

Am I missing something..?
Solved - there are hidden formatting issues. no problems with code

A: Glad I helped Andrew.
My answer from the comments:

When I copy-paste your code there is a hidden char between off and
  set (shows as off-set in notepad). If this char is in your code
  too it might be the problem.


text:
Q: Weak closedness implies closed and convex Let $I=[0, 1]$, $1\leq p<+\infty$ and let $A$ be a non empty subset of $\mathbb R^n$. Denote with $S_p(A)$ the set of functions $u\in L^p(I,\mathbb R^n)$ such that $u(x)\in A$ for almost every $x\in I$. Is it true that if $S_p(A)$ is weakly closed in $L^p(I,\mathbb R^n)$ then $A$ is closed and convex?

A: $A$ is closed. If $x_n\in A$ converge to $x\in \mathbb R^n$, then the constant functions $f_n\equiv x_n$ converge in $L^p$ to $x$. Hence $x\in A$.
$A$ is midpoint-convex. Given $a,b\in A$, let $f_n(x)=a$ if $\lfloor nx\rfloor $ is even, and $f_n(x)=b$ otherwise. This sequence converges weakly in $L^p$ to the constant function $f\equiv (a+b)/2$. To prove this, first show that $\int_J f_n \to\int_J f$ for every subinterval $J\subset I$, and then use the density of step functions in $(L^p)^*=L^q$.
Since $A$ is closed and midpoint-convex, it is convex.