text:
Q: order by budget high to low or low to high for high to low:
$query="select * from sponsors order by budget DESC";

for low to high:
$query="select * from sponsors order by budget ";

When executing this query, it only orders by the first digit. For example:
budget:
95,00,000
6,00,000
3,00,000
29,58,000
22,78,000
What am I doing wrong?

A: I think your column data type is char so please make ensure you use int datatype for column.

A: The "correct" way to solve this problem is to re-architect the table and split budget into two fields, one int and one varchar which describes what the int refers to e.g. "p.a" or "ongoing" or "per month" or whatever. That way you can properly order your data by the int field.
In the interim, you should be able to order the data by stripping the commas out of the numeric part of the field and then casting it to an unsigned integer:
SELECT *
  FROM sponsors
  ORDER BY CAST(REPLACE(budget, ',', '') AS UNSIGNED)

This should work as long as all the budget values start with numbers which may or may not contain commas.

A: ORDER BY in ANSI SQL (you didn't specify your particular variant of sql; that would help :-) is dependent on the column definition.
If you want to order by numerical value (instead of string-based - if we're guessing, it looks like you have a char/varchar/text column here), you'll need to use a numerical column type, e.g., INT, FLOAT, DECIMAL, etc.
In other words, you need to tell SQL (via your schema) that you have numerical data specifically. 10 is only less than 3 in base 10. :-)

A: You need to store budget as numerical datatype such as unsigned INT or BIGINT in database.
For now, ORDER will treat all the data as TEXT. That is why they are ordering by first digits.

A: You can try this one
SELECT *
FROM sponsors
ORDER BY cast(budget as int)

if this is you column value (6,00,00 p.a)
  SELECT *
    FROM sponsors
    ORDER BY cast(LEFT(budget,length(budget)-3) as int)


text:
Q: Show a submit button during 1 minute every 10 minutes I would like create an event where users can post some content every 10 minutes.
So, the submit button must be allow during 1 minute for that. Moreover, users can check a countdown during the unallow period.
Is it possible with JavaScript/jQuery or PHP?

A: Yeah, when the page loads you can start with the submit button disabled by default in the html markup.
then use a coundown timer, here is a jquery one that I have used before
http://keith-wood.name/countdown.html
Click on the callbacks tab in the link provided for code examples, inside your callback/trigger function you will add the following javascript or something similar.
$('#submitButtonId').attr('disabled', 'false);

A: Try this:
In your php post method set the next time in a session var:
<?php

   //intser post code
   $_SESSION['next_post'] = time() + (10 * 60);

Then in your template print this js:
<script>
var nextPostTime = <?=$_SESSION['next_post']?>;
setInterval(function(){
    if((new Date()).getTime() > nextPostTime ){
       $('#newpostID').show(); // this is the element id of the form
       setTimeout(function(){
            $('#newpostID').hide();
            nextPostTime = (new Date()).setMinutes((new Date()).getMinutes + 1)
        }
       ,60000);

    }
}, 1000);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to see if MacBook Air is "talking to" USB to Ethernet adaptor (without an Ethernet device at the other end)? I've been using an Apple USB to Ethernet adaptor plus a short Ethernet cable to connect to an Ether net device (Raspberry Pi in thins case).
Normally when I connect the lights blink on the device and everything works nicely using VNC Viewer.
Today no blinking lights or connection.
Is there a way I can check to see if I at least have a USB connection from my MacBook Air to the Apple USB/Ethernet converting dongle? Something I can do on my laptop that shows the dongle is there and connected by itself?
I'd like to check that part if possible as the first step in debugging my connect problem.

A: You can check if the Mac sees the Ethernet adapter by doing [Apple menu] / About this Mac, clicking System Report, and then looking at USB in the Hardware section.


text:
Q: Button requiring 2 clicks to work. - Vanilla JavaScript My code is in this jsfiddle snippet below. Whenever I press the remove button, it requires 2 clicks to remove the boxes that were originally generated with html. If I have added them, then those boxes work properly with one click. The problem lies with these boxes that are made through the markup.
Link to the code : this
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>

        <button id="add">Add</button>
        <button id="remove">Remove</button>

JS CODE
const boxContainer = document.getElementById("box-container");
const boxItems = document.getElementsByClassName("box-item");
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");

function Box(element) {
    this.__el = element;
    this.activated = true;
}

Box.prototype.init = function() {
    this.activateBox();
    this.__el.addEventListener("click", this.toggleActivation.bind(this));
};

Box.prototype.logger = function() {
    console.log(this);
};

Box.prototype.activateBox = function() {
    if (this.activated) {
        this.__el.classList.add("activated");
    }
};

Box.prototype.deactivateBox = function() {
    if (!this.activated) {
        this.__el.classList.remove("activated");
    }
};

Box.prototype.toggleActivation = function() {
    this.__el.classList.toggle("activated");
    return (this.activated = !this.activated);
};

let box = [];

for (let i = 0; i < boxItems.length; i++) {
    box[i] = new Box(boxItems[i]);
    box[i].init();
}

const addBox = function() {
    const node = document.createElement("span");
    node.classList.add("box-item", "activated");
    boxContainer.appendChild(node);
};

function removeBox() {
    boxContainer.removeChild(boxContainer.lastChild);
}

addBtn.addEventListener("click", addBox);
removeBtn.addEventListener("click", removeBox);

PS: I have checked other 2 questions that have the same title, but they don't solve my issue.

A: The problem is that your HTML includes text nodes between the .box-items:

So, when you call
boxContainer.removeChild(boxContainer.lastChild);

If a parent's last child node is a text node, that text node will be selected when you use lastChild. That's not what you want - you don't want to select the text nodes. You only want to remove the  elements, so you might remove the last item in the .children instead:
const { children } = boxContainer;
boxContainer.removeChild(children[children.length - 1]);

Or, more elegantly, select the lastElementChild property, thanks to Andre's comment:
boxContainer.removeChild(boxContainer.lastElementChild);

(quite confusingly, the final index of children is not the same thing as the node returned by lastChild)

const boxContainer = document.getElementById("box-container");
const boxItems = document.getElementsByClassName("box-item");
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");

function Box(element) {
  this.__el = element;
  this.activated = true;
}

Box.prototype.init = function() {
  this.activateBox();
  this.__el.addEventListener("click", this.toggleActivation.bind(this));
};

Box.prototype.logger = function() {
  console.log(this);
};

Box.prototype.activateBox = function() {
  if (this.activated) {
    this.__el.classList.add("activated");
  }
};

Box.prototype.deactivateBox = function() {
  if (!this.activated) {
    this.__el.classList.remove("activated");
  }
};

Box.prototype.toggleActivation = function() {
  this.__el.classList.toggle("activated");
  return (this.activated = !this.activated);
};

let box = [];

for (let i = 0; i < boxItems.length; i++) {
  box[i] = new Box(boxItems[i]);
  box[i].init();
}

const addBox = function() {
  const node = document.createElement("span");
  node.classList.add("box-item", "activated");
  boxContainer.appendChild(node);
};

function removeBox() {
  boxContainer.removeChild(boxContainer.lastElementChild);
}

addBtn.addEventListener("click", addBox);
removeBtn.addEventListener("click", removeBox);
.box-container {
  display: flex;
}

.box-item {
  display: inline-block;
  height: 30px;
  width: 30px;
  background: orangered;
  margin: 0 10px;
}

.activated {
  background: dodgerblue;
}

<button id="add">Add</button>
<button id="remove">Remove</button>

Or, you can just change the HTML such that there are no text nodes:

const boxContainer = document.getElementById("box-container");
const boxItems = document.getElementsByClassName("box-item");
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");

function Box(element) {
  this.__el = element;
  this.activated = true;
}

Box.prototype.init = function() {
  this.activateBox();
  this.__el.addEventListener("click", this.toggleActivation.bind(this));
};

Box.prototype.logger = function() {
  console.log(this);
};

Box.prototype.activateBox = function() {
  if (this.activated) {
    this.__el.classList.add("activated");
  }
};

Box.prototype.deactivateBox = function() {
  if (!this.activated) {
    this.__el.classList.remove("activated");
  }
};

Box.prototype.toggleActivation = function() {
  this.__el.classList.toggle("activated");
  return (this.activated = !this.activated);
};

let box = [];

for (let i = 0; i < boxItems.length; i++) {
  box[i] = new Box(boxItems[i]);
  box[i].init();
}

const addBox = function() {
  const node = document.createElement("span");
  node.classList.add("box-item", "activated");
  boxContainer.appendChild(node);
};

function removeBox() {
  boxContainer.removeChild(boxContainer.lastChild);
}

addBtn.addEventListener("click", addBox);
removeBtn.addEventListener("click", removeBox);
.box-container {
  display: flex;
}

.box-item {
  display: inline-block;
  height: 30px;
  width: 30px;
  background: orangered;
  margin: 0 10px;
}

.activated {
  background: dodgerblue;
}

<button id="add">Add</button>
<button id="remove">Remove</button>


text:
Q: Spring Boot, Spring Cloud AWS and AWS SQS not reading from the queue I am trying a to build a minimal gradle java project with Spring Boot and Spring Cloud AWS SQS but I can't get it to read from the queue.
These are my project files:
build.gradle:
apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "spring-boot"
apply plugin: "io.spring.dependency-management"

sourceCompatibility = 1.8
targetCompatibility = 1.8

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.5.RELEASE")
        classpath("io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE")
    }
}

dependencyManagement {
     imports {
          mavenBom("org.springframework.cloud:spring-cloud-aws:1.1.0.RELEASE")
     }
}

repositories {
    mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-actuator:1.3.5.RELEASE")
    compile("org.springframework.cloud:spring-cloud-starter-aws:1.1.0.RELEASE")
    // if I don't add the line below, the annotation @MessageMapping is not found :(
    // I would have expected that cloud-starter-aws would have taken care of it
    compile("org.springframework.cloud:spring-cloud-aws-messaging:1.1.0.RELEASE")
    // this has been added to fix an exception happening, please read below
    compile("org.springframework.data:spring-data-commons:1.12.1.RELEASE")
}

