text:
Q: How to keep attributes for an object in javascript if they have a specific key/value I have an api call response with this format.
They are token and I know how to filter an array.
But here instead of an array I have an object.
{
  "AFjQbjBwEF4HfBgKYTeK3SZg4cGRuB9o3rNGmQvHwtFX": {
    "name": "000# Heartbreak",
    "symbol": "NNPOSTER",
    "description": "The crystal broken heart is a mirror through which residents of the NEONEXUS can take a peek into the real world as we know it.",
    "seller_fee_basis_points": 500,
    "image": "https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg",
    "animation_url": "https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4",
    "external_url": "https://neonexus.io",
    "attributes": [
      {
        "trait_type": "City",
        "value": "Miami"
      },
      {
        "trait_type": "Theme",
        "value": "Heartbreak in Miami"
      },
      {
        "trait_type": "Origin",
        "value": "Airdrop"
      },
      {
        "trait_type": "Scene",
        "value": "Moody"
      },
      {
        "trait_type": "Period",
        "value": "Lockdown"
      },
      {
        "trait_type": "Artist",
        "value": "Daramola"
      }
    ],
    "collection": {
      "name": "NEONEXUS Posters",
      "family": "Raynesfere"
    },
    "properties": {
      "files": [
        {
          "uri": "https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg",
          "type": "image/gif"
        },
        {
          "uri": "https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4",
          "type": "video/mp4"
        }
      ],
      "category": "video",
      "creators": [
        {
          "address": "Ef896VQS1tfMACgL5Ce1TR7JZhehkrtowCyZZyYv7SWn",
          "share": 100
        }
      ]
    }
  },
  "F8EeyxkR5EBs7ALaapV2jNos8jdbdgpqjtEaJ6fVfB3K": {
    "name": "Skellies #4107",
    "symbol": "SKULL",
    "description": "Skellies is a collection of 8888 spooky skeletons presented by the SolSocks team",
    "seller_fee_basis_points": 500,
    "image": "https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png",
    "attributes": [
      {
        "trait_type": "Background",
        "value": "Pepto"
      },
      {
        "trait_type": "Skin",
        "value": "Purple Haze"
      },
      {
        "trait_type": "Eyes",
        "value": "Angry"
      },
      {
        "trait_type": "Nose",
        "value": "Double Double"
      },
      {
        "trait_type": "Chest",
        "value": "None"
      },
      {
        "trait_type": "Ears",
        "value": "none"
      },
      {
        "trait_type": "Mouth",
        "value": "WGMI #2"
      },
      {
        "trait_type": "Glasses",
        "value": "none"
      },
      {
        "trait_type": "Headwear",
        "value": "Droid"
      },
      {
        "trait_type": "Limited Edition",
        "value": "no"
      },
      {
        "trait_type": "Dna",
        "value": "82310019050"
      }
    ],
    "collection": {
      "name": "Skellies X SolSocks",
      "family": "Skellies"
    },
    "properties": {
      "files": [
        {
          "uri": "https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png",
          "type": "image/png"
        }
      ],
      "category": "image",
      "creators": [
        {
          "address": "CpvHujvbSJ9btvPmP5FUKC8QpGM8AQjFk7uLJSsomoH2",
          "share": 85
        },
        {
          "address": "BQ6FxfRVDWKUVeqD9uHFqBjebJ9Um8RVzPTPZ1bBoByU",
          "share": 15
        }
      ]
    }
  },
}

I need to keep only the tokens with a specific collection.name: "Skellies X SolSocks".
I cannot use map because is an object.
Is there a map/filter/reduce function I can use?

A: You could use Object.entries(), to get an array of the objects key/value pairs.
We can then use Array.filter() to filter by any property, in this case name, then we can use Object.fromEntries() to create the desired result.

let obj = { "AFjQbjBwEF4HfBgKYTeK3SZg4cGRuB9o3rNGmQvHwtFX": { "name": "000# Heartbreak", "symbol": "NNPOSTER", "description": "The crystal broken heart is a mirror through which residents of the NEONEXUS can take a peek into the real world as we know it.", "seller_fee_basis_points": 500, "image": "https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg", "animation_url": "https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4", "external_url": "https://neonexus.io", "attributes": [ { "trait_type": "City", "value": "Miami" }, { "trait_type": "Theme", "value": "Heartbreak in Miami" }, { "trait_type": "Origin", "value": "Airdrop" }, { "trait_type": "Scene", "value": "Moody" }, { "trait_type": "Period", "value": "Lockdown" }, { "trait_type": "Artist", "value": "Daramola" } ], "collection": { "name": "NEONEXUS Posters", "family": "Raynesfere" }, "properties": { "files": [ { "uri": "https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg", "type": "image/gif" }, { "uri": "https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4", "type": "video/mp4" } ], "category": "video", "creators": [ { "address": "Ef896VQS1tfMACgL5Ce1TR7JZhehkrtowCyZZyYv7SWn", "share": 100 } ] } }, "F8EeyxkR5EBs7ALaapV2jNos8jdbdgpqjtEaJ6fVfB3K": { "name": "Skellies #4107", "symbol": "SKULL", "description": "Skellies is a collection of 8888 spooky skeletons presented by the SolSocks team", "seller_fee_basis_points": 500, "image": "https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png", "attributes": [ { "trait_type": "Background", "value": "Pepto" }, { "trait_type": "Skin", "value": "Purple Haze" }, { "trait_type": "Eyes", "value": "Angry" }, { "trait_type": "Nose", "value": "Double Double" }, { "trait_type": "Chest", "value": "None" }, { "trait_type": "Ears", "value": "none" }, { "trait_type": "Mouth", "value": "WGMI #2" }, { "trait_type": "Glasses", "value": "none" }, { "trait_type": "Headwear", "value": "Droid" }, { "trait_type": "Limited Edition", "value": "no" }, { "trait_type": "Dna", "value": "82310019050" } ], "collection": { "name": "Skellies X SolSocks", "family": "Skellies" }, "properties": { "files": [ { "uri": "https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png", "type": "image/png" } ], "category": "image", "creators": [ { "address": "CpvHujvbSJ9btvPmP5FUKC8QpGM8AQjFk7uLJSsomoH2", "share": 85 }, { "address": "BQ6FxfRVDWKUVeqD9uHFqBjebJ9Um8RVzPTPZ1bBoByU", "share": 15 } ] } }, }

const searchTerm = 'Skellies';
const result = Object.fromEntries(Object.entries(obj).filter(([key, val]) => {
    return val.name.includes(searchTerm);
}));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could also try a for .. in loop to iterate over the object keys, adding any child objects with a matching name value.

let obj = { "AFjQbjBwEF4HfBgKYTeK3SZg4cGRuB9o3rNGmQvHwtFX": { "name": "000# Heartbreak", "symbol": "NNPOSTER", "description": "The crystal broken heart is a mirror through which residents of the NEONEXUS can take a peek into the real world as we know it.", "seller_fee_basis_points": 500, "image": "https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg", "animation_url": "https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4", "external_url": "https://neonexus.io", "attributes": [ { "trait_type": "City", "value": "Miami" }, { "trait_type": "Theme", "value": "Heartbreak in Miami" }, { "trait_type": "Origin", "value": "Airdrop" }, { "trait_type": "Scene", "value": "Moody" }, { "trait_type": "Period", "value": "Lockdown" }, { "trait_type": "Artist", "value": "Daramola" } ], "collection": { "name": "NEONEXUS Posters", "family": "Raynesfere" }, "properties": { "files": [ { "uri": "https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg", "type": "image/gif" }, { "uri": "https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4", "type": "video/mp4" } ], "category": "video", "creators": [ { "address": "Ef896VQS1tfMACgL5Ce1TR7JZhehkrtowCyZZyYv7SWn", "share": 100 } ] } }, "F8EeyxkR5EBs7ALaapV2jNos8jdbdgpqjtEaJ6fVfB3K": { "name": "Skellies #4107", "symbol": "SKULL", "description": "Skellies is a collection of 8888 spooky skeletons presented by the SolSocks team", "seller_fee_basis_points": 500, "image": "https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png", "attributes": [ { "trait_type": "Background", "value": "Pepto" }, { "trait_type": "Skin", "value": "Purple Haze" }, { "trait_type": "Eyes", "value": "Angry" }, { "trait_type": "Nose", "value": "Double Double" }, { "trait_type": "Chest", "value": "None" }, { "trait_type": "Ears", "value": "none" }, { "trait_type": "Mouth", "value": "WGMI #2" }, { "trait_type": "Glasses", "value": "none" }, { "trait_type": "Headwear", "value": "Droid" }, { "trait_type": "Limited Edition", "value": "no" }, { "trait_type": "Dna", "value": "82310019050" } ], "collection": { "name": "Skellies X SolSocks", "family": "Skellies" }, "properties": { "files": [ { "uri": "https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png", "type": "image/png" } ], "category": "image", "creators": [ { "address": "CpvHujvbSJ9btvPmP5FUKC8QpGM8AQjFk7uLJSsomoH2", "share": 85 }, { "address": "BQ6FxfRVDWKUVeqD9uHFqBjebJ9Um8RVzPTPZ1bBoByU", "share": 15 } ] } }, }

const result = {};
const searchTerm = 'Skellies';

for(let k in obj) {
    if (obj[k] && ((obj[k].name || "").includes(searchTerm))) {
        result[k] = obj[k];
    }
}
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can simply use a for loop  to loop over the object's entries:

