text:
Q: Fullscreen option in R package leaflet? The following code produces a shiny app with (almost) the same output twice. One uses package "rcharts", the other package "leaflet"
The first map has a fullsreen button. Is this available with package leaflet()?
library(shiny)
library(rCharts)
library(leaflet)

runApp(

  ## UI ####
  list(ui = (basicPage(
    headerPanel("tests"),
    mainPanel(
      chartOutput("map1", "leaflet"),
      "some text...",
      leafletOutput('map2')
    )
  )),

  ## server ####
  server = function(input, output) {

    output$map1  <- renderMap({
      map1 <- Leaflet$new()
      map1$fullScreen(TRUE)
      map1$setView(c(39.603609, -8.415081), 10)
      map1
    })

    output$map2 <- renderLeaflet({
      leaflet() %>%
        addTiles() %>%
        setView(lng = -8.415081, lat = 39.603609, zoom = 10)
    })
    }
      ))

Thanks

A: For future readers
With the package leaflet.extras you can add a full screen control to your map.
library(leaflet)
library(leaflet.extras)
leaflet() %>%
    addTiles() %>%
    addFullscreenControl()

A: There is a plugin for the Leaflet javascript library called Leaflet.Control.FullScreen.
However, this plugin hasn't (yet) been implemented in the R version of leaflet. I have posted a feature request on the leaflet Github page, but haven't heard anything back so far.


text:
Q: Compiler warnings conversion We are compiling using gcc with -Wconversion enabled. I get following warnings when I left shift result returned by isBitSet function below.

warning: conversion to 'u_int16_t {aka short unsigned int}' from 'int'
  may alter its value [-Wconversion]

#include <stdint.h>

using namespace std;

void convertToPos(uint16 in) {

    auto isBitSet = [&in](uint8_t position) -> bool{
        return (in & (1 << position));
    };

    uint16_t signal = 0;
    signal |= isBitSet(1) << 9;  // Calibrated
    signal |= isBitSet(2) << 10; // Corresponds to digital map
    signal |= isBitSet(5) << 13; // DR
    signal |= isBitSet(8) << 15; // 3D Fix

}

int main(int argc)
{
    convertToPos(4);
    return 0;
}

I tried changing lambda to below, but still I get the same error. How can I fix it?
auto isBitSet = [&in](uint8_t position) -> uint16_t {
    return (in & (1 << position)) ? 1u:0u;
};

A: To avoid the warning, you may do:
signal = uint16_t(signal | isBitSet(1u) << 9);

as operator | promotes operator uint16_t to int.

A: In this case both shift operators and bitwise inclusive or operator apply the integer promotions to their operands and since uint16_t can be represented by int the operands are promoted to int and therefore gcc is warning you that the conversion from a larger type int to uint16_t may result in loss.
The C++ way to deal with this is to use static_cast, it looks like the following works:
signal = signal | static_cast<uint16_t>(isBitSet(1) << 9);

it looks like it is not neccessary to cast the result of |, although strictly it should be no different than << but I guess gcc is able to deduce that it is okay in this case. Technically this is better:
signal = static_cast<uint16_t>( signal | isBitSet(1) << 9);

For reference the draft C++ standard in 5.8 Shift operators says:

The operands shall be of integral or unscoped enumeration type and
  integral promotions are performed.[...]

and section 5.13 Bitwise inclusive OR operator says:

The usual arithmetic conversions are performed;[...]

the usual arithmetic conversions in this case ends up applying the integer promotions.

A: It's not an error. What it's saying is that by converting from an integer to an unsigned integer, the value will change if the integer is negative. There's really no "fix" for this; you just need to be careful what values the unsigned is taking from the signed. I'm guessing you're using unsigned because it needs to be 0 and above, so if anything, this will fix any accidentally-entered negative values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding Equivalence Classes Help I am having some trouble with this question.  I am not sure what to do at this point since the instructor said to ignore the reference to example 2.  Below is the questions as they are on the worksheet:

(Ignore the reference to Example 2 as it does not apply)
And Example 2 is:

I am very confused by what is going on here any help would be greatly appreciated.

A: I think your instructor is trying to say that you don't NEED the example 2 to solve the problem, but the book is noting that those pairs are in the equivalence class of R. So if you look at the (x,y) pairs from example 2, say (1,2) and look out our relation R. So 1 is R related to 2 if and only if 2-1 is an integer. So the pair (1,2) is in the equivalence class.
As for part a) you want to find ALL possible pairs that make your relation true such that x = 1. So start with plug and chug and try to pick up a pattern. I will write out a few to check so you can see 1R1, 1R2. Does 1-1 equal an integer? Yes,it equals 0 Does 1 -2 equal an integer? Yes, it equals -1.
Part b) is a little more tricky when you are trying to consider all possible values, but it is the same idea.
In general you want to consider things like "Is it true if I use negatives? Integers? Rationals? Irrationals?" Then from what makes your relation true you can decide what "type" of numbers are related given your specific relation.


text:
Q: document.querySelector always returns null I've looked at the other answers but still don't understand.
For some reason this line of code always returns null.
var els = document.querySelector("[id='MTG_INSTR$2']");

I checked the value of document in the console so I'm pretty sure that's correct.
The id is buried deep inside a table though, could that be an issue?
EDIT 2: If it helps, here's the full code.
content.js
chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if( request.message === "start" ) {
         start();
             }
      }
    );

    function start(){
        var els = document.querySelector("[id='MTG_INSTR$2']");
        console.log(els);
        alert("started");
    }

popup.html
<!DOCTYPE html>

<input id="button1" type=button value=clickme>

popup.js
 function popup() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
   });
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("button1").addEventListener("click", popup);
});

manifest.json
{
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "manifest_version": 2,
  "name": "extensiontest",
  "version": "0.2",
  "content_scripts": [
  {
    "matches": [
      "<all_urls>"
    ],
    "js": ["content.js"]
  }
],
"browser_action": {
  "default_icon": "icon.png",
    "default_popup":"popup.html"
},
//"background": {
// "scripts": ["background.js"]
//},
"permissions": [
    "tabs"
  ]
}

EDIT: I've included a screen shot of what the document structure looks like.

A: I doubt your JS gets loaded before the markup and css. In that case, you could try using

The contents are loaded first and your java script should work fine after that.

A: IDs are handled specially in CSS selector syntax, with a # followed by the ID, so you'd normally want something like document.querySelector('#MTG_INSTR$2'), but $ isn't a legal ID component, so ideally you'd give it a better name. Other approaches are:
document.getElementById('MTG_INSTR$2'); // No need to change ID

That said, on testing, document.querySelector("[id='MTG_INSTR$2']") should work, so you might check if anything actually has that ID on your page.

A: Possible solutions to your problem...
IIFE
(function () {
  var els = document.querySelector("[id='MTG_INSTR$2']");
  console.log(els);
})();

DOMContentLoaded
document.addEventListener("DOMContentLoaded", function () {
  var els = document.querySelector("[id='MTG_INSTR$2']");
  console.log(els);
});

A: I don't know your full javascript code but maybe you are create/append that element after the script loads or something like that and therefor querySelector don't find the element with that id. Check your scope or write the code here if you suspicious of that kind of error.


text:
Q: Trying to complete my coding bootcamp prework using getElementByID and addEventListener I start my coding bootcamp tomorrow and I have been able to complete all my pre-work modules except this one.
Using only html and Javascript, I am to try to get these buttons to work to change this object in the following code:
    <!DOCTYPE html>

    <title>Jiggle Into JavaScript</title>

Press the buttons to change the box!

 .

    <button id="button1">Grow</button>
    <button id="button2">Blue</button>
    <button id="button3">Fade</button>
    <button id="button4">Reset</button>

Here is where I am at, and I am obviously having issues.  I feel like I know just enough to make a mess.

//the following is the fade function,
//currently unattached to button:
//source: https://stackoverflow.com/questions/28662893/fade-in-and-fade-out-in-pure-javascript-without-jquery

var box = document.getElementById('box');

function fadeOut(elem, speed) {

  if (!elem.style.opacity) {
    elem.style.opacity = 1;
  } // end if

  var outInterval = setInterval(function() {
    elem.style.opacity -= 0.02;
    if (elem.style.opacity <= 0) {
      clearInterval(outInterval);
    } // end if
  }, speed / 50);
}

fadeOut(box, 2000);

// end fadeOut()
<!DOCTYPE html>

  <title>Jiggle Into JavaScript</title>

Press the buttons to change the box!

 .

  <button id="growBtn">Grow</button>
  <button id="blueBtn">Blue</button>
  <button id="fadeBtn">Fade</button>
  <button id="resetBtn">Reset</button>

I have been researching for days but have found so many different options and none seem to be the right fit.
Here are the issues as they stand right now:

*

*Grow button:  Well, I can make it get bigger, but just once, not every time the button is clicked.

*Blue button:  I can make it blue when the button is clicked, but the size changes back to the original if the grow button was clicked first.

*Fade button:  I found the code to a fadeOut function on this site (referenced in the code), but I don't know how to apply it to my fadeBtn so the box fades immediately upon opening the page.  This is currently the only code in my js file.

*Reset button:  This works!  Not sure that the code I used to make it work is the appropriate way, but I will take any win at this point!
I will take absolutely any advice/guidance/google links anyone is willing to share to help me!  I'd like to start bootcamp out on the right foot and figure this out.
Thanks in advance!

A: Firstly, there's no reason to continually fetch the element on the page - assign it to a variable once at the start, and then reference that variable through your functions.
const box = document.getElementById('box');

Also, when updating an Element's styles, you should be targeting a specific style that you want to change, and then updating it directly
// Instead of this
document.getElementById("box").style = "height:250px; width:250px;

// Do this ( Also applying the above tip )
const box = document.getElementById('box');

box.style.height = '250px';
box.style.width = '250px';

*

*
Grow button: Well, I can make it get bigger, but just once, not every time the button is clicked

Your code currently doesn't do anything dynamic - You're just setting it to a hard-coded size. What you want to do instead is get the current size of the element, increase this, and then assign that value back to your element
You can use offsetHeight and offsetWidth to get the height / width of an element as a Number for easier addition
let height = box.offsetHeight + 50; // Increasing the current size by 50
let width = box.offsetWidth + 50;

box.style.height = height + 'px'; // Assigning our increased size back to the box
box.style.width = width + 'px';

*
Blue button: I can make it blue when the button is clicked, but the size changes back to the original if the grow button was clicked first.

Throughout your functions, you're overwriting every style on the box element for no reason. Unless you are overwriting a style, or removing a style, the values for each style will stay the same. When you're updating backgroundColor, just update backgroundColor.
box.style.backgroundColor = 'blue'; // This is all you need to change

*
Fade button: I found the code to a fadeOut function on this site (referenced in the code), but I don't know how to apply it to my fadeBtn so the box fades immediately upon opening the page

I'm a little confused as to why you would want this applied to the box as soon as the page loads, surely applying this style to the box on the button press is more appropriate? If that's the case, just move your function call into the click handler on the button
document.getElementById("fadeBtn").addEventListener("click", function() {
  fadeOut(box, 2000);
});

*
Reset button: This works! Not sure that the code I used to make it work is the appropriate way, but I will take any win at this point!

It does, but you don't need to reset margin because you're never changing it.
Also, because your fadeOut function is running it's setInterval until the opacity is 0, we need a way to access and cancel this interval or else the element will keep fading - I've moved the outInterval declaration outside of the function for this, so you can call clearInterval(outInterval) inside your reset function (this is more visible in the Code Snippet at the bottom)
// Reset 'Grow'
box.style.height = '150px';
box.style.width = '150px';

// Reset 'Blue'
box.style.backgroundColor = 'orange';

// Reset 'Fade'
clearInterval(outInterval);
box.style.opacity = 1;

Here's a Snippet with these changes implemented so you can have a look how it works - Feel free to ask any questions if you're not sure on something, or I've missed a detail