Application.java:
package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
    }
}

QueueListener.java:
package com.test.sqs;

import java.util.logging.Logger;
import org.springframework.messaging.handler.annotation.MessageMapping;
import com.test.sqs.model.TestMessage;

public class QueueListener
{
    @MessageMapping("test_queue")
    private void receiveMessage(TestMessage testMessage)
    {
        System.out.println("Test message received: " + testMessage.getMessage());
    }
}

application.yaml in src/main/resources:
cloud:
    aws:
        credentials:
            accessKey: **********************
            secretKey: **********************
        region:
            static: us-west-2

The application throws an exception when starting (but you can see the exception just in log debug mode!):
org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.amazonaws.auth.profile.ProfilesConfigFile]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: AWS credential profiles file not found in the given path: C:\src\collector\default

but always in the log I can see it did pick up my credentials from the yaml file:
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.accessKey' in [systemProperties]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.accessKey' in [systemEnvironment]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.accessKey' in [random]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.accessKey' in [applicationConfigurationProperties]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'cloud.aws.credentials.accessKey' in [applicationConfigurationProperties] with type [String] and value '***'
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.secretKey' in [systemProperties]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.secretKey' in [systemEnvironment]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.secretKey' in [random]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'cloud.aws.credentials.secretKey' in [applicationConfigurationProperties]
2016-05-19 11:15:14.546 DEBUG 11704 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'cloud.aws.credentials.secretKey' in [applicationConfigurationProperties] with type [String] and value '***'

So I am not sure why it is looking somewhere else?
Also it's throwing this exception (always visible just if you are in logging debug mode):
    java.lang.ClassNotFoundException: org.springframework.data.web.config.EnableSpringDataWebSupport

So I had to add in build.gradle
compile("org.springframework.data:spring-data-commons:1.12.1.RELEASE")

But now the exception is not there anymore but the program starts and ends without doing anything, and it's not printing logs anymore!
Some other facts:

*

*the Application.java is in the right package to let the component scan to work, so Spring should see the QueueListener class,

*the application.yaml is read correctly, if a put a wrong region it complains,

*if I put wrong credentials (wrong accessKey or/and wrong secretKey) it does not complain, so I don't think it is trying to connect to AWS at all.

I am not sure if line 34 of build.gradle:
compile("org.springframework.cloud:spring-cloud-starter-aws:1.1.0.RELEASE")
// if I don't add the line below, the annotation @MessageMapping is not found :(
// I would have expected that cloud-starter-aws would have taken care of it
compile("org.springframework.cloud:spring-cloud-aws-messaging:1.1.0.RELEASE")
// this has been added to fix an exception happening, please read below
compile("org.springframework.data:spring-data-commons:1.12.1.RELEASE")

could be a symptom of the issue, I would expect for all the needed libraries to be loaded by the cloud-starter-aws automatically.
What am I missing? Thank you!

A: Found the issue, and it was something stupid of course.
Spring was not loading the QueueListener class because it didn't have the Service / Component annotation, so:
@Service
public class SqsQueueSender
{
...
}

fixed the issue.


text:
Q: Dictionary Using Hash Of Object My program allows the server to send a module to a client, and the client will a respond back with module information after it has loaded it. The server store stores the client information in a List called 'loadingModules'. When the server receives that response from the client, it will remove the information from said list to indicate the load operation has completed for that module.
The problem here is is the way I'm currently doing it is by looping through the entire list and checking if two members are equal (ModuleName, and TimeStamp). This is not only just inefficient, but also makes the code look terrible. I am wondering if there is some way to do it using a hash of those two members to access the modules in perhaps a dictionary instead of what I am currently doing.
public List<ClientModule> LoadingClientModules = new();
public List<ClientModule> LoadedClientModules = new();

private void ClientModuleAdded_Callback(Packet packet)
{
    ClientModule f = Utils.ByteArrayToStructure<ClientModule>(packet.Payload, 0);
    Utils.Log.Information($"{_ClientInformation.ComputerUser} Loaded  {f.ModuleName} TimeDateStamp: {f.TimeDateStamp} Address: {f.Address}");
    LoadedClientModules.Add(f);

    LoadingClientModules.RemoveAll(i => i.ModuleName == f.ModuleName && i.TimeDateStamp == f.TimeDateStamp);

    OnClientModuleLoaded?.Invoke(this, f);
}

A: You could provide a custom IEqualityComparter<ClientModule> that compares these 2 properties. Then you can use that for a Dictionary or - better here - a HashSet<ClientModule>:
public HashSet<ClientModule> LoadingClientModules = new(new ClientModuleComparer());
public HashSet<ClientModule> LoadedClientModules = new(new ClientModuleComparer());

private void ClientModuleAdded_Callback(Packet packet)
{
    ClientModule f = Utils.ByteArrayToStructure<ClientModule>(packet.Payload, 0);
    LoadedClientModules.Add(f);
    LoadingClientModules.Remove(f);
}

Here's a possible implementation:
public class ClientModuleComparer : IEqualityComparer<ClientModule>
{
    public bool Equals(ClientModule? x, ClientModule? y)
    {
        if (x == null && y == null) return true;
        if (x == null || y == null) return false;
        return x.ModuleName == y.ModuleName && y.TimeDateStamp == y.TimeDateStamp;
    }

    public int GetHashCode([DisallowNull] ClientModule obj)
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            // Suitable nullity checks etc, of course :)
            hash = hash * 23 + obj.ModuleName.GetHashCode();
            hash = hash * 23 + obj.TimeDateStamp.GetHashCode();
            return hash;
        }
    }
}

Note that this does not allow duplicates anymore. So you will not have multiple with the same ModuleName and TimeDateStamp in these collections. Add returns false in case of a duplicate.

A: Using a dictionary to store and find the data is always faster than implementing a list and searching through the list item but it costs more memory.
You may use a Tuple created from ModuleName and TimeDateStamp and use it as the key to define a dictionary:
public Dictionary<(string,DateTime),ClientModule> LoadingModulesDictionary = new ...;

then use the dictionary as:
private void ClientModuleAdded_Callback(Packet packet)
{
    ClientModule f = Utils.ByteArrayToStructure<ClientModule>(packet.Payload, 0);
    LoadedClientModules.Add(f);
    LoadingModulesDictionary.Remove((f.ModuleName,f.DataTimeStam));
}

or define a unique id for each ClientModule object is to add a Guid field to the class and use the guid as the key for dictionary alternatively.


text:
Q: asp.net core 2 load and display images from local disk drive
Is there any way to display image in an asp.net core 2 (razor) web application from local drive ?
The reason I want do to this is that I'm developing a game server which contains a game server and two websites (front end and an admin panel) and all of those will require access to the mentioned images which in this case is profile images and that's why I didn't put those images in the wwwroot folder.
Sample image address: "C:\game_data\avatars\default.png"

A: In most cases, the most secure (and easiest) optin is to store images under the site's root folder to avoid giving the web site's account access outside the site folder itself.
User profile images aren't static though. That's why they're often stored in a database or other storage.
You can map a specific request path to a custom location in UseStaticFiles. From the documentation example :
public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
        RequestPath = "/StaticFiles"
    });
}

The first call configures wwwroot as the root for static files. The second call overrides this for requests starting with /StaticFiles and points to a folder called MyStaticFiles under the application's folder.
You could expose all profile pictures under the avatar path with this code:
public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            "X:\game_data\avatars\"),
        RequestPath = "/avatars"
    });
}

A better option would be to load the location from a configuration file.
Another consideration is that simply mapping the folder to a path will allow anyone to read profile pictures if they can guess their name. This may or may not be a concern.
If it is, you use a controller that only returns the current user's as a FileResult, eg:
class AvatarsController
{
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var userID=SomehowFindTheCurrentUserID();
        var avatarPath= Path.Combine(_avatarRoot,$"{userID}.jpeg");
        return File(avatarPath, "image/jpeg");
    }
}

A: Add below code in startup class and instead of images, set your folder:
app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "images")),
                RequestPath = "/images"
            });


text:
Q: How to return promise from recursive method I'm actually working with Firebase in a Javascript project, and trying to get informations of nested child of all elements of in a collections.
Since I need to recursively trigger the db, I'm trying to create a self calling recursive method that will map the actual db schema and pull needed data.
For the purpose of this post, I created fake method that demonstrate my actual logic. Maybe someone could help me, it's a never ending loop that trigger the last item infinitely. It never store the first results
function fakeWait(toReturn) {
  return new Promise((resolve) => {
    setTimeout(function(){ resolve(toReturn); }, 8000);
  });
}

function callMe(params = null) {
  return new Promise((resolve, reject) => {
   console.log('Promise called', {...params});

    const promises = [];

    if (params === null) {
      promises.push(fakeWait(
        {
          id1:{title:'Title1'},
          id2:{title:'Title2'},
          id3:{title:'Title3'},
          id4:{title:'Title4'},
        }).then(results => {
          params = {};
          params.formations = results;
          resolve(callMe(params));
        }));
    }

    else {
      if (!params.hasOwnProperty('formationId') &&
          params.hasOwnProperty('formations')) {
        Object.keys(params.formations).forEach(formationId => {
          params.formationId = formationId;
          promises.push(resolve(callMe(params)));
        });
            }

      else if (params.hasOwnProperty('formationId') &&
               params.hasOwnProperty('formations') &&
               !params.formations[params.formationId].hasOwnProperty.modules)
      {
        promises.push(fakeWait({
          id1:{title:'Title1.1'},
          id2:{title:'Title1.2'},
          id3:{title:'Title1.3'},
          id4:{title:'Title1.4'},
        }).then(result => {
          params.formations[params.formationId].modules = result;
          resolve(callMe(params));
        }))
            }
    }

    Promise.all(promises).then(() => { console.log('Resolved.'); resolve(params); }).catch(()=> reject('oops'));
  });
}