const yourObject = {"AFjQbjBwEF4HfBgKYTeK3SZg4cGRuB9o3rNGmQvHwtFX":{"name":"000# Heartbreak","symbol":"NNPOSTER","description":"The crystal broken heart is a mirror through which residents of the NEONEXUS can take a peek into the real world as we know it.","seller_fee_basis_points":500,"image":"https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg","animation_url":"https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4","external_url":"https://neonexus.io","attributes":[{"trait_type":"City","value":"Miami"},{"trait_type":"Theme","value":"Heartbreak in Miami"},{"trait_type":"Origin","value":"Airdrop"},{"trait_type":"Scene","value":"Moody"},{"trait_type":"Period","value":"Lockdown"},{"trait_type":"Artist","value":"Daramola"}],"collection":{"name":"NEONEXUS Posters","family":"Raynesfere"},"properties":{"files":[{"uri":"https://arweave.net/8TpUvw7hi7N_rVuG6avV_cOX2bXQ7OsY-ZNtILCM-zo?ext=jpg","type":"image/gif"},{"uri":"https://arweave.net/WdzVw-_XE7LQArXArYJNpeMSgFbYYwa1ATpCVrfrTK8?ext=mp4","type":"video/mp4"}],"category":"video","creators":[{"address":"Ef896VQS1tfMACgL5Ce1TR7JZhehkrtowCyZZyYv7SWn","share":100}]}},"F8EeyxkR5EBs7ALaapV2jNos8jdbdgpqjtEaJ6fVfB3K":{"name":"Skellies #4107","symbol":"SKULL","description":"Skellies is a collection of 8888 spooky skeletons presented by the SolSocks team","seller_fee_basis_points":500,"image":"https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png","attributes":[{"trait_type":"Background","value":"Pepto"},{"trait_type":"Skin","value":"Purple Haze"},{"trait_type":"Eyes","value":"Angry"},{"trait_type":"Nose","value":"Double Double"},{"trait_type":"Chest","value":"None"},{"trait_type":"Ears","value":"none"},{"trait_type":"Mouth","value":"WGMI #2"},{"trait_type":"Glasses","value":"none"},{"trait_type":"Headwear","value":"Droid"},{"trait_type":"Limited Edition","value":"no"},{"trait_type":"Dna","value":"82310019050"}],"collection":{"name":"Skellies X SolSocks","family":"Skellies"},"properties":{"files":[{"uri":"https://www.arweave.net/mG5dY4GC-3g9j661NRQWoGYWKUtbqDvfhW8whDVVEF0?ext=png","type":"image/png"}],"category":"image","creators":[{"address":"CpvHujvbSJ9btvPmP5FUKC8QpGM8AQjFk7uLJSsomoH2","share":85},{"address":"BQ6FxfRVDWKUVeqD9uHFqBjebJ9Um8RVzPTPZ1bBoByU","share":15}]}}};

const tokens = [];
const filteredObject = {};

for (let [token, entry] of Object.entries(yourObject)) {
    if (entry.collection.name === 'Skellies X SolSocks') {
        tokens.push(token);
        filteredObject[token] = entry;
    }
}

console.log(tokens);
console.log(filteredObject);


text:
Q: Can I explicity specify which keyboard can be used as input device in Qt? I currently have keyboard's Vendor ID,product id, revison number - extracted from interception library(specific function call: interception_get_hardware_id more information on it here:(Scroll to the bottom of the page).
What I want to do is to explicity specify, input device (i.e keyboard, based on its vendor,product ID and revision number) that my Qt application can interact with regardless of how many input devices are physically connect to my machine (i.e more than 1 keyboard may be attached, just want to use one specific keyboard). Is this functionality implementable using Qt ?
Kindly point me to Qt documentation where I could look into, to implement such functionality. Just need a push in the right direction, thanks.
EDIT: Im on windows platform.
EDIT: Inteception library(API for controlling input devices based on Win32 API) : https://github.com/oblitum/Interception

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sending TMemoryStream as mail attachment I am exporting a FastReport as PDFFile using TfrxPDFExport. I made a function that returns me a PDF as IStream:
Function TPDFReport.GetAsFile (): IStream;
var
  MStream: TMemoryStream;
Begin
  MStream := TMemoryStream.Create;
  try
    With formReport.Create (NIL) do begin
      frxPDFExport.Stream := MStream;
      frxReport.PrepareReport;
      frxReport.Export(frxPDFExport);
    end;
    Result := TStreamAdapter.Create(MStream) as IStream;
  finally

  end;
End;

Afterwards in a different unit I execute this function, get an IStream and load it into a TMemoryStream:
  PDFOleStream := TOleStream.Create(PDFReport.GetAsFile ());
  PDFMemoryStream.LoadFromStream(PDFOleStream);

Now I got the MemoryStream, but I don't really know the next step. I searched through web and found out that's not possible to send a Stream as a mail attachment with Indy. So I think, it's better to save a TMemoryStream as a temp file and then send it as an attachment. But as soon as I execute
PDFMemoryStream.SaveToFile('c:\\PDFExp.pdf');

I get an access violation. What have I done wrong? Thanks.

A: You do not need to save the TMemoryStream to a file just to attach it to an email. Indy's TIdMessage component is flexible in the types of data you can attach to it.
For instance, Indy has a TIdAttachmentMemory class you can use, eg:
uses
 ..., IdAttachmentMemory;

var
  Attach: TIdAttachmentMemory;
begin
  ...

  Attach := TIdAttachmentMemory.Create(IdMessage1, PDFMemoryStream); // alternatively, use PDFOleStream instead...
  Attach.FileName := 'report.pdf';
  // set other properties as needed...

  // send the email...

  ...
end;

Note that TIdAttachmentMemory uses its own internal TMemoryStream and will copy the source TStream's data into that internal stream. If you want to avoid that copy and send your own TStream as-is, you can derive your own class from TIdAttachment for that, eg:
uses
  Classes, IdAttachment, IdMessageParts, IdGlobal;

type
  TIdAttachmentStream = class(TIdAttachment)
  protected
    FDataStream: TStream;
    FDataStreamBeforeLoadPosition: TIdStreamSize;
  public
    constructor Create(Collection: TIdMessageParts; Stream: TStream); reintroduce;
    property DataStream: TStream read FDataStream;
    function OpenLoadStream: TStream; override;
    procedure CloseLoadStream; override;
    procedure FinishTempStream; override;
    function PrepareTempStream: TStream; override;
  end;

constructor TIdAttachmentStream.Create(Collection: TIdMessageParts; Stream: TStream);
begin
  inherited Create(Collection);
  FDataStream := Stream;
end;

procedure TIdAttachmentStream.CloseLoadStream;
begin
  DataStream.Position := FDataStreamBeforeLoadPosition;
end;

function TIdAttachmentStream.OpenLoadStream: TStream;
begin
  FDataStreamBeforeLoadPosition := DataStream.Position;
  DataStream.Position := 0;
  Result := DataStream;
end;

procedure TIdAttachmentStream.FinishTempStream;
begin
  DataStream.Position := 0;
end;

function TIdAttachmentStream.PrepareTempStream: TStream;
begin
  DataStream.Size := 0;
  Result := DataStream;
end;

var
  Attach: TIdAttachmentStream;
begin
  ...

  Attach := TIdAttachmentStream.Create(IdMessage1, PDFMemoryStream); // alternatively, use PDFOleStream instead...
  Attach.FileName := 'report.pdf';
  // set other properties as needed...

  // send the email...

  ...
end;

Or, you can write a class to send the original IStream directly, eg:
uses
  Classes, IdAttachment, IdMessageParts, IdGlobal;

type
  TIdAttachmentIStream = class(TIdAttachment)
  protected
    FDataStream: TStream;
    FDataStreamBeforeLoadPosition: TIdStreamSize;
  public
    constructor Create(Collection: TIdMessageParts; Stream: IStream); reintroduce;
    destructor Destroy; override;
    property DataStream: TStream read FDataStream;
    function OpenLoadStream: TStream; override;
    procedure CloseLoadStream; override;
    procedure FinishTempStream; override;
    function PrepareTempStream: TStream; override;
  end;

constructor TIdAttachmentIStream.Create(Collection: TIdMessageParts; Stream: IStream);
begin
  inherited Create(Collection);
  FDataStream := TOleStream.Create(Stream);
end;

destructor TIdAttachmentIStream.Destroy;
begin
  FDataStream.Free;
  inherited;
end;

procedure TIdAttachmentIStream.CloseLoadStream;
begin
  DataStream.Position := FDataStreamBeforeLoadPosition;
end;

function TIdAttachmentIStream.OpenLoadStream: TStream;
begin
  FDataStreamBeforeLoadPosition := DataStream.Position;
  DataStream.Position := 0;
  Result := DataStream;
end;

procedure TIdAttachmentIStream.FinishTempStream;
begin
  DataStream.Position := 0;
end;

function TIdAttachmentIStream.PrepareTempStream: TStream;
begin
  DataStream.Size := 0;
  Result := DataStream;
end;

var
  Attach: TIdAttachmentIStream;
begin
  ...

  Attach := TIdAttachmentIStream.Create(IdMessage1, PDFReport.GetAsFile());
  Attach.FileName := 'report.pdf';
  // set other properties as needed...

  // send the email...

  ...
end;


text:
Q: Why "Disable" or "Restart" methods are not working (Using WMI in C#) I just wrote 3 different codes. One of them works fine. But other two, don't work and throw an ManagementException with the message:

This method is not implemented in any class

Here is the code that works fine:
string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

Scope.Connect();

string WQL = String.Format("SELECT * FROM Win32_Volume");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Defrag");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Defrag", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "DefragAnalysis", outParams["DefragAnalysis"]);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
}

Console.ReadLine();

Here is the code that is not working and throwing the exception (See that is basically the same code) The one thing that had changed is the WMI class used. The exception happens on InvokeMethod.
string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_PnPEntity");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Disable");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Disable", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
    Console.WriteLine("{0,-35} {1,-40}", "rebootNeeded", outParams["rebootNeeded"]);
}

Console.ReadLine();

I also tried to use the method "Reset" instead of "Disable". it does not work. But this time, the exception occurred on GetMethodParameters. It said that this method was not implemented in any class.
string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_PnPEntity");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Reset");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Reset", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
    Console.WriteLine("{0,-35} {1,-40}", "rebootNeeded", outParams["rebootNeeded"]);
}

Console.ReadLine();

I need a code that enables and disables PNP devices, also, I need to use WMI classes to keep the same standard of the rest of the code, so I need to use namespace System.Management;

A: The code for disabling devices is correct, but you need to run it with administrator rights. Without the admin permission, I'm getting System.Management.ManagementException 'Generic failure'.


text:
Q: Trying to snap a group to grid with kineticJS having one shape presently weird offset     function draw_shape(sides) {

      var shape_group = new Kinetic.Group({
        x: 10,
        y: 10,
        width: 10,
        height: 10,
        draggable: true
      });

      var shape_size = 10
      var radius = shape_size / 2
      var shape = new Kinetic.RegularPolygon({
        x: 10,
        y: 10,
        sides: sides,
        radius: radius,
        fill:'#fff',
        stroke: 'black',
        strokeWidth: 1,
        lineJoin: 'bevel'
      });

      shape_group.on('dragmove', function() {
        var current_cell = current_cell_from_mouse_position()
        shape_group.setX(current_cell.x);
        shape_group.setY(current_cell.y);
      });
      shape_group.add(shape);
      board_layer.add(shape_group);
      stage.add(board_layer);
    }