const box = document.getElementById('box');
let outInterval = null;

document.getElementById("growBtn").addEventListener("click", function() {
  let height = box.offsetHeight + 50;
  let width = box.offsetWidth + 50;

  box.style.height = height + 'px';
  box.style.width = width + 'px';
});

document.getElementById("blueBtn").addEventListener("click", function() {
  box.style.backgroundColor = 'blue';
});

document.getElementById("fadeBtn").addEventListener("click", function() {
  fadeOut(box, 2000);
});

document.getElementById("resetBtn").addEventListener("click", function() {
  // Reset 'Grow'
  box.style.height = '150px';
  box.style.width = '150px';

  // Reset 'Blue'
  box.style.backgroundColor = 'orange';

  // Reset 'Fade'
  clearInterval(outInterval);
  box.style.opacity = 1;
});

function fadeOut(elem, speed) {
  if (!elem.style.opacity) {
    elem.style.opacity = 1;
  } // end if

  outInterval = setInterval(function() {
    elem.style.opacity -= 0.02;
    if (elem.style.opacity <= 0) {
      clearInterval(outInterval);
    } // end if
  }, speed / 50);
};

Press the buttons to change the box!

 .

  <button id="growBtn">Grow</button>
  <button id="blueBtn">Blue</button>
  <button id="fadeBtn">Fade</button>
  <button id="resetBtn">Reset</button>

A: here you go I explained what and why but if you have questions just ask:
HTML :
<!DOCTYPE html>

  <title>Jiggle Into JavaScript</title>

  <met charset="utf-8">

Press the buttons to change the box!

 .

  <button id="growBtn">Grow</button>
  <button id="blueBtn">Blue</button>
  <button id="fadeBtn">Fade</button>
  <button id="resetBtn">Reset</button>

And javascript.js:
//the following is the fade function,
   //currently unattached to button:
   //source: https://stackoverflow.com/questions/28662893/fade-in-and-fade-out-in-pure-javascript-without-jquery

   function fadeOut(elem, speed) {

   if (!elem.style.opacity) {
   elem.style.opacity = 1;
   } // end if

   var outInterval = setInterval(function () {
   elem.style.opacity -= 0.02;
   if (elem.style.opacity <= 0) {
       clearInterval(outInterval);
   } // end if
   }, speed / 50);
   }
   // cuz this calls the function just when the page loads so on the start of everything:
   // fadeOut(box, 2000);

   // end fadeOut()

I hope you understand everything now <3.


text:
Q: (CHORD) Peer-2-Peer How does it work/What does it do? https://en.wikipedia.org/wiki/Chord_(peer-to-peer)
I've looked into Chord and i'm having trouble understanding exactly what it does.
It's a protocol for a distributed hash table which stores various keys/values for later usage? Is it just an efficient way to look up in the hash table what value for a given key?
Any help such as a basic example would be much appreciated

A:
An example question is say if I hashed inserting string "Hi" to 3 and there were no peers at 3 it would go to the next available peer and store it there right? Or where does it store it's values to?

I already answered a similar question for bittorrent/kademlia, so just to summarize in a more general sense:
DHTs store the values with some redundancy on N nodes whose ID is closest to the target hash.
Considering the vastness of >= 128bit keyspaces it would be extremely unlikely for nodes to exactly match the key. At least in routing schemes where nodes don't adjust their IDs based on content, and chord is one of those.
It's pretty much the same as regular hash tables, hence distributed hash table. You have a limited set of buckets into which the entries are hashed, where the bucket space is much smaller than the potential input keyspace and thus does not precisely match the keys either.


text:
Q: SubSonic3 SimpleRepository Relationships Generated are Wrong I have been told that it's more than likely my database that is setup wrong causing the problems so below are my tables with key fields and queries.
CREATE TABLE Presentations (
    Id INT NOT NULL IDENTITY(1, 1),
    SpeakerId INT NOT NULL,

    CONSTRAINT PK_Presentations PRIMARY KEY (Id),
    CONSTRAINT FK_Presentations_Speaker FOREIGN KEY (SpeakerId) REFERENCES Speakers (Id)
)

CREATE TABLE Speakers (
    Id INT NOT NULL IDENTITY(1, 1),

    CONSTRAINT PK_Speakers PRIMARY KEY (Id)
)

When I execute the following:
presentations = presentations.OrderBy(x => x.Speaker.FirstName);

The query generated looks like:
SELECT  [t0].[Description], [t0].[EventId], [t0].[Id], [t0].[PresentedOn],
        [t0].[Slug], [t0].[SpeakerId], [t0].[Title], [t0].[Url]
FROM    [Presentations] AS t0
LEFT    OUTER JOIN [Speakers] AS t1 ON ([t1].[Id] = [t0].[Id])
WHERE   ([t1].[FirstName] LIKE 'B' + '%')
ORDER   BY [t1].[FirstName]

The join should be:
LEFT    OUTER JOIN [Speakers] AS t1 ON ([t1].[Id] = [t0].[SpeakerId])

This is an urgent problem, can anyone help?
Related Questions:

*

*ASP.NET MVC2 Linq Where Clause using StartsWith

*Funky Sql Generated using SubSonic Simple Repository, LINQ and ASP.NET MVC
Really appreciate some help.


text:
Q: Mongodb send me incorrect object with different id I use express as backend, mongodb and mongoose.
I don't understand why i get from database incorrect object.
In general, i send from frontend post request with id:  6210915b2b72a91fe72d9201.
On backend i reseive that id and want to fetch object with same id from mongodb
This code:
router.post('/reaction_on_user', async (req, res) => {

  let womanid = req.body.id
  console.log(womanid, ' before findOne')
  const womanData = await User.findOne({womanid}).select('_id name age photos')
  console.log(womanid, ' after findOne')

In console.log i see id which i send -- 6210915b2b72a91fe72d9201.
But object from database have different id -- 6210915b2b72a91fe72d91f5. This different id was some requests ago.

A: Oh. Now i wrote:
const womanData = await User.findOne({_id: womanid}).select('_id name age photos')

and it works...


text:
Q: How to check if a string is built up using only specific characters I need to check if a string is only built up using 1, 0 and comma. It should also starts with either 0 or 1 and also ends with 0 or 1:
The checking for start and end can be done like this (Or if you think it can be improved peplase let me know!)
if ((text.StartsWith("0") || text.StartsWith("1")) //Starts with 0 or 1
    && (text.EndsWith("0") || text.EndsWith("1")) //Ends with 0 or 1
    && //How to check if it only has 0, 1 and comma?            )
{
    //Do Something!
}

A: You can use Regex, try this:
if (new Regex("^[01][01,]*[01]$").Match(text).Success)
{
   // do your stuffs
}

A: public bool CheckMyString(string text)
{
    if ((text.StartsWith("0") || text.StartsWith("1"))
       && (text.EndsWith("0") || text.EndsWith("1")))
    {
      foreach (char c in text)
      {
         if (c != "1" && c != "0" && c != ",")
         {
            return false;
         }
      }
    }
    else
    {
       return false;
    }

    return true;
}

A: Use a regular expression like this [01][01,]+?[01]. Im sure there could be better regex patterns to use. But that would work.
if(Regex.IsMatch(mystring, "[01][01,]+?[01]"))
   //yes it matches;

This regex pattern will look for a 0 or a 1 and then an optional sequence of 0, 1 or "," and then ending in a 0 or a 1 again.

A: if (Regex.IsMatch("0101,1010", "^[01][01,]*[01]$"))
{
     doSomething();
}

you need to add
using System.Text.RegularExpressions;

to the top of your file for this to work.

A: Is it one way ?
if (value.Trim("01,".ToCharArray()).Length == 0 )

A: You can try this,
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[01][01,]+?[01]");
if (!reg.IsMatch("3452"))
{
    Response.Write("Does Not Match");
}

if (reg.IsMatch("01111,1"))
{
    Response.Write("Yes Match!");
}


text:
Q: Use reference for array in swagger api doc I'm trying to reference an object in an array in the swagger api-doc like that (with more objects but in the same pattern):
  definitions: {
    obj: {
      type: 'object',
      properties: {
        login: {
          type: 'string',
        },
        password: {
          type: 'string',
        },
      },
    },

 objArray: {
          type: 'array',
          items: {
            type: 'object',
            $ref: '#/definitions/obj',
          },
        },
}

But i get this error :
error TS2345: Argument of type '{ paths: { path: string; module: any; }[]; app: any; apiDoc: { 'x-express-openapi-additional-midd...' is not assignable to parameter of type 'Args'.
  Types of property 'apiDoc' are incompatible.
    Type '{ 'x-express-openapi-additional-middleware': any[]; swagger: string; basePath: string; info: { ti...' is not assignable to type 'ApiDefinition'.
      Types of property 'definitions' are incompatible.
        Type '{ Error: { type: string; properties: { status: { type: string; }; message: { type: string; }; tra...' is not assignable to type 'DefinitionsObject | undefined'.
          Type '{ Error: { type: string; properties: { status: { type: string; }; message: { type: string; }; tra...' is not assignable to type 'DefinitionsObject'.
            Property 'Orders' is incompatible with index signature.
              Type '{ type: string; properties: { client: { type: { type: string; }; }; metadata: { type: string; pro...' is not assignable to type 'SchemaObject'.
                Types of property 'properties' are incompatible.
                  Type '{ client: { type: { type: string; }; }; metadata: { type: string; properties: { client: { type: s...' is not assignable to type '{ [name: string]: SchemaObject; } | undefined'.
                    Type '{ client: { type: { type: string; }; }; metadata: { type: string; properties: { client: { type: s...' is not assignable to type '{ [name: string]: SchemaObject; }'.
                      Property 'client' is incompatible with index signature.
                        Type '{ type: { type: string; }; }' is not assignable to type 'SchemaObject'.
                          Types of property 'type' are incompatible.
                            Type '{ type: string; }' is not assignable to type 'string | string[] | undefined'.
                              Type '{ type: string; }' is not assignable to type 'string[]'.
                                Property 'length' is missing in type '{ type: string; }'.

Any idea why ?

A: I think you shouldn't define a type inside items: { }. Just delete it.
objArray: {
    type: 'array',
    items: {
        $ref: '#/definitions/obj'
    }
}

You are already referencing to your object. The type of this object is declared inside its definition.


text:
Q: Error adding Row into JTable I have a JButton which, once it is pressed, adds a row into a JTable. I have tried to make this by implementing the following code.
columNames = new Vector<>();
columNames.addElement("Name");
columNames.addElement("CC");
columNames.addElement("Age");
columNames.addElement("PhoneNumber");
columNames.addElement("Date");
columNames.addElement("Amount$");

Object[] dataList = {"name", "cc", "age", "phone", "date", "amount"};

data = new DefaultTableModel(columNames, 0);
data.addRow(dataList);

table = new JTable(data);
JScrollPane scrollTable = new JScrollPane(table);
scrollTable.setBounds(22, 78, 764, 177);
scrollTable.setViewportView(table);

//ActionListener method!.

if(e.getActionCommand().equals("Add client"))
{
    Object[] dataList = {"name", "cc", "age", "phone", "date", "amount"};
    data.addRow(dataList);

    DefaultTableModel defaut = (DefaultTableModel) table.getModel();
    defaut.addRow(dataList);
}

It throws Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:-1
How can I solve it?

A: As shown in the complete example below, your fragments appear to work correctly. The example may help you isolated the problem in your full code. In addition,

*

*Instead of setBounds(), override getPreferredScrollableViewportSize() to return a multiple of getRowHeight(), as suggested here, and pack() the enclosing window.

*See also  What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

*As suggested here, repeated failures to update the TableModel suggests that you may be referencing an unintended instance of an object.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * @see https://stackoverflow.com/a/38926460/230513
 */
public class Test {

    private final Object[] dataList = {"name", "cc", "age", "phone", "date", "amount"};

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Vector columNames = new Vector<>();
        columNames.addElement("Name");
        columNames.addElement("CC");
        columNames.addElement("Age");
        columNames.addElement("Phone");
        columNames.addElement("Date");
        columNames.addElement("Amount$");
        DefaultTableModel data = new DefaultTableModel(columNames, 0);
        data.addRow(dataList);
        JTable table = new JTable(data);
        JScrollPane scrollTable = new JScrollPane(table);
        scrollTable.setViewportView(table);
        f.add(new JScrollPane(table));
        f.add(new JButton(new AbstractAction("Add") {
            @Override
            public void actionPerformed(ActionEvent e) {
                data.addRow(dataList);
            }
        }), BorderLayout.PAGE_END);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}


text:
Q: how to creat such shape as chat bubble I am trying to create such shape, and checked some package but none of them has the same shape, especially the radius between the tail and main part, I found this one is similar but with hard cut with the tail https://pub.dev/packages/flutter_chat_bubble, please tell me how to create this radius corner tail connection, thanks!

A: If you go into  the package you referenced earlier you will find the file below, it lays out how they drew the bubble. If you just copy and edit the file to adjust your bubble to your liking you can easily replicate what you want above. Their package is pretty simple. The perks of being open source.
EdgeInsets setPadding() {
        if (clipper is ChatBubbleClipper1) {
          if ((clipper as ChatBubbleClipper1).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 20);
          } else {
            return EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 10);
          }
        } else if (clipper is ChatBubbleClipper2) {
          if ((clipper as ChatBubbleClipper2).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 25);
          } else {
            return EdgeInsets.only(top: 10, bottom: 10, left: 25, right: 10);
          }
        } else if (clipper is ChatBubbleClipper3) {
          if ((clipper as ChatBubbleClipper3).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 20);
          } else {
            return EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 10);
          }
        } else if (clipper is ChatBubbleClipper4) {
          if ((clipper as ChatBubbleClipper4).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 20);
          } else {
            return EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 10);
          }
        } else if (clipper is ChatBubbleClipper5) {
          if ((clipper as ChatBubbleClipper5).type == BubbleType.sendBubble) {
            return EdgeInsets.all(10);
          } else {
            return EdgeInsets.all(10);
          }
        } else if (clipper is ChatBubbleClipper6) {
          if ((clipper as ChatBubbleClipper6).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 20, left: 10, right: 20);
          } else {
            return EdgeInsets.only(top: 10, bottom: 20, left: 20, right: 10);
          }
        } else if (clipper is ChatBubbleClipper7) {
          if ((clipper as ChatBubbleClipper7).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 10, left: 15, right: 15);
          } else {
            return EdgeInsets.only(top: 10, bottom: 10, left: 15, right: 15);
          }
        } else if (clipper is ChatBubbleClipper8) {
          if ((clipper as ChatBubbleClipper8).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 15);
          } else {
            return EdgeInsets.only(top: 10, bottom: 10, left: 15, right: 10);
          }
        } else if (clipper is ChatBubbleClipper9) {
          if ((clipper as ChatBubbleClipper9).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 10, bottom: 15, left: 10, right: 15);
          } else {
            return EdgeInsets.only(top: 10, bottom: 15, left: 15, right: 10);
          }
        } else if (clipper is ChatBubbleClipper10) {
          if ((clipper as ChatBubbleClipper10).type == BubbleType.sendBubble) {
            return EdgeInsets.only(top: 15, bottom: 10, left: 10, right: 15);
          } else {
            return EdgeInsets.only(top: 15, bottom: 10, left: 15, right: 10);
          }
        }

        return EdgeInsets.all(10);
      }
    }