callMe().then(results =>console.log(results)).catch(msg => console.log(msg));

You can also view and try the code on a stackblitz here : https://stackblitz.com/edit/js-wuvp9z
Firebase data structure :
Formations - Collection
- Formation - Document
-- Modules - Collection
--- Module - Document
---- Chapters - Collection
----- Chapter - Document
------ Screens - Collection
------- Screen - Document

A: Here is the code of a Firestore transaction that will write a new Screen document and update the nbrScreens counters in, respectively, the Formation, Module and Chapter parent documents.
It is a full HTML page. Do as follows:
1/ Adapt your Firebase config values in the HTML.
2/ Create, in Firestore, the parent collections and documents, with the desired Ids.
3/ For each document (Formation, Module and Chapter) add a field of type number named nbrScreens with value 0
4/ Adapt, in the HTML page, the value of screenId, screenData and the parameters of the setNewScreen() function call to what you want.
5/ Open the page in a browser (e.g. locally), the function will be called and the transaction executed
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-firestore.js"></script>
</head>

<body>

<script>

    var config = {
        apiKey: "...",
        authDomain: "...",
        databaseURL: "...",
        projectId: "..."
    };

    firebase.initializeApp(config);

    var firestoredb = firebase.firestore();

    function setNewScreen(formationId, moduleId, chapterId, screenId, screenData) {

        var formationDocRef = firestoredb.collection("Formations").doc(formationId);
        var moduleDocRef = formationDocRef.collection("Modules").doc(moduleId);
        var chapterDocRef = moduleDocRef.collection("Chapters").doc(chapterId);
        var screenDocRef = chapterDocRef.collection("Screens").doc(screenId);

        return firestoredb.runTransaction(function (transaction) {

            var newChaptersNbrScreens;
            var newModulesNbrScreens;
            var newFormationsNbrScreens;

            return transaction.get(chapterDocRef)
                .then(function (sfDoc) {

                    if (!sfDoc.exists) {
                        throw "Document Chapter does not exist!";
                    }

                    newChaptersNbrScreens = sfDoc.data().nbrScreens + 1;
                    return transaction.get(moduleDocRef);

                })
                .then(function (sfDoc) {

                    if (!sfDoc.exists) {
                        throw "Document Module does not exist!";
                    }

                    newModulesNbrScreens = sfDoc.data().nbrScreens + 1;
                    return transaction.get(formationDocRef);

                })
                .then(function (sfDoc) {

                    if (!sfDoc.exists) {
                        throw "Document Formation does not exist!";
                    }

                    newFormationsNbrScreens = sfDoc.data().nbrScreens + 1;
                    return transaction
                        .set(formationDocRef, {nbrScreens: newFormationsNbrScreens}, { merge: true })
                        .set(moduleDocRef, {nbrScreens: newModulesNbrScreens}, { merge: true })
                        .set(chapterDocRef, {nbrScreens: newChaptersNbrScreens}, { merge: true })
                        .set(screenDocRef, screenData)

                });

        });

    }

    //Calling the function
    //The formation, module and chapter docs must be created before calling it!!

    var screenId = 's1';
    var screenData = {title: 'screenTitle_s1', content: 'foo'};

    setNewScreen("f1", "m1", "c1", screenId, screenData)  //Screen will be saved under Formation f1, Module m1 and Chapter c1
        .then(function () {
            console.log("Transaction successfully committed!");
        })
        .catch(function (error) {
            console.log("Transaction failed: ", error);
        });

</script>

</body>
</html>