in this example current_cell_from_mouse_position() gives me back the correct x and y cordinates. This example works great without the group. I am not sure why but when I add the group a wierd offset is created moving the group and shape to the bottom right.
Any help would be appreciated thank you

A: Setting the shape's x/y to 10/10 will cause that shape to shift down-right within the group by 10 pixels.
So your group is properly aligned to the grid.
But your shape within the group is offset by 10 pixels.
Cure: set your shape's x/y to 0,0 instead of 10/10.


text:
Q: Correct usage of wglMakeCurrent? Is wglMakeCurrent supposed to be called only once or does it need to be called before every buffer swap?
Can current opengl context be reset by some external thing other then setting it via wglMakeCurrent?
I am here just to narrow the possible problem. I can't post relevant code here because I have no idea which part is relevant.
Currently I have loop that does makeCurrent -> clear -> render. It renders correctly. I tried make context current on initialization without making it current every draw, but it rendered empty screen. Only when I exited window the correct render flickered for one frame. I figured that something is wrong by using nvidia's graphics debugger. The debugger's overlay strangelly flickered. It doesn't do that with other applications.

A:
Is wglMakeCurrent supposed to be called only once

Each GL context can be made current to at most one thread and drawable at every single point in time. If you only use one Window and one GL Context, it is enough to call wglMakeCurrent only once after you created the context and the window.
If you use one context for multiple windows, you have to re-bind it at least once per frame and window. Note that switching the current context or window traditionally implied flushing the GL pipeline, but this can nowadays be prevented via the KHR_context_flush_control extension, making such a scheme much more efficient.
If you use multiple threads but a single GL context, you must push around the context from thread to thread by making it uncurrent in some thread, and making it current again in the new thread, and so on. But that scheme should almost never be necessary. Fur mutli-threaded GL, you should create mutlipe shared contexts, and then, you usually need one wglMakeCurrent per thread.

or does it need to be called before every buffer swap?

Note that the SwapBuffers function is not a GL function (hence also no gl prefix in the name), and therefore, does work independently of the currently active GL context - the function takes the HDC of the window you want the buffer swap to occur.

Can current opengl context be reset by some external thing other then setting it via wglMakeCurrent?

No, not really. There is the graphics reset situation which can be handled via ARB_robustness:

*   Provide a mechanism for an OpenGL application to learn about
    graphics resets that affect the context.  When a graphics reset
    occurs, the OpenGL context becomes unusable and the application
    must create a new context to continue operation. Detecting a
    graphics reset happens through an inexpensive query.

But such a _graphics reset does not unbind the current GL context - the affected context is just not usable any more.


text:
Q: Django: Where does this zip file create to? For some context, I have a django-rest-framework project. This particular endpoint takes a json blob, and zips it before saving it to a FileField. My question is– where exactly is this zip file I'm creating saving to? Just the root directory? Will these regularly need to be cleaned up?
class MyModel(models.Model):
    ...
    def create_zip(self, user, jsondata):
        filename = "data" + ".zip"
        with gzip.GzipFile(filename, "w") as fout:
            fout.write(jsondata.encode("utf-8"))

        my_model = MyModel.objects.create(
            user=user, animation_file=filename
        )

A: Yes, it seems that the zip file is created in the current directory of your project script. And that needs to be cleaned up.
A more clear way to do this is to use some temp directory. For e.g. you may create a setting TEMP_ROOT and prefix your file with the temp root path using os module i.e
from django.conf import settings

import os
file_path = os.path.join(settings.TEMP_ROOT, filename)

and use this file_path to be given to gzip.GzipFile() method instead of filename.
Please make sure that the temp directory exists already.


text:
Q: How can System.Object.GetType throw NullRefernceException I have .NET application that crashes with NullReferenceException. The funny thing is that the log shows this:
Inner Exception System.NullReferenceException: Object reference not set to an instance of an object.
           at System.Object.GetType()

The thing that's puzzling me is that the exception happens inside of GetType instead on the line that calls GetType. I've tested following situations.
If I call GetType on an object that is null, the exception happens on a line that's calling GetType, not within GetType.
I also tried How can I get a NullReferenceException in this code sample? but strangely
I get the exception in Program.Main not within Object.GetType (although in that post it's within GetType).
I also tried concurrently creating objects and calling GetType, but needlesly to say,
there is no window in creation of .net objects where GetType throws NullReferenceException.
The only thing that crosses my mind right now is that this was maybe behavior of some older .NET implementation.
So any idea how to cause NullReferenceException within GetType, and if you could provide proof of concept code I would be eternally grateful.
Thank you for your time.

A: One way would be to call the GetType method ("on" a null-reference) with the call instruction rather than the with the callvirt instruction that C# normally uses. This will prevent the pre-method-call runtime null-check from occurring. Instead, the null-reference would be passed to the method, causing the exception to be thrown inside the method itself.
For example, using the InvokeNonVirtual sample provided here, you can do:
var method = typeof(object).GetMethod("GetType");
object[] args = { null };

InvokeNonVirtual(method, args);

This produces a TargetInvocationException with the InnerException being a NullReferenceException having  stack-trace:
at System.Object.GetType()
at NonVirtualInvoker(Object )

A: I know this post is a little old, but I thought this problem was worth investigating further.
Although the stack trace now doesn't have the additional stack trace line 'at System.Object.GetType()', I managed to replicate most of the error in a small demo application.
I don't really know what is causing it, but I narrowed the suspects down to the DataGrid, ComboBox.SelectedIndex property or the markup extension. If I replace any of these three, the problem goes away, or a different error is shown which is more understanable.
The main window: (a DataGrid with an editable column)
<Window       x:Class="WpfApplication2.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:src="clr-namespace:WpfApplication2"
                Title="MainWindow"
               Height="350"
                Width="525"
                     >
    <DataGrid ItemsSource="{Binding Items}">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Column 1" Width="120">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Description}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox SelectedIndex="{src:ValidatedBinding SelectedIndex}"
                                  VerticalAlignment="Center" HorizontalAlignment="Center" Width="100">
                            <ComboBoxItem>Not Specified</ComboBoxItem>
                            <ComboBoxItem>First</ComboBoxItem>
                            <ComboBoxItem>Second</ComboBoxItem>
                        </ComboBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Window>

The code driving this window:
using System.Windows;

namespace WpfApplication2
{
    /// <summary>
    /// The main window.
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //DataContext = new Item { Description = "Item 1", SelectedIndex = 0 };

            DataContext = new DemoDataContext();
        }
    }

    /// <summary>
    /// An object with 'Items'.
    /// </summary>
    public sealed class DemoDataContext
    {
        readonly Item[] _items = new Item[] {
            new Item { Description = "Item 1", SelectedIndex = 0 },
            new Item { Description = "Item 2", SelectedIndex = 1 },
            new Item { Description = "Item 3", SelectedIndex = 2 },
        };

        public Item[] Items { get { return _items; } }
    }

    /// <summary>
    /// An object with a string and an int property.
    /// </summary>
    public sealed class Item
    {
        int _selectedIndex;
        string _description;

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

        public int SelectedIndex
        {
            get { return _selectedIndex; }
            set { _selectedIndex = value; }
        }
    }
}

The markup extension code:
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace WpfApplication2
{
    /// <summary>
    /// Creates a normal Binding but defaults NotifyOnValidationError and ValidatesOnExceptions to True,
    /// Mode to TwoWay and UpdateSourceTrigger to LostFocus.
    /// </summary>
    [MarkupExtensionReturnType(typeof(Binding))]
    public sealed class ValidatedBinding : MarkupExtension
    {
        public ValidatedBinding(string path)
        {
            Mode = BindingMode.TwoWay;

            UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;

            Path = path;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var Target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

            /* on combo boxes, use an immediate update and validation */
            DependencyProperty DP = Target.TargetProperty as DependencyProperty;
            if (DP != null && DP.OwnerType == typeof(System.Windows.Controls.Primitives.Selector)
                && UpdateSourceTrigger == UpdateSourceTrigger.LostFocus) {
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            }

            return new Binding(Path) {
                Converter = this.Converter,
                ConverterParameter = this.ConverterParameter,
                ElementName = this.ElementName,
                FallbackValue = this.FallbackValue,
                Mode = this.Mode,
                NotifyOnValidationError = true,
                StringFormat = this.StringFormat,
                ValidatesOnExceptions = true,
                UpdateSourceTrigger = this.UpdateSourceTrigger
            };
        }

        public IValueConverter Converter { get; set; }

        public object ConverterParameter { get; set; }

        public string ElementName { get; set; }

        public object FallbackValue { get; set; }

        public BindingMode Mode { get; set; }

        [ConstructorArgument("path")]
        public string Path { get; set; }

        public string StringFormat { get; set; }

        public UpdateSourceTrigger UpdateSourceTrigger { get; set; }
    }
}

When I run the application, I see this:

If I click again on the first column, taking the cell into edit mode, I get this exception:

System.NullReferenceException was unhandled   HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=PresentationFramework   StackTrace:
         at System.Windows.Data.BindingExpressionBase.ConvertValue(Object value,
  DependencyProperty dp, Exception& e)
         at System.Windows.Data.BindingExpressionBase.ConvertFallbackValue(Object
  value, DependencyProperty dp, Object sender)
         at System.Windows.Data.BindingExpressionBase.get_FallbackValue()
         at System.Windows.Data.BindingExpressionBase.UseFallbackValue()
         at System.Windows.Data.BindingExpressionBase.get_Value()
         at System.Windows.Data.BindingExpressionBase.GetValue(DependencyObject d,
  DependencyProperty   (trimmed)

If I simplify the main window, and remove everything except the ComboBox, and uncomment the line which will create a valid DataContext item, then I get this error:

System.Windows.Markup.XamlParseException occurred
  HResult=-2146233087   Message='Set property
  'System.Windows.Controls.Primitives.Selector.SelectedIndex' threw an
  exception.' Line number '19' and line position '39'.
  Source=PresentationFramework   LineNumber=19   LinePosition=39
  StackTrace:
         at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean
  skipJournaledProperties, Object rootObject, XamlObjectWriterSettings
  settings, Uri baseUri)
         at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject,
  XamlAccessLevel accessLevel, Uri baseUri)
         at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
         at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
         at WpfApplication2.MainWindow.InitializeComponent() in c:\Users\Administrator\Documents\Visual Studio
  2012\Projects\WpfApplication2\MainWindow.xaml:line 1
         at WpfApplication2.MainWindow..ctor() in c:\Users\Administrator\Documents\Visual Studio
  2012\Projects\WpfApplication2\MainWindow.xaml.cs:line 12
  InnerException: System.ArgumentException
         HResult=-2147024809
         Message='System.Windows.Data.Binding' is not a valid value for property 'SelectedIndex'.
         Source=WindowsBase
         StackTrace:
              at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp,
  Object value, PropertyMetadata metadata, Boolean
  coerceWithDeferredReference, Boolean coerceWithCurrentValue,
  OperationType operationType, Boolean isInternal)
              at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object
  value)
              at System.Windows.Baml2006.WpfMemberInvoker.SetValue(Object instance,
  Object value)
              at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member,
  Object obj, Object value)
              at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst,
  XamlMember property, Object value)
         InnerException:


text:
Q: How to Add Two Input Values And Show In The Third Input Box ?? with simple JavaScript like this help me where i was wrong 1)I want to add the values of two input boxes and show it in the third input. It shows an error
2)Error:  Uncaught TypeError: Cannot read property 'value' of null
at sum (js.php:21)
at HTMLButtonElement.onclick (js.php:12)
<!DOCTYPE html>

    <title>JavaScript</title>

    <input type="text" name="val1">

    <input type="text" name="val2">

    <input disabled name="total" value="">

    <button type="button" onclick="sum()" name="btn">Add</button>

I expected the sum of two inputs but it shows nothing.

A: document.getElementsByName returns a NodeList of elements so it doesn't have property .value.
This is getElementsByName snippet.

<!DOCTYPE html>

  <title>JavaScript</title>

  <input type="text" name="val1">

  <input type="text" name="val2">

  <input type="hidden" name="total" value="">

  <button type="button" onclick="sum()" name="btn">Add</button>

This is getElementById snippet

<!DOCTYPE html>

  <title>JavaScript</title>

  <input type="text" name="val1" id="val1">

  <input type="text" name="val2" id="val2">

  <input type="hidden" name="total" value="" id="total">

  <button type="button" onclick="sum()" name="btn">Add</button>

A: You should add Id to your input. You use getElementById, but your input doesn't have any id, so it will retourn null.
<input type="text" name="val1" id="val1">

<input type="text" name="val2" id="id="val2">

<input type="hidden"  name="total" value="" id="total">

A: Try This

    <input type="text" name="val1" id="val1">

    <input type="text" name="val2" id="val2">

     <input type="hidden"  name="total" id="total" value="">

     <button type="button" onclick="sum()" name="btn">Add</button>

OR Fetch through name

    <input type="text" name="val1" >

    <input type="text" name="val2" >

     <input type="hidden"  name="total" value="">

     <button type="button" onclick="sum()" name="btn">Add</button>

A: You are using HTML DOM getElementById() Method, so you should assign an Id to your input total in order to resolve the issue:
<input type="hidden" name="total" id="total" value="">

A: You should have the attribute id for the controls which you are referencing in your code with getElementById(). You also have to convert the string value to number to perform the arithmetic operation:

function sum(){
  var val1 = document.getElementById('val1').value;
  var val2 = document.getElementById('val2').value;
  var sum = Number(val1) + Number(val2);
  document.getElementById('total').value = sum;
}
<input type="text" name="val1" id="val1">

<input type="text" name="val2" id="val2">

<input name="total" id="total" value="">

<button type="button" onclick="sum()" name="btn">Add</button>

A: You can do with click on button to sum of two input value OR with use of onblur events also

                <input type="text" id="val1" onblur="sum()">

                <input type="text" id="val2" onblur="sum()">

                <input id="total" value="">

                <button type="button" onclick="sum()" name="btn">Add</button>

A: You should use id attribute to get the input value which you are referencing in your code with getElementById().
and You also have to convert the string value to number to perform the arithmetic operation because when we get value from inputs it will a string value
for convert string to number you can use + sign like in code
<!DOCTYPE html>

    <title>JavaScript</title>

  <input type="text" name="val1" id="val1">

  <input type="text" name="val2" id="val2">

    <input type="hidden"  name="total" id="total" value="">

    <button type="button" onclick="sum()" name="btn">Add</button>


text:
Q: Synchronization of data across microservices We have 2 to 3 dozen microservices that serve our customers.
These services are deployed in a Kubernetes cluster, and they're only accessible to the outside world through 3 or 4 API gateways.
We found that sometimes the same data is needed by two or more microservices, so we evaluated a couple of strategies to solve this problem and have implemented a solution in pieces.
Like any design, we are not 100% sure if we're using the right approach, and whether we're missing potential pitfalls in the design.
Case 1:
When a service of lesser business importance ServiceL needs data from a service of higher business importance ServiceH, then
ServiceL calls ServiceH directly to get the necessary data.
Case 2:
When a service of lesser business importance ServiceL needs data from many important services ServiceH1, ServiceH2, etc), then
ServiceH1, ServiceH2 publish messages with that data to RabbitMQ.
The publishing of messages is fire-and-forget, so the services are not blocked.
ServiceL subscribes to these messages and stores the data in its own data store.
We are okay with the delay in the data becoming available to ServiceL.
Case 3:
When a service of higher business importance ServiceH needs data from a less-important service ServiceL, then ServiceL publishes a message with that data to RabbitMQ via a fire-and-forget or blocking mechanism, depending on urgency of syncing the data.
ServiceH consumes the message and stores it in its data store.
Often the data is needed by ServiceH for reports and summary, and we are okay with the summary not being perfectly up to date at all times (eventually consistent) .
Case 4:
When data is needed by two services and both of them not only read data but also modify it, then we believe the domain identification is wrong in which case we redesign them, often merging these two microservices into one.
Additional Info for Case 2 & 3:
Now when we use a messaging framework like RabbitMQ for syncing data across services, over a period of time we observed data is getting out of sync between services.
When data gets out of sync, we could see the statistics from RabbitMQ and replay messages, but we believe this brings in unnecessary complexity.
We've ended up running jobs once a day to sync the data from the source service to the destination service, where the data is retrieved from the applicable services and not directly from their data stores.
Is this a good approach to sync data between microservices? Are there any pitfalls?

A: I would take a look at one of Microsoft's newer projects code named "Ambrosia" (link will take you to their Github page where the project is being developed open source) which focuses on providing a solution to this exact problem and several other major data consistency problems when developing distributed services.
The cliff-notes version is that they provide Virtual Resiliency which they desribe as the holding the following meaning:

Virtual Resiliency is a mechanism in a (possibly distributed) programming and execution environment, typically employing a log, which exploits the replayably deterministic nature and serializability of an application to automatically mask failure.

With one of the key benefits of utilizing the Ambrosia project being, that you are then provided with a layer of abstraction over the top of all the Transient Fault handling and Data Consistency problems, which are encountered thanks to the transport layer's reliability! This means that your developers DO NOT have to write any fault handling or data consistency into your code base as the underlying Ambrosia framework manages all of those cross cutting issues, as well as handling reconnecting any disconnected connections (tunnels, ssh, etc).
All of the information below, is taken straight from the project's Github page, and you can thus find this information and much, much more detailed sample use cases, etc. by following the link in the first paragraph above! I hope that this helps you guys out! It has been working great for the projects I currently am running in cloud native context!

How it works

The figure below outlines the basic architecture of an AMBROSIA application, showing two communicating AMBROSIA services, called Immortals. Each inner box in the figure represents a separate process running as part of the Immortal. Each instance of an Immortal exists as a software object and thread of control running inside of an application process. An Immortal instance communicates with other Immortal instances through an Immortal Coordinator process, which durably logs the instance's RPCs and encapsulates the low-level networking required to send RPCs. The position of requests in the log determines the order in which they are submitted to the application process for execution and then re-execution upon recovery.

Ambrosia Architecture

In addition, the language specific AMBROSIA binding provides a state serializer. To avoid replaying from the start of the service during recovery, the Immortal Coordinator occasionally checkpoints the state of the Immortal, which includes the application state. The way this serialization is provided can vary from language to language, or even amongst bindings for the same language.

A: I'd avoid the separation into "high-business importance" and "low-business importance". Seems like an arbitrary distinction, and one which could change from outside reasons - new business focus, better understanding of the domain etc. - leaving you with some hard-to-change architectural decisions. I'm curious to why this separation exists and what are it's implications on the development side for you?
In general, you should prefer RPCs/direct calls between services whenever possible, and leave queues and other communication mechanisms for special cases - which usually involve performance. And even in those cases, I'd much rather have some backend job doing some eventually consistent update of derived data, than have some services listening on a queue do the same thing in a "streaming" fashion. Many/all of the cases I've encountered in practice of having queues, could have been replaced by a more robust "backend job". It doesn't have to be Hadoop or anything fancy though - just a periodically running binary / cron can do it. There's always a lot of ceremony around queues and services. Many times there's a write to the db and a write to the queue. Which needs special care - tracking of which write was sent, reconciliation jobs for failed writes, retries etc. Not to mention that it makes reasoning about the system harder, backfilling super-hard, local testing grosser etc.


text:
Q: Generated DocSet causes Xcode 4.6 crash I currently use Xcode 4.6.
I wrote a script in order to generate HTML and DocSet documentation (XCode Run Script).
My script work like a charm. I'm able to access HTML documentation and also
(re)load it within Xcode.
However accessing of some of my tabs like "Main Page" or "Related Pages" causes
Xcode crash.
If you've any ideas about a temporary solutions (maybe in doxygen conf file ?), I'm interested !
Best regards !
Pebie
PS : I've bug report with file attachement here : https://bugzilla.gnome.org/show_bug.cgi?id=697706

A: It seems this is not a doxygen bug but Apple one.
See answers here from doxygen team : https://bugzilla.gnome.org/show_bug.cgi?id=697706
Best regards !


text:
Q: How to masking a credit card number in Nativescript Angular I want to display credit card number as 1234****6789 format in my Nativescript Angular app.
My data source is an array. I am displaying list of credit card numbers in a Listview.
let creditCards = [
            {
                cardNo : 123456789,
                expiryDate: 25/12/2020,
            },
            {
                cardNo : 987654321,
                expiryDate: 25/12/2020,
            },

        ];

Html
<ListView [items]="creditCards">
     <ng-template let-item="item">
         <GridLayout rows="*,*" columns="*,*">

         </GridLayout>
      </ng-template>
</ListView>

I know, I can achieve this by replacing the cardNo string. But
What is the best way to masking the credit card number without modifying the actual data source.
Can this be done in html/css?

A: It occurs to me that before displaying the array data, you pass the fix by a masked function and then show it in the list you need.
http://www.forosdelweb.com/f13/enmascarar-input-tarjeta-credito-954207/