text:
Q: How do I counting overlapping dimers for multiple sequences? I have to count the number of overlapping dimers (AA, AG, AC, AT, GA, GG, GC, GT, CC, CG, CA, CT, TT, TA, TG, TC) in multiple sequences using Perl. I wrote the following code but it only works for one sequence. How can I extend it to multiple sequences?
#!/usr/bin/perl -w
open FH, "sample.txt";
$genome=<FH>;
%count=();
$count{substr($genome, $_, 2)}++ for 0..length($genome)-2;
print "AA: $count{AA}\n";
print "AG: $count{AG}\n";
print "AC: $count{AC}\n";
print "AT: $count{AT}\n";

print "TA: $count{TA}\n";
print "TG: $count{TG}\n";
print "TC: $count{TC}\n";
print "TT: $count{TT}\n";

print "GA: $count{GA}\n";
print "GG: $count{GG}\n";
print "GC: $count{GC}\n";
print "GT: $count{GT}\n";

print "CA: $count{CA}\n";
print "CG: $count{CG}\n";
print "CC: $count{CC}\n";
print "CT: $count{CT}\n";

I need:

*

*counts for each sequence and

*the total counts

input example: sample.txt
ATGGGCTCCTCCGCCATCACCGTGAGCTTCCTCCTCTTTCTGGCATTTCAGCTCCCAGGGCAAACAGGAGCAAATCCCGTGTATGGCTCTGTGTCCAATGCAGACCTGATGGATTTCAAGTAAAAG
ATGGTGAGAAAATGGGCCCTGCTCCTGCCCATGCTGCTCTGCGGCCTGACTGGTCCCGCACACCTCTTCCAGCCAAGCCTGGTGCTGGAGATGGCCCAGGTCCTCTTGGATAACTACTGCTTCCCAGAGAACCTGATGGGGATGCAGGGAGCCATCGAGCAGGCCATCAAAAGTCAGGAGATTCTGTCTATCTCAGACCCTCAGACTCTGGCCCATGTGTTGACAGCTGGGGTGCAGAGCTCCTTGAATGACCCTCGCCTGGTCATCTCCTATGAGCCCAGCACCCTCGAGGCCCCTCCGCGAGCTCCAGCAGTCACGAACCTCACACTAGAGGAAATCATCGCAGGGCTGCAGGATGGCCTTCGCCATGAGATTCTGGAAGGCAATGTGGGCTACCTGCGGGTGGACGACATCCCGGGCCAGGAGGTGATGAGCAAGCTGAGGAGCTTCCTGGTGGCCAACGTCTGGAGGAAGCTCGTGAACACGTCCGCCTTGGTGCTGGACCTCCGGCACTGCACTGGGGGACACGTGTCTGGCATCCCCTATGTCATCTCCTACCTGCACCCAGGGAGCACAGTCTCGCACGTGGACACCGTCTACGACCGCCCCTCCAACACAACCACTGAGATCTGGACCCTGCCTGAAGCCCTGGGAGAGAAGTACAGTGCAGACAAGGATGTGGTGGTCCTCACCAGCAGCCGCACGGGGGGCGTGGCTGAGGACATCGCTTACATCCTCAAACAGATGCGCAGGGCCATCGTGGTGGGCGAGCGGACTGTTGGGGGGGCTCTGAACCTCCAGAAGCTGAGGGTAGGCCAGTCCGACTTCTTTCTCACTGTGCCTGTGTCCAGATCCCTGGGGCCCCTGGGTGAGGGCAGCCAGACGTGGGAGGGCAGTGGGGTGCTGCCCTGTGTGGGGACACCGGCCGAGCAGGCCCTGGAGAAAGCCCTGGCCGTTCTCATGCTGCGCAGGGCCCTGCCAGGAGTCATTCAGCGCCTTCAGGAGGCGCTGCGCGAGTACTACACGCTGGTGGACCGTGTGCCCGCCCTGCTGAGCCACCTGGCCGCCATGGACCTGTCCTCGGTGGTCTCCGAGGACGATCTGGTCACTAAGCTCAATGCTGGCCTGCAGGCTGTGTCTGAGGACCCCAGGCTCCAGGTGCAGGTGGTCAGACCCAAAGAAGCCTCTTCTGGGCCTGAGGAAGAAGCTGAAGAACCTCCAGAGGCGGTCCCGGAAGTGCCCGAGGACGAGGCTGTTCGGCGGGCTCTGGTGGACTCCGTGTTCCAGGTTTCTGTGCTGCCGGGCAACGTGGGCTACCTGCGCTTCGACAGTTTCGCTGATGCCTCTGTCCTGGAGGTGCTGGGCCCCTACATCCTGCACCAGGTGTGGGAGCCCCTGCAGGACACGGAGCACCTCATCATGGACCTGCGGCAGAACCCCGGGGGGCCGTCCTCCGCGGTGCCCCTGCTGCTCTCCTACTTCCAGAGCCCTGACGCCAGCCCCGTGCGCCTCTTCTCCACCTACGACCGGCGCACCAACATCACACGCGAGCACTTCAGCCAGACGGAGCTGCTGGGCCGGCCCTACGGCACCCAGCGTGGCGTGTACCTGCTCACTAGCCACCGCACCGCCACCGCGGCCGAGGAGCTGGCCTTCCTCATGCAGTCACTGGGCTGGGCCACGCTGGTGGGCGAGATCACCGCGGGCAGCCTGCTGCACACACACACAGTATCCCTGCTGGAGACGCCCGAGGGCGGCCTGGCGCTCACGGTGCCTGTGCTCACCTTCATCGACAACCATGGCGAGTGCTGGCTGGGGGGCGGTGTGGTCCCCGATGCCATTGTGCTGGCCGAGGAAGCCCTAGACAGAGCCCAGGAGGTGCTGGAGTTCCACCGAAGCTTGGGGGAGTTGGTGGAAGGCACGGGGCGCCTGCTGGAGGCCCACTACGCTCGGCCAGAGGTCGTGGGGCAGATGGGTGCCCTGCTGCGAGCCAAGCTGGCCCAGGGGGCCTACCGCACCGCGGTGGACCTGGAGTCGCTGGCTTCCCAGCTTACGGCCGACCTGCAGGAGATGTCTGGGGACCACCGTCTGCTGGTGTTCCACAGCCCCGGCGAAATGGTGGCTGAGGAGGCGCCCCCACCGCCTCCCGTCGTCCCCTCCCCGGAGGAGCTGTCCTATCTCATCGAGGCCCTGTTCAAGACTGAGGTGCTGCCCGGCCAGCTGGGCTACCTGCGTTTCGACGCCATGGCTGAGCTGGAGACGGTGAAGGCCGTCGGGCCACAGCTGGTGCAGCTGGTGTGGCAGAAGCTGGTGGACACGGCCGCGCTGGTGGTCGACCTGCGCTACAACCCCGGCAGCTACTCCACAGCCGTGCCTCTACTCTGCTCCTACTTCTTCGAGGCAGAGCCCCGCCGGCACCTCTACTCTGTCTTTGACAGGGCCACGTCAAGGGTCACAGAGGTATGGACCCTGCCCCACGTTACAGGCCAGCGCTATGGCTCCCACAAGGACCTCTACGTTCTGGTGAGCCACACCAGCGGTTCAGCAGCTGAGGCTTTTGCTCACACCATGCAGGATCTGCAGCGAGCCACCATCATCGGGGAGCCCACGGCCGGAGGGGCACTCTCCGTGGGAATCTACCAGGTGGGCAGCAGCGCCTTATACGCCTCCATGCCCACGCAGATGGCCATGAGTGCCAGCACCGGCGAGGCCTGGGATCTGGCTGGGGTGGAGCCGGACATCACTGTGCCCATGAGCGTGGCCCTCTCCACAGCCCGGGACATAGTGACCCTGCGTGCCAAGGTGCCCACTGTGCTGCAGACAGCTGGGAAGCTCGTAGCGGATAACTACGCCTCCCCTGAGCTGGGAGTCAAGATGGCAGCCGAACTGAGTGGTCTGCAGAGCCGCTATGCCAGGGTGACCTCAGAAGCCGCCCTCGCCGAGCTGCTGCAAGCCGACCTGCAGGTGCTGTCCGGGGACCCACACCTGAAGACAGCTCATATACCTGAGGATGCCAAAGACCGCATTCCTGGCATTGTACCCATGCAGTAACAG
ATGGACATGATGGACGGCTGCCAGTTCTCGCCCTCTGAGTACTTCTACGACGGCTCCTGCATCCCATCCCCCGACGGTGAGTTCGGGGACGAGTTTGAGCCGCGAGTGGCTGCTTTCGGGGCTCACAAGGCAGACCTGCAAGGCTCAGACGAGGACGAGCACGTGCGAGCACCCACGGGCCACCACCAGGCCGGCCACTGCCTCATGTGGGCCTGCAAAGCATGCAAAAGGAAGTCCACCACCATGGATCGGCGGAAGGCGGCCACCATGCGCGAGCGGAGACGCCTGAAGAAGGTCAACCAGGCTTTCGACACGCTCAAGCGGTGCACCACGACCAACCCTAACCAGAGGCTGCCCAAGGTGGAGATCCTCAGGAATGCCATCCGCTACATTGAGAGTCTGCAGGAGCTGCTTAGGGAACAGGTGGAAAACTACTATAGCCTGCCGGGGCAGAGCTGCTCTGAGCCCACCAGCCCCACCTCAAGTTGCTCTGATGGCATGTAAATG