Note that you can adapt the code in order to create the Formation, Module and Chapter. As a matter of fact this cannot be done in the transaction because all read(s) shall be executed before the write(s).
You could something like (pseudo-code):
FormationDocumentReference.set({}) // <- returns a promise
.then(function() {
    ModuleDocumentReference.set({}) // <- returns a promise
})
.then(function() {
    ChapterDocumentReference.set({}) // <- returns a promise
})
.then(function() {
    setNewScreen(id_f, id_m1, id_c1, screenId, screenData)  // <- returns a promise
.then(function () {
    console.log("Transaction successfully committed!");
})
.catch(function (error) {
    console.log("Transaction failed: ", error);
});

Finally, here is a couple of notable points about the transaction code above:
1/ transaction.get() returns a promise containing non-null firebase.firestore.DocumentSnapshot, as explained here. Therefore you have to chain them with then().
2/ On the other hand, transaction.set() returns "This Transaction instance", see here. Therefore you should just chain them one after the other (like return transaction.set().set()...)


text:
Q: Linking OpenCV library in QtCreator Linux I already had OpenCV installed from the arch-repositories, but removed it. Now i installed OpenCV from source like descriped here. I have problems linking the libs in the Qt-Creator.pro-file in this way:
`pkg-config opencv --cflags --libs`

In the old repository-installation this has worked.
if i manually give it the path like the following everything works fine:
LIBS += -L/usr/local/lib -lopencv_core -lopencv_imgcodecs -lopencv_highgui

I already added the line export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig  in ~/.bashrc
If i enter the line i want to use in a terminal i get the following output:
-I/usr/local/include/opencv -I/usr/local/include -L/usr/local/lib -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_photo -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_dpm -lopencv_face -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_img_hash -lopencv_line_descriptor -lopencv_optflow -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_dnn -lopencv_plot -lopencv_ml -lopencv_xfeatures2d -lopencv_shape -lopencv_video -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d -lopencv_highgui -lopencv_videoio -lopencv_flann -lopencv_xobjdetect -lopencv_imgcodecs -lopencv_objdetect -lopencv_xphoto -lopencv_imgproc -lopencv_core

Edit: There is also a file /etc/local/lib/pkgconfig/opencv.pc containing the following lines:
 Package Information for pkg-config

prefix=/usr/local
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir_old=${prefix}/include/opencv
includedir_new=${prefix}/include

Name: OpenCV
Description: Open Source Computer Vision Library
Version: 3.3.0
Libs: -L${exec_prefix}/lib -lopencv_stitching -lopencv_superres -lopencv_videos$
Libs.private: -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpango-1.0 -latk-1.0 -lcairo-go$
Cflags: -I${includedir_old} -I${includedir_new}

I hope someone can help me, so that i can use the short way of linking the libs again.


text:
Q: CORS aiohttp, fetch js у меня есть сервер на aiohttp, для поддержки CORS я использую сигнал
app.on_response_prepare(on_prepare)
async def on_prepare(request, response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Content-Type'] = 'application/json'

На клиенте следующее
var myHeaders = new Headers();
    myHeaders.append('Content-Type', 'application/json');
    myHeaders.append('Access-Control-Allow-Origin', '*');
    let options = {
      method: 'GET',
      headers: myHeaders
    };
    console.log("Try to fetch");
    fetch("http://localhost:8000/login", options)
        .then((response) => {
          return response.json();
        })
        .then((auth) => {
          console.log(auth);
        })
        .catch( (err) => {console.log("error -> " + err)});

Ошибка

Failed to load http://localhost:8000/login: Response for preflight
  does not have HTTP ok status.

До того, как я поставил сигнал, была ошибка кросдоменного запроса, сейчас ее вроде нет, но появилась та, которую я указал выше. В чем может быть дело ?

A: Достаточно убрать все заголовки на клиенте.


text:
Q: Recording coverage from a tox-installed wheel I have a problem similar to Tox 0% coverage, but I do have some coverage. My runtime code is being covered, but my test code is not. I have built an example app that reproduces the problem.
Name                                                             Stmts   Miss  Cover
------------------------------------------------------------------------------------
.tox/py38/lib/python3.8/site-packages/org/app/__init__.py            0      0   100%
.tox/py38/lib/python3.8/site-packages/org/app/app.py                 2      0   100%
.tox/py38/lib/python3.8/site-packages/org/app/test/__init__.py       0      0   100%
.tox/py38/lib/python3.8/site-packages/org/app/test/test_it.py        5      5     0%
------------------------------------------------------------------------------------
TOTAL                                                                7      5    29%

One hypothesis might be that unittest is only actually running src/org/app/test/test_it.py, and never running .tox/py38/lib/python3.8/site-packages/org/app/test/test_it.py. But the unittest command is coverage run --omit 'src/**' -m unittest discover '{envsitepackagesdir}/org/app', which I would expect to cause discovery to look for tests inside the site-packages directory. Here is the whole tox.ini:
[tox]
envlist = py38

[testenv]
deps = coverage
commands_pre = coverage erase
download = true
commands = coverage run --omit 'src/**' -m unittest discover '{envsitepackagesdir}/org/app'
commands_post = coverage report

[coverage:run]
source_pkgs = org.app

[coverage:paths]
source =
    ${TOX_ENV_DIR-src}/org/app
    src/org/app

[coverage:report]
exclude_lines =
    def __repr__
    if 0:
    if TYPE_CHECKING:
    if __name__ == .__main__.:
    if self.debug:
    if settings.DEBUG
    pragma: no cover
    raise AssertionError
    raise NotImplementedError

How can I get coverage to report the test in site-packages as having been run, or get test discovery to actually run that test instead of the same test someplace else?

A: I figured it out. The problem was due to my mistaken thinking about how coverage handles the source directive. For the commands being run by tox, directly, I need to supply --source explicitly:
[testenv]
commands = coverage --source '{envsitepackagesdir}/org/app' run --omit 'src/**' -m unittest discover '{envsitepackagesdir}/org/app'

then, removing the [coverage:paths] section and setting the source in [coverage:run]:
[coverage:run]
source = src/org/app

will enable someone to directly run coverage run -m pytest or pytest --cov and get accurate coverage outside of the toxenv. They won't interfere.


text:
Q: Maximum of Frechet Distributions Consider $Z_i$ with $i=1,...,n$ a family of independent Frechet random variables with parameters $\varepsilon$ and $B_i$, i.e. the CDF of $Z_i$ is $G(z)=e^{-\left(\frac{z}{B_i}\right)^{-\varepsilon}}$ for $z>0$
I think the distribution of the random variable $Y=\max(X_1,...,X_n)$ is Frechet with parameters $\varepsilon$ and $(B_1^\varepsilon+\cdots+B_n^\varepsilon)^{\frac{1}{\varepsilon}}$ but I'm unable to find a proof of this result. Does anyone know a reference where I can find more information? Thanks in advance.

A: I found a proof, let $F_Y$ be the CDF of $Y$, then by definition
$$F_Y(y)=\Pr(Y\leq y)=\Pr(X_1\leq y,\dots,X_n\leq y)=\prod_{i=1}^n \Pr(X_i\leq y)=\prod_{i=1}^n G_i(y)$$
where the step to the product is given by independence. Using the definition of the individual CDF and the properties of exponential function one gets
$$F_Y(y)=\exp\left(-\left(\frac{y}{(B_1^\varepsilon+\cdots+B_{n}^\varepsilon)^{\frac{1}{\varepsilon}}}\right)^{-\varepsilon}\right)$$
which gives $Y\sim Frechet(\varepsilon, (B_1^\varepsilon+\cdots+B_{n}^\varepsilon)^{\frac{1}{\varepsilon}})$.


text:
Q: How to stop Math.random activity when used with onmousemove? I want to make Math.random() activity stop and not continue anymore when I clicked the button. How can I do that with this code?

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

  var x =document.getElementById('text');

  var btn = document.querySelector('#btn');

window.onmousemove =function() {
result.innerHTML = Math.random() ;
   }

btn.onclick = function () {
result.innerHTML = "stop" ;
 }

JS EGITIMI

<button type="button" id="btn" class="btn btn-dark">CLICK</button>

A: You could just add in a boolean that checks if you can change the value or not.
This way you can turn it on and off by toggling the boolean between true and false;

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

var x = document.getElementById('text');

var btn = document.querySelector('#btn');

var canChange = true;

window.onmousemove =function() {
  if(canChange) {
    result.innerHTML = Math.random() ;
  }
}

btn.onclick = function () {
  canChange = false;
  result.innerHTML = "stop";
}

JS EGITIMI

  <button type="button" id="btn" class="btn btn-dark">CLICK</button>

A: simple reset event on window on button click :
btn.onclick = function() {
  result.innerHTML = "stop";
  window.onmousemove = null;
}

see snippet

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

var x = document.getElementById('text');

var btn = document.querySelector('#btn');

window.onmousemove = function() {
  result.innerHTML = Math.random();
}

btn.onclick = function() {
  result.innerHTML = "stop";
  window.onmousemove = null;
}

JS EGITIMI

  <button type="button" id="btn" class="btn btn-dark">CLICK</button>

A: Here you go;

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

  var x =document.getElementById('text');

  var btn = document.querySelector('#btn');

window.onmousemove =function() {
result.innerHTML = Math.random() ;
   }

btn.onclick = function () {
result.innerHTML = "stop" ;
if(window.onmousemove !== null) {
window.onmousemove = null;
}else {
    window.onmousemove =function() {
        result.innerHTML = Math.random() ;
   }
}
 }

JS EGITIMI

<button type="button" id="btn" class="btn btn-dark">CLICK</button>


text:
Q: Using PyQGIS to buffer point? We extracted the start and end points in the link layer.
Can I buffer at the start and end points? (Size 0.001)
layer = iface.activeLayer()
for f in layer.getFeatures():
  geom = f.geometry().asPolyline()
  start_point = QgsPoint(geom[0])
  end_point = QgsPoint(geom[-1])


text:
Q: 'mvn' is not recognized as an internal or external command (tried everything, still not working) Sorry I bother you, but this is my last option. I've read lot of an articles also from here Stackoverflow, and tried all things in those articles, but still not working. I really have a headache of this maven-enviromental-case, it is exploding my head very soon.
I have installed Maven to C:\Program Files\apache-maven-3.8.4
I have put it to the System Enviroment variables like this:
Variable          Value
MAVEN_HOME        C:\Program Files\apache-maven-3.8.4

Included MAVEN_HOME to System Enviroment Variables path like this: %MAVEN_HOME%\bin. Also tried to include location itself to the path like this C:\Program Files\apache-maven-3.8.4
.
Also tried to add those all in User variables. Restarted computer, tried to run CMD as Administrator, any of these working. If I echo %MAVEN_HOME% I get C:\Program Files\apache-maven-3.8.4. In IntelliJ IDEA I see the MAVEN_HOME variable in terminal variables.
Added it to System like this:

And to the PATH like this:

Echoing %PATH% in CMD:

Maven install directory:

A: Ah something I expected. You have downloaded the github archive but not installation archive https://maven.apache.org/download.cgi (-bin.zip file!). Remove the whole directory first (delete it!)...download the zip archive from the download side and unpack it into the same location...


text:
Q: Make Dictionary> strongly-typed In my application users can search for different things in various places. The same search code could be used for different things. I'm trying to create a cache in order to avoid querying the database every time.
// CustomerViewModel.cs
public async Task<Customer> SearchCustomerAsync(string searchCode)
{
    if (Cache.GetOrDefault<Customer>(searchCode) is Customer c)
    {
        return c;
    }

    var customer = await GetCustomerFromDatabaseAsync(searchCode);

    Cache.AddOrReplace(searchCode, customer);

    return customer;
}

// SupplierViewModel.cs
public async Task<Supplier> SearchSupplierAsync(string searchCode)
{
    if (Cache.GetOrDefault<Supplier>(searchCode) is Supplier s)
    {
        return s;
    }

    var supplier = await GetSupplierFromDatabaseAsync(searchCode);

    Cache.AddOrReplace(searchCode, supplier);

    return supplier;
}

Here is my cache implementation
public static class Cache
{
    private static readonly Dictionary<Type, Dictionary<string, object>> _dictionary =
        new Dictionary<Type, Dictionary<string, object>>();

    public static void AddOrReplace<T>(string key, T value) where T : class
    {
        Type t = typeof(T);

        if (!_dictionary.ContainsKey(t)) _dictionary.Add(t, new Dictionary<string, object>());

        var cache = _dictionary[t];

        if (cache.ContainsKey(key)) cache.Remove(key);

        cache.Add(key, value);
    }

    public static T GetOrDefault<T>(string key) where T : class
    {
        Type t = typeof(T);

        if (!_dictionary.ContainsKey(t)) return default;

        var cache = _dictionary[t];

        if (!cache.ContainsKey(key)) return default;

        // Have to explicitly cast the object to T
        return (T)cache[key];
    }
}

The thing that bothers me is the inner dictionary being Dictionary<string, object>. For a given type, say Customer, I know that the inner dictionary will only ever contains customers, and should be Dictionary<string, Customer>.
Is there a way to have the inner dictionary strongly typed?
If not, would a Dictionary<string, Dictionary<Type, object>> be better suited? So I would check whether or not I've got something cached for the search code, and if so something cached for the given type.
I'm open to all suggestions, so if you think my approach is bad and I shouldn't even use a dictionary in the first place I'm all ears.
UPDATE:
As pointed out, given I'm only caching reference types I shouldn't be too worried about dealing with objects, since I won't be boxing value types. I've replaced the nested dictionaries with a Dictionary<(string, Type), object>.
public static class Cache
{
    private static readonly Dictionary<(string, Type), object> _dictionary =
        new Dictionary<(string, Type), object>();

    public static void AddOrReplace<T>(string key, T value) where T : class
    {
        var typedKey = (key, typeof(T));

        if (_dictionary.ContainsKey(typedKey)) _dictionary.Remove(typedKey);

        _dictionary.Add(typedKey, value);
    }

    public static T GetOrDefault<T>(string key) where T : class
    {
        var typedKey = (key, typeof(T));

        if (!_dictionary.TryGetValue(typedKey, out object value)) return default;

        return (T)value;
    }
}


text:
Q: DMP MPU 6050 using STM32F4 I am trying to combine both data (accelerometer and gyroscope) from my MPU 6050 to get pitch, roll, and yaw value. I've able to get the accelerometer and gyroscope data, but I had problems combining it. I use Keil uVison as my IDE. Has anyone ever made the library to get that value using DMP on Keil?

A: Yes there is are a few Arduino libraries that do this. You can just translate the code to the stm32F4. The hardest part to find is the datasheet for the DMP


text:
Q: ¿Cómo envío los datos de un textbox aún estos estando deshabilitados? Este es mi caso:
Tengo un formulario con varios textbox.Unos cuantos texbox tengo que rellenarlos manualmente y los otros textbox no, ya que estos se llenan automáticamente al hacer un calculo en otra parte de la misma pagina.
Cuando les pongo la propiedad Enabled=True, se llenan con los datos calculados, pero cuando intento enviar todos los datos del formulario hacia la base de datos, no se registran ninguno.
¿Por qué los quiero tener deshabilitados? Porque no quiero que el usuario los modifique directamente, ya que ellos toman el resultado del calculo que mencioné.

A: puedes poner en
readonly = true


text:
Q: CloudWatch log groups which are not in use Is there a way to list all the AWS CloudWatch log groups which are not in use?

A: Using a tool like aws-cloudwatch-log-clean would be the easiest way if you have a lot of log groups to clean up.


text:
Q: Is it possible to disable new version checking in pgAdmin 4? New versions of pgAdmin 4 are being released every month, and it's so annoying to see a popup with notification about another update. There's no option in preferences to disable it. Is there a trick to disable this particular popup, except installing the new version?

A: In Windows you can change this value directly in the config.py file found in: \%ProgramFiles%\PostgreSQL\version\pgAdmin\web**config.py**

A: If you're using the dpage/pgadmin4 Docker image, adding an environment variable disabled the check and notification.

PGADMIN_CONFIG_UPGRADE_CHECK_ENABLED=False

PGADMIN_CONFIG_ is further documented at:
https://www.pgadmin.org/docs/pgadmin4/latest/container_deployment.html

A: Add this line to config_local.py and restart the pgadmin4:
UPGRADE_CHECK_ENABLED=False

Note:
The location of config_local.py is same as config.py. You can find the location of config.py with this command in linux:
$ find / -wholename "*/web/config.py" 2>/dev/null

If the config_local.py file doesn't exist yet, you can create one.


text:
Q: Insert a symbol before and after a number in Notepad++ Is there a way to add a character before and after a number in Notepad++?
Right now I have:
Awareness 200 Skill —
What I would like is:
Awareness |200| Skill —
Thanks!

A: ctrl+F -> replace Awareness 200 Skill by Awareness |200| Skill
You can also do it in multiple files

A: Use reg expression in the find/replace dialogue (it is the last option in the find/replace dialogue box under search mode). In your case u can use search with
([0-9]*)
Make sure to put space after bracket end.  In Replace put
|\1|

"|" can be replaced with any other symbol of ur choice. \1 is nothing but argument so should not be changed.


text:
Q: about user authentication with username and subdomain I am using devise as my authentication system. And i want to
authenticate user with username along with subdomain.
It seems that devise needs both the username and subdomain field in
the same table which is not in my case.
I have subdomain field in Company table while username and password in
the UserAccount table.
And there is references_many relation between UserAccount and Company table
Now how can i authenticate the user with both username and subdomain
Please help me out.

A: !#user.rb
devise :all, :authentication_keys => [:email, :subdomain]

OR

!#config/initializer/devise.rb
Devise.setup do |config|
  config.authentication_keys = [ :email, :subdomain ]
end

!#login.erb.html
...
f.hidden_field :subdomain, :value => current_subdomain
...

!#user.rb
def self.find_for_authentication(conditions={})
  find(:first, :conditions => { :companies => { :subdomain => conditions.delete(:subdomain) } }, :joins => :companies)
end


text:
Q: Parse  parameter in XML response I have a web service that returns a response and I cant seem to find a good answer on how to parse the a:FileContent parameter using php or c#
The response looks like:
<GetReturnFileResponse xmlns="http://tempuri.org/">
<GetReturnFileResult xmlns:a="http://schemas.datacontract.org/2004/07/SigmaAPIService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:FileContent>/*Byte[] data type long string looks like 'IkRWTEoxMDI2LkVGQiIsIkVGVCIsIjgxOCIsIlZBTlNQRVlCUk9FQ0siLCIxMC8yNi8xNSIsIjA3Mzk3MjE4MSIsIjcwMDA3ODc5MDY5MDUwJSMDEiLCIxMC8yOC8xNSIsIlBCIiLCIiDQo=' here. **removed some chars just a sample*/</a:FileContent>
    <a:Response>
        <a:ResponseCode>1</a:ResponseCode>
        <a:ResponseMessage>Successfully processed</a:ResponseMessage>
        <a:ResponseType>Success</a:ResponseType>
    </a:Response>
</GetReturnFileResult>

A: Easy with xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                "<GetReturnFileResponse xmlns=\"http://tempuri.org/\">" +
                  "<GetReturnFileResult xmlns:a=\"http://schemas.datacontract.org/2004/07/SigmaAPIService\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                    "<a:FileContent>/*Byte[] data type long string looks like 'IkRWTEoxMDI2LkVGQiIsIkVGVCIsIjgxOCIsIlZBTlNQRVlCUk9FQ0siLCIxMC8yNi8xNSIsIjA3Mzk3MjE4MSIsIjcwMDA3ODc5MDY5MDUwJSMDEiLCIxMC8yOC8xNSIsIlBCIiLCIiDQo=' here. **removed some chars just a sample*/</a:FileContent>" +
                    "<a:Response>" +
                      "<a:ResponseCode>1</a:ResponseCode>" +
                      "<a:ResponseMessage>Successfully processed</a:ResponseMessage>" +
                      "<a:ResponseType>Success</a:ResponseType>" +
                    "</a:Response>" +
                  "</GetReturnFileResult>" +
                "</GetReturnFileResponse>";
            XDocument doc = XDocument.Parse(xml);

            XElement fileContent = doc.Descendants().Where(x => x.Name.LocalName == "FileContent").FirstOrDefault();
            XNamespace ns_a = fileContent.Name.Namespace;
        }
    }
}