text:
Q: Cannot import 'swish' in 'tensorflow.python.keras.activations' I am running a jupyter notebook from an Anaconda Prompt (Anaconda 3), and I am trying to use tensorflow keras.
I am trying to run the import statement:
from tensorflow.keras.models import Sequential

I get the following error:
ImportError                               Traceback (most recent call last)
<ipython-input-1-d23f18c08372> in <module>
      4 from keras.models import Model
      5
----> 6 from tensorflow.keras.models import Sequential
      7
      8 from tensorflow.keras.layers import Dense, Activation, Dropout

~\Anaconda3\lib\site-packages\tensorflow\keras\__init__.py in <module>
     12 import sys as _sys
     13
---> 14 from . import activations
     15 from . import applications
     16 from . import backend

~\Anaconda3\lib\site-packages\tensorflow\keras\activations\__init__.py in <module>
     21 from tensorflow.python.keras.activations import softplus
     22 from tensorflow.python.keras.activations import softsign
---> 23 from tensorflow.python.keras.activations import swish
     24 from tensorflow.python.keras.activations import tanh
     25

ImportError: cannot import name 'swish' from 'tensorflow.python.keras.activations' (C:\Users\FlamePrinz\Anaconda3\lib\site-packages\tensorflow\python\keras\activations.py)

A: Try this way
from keras.utils.generic_utils import get_custom_objects
from keras.layers import Activation
get_custom_objects().update({'swish': Activation(swish)})

swish function needs to be passed into activation class to actually build it.
And then you can do
model.add(Dense(64, activation = "swish"))

A: You can download swish activation from pypi. Try the following:

*

*pip install swish-activation

*import swish_package

*from swish_package import swish

A: This is an older question, but I ended up taking Dr. Snoopy's suggestion uninstalling and reinstalling TensorFlow which solved my issue.


text:
Q: Converting the text file into a string or list I have the following data in my text file:
5*0 4 3 2 5 7 7 3 6 3 2 6
8*2 4 5 6 7 8 7 3 7 7 3
I want to work on the data in python. so, I guessed it is better to convert it to string or list.
I used the following code:
a = open('test.txt', 'r')
b = a.readlines()
c = [x.replace('\n','') for x in b]
print(c)

but it gives:
['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']

I wondered to know how I can convert it to the following:
['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

A: try this
a = open('test.txt', 'r')
b = a.readlines()

new_list = []
for line in b:
    for item in line.strip().split():
        new_list.append(item)
print(new_list)

A: I would simply change the readlines by the read method (does not split the lines into different list items), then change the '\n' newline character by spaces and finally split the string by spaces.
a = open('test.txt', 'r')
b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
a.close()
print(c)

I would suggest to use the with statement so as to not forget to close the file
with open('test.txt', 'r') as a:
    b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
print(c)

A: I will convert this to list compression and edit the post, but here it is without
a = open('test.txt', 'r')
b = a.readlines()
c = [a for n in str(b).split('\n') for a in n.split(' ') if a != '']
print(c)

>>> ['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

A: you can do like this
c=['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
c=[j for i in c for j in i.split()]
print(c)

output
['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

A:  with open('test.txt') as file:
        print(file.read().split())

I used the with method to open and read the file along with the .read() method which reads the whole file instead of one line at a time, then the .split() method splits string at each ' ', returning a list.


text:
Q: How can I check the current time on a droid device and put that into an integer? I know there is the Date() class built into the API, but what line of code actually grabs the time of day?

A: use this Calendar.get(Calendar.HOUR_OF_DAY) take a look at link text

A: The getTime() method returns the number of milliseconds since 1970.  However, it's a long and will not fit into an integer.
Date now = new Date();
long millis = now.getTime();

A: See System in Android docs for proper uses, but you could
import java.lang.System;

long now = System.getcurrentTimeMillis()


text:
Q: Query a JSON array in Mysql I have the following JSON object.
SET @j = '{"id": [1, 2, 4]}'

I'm trying to query the JSON object to find if the id contain 2 in it.
select JSON_CONTAINS(@j,'one','%2')

I don't think the above JSON_CONTAINS are correct but I'm not sure what would I do to run it.

A: You could try this
SELECT JSON_SEARCH(JSON_EXTRACT(@j, "$.id"), 'one', '2');

A: Sorry @rev_dihazum that did not work but this did.
SELECT JSON_CONTAINS(@j, '1', '$.id');


text:
Q: Determine the center of mass of a triangular lamina shown whose density at any point is equal to its distance from the x-axis. Determine the center of mass of a triangular lamina shown whose density at any point is equal to its distance from the x-axis.
The triangle has vertices at (0,0)(3,9)(7,0).

A: It can be done by one-variable methods, but because of the tag we use two variables. Let $T$ be our triangle. Then the mass $m$ is given by
$$m=\iint_T y \,dx\,dy.$$
The moment $A$ about the $y$-axis is given by
$$\iint_T xy \,dx\,dy.$$
The moment $B$ about the $x$-axis is given by
$$\iint_T y^2 \,dx\,dy.$$
The centre of mass is $\left(\frac{A}{m},\frac{B}{m}\right)$.
There are $3$ double integrals to evaluate.


text:
Q: Is there a way to set up structured streaming with pyspark from Kafka to Cassandra I'm writing some script for analytics in Pyspark. And I can not set up streaming to Cassandra from Kafka. When it's one data it is ok, but when is streaming it wont work.
I'm reading about some way with foreachBatch, but I'm new in Pyspark, and I can't successfully write down that, because documentation for that is lame.
Can someone help me about foreachBatch in my script.
I'm providing datas from Kafka topic to Cassandra.
import os, json, time
from pyspark.sql import  functions as F
from pyspark.sql import types
from pyspark.sql import SparkSession

def parse_value(value):
    value_object = json.loads(value)
    return [value_object["topicData"]["serialNumber"]+":"+str(value_object["msg"]["params"]["device_id"])+":"+str(value_object["msg"]["timestamp"]),
    value_object["msg"]["params"]["service_name"],
    str(value_object["msg"]["timestamp"]),
    value_object["msg"]["params"]["property_value"]]

parse_value_udf = F.udf(lambda x: parse_value(x), types.ArrayType(types.StringType()))

spark = SparkSession \
    .builder \
    .appName("StructuredNetworkWordCount") \
    .getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

df = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "localhost:9092") \
  .option("subscribe", "topicsForEvents123") \
  .load() \
  .selectExpr("CAST(value AS STRING)")

df = df.withColumn('_id', parse_value_udf(df.value)[0]).withColumn('property_name', parse_value_udf(df.value)[1]).withColumn('time', parse_value_udf(df.value)[2]).withColumn('value', parse_value_udf(df.value)[3])

df = df.select('_id','property_name','time','value')
query = df \
    .writeStream \
    .outputMode("append") \
    .format("org.apache.spark.sql.cassandra") \
    .option("property_change","strat_history_keyspace_cassandra_raw1")\
    .start()

query.awaitTermination()

I just want someone to show me example of foreachBatch in Pyspark on this script, if it is ok to try. Because I can't understand documentation and how to put this, with my piece of code.
DOCUMENTATION SAYS:
def foreach_batch_function(df, epoch_id):
    # Transform and write batchDF
    pass

streamingDF.writeStream.foreachBatch(foreach_batch_function).start()

And I can't understand how to send df and epoch_id. Where to find id, and which exactly df to send function as a parameter.

A: foreachBatch is an output sink that let you process each streaming micro-batch as a non-streaming dataframe.
If you want to try a minimal working example you can just print the dataframe to the console:
def foreach_batch_function(df, epoch_id):
    df.show()

df.writeStream \
    .outputMode("append") \
    .foreachBatch(foreach_batch_function) \
    .start() \
    .awaitTermination()

There is nothing else to do.
Spark reads from the input stream (Kafka) continuously and send each micro-batch to the function you defined (foreach_batch_function) automatically.
The function will receive the dataframe and the batch id. You don't have to call the function manually.
At this point you can treat the dataframe as a batch dataframe and perform all the transformations and actions you want.
If you want to output the micro-batch dataframe to Cassandra you need to edit the foreach_batch_function function like
def foreach_batch_function(df, epoch_id):
    df.write \
        .format("org.apache.spark.sql.cassandra") \
        .mode('append') \
        .options(table="TABLE_NAME", keyspace="KEYSPACE_NAME") \
        .save()


text:
Q: Android SQLite issue - table __ has no column named ___ I am a new developer and I am having an SQLite issue.  Some reason I am not able to add two columns (table_row_three, and table_row_four) to my SQLite data table.  When I read the database file currently, it has a table with "id", "table_row_one", and "table_row_two", but is missing "table_row_three" and "table_row_four".
The error message in my logcat reads: "(1) table database_table has no column named table_row_three".
I am really confused to why the columns "table_row_three" and "table_row_four" are not showing up on my table, and why only "id", "table_row_one", and "table_row_two" appear in my data table.
Here is my Database class:
DatabaseHandler.java

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler
{

Context context;

private SQLiteDatabase db;

private final String DB_NAME = "database_name";
private final int DB_VERSION = 2;

private final String TABLE_NAME = "database_table";
private final String TABLE_ROW_ID = "id";

private final String TABLE_ROW_ONE = "table_row_one";
private final String TABLE_ROW_TWO = "table_row_two";
private final String TABLE_ROW_THREE = "table_row_three";
private final String TABLE_ROW_FOUR = "table_row_four";

public DatabaseHandler(Context context)
{
    this.context = context;

    // create or open the database
    CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
    this.db = helper.getWritableDatabase();
}

public void addRow(String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
    // this is a key value pair holder used by android's SQLite functions
    ContentValues values = new ContentValues();
    //TABLE_ROW_ONE = Title
    //TABLE_ROW_TWO = Location
    //TABLE_ROW_THREE = Notes
    //TABLE_ROW_FOUR = Picture
    values.put(TABLE_ROW_ONE, rowStringOne);
    values.put(TABLE_ROW_TWO, rowStringTwo);
    values.put(TABLE_ROW_THREE, rowStringThree);
    values.put(TABLE_ROW_FOUR, rowStringFour);

    // ask the database object to insert the new data
    try{db.insert(TABLE_NAME, null, values);}
    catch(Exception e)
    {
        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }
}

public void deleteRow(long rowID)
{
    // ask the database manager to delete the row of given id
    try {db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);}
    catch (Exception e)
    {
        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }
}

public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
    ContentValues values = new ContentValues();
    values.put(TABLE_ROW_ONE, rowStringOne);
    values.put(TABLE_ROW_TWO, rowStringTwo);
    values.put(TABLE_ROW_THREE, rowStringThree);
    values.put(TABLE_ROW_FOUR, rowStringFour);

    try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
    catch (Exception e)
    {
        Log.e("DB Error", e.toString());
        e.printStackTrace();
    }
}

public ArrayList<Object> getRowAsArray(long rowID)
{

    ArrayList<Object> rowArray = new ArrayList<Object>();
    Cursor cursor;

    try
    {

        cursor = db.query
                (
                        TABLE_NAME,
                        new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR },
                        TABLE_ROW_ID + "=" + rowID,
                        null, null, null, null, null
                );

        cursor.moveToFirst();

        if (!cursor.isAfterLast())
        {
            do
            {
                rowArray.add(cursor.getLong(0));
                rowArray.add(cursor.getString(1));
                rowArray.add(cursor.getString(2));
                rowArray.add(cursor.getString(3));
                rowArray.add(cursor.getString(4));
            }
            while (cursor.moveToNext());
        }

        cursor.close();
    }
    catch (SQLException e)
    {
        Log.e("DB ERROR", e.toString());
        e.printStackTrace();
    }

    // return the ArrayList containing the given row from the database.
    return rowArray;
}

public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
{

    ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();

    Cursor cursor;

    try
    {
        cursor = db.query(
                TABLE_NAME,
                new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR},
                null, null, null, null, null
        );

        cursor.moveToFirst();

        if (!cursor.isAfterLast())
        {
            do
            {
                ArrayList<Object> dataList = new ArrayList<Object>();

                dataList.add(cursor.getLong(0));
                dataList.add(cursor.getString(1));
                dataList.add(cursor.getString(2));
                dataList.add(cursor.getString(3));
                dataList.add(cursor.getString(4));
                dataArrays.add(dataList);
            }
            while (cursor.moveToNext());
        }
    }
    catch (SQLException e)
    {
        Log.e("DB Error", e.toString());
        e.printStackTrace();
    }

    return dataArrays;
}