A: #!/usr/bin/perl

use strict;

my @dimers = qw(AA AG AC AT GA GG GC GT CC CG CA CT TT TA TG TC);
my @dimers_totals;

my $i = 1;
for(<>)
{
    my $sequence = $_;
    print("Sequence $i:\n");
    my $j = 0;
    for(@dimers)
    {
        my $number =()= $sequence =~ /$_/gi;
        $dimers_totals[$j++] += $number;
        print "\t$_: $number\n"
    }
    print("\n");
    $i++;
}

print("Totals:\n");
$i = 0;
for(@dimers)
{
    print("\t$_: $dimers_totals[$i++]\n");
}

Use like
./dimers_count.pl < sample.txt

A: The key to this is take what you had so far as a functional unit of what you were trying to build.  Your code worked for one sequence; extending it to multiple sequences is simply a matter of getting rid of the assumption that only one sequence is being considered:
use strict;
use warnings;
use 5.010;

use Data::Dumper ();

sub count_dimers {
    my ($sequence) = @_;

    my %counts;
    $counts{substr($sequence, $_, 2)}++ for 0..length($sequence) - 2;

    my @dimers = qw(AA AG AC AT GA GG GC GT CC CG CA CT TT TA TG TC);
    %counts = map { $_ => $counts{$_} } @dimers;

    return %counts;
}

open(my $fh, '<', 'sample.txt');

my @counts_by_sequence;
while (my $sequence = <$fh>) {
    my %sequence_counts = count_dimers($sequence);
    push @counts_by_sequence, \%sequence_counts;
}

my %total_counts;
for my $sequence_counts (@counts_by_sequence) {
    for my $dimer (keys %$sequence_counts) {
        $total_counts{$dimer} += ${ $sequence_counts}{$dimer};
    }
}

say Data::Dumper->Dump(
    [\%total_counts, \@counts_by_sequence],
    [qw(total_count counts_by_sequence)]
);

I left the output as an exercise to the reader, but the general shape of the transformation should be evident:  What was once the entirety of the program is now a function that gets called once per sequence with the results per call stored and the results over all calls totaled.

A: My first thought was a global match in scalar context with an adjustment to pos() to back up one. This way, I only have to scan the string once for all dimers (whereas the other answers so far scan the sequence once for every dimer). I maintain too hashes; one for the total and one for the sequence. I'm using the $. special variable that holds the current input line number to label the sequence:
use Data::Printer;

while( <DATA> ) {
    while( /\G([ATGC]{2})/g ) {
        $total{$1}++;
        $by_sequence{$.}{$1}++;
        pos() = pos() - 1
        }
    }

p( %total );
p( %by_sequence );

Doing the same thing with substr took a bit much more work because I couldn't limit the substring to just the characters that mattered. I had to pay attention to newlines and odd counts at the end:
use Data::Printer;

LINE: while( <DATA> ) {
    chomp;
    my $pos = 0;
    SUB: while( my $sub = substr( $_, $pos, 2 ) ) {
        last SUB unless 2 == length $sub;
        $total{$sub}++;
        $by_sequence{$.}{$sub}++;
        $pos++;
        }
    }

p( %total );
p( %by_sequence );

The output from Data::Printer is very nice. I've been using it in preference to Data::Dumper since I found out about it at YAPC::Brasil. (And, by the way, its author will be at YAPC::NA in Madison this year to talk about it):
{
    AA   101,
    AC   215,
    AG   268,
    AT   106,
    CA   286,
    CC   388,
    CG   201,
    CT   310,
    GA   239,
    GC   376,
    GG   369,
    GT   168,
    TA   61,
    TC   206,
    TG   317,
    TT   73
}
{
    1   {
        AA   9,
        AC   3,
        AG   8,
        AT   8,
        CA   11,
        CC   12,
        CG   3,
        CT   11,
        GA   5,
        GC   9,
        GG   8,
        GT   6,
        TA   2,
        TC   13,
        TG   10,
        TT   7
    },
    2   {
        AA   68,
        AC   177,
        AG   219,
        AT   80,
        CA   230,
        CC   329,
        CG   168,
        CT   264,
        GA   195,
        GC   316,
        GG   317,
        GT   146,
        TA   50,
        TC   169,
        TG   271,
        TT   54
    },
    3   {
        AA   24,
        AC   35,
        AG   41,
        AT   18,
        CA   45,
        CC   47,
        CG   30,
        CT   35,
        GA   39,
        GC   51,
        GG   44,
        GT   16,
        TA   9,
        TC   24,
        TG   36,
        TT   12
    }
}


text:
Q: Xcode, last version, getting error on builds and archives I am having an issue on my Xcode, lots of times I built or archives the project, I get this error :

Process:               Xcode [2376] Path:
  /Applications/Xcode.app/Contents/MacOS/Xcode Identifier:
  com.apple.dt.Xcode Version:               9.2 (13772) Build Info:
  IDEFrameworks-13772000000000000~2 App Item ID:           497799835 App
  External ID:       825038102 Code Type:             X86-64 (Native)
  Parent Process:        ??? [1] Responsible:           Xcode [2376]
  User ID:               501
Date/Time:             2018-02-19 13:01:31.507 +0100 OS Version:
  Mac OS X 10.13.2 (17C88) Report Version:        12 Anonymous UUID:
  86191C10-4328-FD41-CE74-B094E22BEFE9
Time Awake Since Boot: 510 seconds
System Integrity Protection: enabled
Crashed Thread:        45  Dispatch queue: ConcurrentQueue:
  -[XCWorkQueueCommandBuiltinInvocation startRunning]_block_invoke
Exception Type:        EXC_CRASH (SIGABRT) Exception Codes:
  0x0000000000000000, 0x0000000000000000 Exception Note:
  EXC_CORPSE_NOTIFY
Application Specific Information: ProductBuildVersion: 9C40b Assertion
  failed: (sizeBack == listSize), function
  _has_code_signature_extended_attribute, file /Library/Caches/com.apple.xbs/Sources/IDEXcode3ProjectSupport/IDEXcode3ProjectSupport-13756/Xcode3Core/LegacyProjects/Frameworks/DevToolsCore/BuildTaskPlugIns/CoreBuildTasks/Translators/PBXCp/PBXCp.mm,
  line 453.
Thread 0:: Dispatch queue: com.apple.main-thread 0
  libsystem_kernel.dylib            0x00007fff57ec07c2 mach_msg_trap + 10 1
  libsystem_kernel.dylib            0x00007fff57ebfcdc mach_msg + 60 2
  com.apple.CoreFoundation          0x00007fff30488a15
  __CFRunLoopServiceMachPort + 341 3   com.apple.CoreFoundation         0x00007fff30487d67 __CFRunLoopRun + 1783 4   com.apple.CoreFoundation
    0x00007fff304873d7 CFRunLoopRunSpecific + 487 5   com.apple.HIToolbox
    0x00007fff2f794e26 RunCurrentEventLoopInMode + 286 6
  com.apple.HIToolbox               0x00007fff2f794b96
  ReceiveNextEventCommon + 613 7   com.apple.HIToolbox
    0x00007fff2f794914 _BlockUntilNextEventMatchingListInModeWithFilter +
  64 8   com.apple.AppKit               0x00007fff2da5ff5f _DPSNextEvent
  + 2085 9   com.apple.AppKit               0x00007fff2e1f5b4c -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 3044 10  com.apple.dt.DVTKit               0x000000010f84ff9a -[DVTApplication
  nextEventMatchingMask:untilDate:inMode:dequeue:] + 390 11
  com.apple.AppKit                  0x00007fff2da54d6d -[NSApplication run]
  + 764 12  com.apple.AppKit                0x00007fff2da23f1a NSApplicationMain + 804 13  libdyld.dylib
    0x00007fff57d7a115 start + 1
Thread 1:: Dispatch queue: shared-compile-command-queue (QOS:
  UNSPECIFIED) 0   libsystem_kernel.dylib           0x00007fff57ecb41a
  read + 10 1   com.apple.Xcode.DevToolsCore    0x0000000122e9a7aa
  -[XCWorkQueueCommandLocalSubprocessInvocation handleOutputFileDescriptorActivity] + 86 2
  com.apple.Xcode.DevToolsCore      0x0000000122f094f3 -[Xcode3BuildTask
  main] + 1042 3   com.apple.Foundation             0x00007fff3259b53e
  -[__NSOperationInternal _start:] + 778 4   libdispatch.dylib              0x00007fff57d40d50 _dispatch_client_callout + 8 5   libdispatch.dylib
    0x00007fff57d53333 _dispatch_block_invoke_direct + 317 6
  libdispatch.dylib                 0x00007fff57d40d50
  _dispatch_client_callout + 8 7   libdispatch.dylib                0x00007fff57d53333 _dispatch_block_invoke_direct + 317 8
  libdispatch.dylib                 0x00007fff57d531d6
  dispatch_block_perform + 109 9   com.apple.Foundation
    0x00007fff3259754c __NSOQSchedule_f + 342 10  libdispatch.dylib
    0x00007fff57d40d50 _dispatch_client_callout + 8 11  libdispatch.dylib
    0x00007fff57d53e76 _dispatch_continuation_pop + 472 12
  libdispatch.dylib                 0x00007fff57d4b6cb
  _dispatch_async_redirect_invoke + 703 13  libdispatch.dylib               0x00007fff57d42941 _dispatch_root_queue_drain + 515 14
  libdispatch.dylib                 0x00007fff57d426ed
  _dispatch_worker_thread3 + 101 15  libsystem_pthread.dylib        0x00007fff580051ca _pthread_wqthread + 1387 16
  libsystem_pthread.dylib           0x00007fff58004c4d start_wqthread + 13
Thread 2:: Dispatch queue: -[IDEExecutionEnvironment
  initWithWorkspaceArena:] (QOS: UNSPECIFIED) 0   libsystem_kernel.dylib
    0x00007fff57ec9cee __psynch_cvwait + 10 1   libsystem_pthread.dylib
    0x00007fff58006662 _pthread_cond_wait + 732 2   com.apple.Foundation
    0x00007fff3264acf8 -[__NSOperationInternal _waitUntilFinished:] + 896
  3   com.apple.Foundation              0x00007fff3261b765
  -[NSOperationQueue waitUntilAllOperationsAreFinished] + 296 4   com.apple.dt.DVTFoundation        0x000000010f12a9c4 -[DVTOperationGroup
  main] + 66 5   com.apple.Foundation           0x00007fff3259b53e
  -[__NSOperationInternal _start:] + 778 6   com.apple.dt.DVTFoundation     0x000000010f12a977 -[DVTOperationGroup start] + 110 7
  com.apple.Foundation              0x00007fff32597567 __NSOQSchedule_f +
  369 8   libdispatch.dylib                 0x00007fff57d40d50
  _dispatch_client_callout + 8 9   libdispatch.dylib                0x00007fff57d53e76 _dispatch_continuation_pop + 472 10
  libdispatch.dylib                 0x00007fff57d4b6cb
  _dispatch_async_redirect_invoke + 703 11  libdispatch.dylib               0x00007fff57d42941 _dispatch_root_queue_drain + 515 12
  libdispatch.dylib                 0x00007fff57d426ed
  _dispatch_worker_thread3 + 101 13  libsystem_pthread.dylib        0x00007fff580051ca _pthread_wqthread + 1387 14
  libsystem_pthread.dylib           0x00007fff58004c4d start_wqthread + 13
  ...