text:
Q: How to add array of objects to angular form Let's say I have a json with these values:
{
car: bmw,
tunes : [{
 name: turbo,
 cost: 350
},
{
 name: exhaust,
 cost: 100
}]
}

How do I create a form that will be able to take these values?
FormGroup won't work I think. FormArray seems like the right thing to use but I haven't seen it being used with pre selected fields that can be assigned values to, which is what I need. I need to be able to assign array of object to the from, edit certain values of the objects and export the form as a json with the array of objects (same as the array came but maybe with different values). The fields wont change so I don't need to add them dynamically, I just need to assign them.
My imagined solution would look something like this:
form: New FormGroup({
 car: new FormControl(),
 tunes: new FormArray([
  name: new FormControl(),
  cost: new FormControl()
 ])
})

Update:
This seems to be the wanted solution:
form: New FormGroup({
     car: new FormControl(),
     tunes: new FormArray([
      new FormGroup({
       name: new FormControl(),
       cost: new FormControl()
      })
     ])
    })

but it gives me error: "Cannot find form control at index 1"
When I look at the json it produces, it is the wanted outcome but I'm not able to assign values right now.

A: I think this is what you are looking for:
import { Component, OnInit } from '@angular/core';
import {
  FormArray,
  FormBuilder,
  FormGroup,
  ValidatorFn,
  Validators
} from '@angular/forms';

export interface ITune {
  name: string;
  cost: string;
}

export interface Icar {
  car: string;
  tunes: ITune[];
}

@Component({
  selector: 'list-overview-example',
  templateUrl: 'list-overview-example.html'
})

export class ListOverviewExample implements OnInit {

  form: FormGroup;
  public validator: { [key: string]: ValidatorFn | null };
  public data: Icar;

  constructor(private fb: FormBuilder) {
    this.validator = {
      name: Validators.compose([Validators.required, Validators.maxLength(50)])
    };
    this.data = {
      car: 'bmw',
      tunes: [
        { name: 'turbo', cost: '100$' },
        { name: 'exhaust', cost: '200$' }
      ]
    };
  }

  public ngOnInit() {
    this.form = this.createFormGroup(this.fb, this.data, {});
    this.form.addControl(
      'tunes',
      new FormArray(this.addTunes(this.data.tunes))
    );
  }

  public addTunes(tunes: ITune[]): FormGroup[] {
    const formGroups: FormGroup[] = [];
    tunes.forEach(x => {
      const formGroup = this.createFormGroup(this.fb, x, this.validator);
      formGroups.push(formGroup);
    });
    return formGroups;
  }

  createFormGroup<T extends { [key: string]: any }>(
    formBuilder: FormBuilder,
    dataSource: T,
    validators: { [key: string]: ValidatorFn | null }
  ): FormGroup {
    // dynamic creation of form control by enumerating the object
    const config: any = {};
    Object.keys(dataSource).forEach((propertyName: string) => {
      const fieldVlidators = validators[propertyName];
      const value = dataSource[propertyName];
      if (!(value instanceof Array)) {
        if (fieldVlidators !== undefined) {
          config[propertyName] = [value, fieldVlidators];
        } else if (fieldVlidators !== undefined) {
          config[propertyName] = [value, fieldVlidators];
        } else {
          config[propertyName] = [value];
        }
      }
    });
    const group = formBuilder.group(config);
    return group;
  }
}

You can use .addControl() method to add control on the formGroup. createFormGroup() is a generalized method that you can use to create the formgroup. You can also pass the validator in that if you need to validate any control. You just need to pass the object with name and validator rule in createFormGroup() function.


text:
Q: Patterns for string manipulation (in C# or other languages) I often find myself writing quite ugly code when doing string manipulations. The code does what's expected, but I would like to feel satisfied with how it looks as well as it performs. Are there any good books, websites, forums that addresses common string manipulation problems? And how would you code the following example scenarios?
A simple scenario: I have a collection of objects that I want to concatenate the result from a specific method on each object and separate each string with " AND ".
This code would do the trick, but it doesn't give that warm cozy feeling you would get after writing some piece of beautiful code.. ;).
List<MyClass> myColl = ..... // initialize the collection..
StringBuilder sb = new StringBuilder();
bool isFirst = true;
foreach (MyClass obj in myColl) {
    if (!isFirst) {
        sb.Append(" AND ");
    }
    isFirst = false;
    sb.Append(obj.MyStringBuildingMethod());
}

This would maybe be a nicer way if I would use lambda expressions:
List<MyClass> myColl = ..... // initialize the collection..
string result = String.Join(" AND ", myColl.Select(i => i.MyStringBuildingMethod()).ToArray());

And now a more complex scenario: I want to split a string on a delimiter and then split each part into a key/value. The value is enclosed in single quotes, and if the delimiter is inside the value, we should not split on that. The following code does what it should, but it feels like I have used duct tape or something.. ;)
string csvString = "name='Andersson, Per',country='Sweden',city='Stockholm'";
Dictionary<string, string> keyValues = new Dictionary<string, string>();

bool isInsideQuote = false;
int lastPosition = 0;
for (int i = 0; i < csvString.Length; i++) {
    if (csvString[i] == ',' && !isInsideQuote) {
        string[] keyValuePair = csvString.Substring(lastPosition, i - lastPosition).Split("=".ToCharArray(), 2);
        if (keyValuePair.Length == 2) {
            keyValues.Add(keyValuePair[0], keyValuePair[1].TrimStart("'".ToCharArray()).TrimEnd("'".ToCharArray()));
        }
        lastPosition = i + 1;
    }

    if (csvString[i] == '\'') {
        isInsideQuote = !isInsideQuote;
    }
}

string[] lastKeyValuePair = csvString.Substring(lastPosition).Split("=".ToCharArray(), 2);
if (lastKeyValuePair.Length == 2) {
    keyValues.Add(lastKeyValuePair[0], lastKeyValuePair[1].TrimStart("'".ToCharArray()).TrimEnd("'".ToCharArray()));
}