private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
    public CustomSQLiteOpenHelper(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {

        String newTableQueryString = "create table " +
                TABLE_NAME +
                " (" +
                TABLE_ROW_ID + " integer primary key autoincrement not null," +
                TABLE_ROW_ONE + " text," +
                TABLE_ROW_TWO + " text" +
                TABLE_ROW_THREE + " text" +
                TABLE_ROW_FOUR + " text" +
                ");";
        db.execSQL(newTableQueryString);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {

    }
}

Here is my Test class:
public class DatabaseExampleActivity extends Activity {
EditText textFieldOne, textFieldTwo, textFieldThree, textFieldFour,
        idField,
        updateIDField, updateTextFieldOne, updateTextFieldTwo,updateTextFieldThree, updateTextFieldFour;

Button addButton, deleteButton, retrieveButton, updateButton;

TableLayout dataTable;

DatabaseHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    // this try catch block returns better error reporting to the log
    try {
        // Android specific calls
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_databaseexample);

        // create the database manager object
        db = new DatabaseHandler(this);

        // create references and listeners for the GUI interface
        setupViews();

        // make the buttons clicks perform actions
        addButtonListeners();

        // load the data table
        updateTable();
    } catch (Exception e) {
        Log.e("ERROR", e.toString());
        e.printStackTrace();
    }
}

private void setupViews() {
    // THE DATA TABLE
    dataTable = (TableLayout) findViewById(R.id.data_table);

    // THE DATA FORM FIELDS
    textFieldOne = (EditText) findViewById(R.id.text_field_one);
    textFieldTwo = (EditText) findViewById(R.id.text_field_two);
    textFieldThree = (EditText) findViewById(R.id.text_field_three);
    textFieldFour = (EditText) findViewById(R.id.text_field_four);
    idField = (EditText) findViewById(R.id.id_field);
    updateIDField = (EditText) findViewById(R.id.update_id_field);
    updateTextFieldOne = (EditText) findViewById(R.id.update_text_field_one);
    updateTextFieldTwo = (EditText) findViewById(R.id.update_text_field_two);
    updateTextFieldThree = (EditText) findViewById(R.id.update_text_field_three);
    updateTextFieldFour = (EditText) findViewById(R.id.update_text_field_four);

    addButton = (Button) findViewById(R.id.add_button);
    deleteButton = (Button) findViewById(R.id.delete_button);
    retrieveButton = (Button) findViewById(R.id.retrieve_button);
    updateButton = (Button) findViewById(R.id.update_button);
}

private void addButtonListeners() {
    addButton.setOnClickListener
            (
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addRow();
                        }
                    }
            );

    deleteButton.setOnClickListener
            (
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            deleteRow();
                        }
                    }
            );

    updateButton.setOnClickListener
            (
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateRow();
                        }
                    }
            );

    retrieveButton.setOnClickListener
            (
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            retrieveRow();
                        }
                    }
            );

}

private void addRow() {
    try {
        // ask the database manager to add a row given the two strings
        db.addRow
                (
                        textFieldOne.getText().toString(),
                        textFieldTwo.getText().toString(),
                        textFieldThree.getText().toString(),
                        textFieldFour.getText().toString()

                );

        // request the table be updated
        updateTable();

        // remove all user input from the Activity
        emptyFormFields();
    } catch (Exception e) {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }
}

private void deleteRow() {
    try {
        // ask the database manager to delete the row with the give rowID.
        db.deleteRow(Long.parseLong(idField.getText().toString()));

        // request the table be updated
        updateTable();

        // remove all user input from the Activity
        emptyFormFields();
    } catch (Exception e) {
        Log.e("Delete Error", e.toString());
        e.printStackTrace();
    }
}

private void retrieveRow() {
    try {
        // The ArrayList that holds the row data
        ArrayList<Object> row;
        // ask the database manager to retrieve the row with the given rowID
        row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString()));

        // update the form fields to hold the retrieved data
        updateTextFieldOne.setText((String) row.get(1));
        updateTextFieldTwo.setText((String) row.get(2));
        updateTextFieldThree.setText((String) row.get(3));
        updateTextFieldFour.setText((String) row.get(4));

    } catch (Exception e) {
        Log.e("Retrieve Error", e.toString());
        e.printStackTrace();
    }
}

private void updateRow() {
    try {
        // ask the database manager to update the row based on the information
        // found in the corresponding user entry fields
        db.updateRow
                (
                        Long.parseLong(updateIDField.getText().toString()),
                        updateTextFieldOne.getText().toString(),
                        updateTextFieldTwo.getText().toString(),
                        updateTextFieldThree.getText().toString(),
                        updateTextFieldFour.getText().toString()
                );

        updateTable();

        emptyFormFields();
    } catch (Exception e) {
        Log.e("Update Error", e.toString());
        e.printStackTrace();
    }
}

private void emptyFormFields() {
    textFieldOne.setText("");
    textFieldTwo.setText("");
    textFieldThree.setText("");
    textFieldFour.setText("");
    idField.setText("");
    updateIDField.setText("");
    updateTextFieldOne.setText("");
    updateTextFieldTwo.setText("");
    updateTextFieldThree.setText("");
    updateTextFieldFour.setText("");
}

private void updateTable() {
    // delete all but the first row.  remember that the count
    // starts at one and the index starts at zero
    while (dataTable.getChildCount() > 1) {
        // while there are at least two rows in the table widget, delete
        // the second row.
        dataTable.removeViewAt(1);
    }

    // collect the current row information from the database and
    // store it in a two dimensional ArrayList
    ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();

    // iterate the ArrayList, create new rows each time and add them
    // to the table widget.
    for (int position = 0; position < data.size(); position++) {
        TableRow tableRow = new TableRow(this);

        ArrayList<Object> row = data.get(position);

        TextView idText = new TextView(this);
        idText.setText(row.get(0).toString());
        tableRow.addView(idText);

        TextView textOne = new TextView(this);
        textOne.setText(row.get(1).toString());
        tableRow.addView(textOne);

        TextView textTwo = new TextView(this);
        textTwo.setText(row.get(2).toString());
        tableRow.addView(textTwo);

        TextView textThree = new TextView(this);
        textThree.setText(row.get(3).toString());
        tableRow.addView(textThree);

        TextView textFour = new TextView(this);
        textFour.setText(row.get(4).toString());
        tableRow.addView(textFour);

        dataTable.addView(tableRow);
    }
}

A: Missing ',' in create statement :
String newTableQueryString = "create table " +
     TABLE_NAME +
     " (" +
     TABLE_ROW_ID + " integer primary key autoincrement not null," +
     TABLE_ROW_ONE + " text," +
     TABLE_ROW_TWO + " text," +
     TABLE_ROW_THREE + " text," +
     TABLE_ROW_FOUR + " text" +
     ");";

A: String newTableQueryString = "create table " +
            TABLE_NAME +
            " (" +
            TABLE_ROW_ID + " integer primary key autoincrement not null," +
            TABLE_ROW_ONE + " text," +
            TABLE_ROW_TWO + " text" +
            TABLE_ROW_THREE + " text" +
            TABLE_ROW_FOUR + " text" +
            ");";

In this statement you missed two commas after type defind. Thats why the field is not created so you found that exception. And one another thing after the close parenthesis ");" the semicolon is not required.
Replace your code to :-
String newTableQueryString = "create table " +
            TABLE_NAME +
            " (" +
            TABLE_ROW_ID + " integer primary key autoincrement not null," +
            TABLE_ROW_ONE + " text," +
            TABLE_ROW_TWO + " text," +
            TABLE_ROW_THREE + " text," +
            TABLE_ROW_FOUR + " text" +
            ")";

I hope this will help you. :)

A:             TABLE_ROW_TWO + " text" +
            TABLE_ROW_THREE + " text" +
            TABLE_ROW_FOUR + " text" +

put , after text
 TABLE_ROW_TWO + " text," +
            TABLE_ROW_THREE + " text," +
            TABLE_ROW_FOUR + " text" +