There are also several times, the built goes succesfully... is anyone sperimentig this issue ?


text:
Q: Distributed jmeter test, with 20 VMs running jmeter-server. Kicks off first thread for each VM during ramp up, across all VMs at the same time I am running a test using a high memory footprint script (don't ask) and I have been given 20 VMs to run jmeter-server. 20 VMs and 8 threads per VM. Ugh. 160 threads total
When I start the test from the Master, every server kicks off the first thread at the same moment (yep of course). But this causes 20 Txn to hammer the system at once.

I thought to put a uniform random timer inside a "once only" controller, for about half the length of Pacing but the graph is still showing thread starts and ends about the same time.

Eventually it evens out because of random think time. Why isn't the uniform random timer doing what I expect it to do?
There must be some assumption I'm missing. Any advice?

A: I don't think your Uniform Random Timer really works, according to JMeter Scoping Rules it really adds a delay only when it's run in context of a Sampler. It means no sampler = no delay.
You need to add a Sampler, i.e. Flow Control Action one under the Once Only Controller and make the Uniform Random Timer the child of this Sampler.
More information: A Comprehensive Guide to Using JMeter Timers


text:
Q: Missing required parameters for route issue in laravel In my laravel based application I have following link in my admin.blade.php

{{ __('Home Page') }}

In my project I have another blade called, create.blade.php which is in the following path
views/cms/home/create.blade.php

I have a controller called, CmsHomeController.php for that blade
In CmsHomeController I have a method called create
public function create()
{
    return view('cms.home.create');
}

Once the user clicks on the above mentioned link in the admin.blade.php, user should go to the create.blade.php blade.
And in my web.php I have registered my route as follows,
Route::resource('cms.home','CmsHomeController');

But now the issue is,
When I click on that link in admin blade, I'm getting an error saying
Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: cms.home.create] [URI: cms/{cm}/home/create]. (View: C:\xampp\htdocs\mylaravelproject\resources\views\layouts\admin.blade.php)

In create.blade.php , I'm  having just a simple form
Where am I doing wrong and what would be the correct fix?
UPDATE:
I tried running
php artisan route:list

This is what I got

I don't have such a param called, 'cm'..

A: As you are using dot (.) operator in your resource route it will generating nested routes.
You need to change your route name with single name like cms-home  or cms_home
Then you can simple use it as:
Route::resource('cms_home','CmsHomeController');

In your blade you can call it:

Please have look at this referance

A: Your route need a parameter (cm)
You should have in your template href="{{ route('cms.home.create', ['cm' => $id_cm]) }}"

A: Just Pass the value in your route cms.home.create like this.

       $value]) }}" class="nav-link">

{{ __('Home Page') }}

A: If you need the route be cms.home, try this:
Route::resource('cms.home', 'CmsHomeController', [
    'parameters' => ['cms' => 'cms']
]);


text:
Q: 1-d random walk probability bound calculation problem I'm recently reading the paper about digital fountain code "LT Codes" by M. Luby.
There is a statement seems simple with the author "The probability a random walk of length $k$ deviates form its mean by more than $\text{ln}(k/\delta)\sqrt{k}$ is at most
$\delta$".
Let me describe this in math formulation. Suppose $X_1, X_2, ..., X_k$ is mutually independent identically distributed, and
$$\text{Pr}(X_i)=\begin{cases} \frac12,&X_i=\pm1\\0, &\text{else}\end{cases}$$
consider a sum of $X_i$,$S_k=\sum_{i=1}^k X_i$ .
Then there is a bound of probability:
$$\text{Pr}\{\max\limits_{1\le{i}\le{k}}|S_i|\gt \text{ln}(k/\delta)\sqrt{k}\}\le{\delta}$$
There's not much material about random walk i can obtain. Please someone show me the proof of the statement. Thanks very much!

A: Kolmogorov's inequality yields more, namely, the upper bound $1/(\ln(k/\delta))^2$.
This is less than $\delta$ for every $\delta$ in $(0,1)$, for every $k\geqslant\exp(1/\sqrt{\delta})$.

A: There are a lot maximal inequalities like this.
You can see: Bernstein inequality
Once you have Bernstein you can proof the following:
There are $c_1, c_2 >0 $ such that
$$ \frac{c_1exp(-k_{n}^{2}/2)}{k_n} \le P(\max\limits_{1\le{i}\le{n}}|S_i|\ge \sqrt{n}k_n) \le \frac{c_2exp(-k_{n}^{2}/2)}{k_n}  $$
If $k_n = o(n^{\frac{1}{6}})$.
The proof, as I said, makes use of Bernstein and the Local Limit Theorem. First you proof a similar statement to $S_n$ and then use that $P(\max\limits_{1\le{i}\le{n}}|S_i|\ge a) \le 4P(S_n \ge a)$ and the fact that $ \{S_n \ge a\} \subset \{\max\limits_{1\le{i}\le{n}}|S_i|\ge a\}$ to get the result.
Note that $log(n/\delta) = o(n^{\frac{1}{6}})$ and you can use $\sqrt{log(n/\delta)}$ instead of $log(n/\delta)$ to get "exactly" what you want.
I can show you all the details if you want. But you can see this reference:
Limit Theorems of Probability Theory - Pál Révész
Hope this can help!


text:
Q: kentico add new form field via API Hello Kentico experts,
I need to create some new form fields dynamically via Kentico API. I found a solution but it is for Kentico 6 and it is not available for my version (i'm using Kentico 8).
https://devnet.kentico.com/articles/how-to-add-a-new-field-to-a-document-type-using-api
Please help !
Thanks,
Duong

A: This should work:
string classname = "classname";
DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(classname);
if (dci != null)
{
    FormInfo fi = new FormInfo(dci.ClassFormDefinition);
    if (fi != null)
    {
        // Field definition
        FormFieldInfo ffi = new FormFieldInfo();
        ffi.Name = "FieldName";
        ffi.AllowEmpty = true;
        ffi.System = false;
        ffi.FieldType = CMS.FormEngine.FormFieldControlTypeEnum.UploadControl;
        ffi.Visible = true;
        ffi.Caption = "Field Caption";
        ffi.Enabled = true;
        // Set whatever properties are relevant to you

        fi.AddFormItem(ffi);

        TableManager tm = new TableManager(null);
        tm.AddTableColumn(dci.ClassTableName, ffi.Name, "uniqueidentifier", true, null);

        dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);
        dci.ClassFormDefinition = fi.GetXmlDefinition();

        // Update DataClassInfo object
        DataClassInfoProvider.SetDataClassInfo(dci);

        // Update inherited classes with new field
        FormHelper.UpdateInheritedClasses(dci);

    }
}

You can always check the API changes between versions on Kentico DevNet.