A: Your can use the String.Join(string delimiter, string[] words) method.  In C# 3.0 syntax, this might look like the following:
var words = new string[]
                      {
                         "this",
                         "that",
                         "the other"
                      };

var concatenatedResult = String.Join(" and ", words);

//should output "this and that and the other"
Console.WriteLine(concatenatedResult);

If you have a generic list and want to concatenate its values, you can do the following:
var words = new List<object>()
                    {
                      5,
                      DateTime.Now,
                      "something else"
                    };

var concatenatedResult = String.Join(" and ", words.Select(i => i.ToString()).ToArray());
//should output "5 and [system time] and something else"
Console.WriteLine(concatenatedResult);

Console.ReadLine();

Please note that the second example was ripped from another StackOverflow post: Convert List(of object) to List(of string).
I've looked at the IL for the Join method, and it should be reasonably comparable in speed if not quicker than using the StringBuilder class.  I wanted to ensure that instances of the String class were not being concatenated in code, which would have been very slow in comparison to the approach shown in the OP.

A: I would add an And for every record, and then simply strip the last And off at the end...
List<MyClass> myColl = ..... // initialize the collection..
StringBuilder sb = new StringBuilder();
foreach (MyClass obj in myColl)
    sb.Append(obj.MyStringBuildingMethod() + " AND ");
string s = sb.ToString(0, sb.Length - 5);

A: I suppose this is slightly less convoluted than what you have for your second example, although it relies on the string being pretty strictly formatted.  String parsing isn't always pretty.
string csvString = "name='Andersson, Per',country='Sweden',city='Stockholm'";

csvString = csvString.Replace("',", "'|");
string[] parts = csvString.Split('|');
foreach (string s in parts)  {
  string[] moreParts = s.Split('=');

  string key = moreParts[0];
  string value = moreParts[1].Trim("'");
  // do stuff?
}


text:
Q: SwiftyJSON unable to parse JSON array I am trying to integrate SwiftyJSON into my project and I am having an issue while parsing the data.
This is the JSON I am trying to parse:
{"results":[{"idwishlist":"8","name":"Test List","date":"2015-11-16 11:01:47","type":"Birthday","privacy":"0","iduser":"1"}]}

This is the code I am using and not seeing any results:
let jsondata = JSON(data)
           // print(jsondata)
            for element in jsondata["results"].arrayValue {
                let id = Int(element["wishlistid"].stringValue)
                print("id",id)
            }

The commented print statement prints out the data fine so I know it's not a problem there but I can't seem to be able to get the values of the array.
Any help would be appreciated thank you.

A: I managed to solve the problem myself I didn't actually convert the string into JSON correctly so the problem is now resolved.
if let dataFromString = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
        let jsondata = JSON(data: dataFromString)

        print(jsondata)
        for element in jsondata["results"].arrayValue {
            let id = element["idwishlist"].string!
             print("id is",id)
            let name = element["name"].string!
              print(name)
            let date = element["date"].string!
             print(date)
        }
    }


text:
Q: Cutting out using DD command I need to cut out a partition, using DD command. How do I achieve this? In my case I need to copy from block 205267 to (including this block) 29311545. The blocksize is 512 Bytes.

A: You can achieve this with:

# make sure you set the right paths for sdX
dd if=/dev/sdX of=~/outputfile bs=512 skip=205266 count=29106280

Explanation of options:

 if=     describes the inputfile path
 of=     describes the output file path
 bs=     states the blocksize in bytes
 skip=   skips bs size blocks at the beginning of input file
 count=  read N blocks (so in your case N = (End+1)-Begin)


text:
Q: Error loading custom synonym file in Elasticsearch I am using Rails, Tire and Elasticsearch on EC2 single server setup, no sharding or replication (this is the Jenkins CI Server). With a custom initializer as such:
analysis:
  filter:
    name_synonyms:
      type: synonym
      synonyms_path: <%= Rails.root.join("config", "synonyms", "name_synonyms.txt") %>

This file runs thru Erubis and the synonyms path is converted to something like this:
/root/workspace/project-project-0f317744a1870b4baf61bbaeb390ebe1/config/synonyms/term_synonyms.txt

When I list the files in the sever I see the following:
root@ip-XX-XXX-XX-XXX:~/workspace/project-project-0f317744a1870b4baf61bbaeb390ebe1/config/synonyms# ls -la
total 20
drwxr-xr-x 2 root root 4096 Feb 11 18:25 .
drwxr-xr-x 7 root root 4096 Feb 11 18:25 ..
-rw-r--r-- 1 root root 3117 Feb 11 18:25 location_synonyms.txt
-rw-r--r-- 1 root root 3999 Feb 11 18:25 name_synonyms.txt
-rw-r--r-- 1 root root 2144 Feb 11 18:25 term_synonyms.txt

Which is exactly I am expecting, however I see the following error when running rake spec
500 : {"error":"IndexCreationException[[test_facilities] failed to create index]; nested: FailedToResolveConfigException[Failed to resolve config path [/root/workspace/project-project-0f317744a1870b4baf61bbaeb390ebe1/config/synonyms/term_synonyms.txt], tried file path [/root/workspace/project-project-0f317744a1870b4baf61bbaeb390ebe1/config/synonyms/term_synonyms.txt], path file [/etc/elasticsearch/root/workspace/project-project-0f317744a1870b4baf61bbaeb390ebe1/config/synonyms/term_synonyms.txt], and classpath]; ","status":500}

It seems to me Elasticsearch is not capable of loading the files although the path is correct, could be a load order issue, I am really not too sure.

A: You should look at elasticsearch log files. In my case /var/log/elasticsearch/elasticsearch.log
In my case, I had this:
    [2016-02-26 10:28:26,321][WARN ][cluster.action.shard     ] [Batragon] [myindex-1][2] received shard failed for [myindex-1][2], node[mynode], [P], v[1223], s[INITIALIZING], a[id=myid], unassigned_info[[reason=ALLOCATION_FAILED], at[2016-02-26T09:28:26.168Z], details[failed to create index, failure IndexCreationException[failed to create index]; nested: AccessControlException[access denied ("java.io.FilePermission" "/home/myuser/elasticsearch/my_synonyms.txt" "read")]; ]], indexUUID [haZBzLsuSmmxteIq-1K0vw], message [failed to create index], failure [IndexCreationException[failed to create index]; nested: AccessControlException[access denied ("java.io.FilePermission" "/home/myuser/elasticsearch/my_synonyms.txt" "read")]; ]
[myindex-1] IndexCreationException[failed to create index]; nested: AccessControlException[access denied ("java.io.FilePermission" "/home/myuser/elasticsearch/my_synonyms.txt" "read")];
  at org.elasticsearch.indices.IndicesService.createIndex(IndicesService.java:360)
  at org.elasticsearch.indices.cluster.IndicesClusterStateService.applyNewIndices(IndicesClusterStateService.java:307)
  at org.elasticsearch.indices.cluster.IndicesClusterStateService.clusterChanged(IndicesClusterStateService.java:176)
  at org.elasticsearch.cluster.service.InternalClusterService$UpdateTask.run(InternalClusterService.java:494)
  at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.runAndClean(PrioritizedEsThreadPoolExecutor.java:231)
  at org.elasticsearch.common.util.concurrent.PrioritizedEsThreadPoolExecutor$TieBreakingPrioritizedRunnable.run(PrioritizedEsThreadPoolExecutor.java:194)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
  at java.lang.Thread.run(Thread.java:745)
  Caused by: java.security.AccessControlException: access denied ("java.io.FilePermission" "/home/myuser/elasticsearch/my_synonyms.txt" "read")
  ...

I solved this by granting read permissions to the java.policy file (in my case /usr/lib/jvm/java-7-oracle/jre/lib/security/java.policy):
grant {
    permission java.io.FilePermission "/home/myuser/elasticsearch/my_synonyms.txt", "read";
};

and restarting elasticsearch service.
You can grant permission at directory level in a more generic way, to any file in a directory, like this, for example:
    grant {
    permission java.io.FilePermission "/home/myuser/current/config/elasticsearch/-", "read";
    permission java.io.FilePermission "/home/myuser/current/config/elasticsearch/", "read";
};

Execute permissions on the whole path up to the file are necessary too. In my case: current and current/config

A: The path to the file is included in the ES index mappings.  The file itself is expected to live on the ES server when the index is being created, but you have defined the path to this file relative to your Rails application.


text:
Q: cakephp acl control access of a plugin (FullCalendar) I'm using acl (followed cake's tutorial) in cake 2.4 and the FullCalendar plugin.
As for the FullCalendar plugin permisions are not working. I'm currently using the console to create aros, acos and granting permissions.
users table:
id | username | role_id
-----------------------
12 | company  | 2
13 | regular  | 3
14 | admin    | 1

roles table:
id | role
--------------------
12 | Administrador
13 | Company
14 | Regular

aro table:
+----+-----------+-------+-------------+-------+------+------+
| id | parent_id | model | foreign_key | alias | lft  | rght |
+----+-----------+-------+-------------+-------+------+------+
|  1 |      NULL | Role  |           1 | NULL  |    1 |    4 |
|  2 |      NULL | Role  |           2 | NULL  |    5 |    8 |
|  3 |      NULL | Role  |           3 | NULL  |    9 |   12 |
|  4 |         1 | User  |          14 | NULL  |    2 |    3 |
|  5 |         2 | User  |          12 | NULL  |    6 |    7 |
|  6 |         3 | User  |          13 | NULL  |   10 |   11 |
+----+-----------+-------+-------------+-------+------+------+

The plugin is in this path:
    cake/app/Plugin/FullCalendar
-Controller
    -FullCalendarAppController
    -EventsController
    -FullCalendarController
    -EventTypesController
-Model
    -Event
    -EventType
    -FullCalendar
    -FullCalendarAppModel
-View
    -Events: add, edit, feed, index, view
    -EventTypes: add, edit, index, view
    -FullCalendar: index
    -Layouts