A: Change CustomSQLiteOpenHelper code like this,
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
    public CustomSQLiteOpenHelper(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {

        String newTableQueryString = "create table " +
                TABLE_NAME +
                " (" +
                TABLE_ROW_ID + " integer primary key autoincrement not null," +
                TABLE_ROW_ONE + " text," +
                TABLE_ROW_TWO + " text," +
                TABLE_ROW_THREE + " text," +
                TABLE_ROW_FOUR + " text" +
                ");";
        db.execSQL(newTableQueryString);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {

    }
}


text:
Q: Write a new ArrayList Object to a file without overwriting its contents I have this problem: I want to add an ArrayList object to a file "clientes.dat" in order to store information on that file and display it later. However, whenever I write to said file again, the new ArrayList object overwrites the first one.
Here's the code:
import java.io.*;
import java.util.ArrayList;

public class Archivo implements Serializable{

    private static final long serialVersionUID = 1L;

    public static void nuevoCliente(Cliente cliente){
        Cliente wo=cliente;
        File f = new File("clientes.dat");
        ArrayList<Cliente> woi=new ArrayList<>();
        try {
            FileOutputStream fop=new FileOutputStream(f);
            ObjectOutputStream oos=new ObjectOutputStream(fop);
            woi.add(wo);
            oos.writeObject(woi);
            oos.close();

        } catch (IOException e) {
            System.out.println("El Cliente no pudo ser agregado.");
        }
    }

    @SuppressWarnings("unchecked")
    public static void leerCliente() throws IOException, ClassNotFoundException{
         try {
             FileInputStream fis=new FileInputStream("clientes.dat");
             ObjectInputStream ois=new ObjectInputStream(fis);
             ArrayList<Cliente> woi=new ArrayList<>();
             woi=(ArrayList<Cliente>)ois.readObject();

             for(int i=0;i<woi.size();i++){
                 System.out.println(woi.get(i).getNombre());
             }

             ois.close();

         }catch(IOException e){
             System.out.println("El archivo no se pudo leer");
         }

    }
}

I have tried using FileOutputStream fop=new FileOutputStream(f, true); But if I do it that way, the leerCliente() method will only return the first ArrayList that was stored, not the new one.


text:
Q: How to wait for async data to be fetched in angularJS? I have a service that populates a view data. The view data depends on the data that is fetched from the database and it needs to wait until the data is loaded.
E.g:
services.factory('viewService', function (serviceX) {
    var generateView = function (s) {
        var data=[];
        var viewData=[];
        serviceX.getData().then(function (d) {
            data=d;
        });
        console.log("data:"+d);
        for(x in data){
            viewData[x]=data[x].view;
            ....
        }
        return viewData;
    };
    return{
        generateView: generateView
    }
});

The serviceX.getData() already uses the promise pattern. The line for(x in data){ needs that data to generate the viewData.

A: You should use promise to separate concerns :
angular.module('myModule', [])

.factory('Table', function($resource, $q) {
  return {
    data: function() {
      edsql = edsql || '';
      var deferred = $q.defer();
      $resource('my-resource-url').get({}, function(r) {
        deferred.resolve(r);
      }, deferred.reject);

      return deferred.promise;
    }
  };
});

And use it as follows in your controller :
$scope.data = Table.data();

A: You can just bind it to your scope variable. AngularJS will wait automatically for the data and then starts rendering. Of course, you need to modify the data that is fetched from within the callback function before setting it on the scope.
In your case this means that your service's generateView method needs to return a promise which you can than set on your scope variable.

A: Another way is to use deferred & promise.
More info here: http://docs.angularjs.org/api/ng.$q


text:
Q: A cross table in R I have a data frame like this one:
   v1   v2  wght
1  3    5   0.2
2  2    8   0.5
3  3    5   0.6
................

So I want to produce some descriptive statistics for multiple variables, a cross table more precisely. The values of v1 and v2 are all integers between 1 and 10 and wght is a weight variable. The desired result should be a data frame like this one for example:
        v2_1 ... v2_5 ... v2_8 ...   v2_10
v1_1
v1_2                       0.5
v1_3         0.8=0.2+0.6
...
v1_10

where in each cell you have the number of people who are v2_i amongst those who have v1_j for i and j in [1:10]. These data should be weighted by wght.
I tried using Crosstable but the results are impossible to be used afterwards because I need a data frame. Thanks in advance

A: Try
library(reshape2)
df1[1:2] <- lapply(df1[1:2], function(x) factor(x, levels=1:10))
res1 <- as.data.frame(acast(df1, v1 ~v2 , value.var='wght',
                         fill=0, drop=FALSE, sum))

Or
as.data.frame.matrix(xtabs(wght~v1+v2, df1))

data
set.seed(24)
df1 <- data.frame(v1= sample(1:10, 20, replace=TRUE),
      v2= sample(1:10, 20, replace=TRUE), wght=rnorm(20))


text:
Q: wpf fire PropertyChanged event in binding source that binding gets updated I'm trying to make some CustomControl Textboxes with validation features.
(for example a number only textbox or a zip-code textbox etc.)
It should realized in a .dll library file.
My project contains a CustomControl for the textbox, a class wich handles the validations,
and a ErrMsgGui CustomControl that should show a error message in a TextBlock
(exmp.: Only numbers allowed...)
My problem is that I don't get the TextBlock Text updated when a method in the validation class is called
Is there a way to trigger the PropertyChangeEvent which updates the Textblock text within the validaiton class?
(Im quite new to wpf)
Generic.xaml:
<Style TargetType="{x:Type local:NumTb}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:NumTb}">
                    <TextBox Background="{TemplateBinding Background}" Text="{Binding Source={StaticResource NumTbVm}, Path=NumTbText, UpdateSourceTrigger=PropertyChanged}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="{x:Type local:ErrMsgGui}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ErrMsgGui}">
                <TextBlock Text="{ Binding  Source={StaticResource val}, Path=ErrMsgGuiText, UpdateSourceTrigger=PropertyChanged}" Background="{TemplateBinding Background}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Validations.cs:
    private const string ONLY_NUMBERS_REGEX = @"^[0-9]+$";  //Nur Zahlen

    private string _ErrMsgGuiText;
    public string ErrMsgGuiText
    {
        get { return _ErrMsgGuiText; }
        set
        {
            _ErrMsgGuiText = value;
            Debug.Print("QueryText: " + value);
            OnPropertyChanged("ErrMsgGuiText");
        }
    }

    public object[] onlyNumbers(string s2c, bool output)
    {
        object[] objRes = new object[2];
        bool result = true;
        string errMsg = "";

        Regex regex = new Regex(ONLY_NUMBERS_REGEX);

        if (s2c != null && s2c != "" && !regex.IsMatch(s2c))
        {
            result = false;
            errMsg = "Nur Zahlen sind zulässig";
        }

        objRes[0] = result;
        objRes[1] = errMsg;

        if (output == true)
        {
           ErrMsgGuiText = errMsg;

        }
         return objRes;
    }

    public void onlyNumbers(string s2c)
    {
        onlyNumbers(s2c, true);
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    protected void OnPropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));

        }

    }

NumTbViewModel.cs:
    Validations val = null;

    public NumTbViewModel()
    {
        val = new Validations();
    }

    private string _NumTbText;
    public string NumTbText
    {
        get { return _NumTbText; }
        set
        {
            _NumTbText = value;
            this.OnPropertyChanged("NumTbText");
            val.onlyNumbers(_NumTbText);

        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    protected void OnPropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));

        }

    }

A: It looks like the TextBlock source is looking at a static resource for the Validations class and the Validations called in your NumTbViewModel is NOT the same as the static resource. A solution could be to add a property to NumTbViewModel.cs and point your binding to that property so the Validations class instances will be the same. In NumTbViewModel.cs add:
Validations _val;
    public Validations Val
    {
        get { return _val; }
        set
        {
            _val = value;
            this.OnPropertyChanged("Val");
        }
    }

Change your source and path in xaml binding on the TextBlock:
<TextBlock Text="{ Binding  Source={StaticResource NumTbVm}, Path=Val.ErrMsgGuiText, UpdateSourceTrigger=PropertyChanged}" Background="{TemplateBinding Background}"/>

Another way:
You could also set the Val property of your NumTbViewModel when you define your static resource like so:
<local:Validations x:Key="val" />
<local:NumTbViewModel x:Key="NumTbVm" Val="{StaticResource val}" />

Doing this you can keep the bindings like you originally had.


text:
Q: Implicit transaction with explicit implementation As a framework developper, I would like to provide an implicit transaction scope environment that works across threads.
This would imply that a CommittableTransaction could be created from the existing ambiant transaction if any.
Could I create a CommitableTransaction from the ambiant Transaction ?
I'll try to implement a new TransactionScope using the concept explained here.


text:
Q: Transpose date into local timezone without shifting the date I have an input date with a specific time zone in string. For example:
Sat May 20 2017 17:00:00 GMT-0300 (-03)
I want to change the timezone of this date to my local timezone without converting the time. As if the input date was in my correct timezone.
Sat May 20 2017 17:00:00 GMT+0200 (CEST)
I played around with moment and found this:
const date = moment(moment.utc('Sat May 20 2017 17:00:00 GMT-0300 (-03)').format('LLL'))
Is it the simplest way to do it? I don't like the copy of the moment object but I can't find a method to do it in a "single shot".

A: To parse your input in local time, you can simply use moment(String, String) function. As docs says:

By default, moment parses and displays in local time.

Here a live sample:

var input = 'Sat May 20 2017 17:00:00 GMT-0300 (-03)';
var m = moment(input, 'ddd MMM DD YYYY HH:mm:ss');
console.log(m.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


text:
Q: Removing similar strings from csv using another csv I need to remove strings from one csv (file-a) that match or partially match the strings in another csv (file-b), based on the email address:
file-a
email,Firstname,Lastname
Peter@hotmail.com,pete,Smith
Paul@gmail.com,paul,
Mary@hotmail.com,,Jones
puff@yahoo.com,puff,Dragon

file-b
email,Firstname,Lastname
Peter@hotmail.com,,Smith
Mary@hotmail.com,Mary

deduped-output-file
email,Firstname,Lastname
Paul@gmail.com,paul,
puff@yahoo.com,puff,Dragon

I came across a similar question here:
Removing similar lines from two files
However, this only works for exact matches, I tried using "notmatch" instead of "notcontains" but this did not work. I'm quite new to powershell and I can't quite figure out what I need to do. Any help would be greatly appreciated.

A: I'd first Import-Csv the files and use Compare-Object restricted to the property email
## Q:\Test\2019\02\28\SO_54929339.ps1

$fileA = Import-csv '.\file-a.csv'
$fileB = Import-csv '.\file-b.csv'

$deduped = Compare-Object -Ref $fileA -Diff $fileB -Property email -PassThru |
  Where-Object Sideindicator -eq '<=' |
    Select-Object * -ExcludeProperty Sideindicator

$deduped
$deduped | Export-Csv '.\deduped-output-file.csv' -NoTypeInformation

Sample output:
> Q:\Test\2019\02\28\SO_54929339.ps1

email          Firstname Lastname
-----          --------- ---------
Paul@gmail.com paul
puff@yahoo.com puff      Dragon


text:
Q: How to pass environment variables to a sql file from bash shell (PostgreSQL) I need to be able to pass environment variables, from a bash shell executing a .sql file using psql.
The psql command I am running is:
su postgres -c "psql -v ON_ERROR_STOP=1 -v dbname=example -v dbuser=example -e" < ./create-db.sql

Where I have put example is usually set to $DATABASE_NAME and DATABASE_USER respectively which is set in the bash script before executing the psql command.
The create-db.sql file is:
\connect postgres
DROP DATABASE IF EXISTS :dbname;
DO $$BEGIN
    CREATE USER :dbuser;
EXCEPTION WHEN duplicate_object THEN
    RAISE NOTICE 'user already exists';
END$$;
ALTER ROLE :"dbuser" SET search_path TO :"dbname",public;
CREATE DATABASE :"dbname"
    OWNER=:dbuser
    ENCODING=UTF8
    LC_COLLATE='en_US.UTF-8'
    LC_CTYPE='en_US.UTF-8'
    TEMPLATE=template0;
\connect :"dbname"
CREATE SCHEMA zulip AUTHORIZATION :"dbuser";

The variable substitution in the line DROP DATABASE IF EXISTS :dbname; works, but everything after fails at the CREATE USER :dbuser; line fails and I have tried it as each of the following ways:
CREATE USER :dbuser;
CREATE USER :'dbuser';
CREATE USER :"dbuser";
And it always errors with:
You are now connected to database "postgres" as user "postgres".
DROP DATABASE IF EXISTS example;
NOTICE:  database "example" does not exist, skipping
DROP DATABASE
DO $$BEGIN
    CREATE USER :dbuser;
EXCEPTION WHEN duplicate_object THEN
    RAISE NOTICE 'user already exists';
END$$;
ERROR:  syntax error at or near ":"
LINE 2:     CREATE USER :dbuser;
                        ^

I'm really not sure where I'm going wrong with the above. Output of psql -V is psql (PostgreSQL) 12.6 (Ubuntu 12.6-0ubuntu0.20.04.1)

A: This will allow you to do it.  In your case, everything between '$$' is a "dollar-quoted string constant, so nothing gets interpreted.  See sql syntax, 4.1.2.4.
\set CREDO 'begin create user ' :dbuser '; exception when duplicate_object then raise notice ''user already exists''; end';
do :'CREDO';


text:
Q: Python .words issue? Ok so I'm trying to create a program that tells me how positive or negative each line of that paulryan.txt file is. I'm using the opinion_lexicon, and the file is '_io.TextIOWrapper'
Is there something I can use instead of .words?
Other less important problem: any ideas how to make my WHOLE paulryan.txt file lowercase while keeping it tokenized by line? Thinking it won't give me an accurate positive or negative score if I don't make the whole thing lowercase because there are only lowercase words in the opinion_lexicon.
import nltk
from nltk.corpus import opinion_lexicon
from nltk.tokenize.simple import (LineTokenizer, line_tokenize)

poswords = set(opinion_lexicon.words("positive-words.txt"))
negwords = set(opinion_lexicon.words("negative-words.txt"))

f=open("paulryan.txt", "rU")
raw = f.read()
token= nltk.line_tokenize(raw)

print(token)

def finddemons():
    for x in token:
        y = token.words()
        percpos = len([w for w in token if w in poswords ]) / len(y)
        percneg = len([w for w in token if w in negwords ]) / len(y)
        print(x, "pos:", round(percpos, 3), "neg:", round(percneg, 3))

finddemons()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in finddemons
AttributeError: 'list' object has no attribute 'words'

A: I suggest you to read the file line by line. Then , use word_ tokenize:
for line in f:
    tokens = word_tokenize(line)

You are right about lowercase the text for searching in the lexicon :
for line in f:
    tokens = word_tokenize(line.lower())

You could even try to lemmatize the tokens by using wordnet, because the opinion lexicon is not that rich in vocabulary. Especially if you use tweets, where words are often in different forms.


text:
Q: Implement call retries with httr::RETRY() function in API call (R) I use the UN Comtrade data API with R.
library(rjson)

get.Comtrade <- function(url="http://comtrade.un.org/api/get?"
                         ,maxrec=50000
                         ,type="C"
                         ,freq="A"
                         ,px="HS"
                         ,ps="now"
                         ,r
                         ,p
                         ,rg="all"
                         ,cc="TOTAL"
                         ,fmt="json"
)
{
  string<- paste(url
                 ,"max=",maxrec,"&" #maximum no. of records returned
                 ,"type=",type,"&" #type of trade (c=commodities)
                 ,"freq=",freq,"&" #frequency
                 ,"px=",px,"&" #classification
                 ,"ps=",ps,"&" #time period
                 ,"r=",r,"&" #reporting area
                 ,"p=",p,"&" #partner country
                 ,"rg=",rg,"&" #trade flow
                 ,"cc=",cc,"&" #classification code
                 ,"fmt=",fmt        #Format
                 ,sep = ""
  )

  if(fmt == "csv") {
    raw.data<- read.csv(string,header=TRUE)
    return(list(validation=NULL, data=raw.data))
  } else {
    if(fmt == "json" ) {
      raw.data<- fromJSON(file=string)
      data<- raw.data$dataset
      validation<- unlist(raw.data$validation, recursive=TRUE)
      ndata<- NULL
      if(length(data)> 0) {
        var.names<- names(data[[1]])
        data<- as.data.frame(t( sapply(data,rbind)))
        ndata<- NULL
        for(i in 1:ncol(data)){
          data[sapply(data[,i],is.null),i]<- NA
          ndata<- cbind(ndata, unlist(data[,i]))
        }
        ndata<- as.data.frame(ndata)
        colnames(ndata)<- var.names
      }
      return(list(validation=validation,data =ndata))
    }
  }
}

However, sometimes it fails to connect server and I need to run the code several times to start working. Solution given here, to use Retry() function, which retries a request until it succeeds, seems attractive.
However, I have some difficulties implementing this function in the code given above. has anybody used it before and knows how to recode it?

A: An API call using httr::RETRY could look like the following:
library(httr)
library(jsonlite)

res <- RETRY(
    verb = "GET",
    url = "http://comtrade.un.org/",
    path = "api/get",
    encode = "json",
    times = 3,
    query = list(
      max = 50000,
      type = "C",
      freq = "A",
      px = "HS",
      ps = "now",
      r = 842,
      p = "124,484",
      rg = "all",
      cc = "TOTAL",
      fmt = "json"
    )
  )

# alternativ: returns dataset as a `list`:
# parsed_content <- content(res, as = "parsed")

# returns dataset as a `data.frame`:
json_content <- content(res, as = "text")
parsed_content <- parse_json(json_content, simplifyVector = TRUE)
parsed_content$validation
parsed_content$dataset

I'd suggest rewriting the get.Comtrade function using httr:
get.Comtrade <- function(verb = "GET",
                         url = "http://comtrade.un.org/",
                         path = "api/get",
                         encode = "json",
                         times = 3,
                         max = 50000,
                         type = "C",
                         freq = "A",
                         px = "HS",
                         ps = "now",
                         r,
                         p,
                         rg = "all",
                         cc = "TOTAL",
                         fmt = "json") {
  res <- httr::RETRY(
    verb = verb,
    url = url,
    path = path,
    encode = encode,
    times = times,
    query = list(
      max = max,
      type = type,
      freq = freq,
      px = px,
      ps = ps,
      r = r,
      p = p,
      rg = rg,
      cc = cc,
      fmt = fmt
    )
  )
  jsonlite::parse_json(content(res, as = "text"), simplifyVector = TRUE)
}

s1 <- get.Comtrade(r = "842", p = "124,484", times = 5)
print(s1)

Please see this and this for more information on library(httr).


text:
Q: Does caja fix malformed HTML when using GAS createHtmlOutput() method? In the following example the content "Here is some more text" is clearly outside the closing HTML tag. But when I run the script as a web app and view the page source it's inside the closing tag. Is this because caja is sanitizing the malformed HTML? Why sanitize in this way instead of informing me of the error?
GAS code:
function doGet() {
    var ParagraphContent ='So much to do in so little time... '
    var HTMLToOutput = '
A header

' + ParagraphContent + '
';
    var HtmlAndMore = HTMLToOutput + 'Here is some more text';
    var it = HtmlService.createHtmlOutput(HtmlAndMore);
    Logger.log(HtmlAndMore)
    return it
}

GAS script editor Logging Output:

A header

So much to do in so little time...
Here is some more text

A: Caja is designed to operate according to the HTML5 parsing algorithm (which is designed to codify browser vendors' consensus as to how HTML-in-the-wild must be parsed, and define a single correct parse-error-recovery strategy). That algorithm effectively specifies that trailing content after  shall be inserted into the , so the result you are seeing is what is specified.
However, it does also specify that that input is a parse error (which just means that it may be reported or may abort processing). Our latest technology ('ES5 mode') unfortunately does not yet make any attempt to report parse errors. I've made a note to fix that.


text:
Q: Matrix multiplication returning wrong matrix python parallel I have a school project, where I have to do some python parallel function. One of them is matrix multiplication(I cannot use numpy). I tried to do it in multithreading, but it was too slow and I was recommented to do it in multiprocessing. It is much faster, but there is one problem. I get the right matrix only when I use one process. Can anyone help? Here is the code:
import numpy as np
import time
import multiprocessing.dummy as mp

min = -10
max = 10
n = 10
x = ((np.random.rand(n, n) * (max - min) ) + min).astype('int')
y = ((np.random.rand(n, n) * (max - min) ) + min).astype('int')

z = [[0 for i in range(n)] for j in range(n)]
jump = 0

def matrixMult(start):
    for i in range(start, start + jump):
        print("HEJ")
        for k in range(n):
            for j in range(n):
                z[i][j] += x[i][k] * y[k][j]

def multPrepare(x, y, i):
    pool = mp.Pool(i)
    pool.map(matrixMult, range(0, n, jump))
    return z

if __name__ == '__main__':

    i = 1
    while i < 5:
        start_time = time.time()
        jump = int(round(n / i))
        z = multPrepare(x, y, i)
        print("number of cores: " + str(i) + ", TIME: "+ str(time.time()-start_time) + " seconds")
        i += 1

    print(z)
    print(z == x.dot(y))

The result matrix is only right when i = 1.