text:
Q: Can a tripod table be placed upon any surface? When I try to sleep at night, I find myself envisioning topological objects and wondering about the behavior of material in the abstract. Here's my latest quandary:
Let an equilateral triangle be constrained so that one vertex lies on a surface, at some point. Is there a surface such that the other two points of the triangle cannot also be placed upon the surface?
More intuitively, is there any finite object upon which a pizza saver/tripod table cannot be set to rest?
More precisely, in 3-dimensional Euclidean space, is there a surface with a point at which one of an equilateral triangle's vertices can be placed, while the other two vertices cannot be be simultaneously also placed onto some other points of the surface?
Note that the the plane of the triangle may be pierced by the surface (alternatively, the length of the pizza saver's legs may be arbitrarily long).

Fig. 1 A trivial case. Credit
.
Notes:

*

*The triangle's sides can be made arbitrarily small.

.
After more careful thought:
Perhaps what I'm really wondering is What limitations should be set upon this scenario so that the problem is non-trivial?

A: Yes, there are such surfaces. For example, take the sphere that you pictured, and shrink it down so that the other two vertices are much farther apart than the edges of the sphere. Then, if one vertex has been constrained to lie on the sphere, then the other two can't, because the sphere just isn't big enough.
However, there are further versions of this which ARE true, in a sense. Look up the Wobbly Table Theorem.

A: Imagine 2 points on the surface, $d$ distance apart. Imagine a circle in the plane perpendicular to the segment joining them, centered at the midpoint of the segment and having radius $\frac{\sqrt{3}}{2}d$. If this circle intersects the surface, the point of intersection is the third point, otherwise we can make $d$ arbitrarily smaller until it intersects.


text:
Q: apex select list item should return default values I have an select list item which is having LOV as select name, name from dual, but I need to display some default value for that item, the default PL/SQL code is
DECLARE
   l_workspace   VARCHAR2 (4000);
   l_email       VARCHAR2 (4000);
BEGIN
   SELECT WORKSPACES
     INTO l_workspace
     FROM ALLUSER_WORKSPACES_FACT
    WHERE LOWER (email) = LOWER ( :app_user);

   FOR i
      IN (SELECT COLUMN_VALUE col1
            FROM TABLE (f_str2tbl (LOWER (l_Workspace), ',')))
   LOOP
      l_email := i.col1;
      RETURN l_email;
   END LOOP;
END;

o/p is like:
a
b
c

The select list value is displaying only the 1st value as remaining data is not being displayed.
What's wrong with the PL/SQL code? I need to get all the output in the select list as
a
b
c

Thanks

A: If your select list is defined with Allow Multi Selection = Yes then the selected values are held as a colon-delimited list e.g. 'A:B:C'.  So you need to make your default the same.  The apex_string.join function can help - in fact their example is:
apex_string.join(apex_t_varchar2('a','b','c'),':')
-> a:b:c

A: Statement
return l_email;

always ends function, so it breaks the loop.
For this LOV you should use PL/SQL Function Body returning SQL Query with code like
DECLARE
   l_workspace   VARCHAR2 (4000);
   l_email       VARCHAR2 (4000);
BEGIN
  SELECT WORKSPACES
     INTO l_workspace
     FROM ALLUSER_WORKSPACES_FACT
    WHERE LOWER (email) = LOWER ( :app_user);

   return 'SELECT COLUMN_VALUE col1
            FROM TABLE (f_str2tbl (LOWER (l_Workspace), '',''))';
END;


text:
Q: Kendo Angular Grid Gives 'Unresolved Local Varibale' I'm using Kendo UI for Angular Grid and I'm getting a warning from TypeScript that says 'Unresolved variable Name' and 'Unresolved variable Id' on this HTML:
<kendo-grid [selectable]="selectable360"
            [resizable]="true"
            [kendoGridSelectBy]="SelectedCallback"
            [selectedKeys]="Selected360"
            (cellClick)="SetGridDraggable()"
            *ngIf="ShowModelAsList && CurrentFolder"
            [kendoGridBinding]="CurrentFolder.Models">
  <kendo-grid-column title="Name" field="Name">
    <ng-template kendoGridCellTemplate let-dataItem>

{{dataItem.Name}}

{{dataItem.Id}}

    </ng-template>
  </kendo-grid-column>
  <kendo-grid-column title="Last Update" field="LastUpdate" width="150" format="g"></kendo-grid-column>
  <kendo-grid-column title="Update By" field="UpdateBy"></kendo-grid-column>
  <kendo-grid-column title="Version" field="Version" width="70" [style]="{'text-align': 'center'}"></kendo-grid-column>
</kendo-grid>

The data that it's bound as is just Models: FileUI[]; and FileUI definitely has those properties:
export class FileUI implements BIM360ItemBase {
  // Interface Implementation
  public IsFolder = false;

  @JsonProperty('id', String)
  Id: string = undefined;

  @JsonProperty('parentId', String, true)
  ParentId: string | null = undefined;

  @JsonProperty('projectId', String)
  ProjectId: string = undefined;

  @JsonProperty('name', String)
  Name: string = undefined;

  // Class Properties
  @JsonProperty('thumbnail', String, true)
  ImagePath: string | null = undefined;
  Version: string;
  LastUpdate: Date;
  UpdateBy: string;

  @JsonProperty('directoryId', String)
  DirectoryId: string = undefined;

  @JsonProperty('fileType', FileType)
  FileType: FileType = undefined;
}

I'm getting similar warnings in many other ng-template tags as well but this is a good concise example.  I know that it's all working because I can build it and it displays correctly, but I'd like to get rid of the warnings if possible.
Why is it telling me it's not defined and how can I fix it?


text:
Q: jquery datepicker with codeigniter issues I'm trying to write a sign up form using CodeIgniter and want to use the jquery datepicker for DOB, but the following isn't working.  This is the entire page:
<!DOCTYPE HTML>
<html>
<head>

    <link rel="stylesheet" href="http://localhost/cc/css/style.css" type="text/css" media="screen" charset="utf-8">
    <link rel="stylesheet" href="http://localhost/cc/jquery/css/dot-luv/jquery-ui-1.8.16.custom.css" type="text/css" media="screen" charset="utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
    <script src="http://localhost/cc/jquery/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
    <title>CC - Card Central</title>
</head>

<body>
    <script>
        $(function() {
            $( ".datepicker" ).datepicker();
        });
    </script>

    <fieldset>
        <legend>Create a new account!</legend>
            <fieldset>
                <legend>Personal Information</legend>
                <form action="http://localhost/cc/index.php/account/create_account" method="post" accept-charset="utf-8">
                    <input type="text" name="firstname" value="" placeholder="First Name" />
                    <input type="text" name="middlename" value="" placeholder="Middle Name" />
                    <input type="text" name="lastname" value="" placeholder="Last Name" />
                    <input type="text" name="dob" value="" placeholder="Date of Birth" class="datepicker" />
            </fieldset>
            <fieldset>
                <legend>Account Information</legend>
                    <input type="text" name="username" value="" placeholder="Username" />
                    <input type="text" name="password" value="" placeholder="Password" />
                    <input type="text" name="passwordconfirm" value="" placeholder="Password Confirm" />
                    <input type="submit" name="submit" value="Done!"  />
            </fieldset>
        </fieldset>
    </body>
</html>

A: You've forgotten to include the jQuery library :-)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

Put that before the script tag that references jQuery UI and you should be good to go


text:
Q: R+shiny: Read an input variable from a non-reactive function I have the following code:
library(shiny)

foo <- function(a, b){
  a*b*input$ni
}

ui <- fluidPage(
  numericInput("ni", label = "in", value = 3),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {
  output$out <- renderText(foo(a = 2, b = 4))
}

shinyApp(ui = ui, server = server)

Running this results in the error object 'input' not found. The foo function does not know about the shiny inputs because it's written outside the shiny functions and it's not a reactive function.
How can I make it work? Because of how my code is built (beyond this MWE), I need that the function foo only takes the parameters a and b and none else. That is, the input cannot be passed into it as an argument. It also needs sit outside of the server function.
Is there a way to make it take the input variable from the shiny environment somehow?

A: If you can't change the function arguments you can make use of global assignment operator (<<-) so that the variable is available outside the scope of function.
library(shiny)

foo <- function(a, b){
  a*b*ni
}

ui <- fluidPage(
  numericInput("ni", label = "in", value = 3),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {

  output$out <- renderText({
    ni <<- input$ni
    foo(a = 2, b = 4)
  })
}

shinyApp(ui = ui, server = server)


text:
Q: How to repeat specific request multiple times when loop controller cannot serve the purpose? The requirement is we have 4 requests req1, req2, req3, req4. Since, we have to add pass 20 days data, we are using ${__timeShift(yyyy-MM-dd HH:mm:ss,,-P${__intSum(21,-${__counter(FALSE,)},)}DT2M,,)} to serve date purpose under loop controller for 20 loop count.
But here, req1 we want to call 3 times for same date and rest others just once. When we are adding loop controller(3 times) to req1 under parent loop controller, the date is 2021-04-14 12:12:02, 2021-04-15 12:12:02, 2021-04-16 12:12:02 each times its called for all requests BUT what we want is:
req1 to be called thrice per day 2021-04-14 12:12:02, 2021-04-14 12:12:02, 2021-04-14 12:12:02.
req2, req3, re4 2021-04-14 12:12:02 once only.
When loop controller was added to req1 for 3 times loop, it did not work. It shows 2021-04-14 12:12:02, 2021-04-15 12:12:02, 2021-04-16 12:12:02
Please help.

    Thread group
----Parent loop controller(20 count so as to add past 20 days record starting from 2021-04-14 12:12:02, 2021-04-15 12:12:02, till 20 days)
------req1(want to call this request 3 times per day 2021-04-14 12:12:02,2021-04-14 12:12:02,2021-04-14 12:12:02)
------req2(just once per day)
------req3(just once per day)
------req4(just once per day)

This is how it looks currently.

A: You're using __counter() function which produces incremented value each time it's being called, if you need the described behaviour you need to amend your test as follows:

*

*Loop Controller (3 count)

*

*req 1 ${__timeShift(yyyy-MM-dd HH:mm:ss,,-P20DT2M,,)}

*Loop Controller (20 count)

*

*req 1 ${__timeShift(yyyy-MM-dd HH:mm:ss,,-P${__intSum(21,-${__counter(FALSE,)},)}DT2M,,)}
More information: How to Use a Counter in a JMeter Test
Also be aware that there is ${__jm__Loop Controller__idx} pre-defined variable which exposes the current iteration of the Loop Controller so you might want to use it instead of the __counter() function


text:
Q: Got 70 Items in Cart which I can't remove! Good Morning to all.
First of all please note that I am not the merchant but a buyer. I do use shop.funko.com to purchase Pop Vinyl Figures. This problem has been persistent and I ended up buying via guest to temporary be able to buy.
However I want to see my order history but whenever I log in (successfully). Whenever I try getting either into my basket or my order history I keep getting the blank white page with

There has been an error processing your request Error log record
  number: 712693230067 (numbers vary this is just one).

It is happening on all browsers and cache is clear.
Thanks for any help.
Clayton :)


text:
Q: Suggested Neural Network for small, highly varying dataset? I am currently working with a small dataset of training values, no more than 20, and am getting large MSE.  The input data vectors themselves consist of 16 parameters, many of which are binary variables.  Across all the training values, a majority of the 16 parameters stay the same (but not all).  The remaining input variables, across all the exemplars, vary a lot amongst one another.  This is to say, two exemplars might appear to be the same except for two parameters in which they differ, one parameter being a binary variable, and another being a continuous variable, where the difference could be greater than a single standard deviation (for that variable's set of values).
My single output variable (as of now) can either be a continuous variable, OR depending on the true difficulty of reducing the error in my situation, I can make this a classification problem instead, with 12 different forms for classification.
I have long been researching different neural networks than my current implementation of a feed-forward MLP, as I have read into Stochastic NNs, Ladder NNs, and many forms of recurrent NNs.  I am stuck with which one I should investigate, as I do not have time to try every NN available.
While my description may be vague, could anyone make a suggestion as to which network I should investigate to minimize my cost function (as of now, MSE) the most?
If my current setup must be rendered implacable because of the sheer difficulty involved with predicting correct output for such a small set of highly variant training values, which network would best work, should my dataset be expanded to the order of thousands of exemplars (at the cost of having a significantly more redundant, seemingly homogenous set of input values)?
Any help is most certainly appreciated.

A: 20 samples is very small especially if you have 16 input variables. It will be hard to determine which one of those inputs is responsible for your output value. If you keep your network simple (fewer layers) you may be able to use as many samples as you would need for traditional regression.


text:
Q: How to configure a VisualizationViewer so users can move nodes with the mouse? I'm using Jung 2.0 for a while now, but I'm a bit confused with all the configuration code that is done in the various demos that ship with the package.
Could anyone tell me how to configure a VisualizationViewer so that I can move the graph nodes around by clicking and draging them with the mouse?
The code I have is below. It's a mix of the various demos I studied. But I can only pan and rotate the graph with it.
public class GrafoParticipacaoSocietaria extends JFrame {

    Graph<VerticeParticipacaoSocietaria, Integer> graph;
    VisualizationViewer<String, String> vv;
    Layout<VerticeParticipacaoSocietaria, Integer> layout;

    public GrafoParticipacaoSocietaria(Graph<VerticeParticipacaoSocietaria, Integer> grafoPart) {
        super("Participação Societária");

        graph = grafoPart;
        layout = new ISOMLayout(graph);

        final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout);
        vv = new VisualizationViewer(visualizationModel);

        vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
        vv.setForeground(Color.blue);
        getContentPane().add(vv);

        // this class will provide both label drawing and vertex shapes
        VertexLabelAsShapeRenderer<String, String> vlasr = new VertexLabelAsShapeRenderer<String, String>(
                vv.getRenderContext());

        vv.getRenderContext().setVertexShapeTransformer(vlasr);
        vv.getRenderContext().setVertexLabelRenderer(new DefaultVertexLabelRenderer(Color.lightGray));
        vv.getRenderContext().setEdgeDrawPaintTransformer(new ConstantTransformer(Color.lightGray));
        vv.getRenderContext().setEdgeStrokeTransformer(new ConstantTransformer(new BasicStroke(1.0f)));

        // customize the renderer
        // vv.getRenderer().setVertexRenderer(new MyGradientVertexRenderer<String, String>(Color.cyan, Color.white, true));
        vv.getRenderer().setVertexLabelRenderer(vlasr);

        vv.setGraphMouse(new DefaultModalGraphMouse());
    }
}

A: Thanks to GrahamA's answer, I found the code I was looking for:
    DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);
    vv.setGraphMouse(graphMouse);

That code changes the mode in ModalGraphMouse to the PICKING, which allows the user to select and move nodes around.

A: You can find an example on the Jung website here use Editing to add nodes and then switch to Picking to move the nodes you have added.  The sourcode is avalaible from SourceFource check out jung-samples-X.X.X.jar the class called GraphEditorDemo

Screen shot from the Jung Website


text:
Q: Approved behaviour of disconnected router receiving DHCP discover packet What is the normal/approved behaviour of a router if it receives a DHCP discover packet when it has no connection to the Internet?
Background: I have lost my home broadband connection. The ISP (Virgin Media) want to send an engineer, who cannot come for a week.  However, various evidence suggests to me that it is just the router that is broken, and if I could convince the ISP of that, I could perhaps get a new router more quickly.  Anyway, I would like to understand the situation.
Two different PCs fail to connect through the router via cables, and a phone fails to connect wirelessly, so it cannot be a problem with the network card in the PC.
Wireshark shows my PC sending out DHCP discover packets.  I think that if the router received these packets and it was working correctly, then it should reply even if there was no connection from the router to the external Internet.   Is my understanding correct here?
In fact, I see no packets of any kind coming back from the router.


text:
Q: I have a problem with Bootstrap grid system not changing the columns correctly according to pixel sizes specified on getbootstrap guidelines I have a code that is supposed to make the columns collapse at the size of 991px but it keeps doing it at 767px, in otherwords I'm specifying that it should collapse when it's less than a medium device but it's only doing it when it's less than a small device, I checked my code many times and I'm confused as to what's going on since I'm following the exact code in my class, here's the code:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Starter Page</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">

Col 1

Col 2

Col 3

See it's still treating it as 4 4 4 even though the size is below 991px
And here it finally works at 767px

A: I need to ask, what is all of the other code. Since the problem is 100% not in the HTML. (Just saying I am just putting this as an answer because I don't have the 50 reputation needed to add a comment on other people's questions.)


text:
Q: jQuery .addClass() not working with Angular.js In my code, I did
element.attr('class', element.attr('class') + ' state-active');

and the class .state-active got added to the element.
But when I try
element.addClass('state-active');

nothing happens.
It doesn't work, doesn't matter if I get the element with any of those:
var element = $('.state');
var element = angular.element($('.state'));
var element = angular.element($('.state')[0]);

I tried everything I could imagine, but none was enough. I noticed that .css() doesn't work either.
What could cause this issue and how do I solve this? For now my code is working, but that solution is not elegant...

A: Rather than using jQuery, try to approach the problem from a different angle (no pun intended!) such as using ngClass. This allows you to set classes according to conditions using data binding. It's usually better that way, letting Angular do the nuts&bolts of actually changing the DOM.


text:
Q: How can I apply the hough circle method to a thresholded image? I currently have a program that can detect colored balls with openCV and I'd like to add the HoughCircle method to make it better.
I had the idea to apply the HoughCircle method on the thresholded image that i got from the inRange method but unfortunately it does not work.
I saw that the HoughCircle method is only taking gray-scale images, is there a way to pass the thresholded image to it ?
this is how I do :
int isBall(Mat threshold){
    Mat temp;
    threshold.copyTo(temp);
    std::vector<Vec3f> circles;
    HoughCircles(temp, circles, CV_HOUGH_GRADIENT, 1, temp.rows/8
                                                    , 100
                                                    , 50
                                                    , 15 /* min radius */
                                                    , 200 /* max radius */
                                                    );
    printf("nb circles = %d\n", circles.size());
    if(circles.size() > 0){
        return 1;
    }
    return 0;

}

the thresholded image is coming from :
inRange(HSV,Scalar(H_MIN,S_MIN,V_MIN),Scalar(H_MAX,S_MAX,V_MAX),threshold);

Here is an example of a thresholded image that i can get :
https://www.noelshack.com/2019-39-5-1569586501-threshold.png
Thanks in advance for your help.

A: The problem you are facing is related to the parameters used in HoughCircles. You can use the example image just fine if you convert it to a gray-scale one.
The main culprit is param2=50, that is a threshold for circle centers at detection stage. If you set it to a smaller value, the algorithm will be able to return the circle.
I have tested HoughCircles() using param2=10 and the result is this:


text:
Q: How to loop through a range using a variable in vba I'm trying to loop through a range below and get runtime error 1004. The highlighted row is this one here:
ActiveChart.SeriesCollection(i).Values = Worksheets("Chart Help").Range(Cells(10 + j, 5), Cells(10 + j, 1006))

Can anyone tell me what's wrong?
If Worksheets("Chart Help").Cells(4, 9 + j) <> " " Then
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(i).Name = Worksheets("Chart Help").Cells(4, 9 + j)
    ActiveChart.SeriesCollection(i).XValues = Worksheets("Chart Help").Range("J5:J1006")
    ActiveChart.SeriesCollection(i).Values = Worksheets("Chart Help").Range(Cells(10 + j, 5), Cells(10 + j, 1006))
    ActiveChart.SeriesCollection(i).Select

    With Selection.Format.Line
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorAccent6
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = 0
        .Transparency = 0
    End With

    i = i + 1
End If

j = j + 1

A: Replace
.Range(Cells(10 + j, 5), Cells(10 + j, 1006))

with
.Range("E10").Offset(j,0).Resize(1, 1001)

In general avoid using the Cells to target cells, and instead start from a fixed address (like "E10" above) and using a combination of .Offset() and .Resize() to tweak the range of cells you want to act upon.

A: I assume your loop has the proper code and you simply didn't paste it all.
Your 2 calls to Cells refer to the ActiveSheet and not the Chart Help worksheet like you intend.  You will need to prefix Cells with Worksheets("Chart Help").Cells for it to not error.
Something like this:
ActiveChart.SeriesCollection(i).Values = Worksheets("Chart Help").Range(Worksheets("Chart Help").Cells(10 + j, 5), Worksheets("Chart Help").Cells(10 + j, 1006))

Ideally you would define a reference to that worksheet to clean up the code.  You also do not have to prefix the Range with the worksheet in this case.  Those two ideas combined give:
Dim sht_chart As Worksheet
Set sht_chart = Worksheets("Chart Help")
ActiveChart.SeriesCollection(i).Values = Range(sht_chart.Cells(10 + j, 5), sht_chart.Cells(10 + j, 1006))


text:
Q: jQuery Joyride plugin - nothing happens? I'm having a lot of trouble getting the Joyride plugin for jQuery to work.  I thought it seemed pretty simple, but it's not happening.
I have the following script includes on my page:

And all three are loading correctly.  In application.js I have called joyride in the following way:
$(window).load(function () {
    $('#tour').joyride();
});

And my HTML looks like this:

This is the tour.

For some reason, absolutely nothing is happening when I load the page.  I don't get any errors in the console, literally nothing happens.  Anyone had this problem?

A: To see anything happen, put the option autoStart: true into the joyride function:
$(window).load(function () {
    $('#tour').joyride({
        autoStart: true
    });
});

Here's a working plunk.
By the way, if you give your ol an id of joyRideTipContent that will automatically be set to display: none by the CSS.


text:
Q: extract payload from tcpflow output Tcpflow outputs a bunch of files, many of which are HTTP responses from a web server. Inside, they contain HTTP headers, including Content-type: , and other important ones.  I'm trying to write a script that can extract just the payload data (i.e. image/jpeg; text/html; et al.) and save it to a file [optional: with an appropriate name and file extension].
The EOL chars are \r\n (CRLF) and so this makes it difficult to use in GNU distros (in my experiences).
I've been trying something along the lines of:
sed /HTTP/,/^$/d

To delete all text from the the beginning of HTTP (incl) to the end of \r\n\r\n (incl) but I have found no luck. I'm looking for help from anyone with good experience in sed and/or awk. I have zero experience with Perl, please I'd prefer to use common GNU command line utilities for this
Find a sample tcpflow output file here. (bad link)
Thanks,
Felipe

A: This article recommends running foremost on output from tcpflow to extract the images. It's available at that link and in the repositories of (at least) Debian, Fedora and Ubuntu.
I tried it on the sample file you linked to and it seemed to work fine.
foremost -i tcpflow.out

It created a directory called "output" with subdirectories called "gif" and "jpeg" with files in each. The names of the files don't match the filenames in the headers, though.
To change the line endings of your files do:
dos2unix filename

or in a pipe:
dos2unix < filename | nextcommand

Other links of interest:

*

*httpflow - parses tcpflow output

*tcpxtract - another file extractor

*Forensic Tools for Unix - a list of open source tools


text:
Q: Compare datetime fields without time element Currently I have the following line:
AND date_sent + INTERVAL 3 DAY <= NOW()

However this doesn't get results where the time is later than NOW(), how would I simply compare dates in date_sent that were 3 days later than the original?

A: For anyone else looking I solved it using:
AND DATE(value_sent) + INTERVAL 3 DAY <= CURDATE()


text:
Q: Making function for calculating distance Hello I am using Python to calculate the distance that user walked. I am determining whether they walked or not by speed. If there speed was slower than 5m/s, they I will consider as walking. But I am having trouble making this function. Could you help me out how to make function for this? So far my input is manually put another function called "make_timestamped_loc" and calculating the distance by function called "total_dist" Here is my code...
import ctp17hw1
dic_loc = []
def make_timestamped_loc(La, Lng, TS):
    new_loc = {}
    new_loc['latitude'] = La
    new_loc['longitude'] = Lng
    new_loc['timestamp'] = int(TS)
    dic_loc.append(new_loc)

make_timestamped_loc(37.481236, 126.952733, 1483196400)
make_timestamped_loc(37.310045, 127.101255, 1408323255)
make_timestamped_loc(37.383065, 126.672596, 1508322531)
make_timestamped_loc(37.383065, 116.672596, 1444999230)

# make_timestamped_loc(37.383065, 112.672596, 1444999230) #error sample
print(dic_loc)
def sort_locs(sortingDict):
    newlist = sorted(sortingDict, key=lambda k: k['timestamp'])
    for i in range(len(dic_loc) - 1, -1, -1):
       dic_loc.remove(dic_loc[i])
    for i in range(len(newlist)):
        for j in range(len(newlist)):
            if (newlist[i]['timestamp'] == newlist[j]['timestamp']
                and (newlist[i]['latitude'] != newlist[j]['latitude'] or newlist[i]['longitude'] != newlist[j]['longitude'])
                and i != j):
                raise ValueError('There is duplicated location on same time!')
        sortingDict.append(newlist[i])
sort_locs(dic_loc)

def total_dist(sortedDict):
        totalDist = 0;
        for i in range(len(sortedDict) - 1):
            sm = ctp17hw1.dist(sortedDict[i]["latitude"], sortedDict[i]["longitude"], sortedDict[i+1]["latitude"], sortedDict[i+1]["longitude"])
            totalDist = totalDist + sm
        return totalDist
total_dist(dic_loc)
print(total_dist(dic_loc))

ctp17hw1 is another file for calculating the distance.
I am confusing because of Unix time.
Thank you very much

A: Using solutions provided in Getting distance between two points based on latitude/longitude and Iterate a list as pair (current, next) in Python I was able to build a Pythonic approach of this problem:
import itertools

from collections import namedtuple
from math import sin, cos, sqrt, atan2, radians

Location = namedtuple('Location', ['long', 'lat', 'time'])
all_locations = [
    Location(lat=37.481236, long=126.952733, time=1488323400),
    Location(lat=37.310045, long=127.101255, time=1488323255),
    Location(lat=37.383065, long=126.672596, time=1488323531),
    Location(lat=37.383065, long=116.672596, time=1488323230),
]

def distance(loc_a, loc_b):
    """Extracted from: https://stackoverflow.com/questions/19412462"""
    R = 6373.0

    lat_a, lat_b = radians(loc_a.lat), radians(loc_b.lat)
    long_a, long_b = radians(loc_a.long), radians(loc_b.long)
    dlat = lat_b - lat_a
    dlong = long_b - long_a

    a = sin(dlat / 2)**2 + cos(lat_a) * cos(lat_b) * sin(dlong / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))

    return R * c