-webroot

I've created this acos:
cake acl create aco controllers FullCalendar
cake acl create aco controllers/FullCalendar index
cake acl create aco controllers Events
cake acl create aco controllers/Events index
cake acl create aco controllers/Events view
cake acl create aco controllers/Events add

I want these permission:
Administrador: all
Company: index, view of the event list
/cake/full_calendar/events
/cake/full_calendar/events/view/1

Regular: index of the event list
/cake/full_calendar/events

and well, I used these to assing permissions:
cake acl grant Role.1 contollers/Fullcalendar all
cake acl grant Role.2 contollers/Fullcalendar/index all
cake acl grant Role.2 contollers/Fullcalendar/view all
cake acl grant Role.3 contollers/Fullcalendar/index all

This is the error I get:
Warning (512): DbAcl::check() - Failed ACO node lookup in permissions check. Node references:
Aro: Array
(
    [User] => Array
        (
            [id] => 14
            [username] => admin
            [role] => admin //this atribute was for testing, but i'm not using it anymore so I guess it doesn't really matters.
            [role_id] => 1
            [Role] => Array
            (
                [id] => 1
                [role] => Administrador
                [alias] =>
            )

    )

)

Aco: controllers/FullCalendar/Events/view [CORE\Cake\Model\Permission.php, line 103]

Also, would you mind telling what does the aros_acos' table "_create, _read, _update, _delete" mean?
Thanks in advance.

A: You need to add the Plugin Name in the ACO path to resolve the ACO correctly.
Your current incorrect path:
controllers/Events/view

What it should be:
controllers/FullCalendar/Events/view

So to create the acos, first create a node for the Plugin:
cake acl create aco controllers FullCalendar

Then carry on like you would as below:
cake acl create aco controllers/FullCalendar FullCalendar
cake acl create aco controllers/FullCalendar/FullCalendar index
cake acl create aco controllers/FullCalendar Events
cake acl create aco controllers/FullCalendar/Events index
cake acl create aco controllers/FullCalendar/Events view
cake acl create aco controllers/FullCalendar/Events add

Additional debugging tip:
Pay attention to that famous error that you are getting; you will get it quite a few times when implementing ACL. It will tell you what it is expecting and cannot find.
E.g. in your case, Warning (512): DbAcl::check() - Failed **ACO** node lookup in permissions check.
Hence check the ACO Node reference it wants:
Aco: controllers/FullCalendar/Events/view

This tells you that it is looking for the above node and cannot find it.


text:
Q: displaying a youtube video using object tag in a html page I have the following code where I am trying to embed a youtube player into a html page.
I do not see any errors on the console, but the player is not added on the html page.
 <form name="urlReaderForm"  onSubmit=" return validateForm()" method="post">
    Url: <input type="text" name="url">

   edit: Times: < input type="Number" name="times"

    <input type="submit" type="submit" value="Submit">
 </form>

A: there's a couple of issues in the sample above...

*

*there is no field for
    var loopCounter=document.forms["urlReaderForm"]["times"].value; to read on the form

*when you extract the URL from the form you strip off the last character. Use var vID=url.substring(vIDpos+2,len);

*unless you add return false;
to the end of the script it will reload the page because of the  so you'll never see your errors

I would recommend using the more modern iframe embeddeding, but if you still need to stick with your solution then try the following:
    function validateForm()
    {
    var url=document.forms["urlReaderForm"]["url"].value;
    //var loopCounter=document.forms["urlReaderForm"]["times"].value;
    loopCounter = 0;
    var len = url.length;
    var vIDpos=url.indexOf("v=");
    var vID=url.substring(vIDpos+2,len);
    alert(''+vID);
    var html_var='';
    html_var ="<object style='height: 390px; width: 640px'><param name='movie' value='https://www.youtube.com/v/"+vID+"?version=3&feature=player_embedded&loop='"+loopCounter+"'&playlist='"+vID+"'><param name='allowFullScreen' value='true'><param name='allowScriptAccess' value='always'><embed src='https://www.youtube.com/v/"+vID+"?version=3&feature=player_embedded&loop='"+loopCounter+"'&playlist='"+vID+"' type='application/x-shockwave-flash' allowfullscreen='true' allowScriptAccess='always' width='425' height='344'></object>";
    console.log(html_var);
    document.getElementById("youPlayer").innerHTML = html_var;
    return false;
    }

A: I have to agree with previous poster about the build-in embeded code. To give you two new ideas I did this myself on two occassion using one and the other on the 2nd site.

Is for the embeded one, the 2nd option I used was that I just made a list with videos and a general iframe just to have a target like so

Videos

And then put the embeded code into separate .html files like so
<!DOCTYPE html>

Your browser does not support frames, please update your browser

But the main point is still, use a iframe and it's still considered HTML5 valid even though frames can be frowned upon, but that is general use. You can still use frames but they should be used to serve a greater purpose and not just because it's "easier" to divide/update content on a page.


text:
Q: TypeScript export-import conventions In contrast to Java (and other languages), TypeScript offers you multiple ways to export and import things (classes, functions etc.).
For example, you can export multiple classes, constants, functions etc. per file.
Also you can define 1 default export per file.
On the other side you can import only the default export, import everything using an alias or import the given things.
Coming from Java, I wonder, if there is any convention, especially regarding constants and functions.
Let's say I have a util-file, having a lot of functions. In Java I would create a File Util.java with class Util, which contains all the static functions.
In TypeScript I have following possibilities:

*

*Export every single function and import it using import * as Util.

*Create a class Util with static functions and export only this class.

In both cases I can call functions using Util.functionName(), just like in java.
Another case is a class with a few constants.
For example I have a class Car with a field type. There are also constants for the available types, like TYPE_SUV, TYPE_SPORT and so on.
Again, I can define them as "top-level" constants and export them and the class Car. But I can also define them as public static readonly inside the Car-class and export that class only.
Using the first approach, I would have a verry big import statement, if I need all constants in other files. Also sub-classes won't "inherit" those constants.
However using readonly instead of const feels kind of strange to me...
So I was looking for some kind of convention, but I did not find much.
I only found a few tips like this.
So, are there any guidelines regarding exports and imports in TypeScript, which take care about the explained problems? I am also looking for the best way, regarding integration of tools (refactoring, auto-importing, organizing imports etc.).
Thanks.

A: (I am afraid this is going to be somewhat opinion based although there are objective elements in choosing one over another)

*

*Export every single function and import it using import * as Util.

*Create a class Util with static functions and export only this class.

I prefer number 1) because 2) does not bring any benefit and may lead to someone instantiating the Util class for no reason (and contrarily to Java, this cannot be prevented).

I can define them as "top-level" constants and export them and the class Car. But I can also define them as public static readonly inside the Car-class and export that class only.

With regards to constants, the readonly modifier only applies at compile time. So as class properties, they can still be modified at runtime. I, hence, prefer to make them top level constants in the module (file)
The excellent handbook from Basarat is also my "reference" and I share his opinion on default exports which do not bring much aside from confusion since with named exports, it is also possible to rename on import e.g.
import { OriginalName as MyPreferredName}  from './OriginalName'