def pairwise(iterable):
    """Extracted from: https://stackoverflow.com/questions/5434891"""
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

sorted_locations = sorted(all_locations, key=lambda l: l.time)
total_distance = sum(distance(a, b) for a, b in pairwise(sorted_locations))
delta_time = sorted_locations[-1].time - sorted_locations[0].time
print(total_distance, delta_time, total_distance / delta_time)

Using namedtuple is not mandatory, but I felt like it would simplify the code. FTR named tuple are simple structures only containing declared fields (here long, lat and time).
The pairwise function allows to iterate over 2 pairs of a list (i.e. current and next element). By using it on the sorted location list by time, I can easily evaluate the distance. Basically:
sorted_locations = [l1, l2, l3]
distances = [distance(a, b) for a, b in pairwise(sorted_locations)]
# equivalent to [distance(l1, l2), distance(l2, l3)]
total_distance = sum(distances)

Not using intermediate list will reduce memory consumption (which is irrelevant in the example, relevant for large lists). I could also declare a generator of distance (using (distance(a, b) for ...) insteand of a list comprehension).

Notice I did not pre-compute radians of long/lat, and they are computed 2 times for non-extrem elements of the list. This could be a little performance improvement but I mostly wanted to keep the algorithm simple here.


text:
Q: MySQL command line client issue + error 2003 Initially, I was able to open MySQL command line client, and when I type the password, error 2003 will flash very quickly and auto close the client.
After looking online, I try some of the suggested solution using cmd.
From the attach photo you can see that I try mysqld -install and try net start mysql commands but they don't work.

So I using the control panel to repair MySQL Server 5.7. Now I can't open MySQL command line client as it will auto close itself.
How do I rectify this issue? Does reinstalling the whole MySQL works?
To sum up:
1) I can't open MySQL command line client
2) Even if I could, the previous problem can't solve -> error 2003, then autoclose
Why I need to fix this:
- I want to import data from a .sql file, and I used to do that via MySQL command.

A: Using the cmd go to mysql folder, there should be a subfolder called bin.
Now navigate to bin and run mysql -u user -p password where user is your user and password is your password, for example: mysql -u root -p abc123
EDIT
Oh, I didn't pay enough attention to your screenshot. You cannot even start the service?
EDIT2
Nevertheless you should be able to start it manually launching directly from mysql/bin folder.

A: After countless articles on fixing this problem. My solution to this is reinstalling or reconfigure.
Edit: Reconfigure the settings to default


text:
Q: Content-Security-Policy - Can't load external scripts for a private Project I want to load some external images, scripts and styles from my homeserver, but it doesnt work. Where is the mistake?
Nginx Config-File
location / {
            index  index.php index.html index.htm;
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            server_tokens off;
            add_header X-Frame-Options SAMEORIGIN;
            add_header X-Content-Type-Options nosniff;
            add_header X-XSS-Protection "1; mode=block";
            add_header Content-Security-Policy  "default-src *; script-src *; object-src *; style-src *; img-src *; media-src *; frame-src *; font-src *; connect-src *";
            add_header X-Content-Security-Policy "default-src *; script-src *; object-src *; style-src *; img-src *; media-src *; frame-src *; font-src *; connect-src *";
            add_header X-WebKit-CSP "default-src *; script-src *; object-src *; style-src *; img-src *; media-src *; frame-src *; font-src *; connect-src *";

}

HTML Meta Tags:
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src *; style-src *; img-src *; font-src *; connect-src *; media-src *; object-src *; prefetch-src *; child-src *; frame-src *; worker-src *; frame-ancestors *; form-action *; sandbox allow-forms allow-same-origin allow-scripts allow-top-navigation allow-popups allow-pointer-lock; reflected-xss allow; base-uri *; manifest-src *;" />
    <meta http-equiv="X-Content-Security-Policy" content="default-src *; script-src *; object-src *; style-src *; img-src *; media-src *; frame-src *; font-src *; connect-src *">
    <meta http-equiv="X-WebKit-CSP" content= "default-src *; script-src *; object-src *; style-src *; img-src *; media-src *; frame-src *; font-src *; connect-src *">

A: The problem the is in that * matches only to network scheme URLs (http/https/ftp etc). So you can

*

*Add network scheme URL to policy (like myserver.com)

*Add cdvfile: into your policy

I would made one single default-src with your homeserver URL and remove all other sources. If you want to allow load content only from same origin you should set your CSP sources to 'self' (in case if your project hosted on your homeserver).
Most of CSP directives in your config are redundant, for example: you should remove base-uri if you want to allow any URIs as base URI for your site. I recommend to review every directive to gain necessary result. There is a good memo for CSP: https://content-security-policy.com/


text:
Q: google apps script mailmerge not extracting arrayformula results I am a novice when it come to google scripting.  I have found some code online that takes the information from the current row of a google sheet (derived from a form) and places it into a google doc (a bit like a mailmerge but just for the current row).  I have adapted it to suit my needs.
Here is what happens.  The user completes a form that is linked to a sheet.  There are a number of calculations that takes place on the sheet using arrayformula to provide additional information for the doc.  Whichever row the user is on he clicks a button I have created, the information from that row will transfer into a template doc.
This works fine for the top row (row 2 where row 1 is the header row) but when I try to run it for row 3 the only information from the sheet that transfers is the non arrayformula information ie the information entered into the form on not the calculated information!
Can anyone give me some insight as to why and if there is a solution?
Here is a copy of the code used:
var employee_ID = "";
var SOURCE_TEMPLATE = "1roWDiQ8NuMF06thK-bim0iwmX1_mbjvvcNIDAxfZZlI";
var employee_SPREADSHEET = "1sFWhuN_nSVEWvuPjWz2gKPdDSKw8DJBe8uoapItC0G4";
var TARGET_FOLDER = "1teL41C9NM0O5ma_2BUNe-MMX0rkSiA4h";

function getCurrentRow() {
  var currentRow =
SpreadsheetApp.getActiveSheet().getActiveSelection().getRowIndex();
  return currentRow;
}

function getRowAsArray(sheet, row) {
  var dataRange = sheet.getRange(row, 1, 1, 99);
  var data = dataRange.getValues();
  var columns = [];

  for (i in data) {
    var row = data[i];

    Logger.log("Got row", row);

    for(var l=0; l<99; l++) {
        var col = row[l];

        if(!col) {
            break;
        }

        columns.push(col);
    }
  }

  return columns;
}

function createDuplicateDocument(sourceId, name) {
    var source = DriveApp.getFileById(sourceId);
    var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
    var newFile = source.makeCopy(name, targetFolder);

    return DocumentApp.openById(newFile.getId());
}

function generateEmployeeDatasheet() {

 var data = SpreadsheetApp.openById(employee_SPREADSHEET);

  if(!employee_ID) {
    employee_ID = getCurrentRow();

    if (employee_ID == 1) {
      var employee_ID = Browser.msgBox("You need your cursor to be on the
row within which you are working ", Browser.Buttons.OK);
    }
  }

  var sheet = data.getSheets()[1];
  var columns = getRowAsArray(sheet, 1);

  Logger.log("Processing columns:" + columns);

  var row = getRowAsArray(sheet, employee_ID);
  Logger.log("Processing data:" + row);

  var employeeName = row[2];
  var timeStamp = row[0];
  var employeeDate = row[51];

  var target = createDuplicateDocument(SOURCE_TEMPLATE, employeeName + "
Final Pay Letter " + employeeDate);

  Logger.log("Created new document:" + target.getId());

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

    var body = target.getActiveSection();
    body.replaceText("<<Name>>",row[2]); //col C
    body.replaceText("<<Final pay period>>",row[4]); //col E
    body.replaceText("<<Training details1>>",row[9]); //col J

  }

}

Update 04/10/18
It appears that my problem exists in the getRowsArray function and in particular the:
if(!col) {
        break;
    }

If there is a null entry in my spreadsheet data the function breaks and therefore the data further along the spreadsheet row is not captured.
Does anyone now how to change this so this function identifies the last column in the row in another way?

A: This is my go-to utility to get the last row containing data in a given column. Two lines - works 100% of the time.
    var Avals = ss.getRange("A1:A").getValues();
    var Alast = Avals.filter(String).length;
    Logger.log("The last row of data is "+Alast);

Credit: "Determining the last row in a single column"


text:
Q: Do "I can't remember" and "I don't remember" mean the same thing?
I don't remember

and

I can't remember

Do these mean the same? I translated it to my mother tongue using Google translate and the translation is the same, but I have a feeling that it's not correct to say "I can't remember".

A: 'I can't remember' is used when you need to show some difficulty in remembering(in general due to some conditions e.g. I can't remember when he told me about the Coffee Plan as I was busy in watching television.)
'I don't remember' is a negative in simple present. It is used for giving normal replies.(e.g. I don't remember the time, I didn't see the clock then.)

A: The difference in meaning of the two phrases appears to me as the following.
When you claim that you "can't remember", it means you tried but failed.
When you claim that you "don't remember", it means that such is the result, but no declaration is made to the actual attempt; in other words, it's not known whether your memory fails/has failed you, or that you simply haven't even tried to remember.


text:
Q: Error using index property c# So my main issue was I had a static class in a VB.NET project that I used for accessing AppSettings. Original Code looks like this
Module AppSettings
    Public Property Value(ByVal NodeName As String) As String
        Get
            ConfigurationManager.RefreshSection("appSettings")
            Return ConfigurationManager.AppSettings(NodeName)
        End Get
        Set(ByVal value As String)
            Dim Config As Configuration = _
                ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location)
            Config.AppSettings.Settings.Item(NodeName).Value = value
            Config.AppSettings.SectionInformation.ForceSave = True
            Config.Save(ConfigurationSaveMode.Modified)
            ConfigurationManager.RefreshSection("appSettings")
        End Set
    End Property
End Module

so after a lot of searching I decided that that using an indexer was the way to go I came up with the following c# code and causes no *compiling errors unless I try to implement it. I don't know if the issue is with my implementation or syntax when I'm trying to use it.
public static class AppSettings
{
    public static class Value
    {
        public static string this[string nodeName]
        {
            get
            {
                ConfigurationManager.RefreshSection("appSettings");
                return ConfigurationManager.AppSettings[nodeName];
            }
            set
            {
                Configuration Config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                Config.AppSettings.Settings[nodeName].Value = value;
                Config.AppSettings.SectionInformation.ForceSave = true;
                Config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
        }
    }
}

this is the code that shows the error when I try to use these new classes
string mySetting = AppSettings.Value["mySettingName"];

this gives me the following error
'...AppSettings.Value' is a 'type', which is not valid in the given context

any help would be greatly appreciated.
Edit
after some helpful comments I realized the code does not compile, for some reason was not showing me an error. So my is how would be the most similar way to the working VB code to implement it in C#.

A: I'm not sure I fully understand your question. Does this code help?
class Program
{
    static void Main(string[] args)
    {
        Value v = new Value();
        string output = v["hello"];
        Console.WriteLine(output);
        Console.ReadLine();
    }
}

public class Value
{
    public string this[string nodeName]
    {
        get
        {
            ConfigurationManager.RefreshSection("appSettings");
            return ConfigurationManager.AppSettings[nodeName];
        }
        set
        {
            Configuration Config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            Config.AppSettings.Settings[nodeName].Value = value;
            Config.AppSettings.SectionInformation.ForceSave = true;
            Config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}

A: The original VB code is not implementing an indexer, but a "parameterized property", which isn't available in C#.  The closest C# equivalent is:
internal static class AppSettings
{
    public static string get_Value(string NodeName)
    {
        ConfigurationManager.RefreshSection("appSettings");
        return ConfigurationManager.AppSettings[NodeName];
    }
    public static void set_Value(string NodeName, string value)
    {
        Configuration Config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
        Config.AppSettings.Settings[NodeName].Value = value;
        Config.AppSettings.SectionInformation.ForceSave = true;
        Config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
    }
}

A: to make something that works very similarly to the vb Code you'd have to do something like the following. notice how the _value class is not static and the static AppSettings class has to initialize the instance of the _value class.
public static class AppSettings{
    public static _value Value { get; set; }

    //static setter
    static AppSettings(){
        Value = new _value();
    }
}

public class _value{
    public string this[string nodeName]{
        get{
            //get code here
        }
        set{
            //set code here
        }
    }
}

to use this code you would do something like the following.
//get a value
string mySetting = AppSettings.Value["mySetting"];
//set a value
AppSettings.Value["mySetting"] = "myNewSettingValue";

hope this helps.

A: Static indexers aren't supported in C# as indexers require a reference to this which doesn't exist in a static context. The reason you are getting that error is because AppSettings.Value is a type, but using an indexer treats it like an array, and that isn't going to fly.
You're going to instead want to use a getter and setter function, t.e.:
AppSettings.Value.GetSetting("settingName");
AppSettings.Value.SetSetting("settingName", "settingValue");

Alternatively, you can use an object reference to handle the indexer. (See the solution on this page for more info.)
See this page on MSDN for more info on indexers in general.


text: Q: NodeJS - XML Parser with DTD Are there any packages for parsing XML files with DTD in nodeJS. Please note, DTD validation is important. I have checked and tried few packages from npmjs.com website but none of the xml parser validates dtd. There are few dtd validation packages as well but then these does not parse xml.