text:
Q: How should "git add /**" work? As noted in this question, I ran into an issue with git add /**.... I can't actually find any documentation on the "/**" form of path specifications - possibly because it's hard to google.
How is it meant to work, exactly? I'm particularly curious that git add /\*\*.py can work but git add /path/foo.py won't - why is the slash allowed at the start of the string with the ** notation?
EDIT more info:
$ echo /**.py
/**.py

(This version of Bash doesn't support shopt -s globstar)
Yet:
$ git add /**.py

adds (silently) a file three directories beneath the current directory. Git apparently doesn't do any globbing at all, so I'm really curious what's going on here.
These also work:
`git add '/**.py'`
`git add /*******.py`

This doesn't:
`git add **.py`

This seems to add all files anywhere in the current working directory.
(Bash 3.2.48 on OSX)

A: Globs are resolved by the shell when you run such a command, not by git. Try echo /** to see what that resolves to. There is a recursive glob pattern in Bash which uses this syntax, but you have to shopt -s globstar to enable it (it seems to be disabled by default).
git add /\*\*.py tries to add a file called literally **.py. While it's possible to create such a file, it's probably not intended.
git /path/foo.py is meaningless - I assume you meant git add /path/foo.py.
In all these commands, you should remove the initial slash - You generally want to refer to files in a repository by their path relative to $PWD.
echo /**.py will print /**.py unless shopt nullglob is off or you actually have a .py file in the root directory.


text:
Q: Transition not working when changing from display none to block I've noticed that transition is not working when the element is also changing from display none to block. Why is that? It works if I remove the display attribute.
CSS:
#box {
    width: 150px;
    height: 150px;
    background: red;
    transform: scale(0);
    display: none;
    transition: transform .5s;
}
    #box.active {
        transform: scale(1);
        display: block;
    }

http://jsfiddle.net/640kL55u/

A: Any change from or to display: none won't trigger transitions.
You can, however, change the display property and then add the class name at the end of the javascript stack. For instance:
function showElem(elem) {
  elem.style.display = "block";

  setTimeout(function() {
    elem.classList.add("active");
  }, 0);
}

And then pass element nodes to this function.

A: Because it has display: none to begin with, the other styles are not being taken into the dom to be transitioned once display: block is added.
Instead, you can hide the div with height, so its still on the page but not showing. Then add the height on the show div.
JS Fiddle

A: You can't transition with display: none; properties...

$("button").on("click", function() {

  $("#box").addClass("active");

});
#box {
  width: 0;
  height: 0;
  overflow: hidden;
  background: red;
  transform: scale(0);
  transition: transform .5s;
}
#box.active {
  width: 150px;
  height: 150px;
  transform: scale(1);
}

<button>CLICK</button>


text:
Q: Unable to install rtools and configure the path correctly I followed this instructions to install R and Rstudio, specifically, in the installation of R, I set C:\R\R-3.4.1 as the folder to store R instead of C:\Program Files\R\R-3.4.1 to avoid any possible issues with space in the path. Then I followed this instruction step by step to download and install the latest version of rtools. Specifically, during the installation of rtools, there is a message box

And I followed the instruction and click both of them.
Then I open Rstudio (at this moment, it is all fresh, I didn't install any R packages except for those basic ones that comes with Rstudio) and install.packages("devtools") then everything looks smooth
package 'withr' successfully unpacked and MD5 sums checked
package 'devtools' successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\FTXX\AppData\Local\Temp\RtmpK2EE70\downloaded_packages

Then
library(devtools)
find_rtools(T)
Error: running command '"C:/R/R-34~1.1/bin/x64/R" --no-site-file --no-
environ --no-save --no-restore --quiet CMD config CC' had status 65535

My system path is
Sys.getenv()['PATH']
PATH                     C:\R\R-
3.4.1\bin\x64;c:\Rtools\bin;c:\Rtools\mingw_32\bin;C:\R\R-
3.4.1\bin;C:\Program
                     Files\mingw-w64\x86_64-5.3.0-posix-seh-rt_v4-rev0\mingw64\bin\;C:\Users\FTXX\AppData\Local\Continuum\Anaconda3;C:\Users\FTXX\AppData\Local\Continuum\Anaconda3\Scripts;C:\Users\FTXX\AppData\Local\Continuum\Anaconda3\Library\bin

I also found that the output of Sys.getenv()['PATH'] and shell("PATH") generates different message. In Shell('PATH') is says
Warning messages:
1: running command 'C:\Program Files\mingw-w64\x86_64-5.3.0-posix-seh-
rt_v4-rev0\mingw64\bin /c PATH' had status 127
2: In shell("PATH") : 'PATH' execution failed with error code 127

I also output some variables
Sys.which("ls.exe")
ls.exe
"c:\\Rtools\\bin\\ls.exe"
Sys.which("gcc.exe")
gcc.exe
"c:\\Rtools\\mingw_32\\bin\\gcc.exe"

and my R is 3.4.1 and I am on Windows 10. Any suggestions are appreciated.

A: Maybe you can use the installr package to download and install Rtools.
try this in your IDE
I did it in RStudio.
install.packages("installr")

Then, when the package is installed, make it available with
library("installr")

At this point, you are good to go!
Install Rtool using the following
install.Rtools()


text:
Q: Lastpass icon is positioned under my own components icon Is there an easy fix for this?
The faint lastpass icon is displayed underneath my own icon which looks pretty bad.

A: You can use this selector to move your own icon to the left.
input[style*='background-image: url("data:image/png'].icon {
  left: 40px;
}

It's little bit hacky but it gets the job done.


text:
Q: Generate Java class from JSON? In a Java Maven project, how do you generate java source files from JSON? For example we have
{
  "firstName": "John",
  "lastName": "Smith",
  "address": {
    "streetAddress": "21 2nd Street",
     "city": "New York"
  }
}

When we run mvn generate-sources we want it to generate something like this:
class Address  {
    JSONObject mInternalJSONObject;

    Address (JSONObject json){
        mInternalJSONObject = json;
    }

    String  getStreetAddress () {
        return mInternalJSONObject.getString("streetAddress");
    }

    String  getCity (){
        return mInternalJSONObject.getString("city");
    }
}

class Person {
    JSONObject mInternalJSONObject;

    Person (JSONObject json){
        mInternalJSONObject = json;
    }

    String  getFirstName () {
        return mInternalJSONObject.getString("firstName");
    }

    String  getLastName (){
        return mInternalJSONObject.getString("lastName");
    }

    Address getAddress (){
        return Address(mInternalJSONObject.getString("address"));
    }
}

As a Java developer, what lines of XML do I need to write in my pom.xml in order to make this happen?

A: Answering this old question with recent project ;-).
At the moment the best solution is probably JsonSchema2Pojo :
It does the job from the seldom used Json Schema but also with plain Json. It provides Ant and Maven plugin and an online test application can give you an idea of the tool. I put a Json Tweet and generated all the containing class (Tweet, User, Location, etc..).
We'll use it on Agorava project to generate Social Media mapping and follow the contant evolution in their API.

A: Thanks all who attempted to help. For me this script was helpful. It process only flat JSON and don't take care of types, but automate some routine
  String str =
        "{"
            + "'title': 'Computing and Information systems',"
            + "'id' : 1,"
            + "'children' : 'true',"
            + "'groups' : [{"
                + "'title' : 'Level one CIS',"
                + "'id' : 2,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Intro To Computing and Internet',"
                    + "'id' : 3,"
                    + "'children': 'false',"
                    + "'groups':[]"
                + "}]"
            + "}]"
        + "}";

    JSONObject json = new JSONObject(str);
    Iterator<String> iterator =  json.keys();

    System.out.println("Fields:");
    while (iterator.hasNext() ){
       System.out.println(String.format("public String %s;", iterator.next()));
    }

    System.out.println("public void Parse (String str){");
    System.out.println("JSONObject json = new JSONObject(str);");

    iterator  = json.keys();
    while (iterator.hasNext() ){
       String key = iterator.next();
       System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));

    System.out.println("}");

A: I'm aware this is an old question, but I stumbled across it while trying to find an answer myself.
The answer that mentions the online json-pojo generator (jsongen) is good, but I needed something I could run on the command line and tweak more.
So I wrote a very hacky ruby script to take a sample JSON file and generate POJOs from it.  It has a number of limitations (for example, it doesn't deal with fields that match java reserved  keywords) but it does enough for many cases.
The code generated, by default, annotates for use with Jackson, but this can be turned off with a switch.
You can find the code on github: https://github.com/wotifgroup/json2pojo

A: I created a github project Json2Java that does this.
https://github.com/inder123/json2java
Json2Java provides customizations such as renaming fields, and creating inheritance hierarchies.
I have used the tool to create some relatively complex APIs:
Gracenote's TMS API: https://github.com/inder123/gracenote-java-api
Google Maps Geocoding API: https://github.com/inder123/geocoding

A: Try http://www.jsonschema2pojo.org
Or the jsonschema2pojo plug-in for Maven:
<plugin>
    <groupId>org.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-maven-plugin</artifactId>
    <version>1.0.2</version>
    <configuration>
        <sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>
        <targetPackage>com.myproject.jsonschemas</targetPackage>
        <sourceType>json</sourceType>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The <sourceType>json</sourceType> covers the case where the sources are json (like the OP). If you have actual json schemas, remove this line.
Updated in 2014: Two things have happened since Dec '09 when this question was asked:

*

*The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules

*I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

A: If you're using Jackson (the most popular library there), try
https://github.com/astav/JsonToJava
Its open source (last updated on Jun 7, 2013 as of year 2021) and anyone should be able to contribute.
Summary
A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generates the necessary java data structures.
It encourages teams to think in Json first, before writing actual code.
Features

*

*Can generate classes for an arbitrarily complex hierarchy (recursively)

*Can read your existing Java classes and if it can deserialize into those structures, will do so

*Will prompt for user input when ambiguous cases exist

A: I had the same problem so i decided to start writing a small tool to help me with this. Im gonna share andopen source it.
https://github.com/BrunoAlexandreMendesMartins/CleverModels
It supports, JAVA, C# & Objective-c from JSON .
Feel free to contribute!

A: I know there are many answers but of all these I found this one most useful for me. This link below gives you all the POJO classes in a separate file rather than one huge class that some of the mentioned websites do:
https://json2csharp.com/json-to-pojo
It has other converters too. Also, it works online without a limitation in size. My JSON is huge and it worked nicely.

A: Here's an online tool that will take JSON, including nested objects or nested arrays of objects and generate a Java source with Jackson annotations.

A: As far as I know there is no such tool. Yet.
The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.
However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.
So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

A: You could also try GSON library. Its quite powerful it can create JSON from collections, custom objects and works also vice versa.  Its released under Apache Licence 2.0 so you can use it also commercially.
http://code.google.com/p/google-gson/

A: Try my solution
http://htmlpreview.github.io/?https://raw.githubusercontent.com/foobnix/android-universal-utils/master/json/generator.html
{
    "auctionHouse": "sample string 1",
    "bidDate": "2014-05-30T08:20:38.5426521-04:00 ",
    "bidPrice": 3,
    "bidPrice1": 3.1,
    "isYear":true
}

Result Java Class
private String  auctionHouse;
private Date  bidDate;
private int  bidPrice;
private double  bidPrice1;
private boolean  isYear;

JSONObject get
auctionHouse = obj.getString("auctionHouse");
bidDate = obj.opt("bidDate");
bidPrice = obj.getInt("bidPrice");
bidPrice1 = obj.getDouble("bidPrice1");
isYear = obj.getBoolean("isYear");

JSONObject put
obj.put("auctionHouse",auctionHouse);
obj.put("bidDate",bidDate);
obj.put("bidPrice",bidPrice);
obj.put("bidPrice1",bidPrice1);
obj.put("isYear",isYear);

A: To add to @japher's post. If you are not particularly tied to JSON, Protocol Buffers is worth checking out.


text:
Q: if $E \subset \mathbb R^n$ is compact, then $E$ is null-set I'm trying to understand the validity of this claim and prove it:
if $E \subset \mathbb R^n$ is compact then $\forall \epsilon >0$ there is a finite covering $E \subset \cup_{j=1}^{m} Q_j$ such that $\sum_{j=1}^{m}v(Q_j) < \epsilon$
But wouldn't make $E$ a null-set? isn't that the definition of a set that has zero measure?
But for instance, $[0,1] \subset \mathbb R$ is compact, but it is not zero measure. Is this statement even true?

A: As pointed out in the comments, your statement is wrong. If $E$ is compact, the only thing you can say is that for any $\epsilon >0$ you can cover $E$ with a finite family of sets such that each of them has measure less than $\epsilon$.
Observe that the cardinality of the covering actually depends on $\epsilon$. Therefore you can't conclude that the measure of $E$ is zero.