text:
Q: How does Microsoft.Extensions.Logging work for full .net framework? The article (Monitor and diagnose Azure Service Fabric applications) indicates following (please note text in bold):
ASP.NET Core logging
Choosing how to instrument your code can be difficult, if you chose poorly and have to reinstrument, you are revisiting and potentially destabilizing your code base. To reduce the risk, developers can choose an instrumentation library such as Microsoft.Extensions.Logging provided by ASP.NET Core. This provides an ILogger interface that allows the provider of your choice to be used while minimizing the impact to existing code. Another nice aspect of this is that the code can be used not only in .NET Core on Windows and Linux, but in the full .NET framework too, giving the ability to standardize your instrumentation code across .NET and .NET Core.
How is this supposed to work because when I tried to add the extensions library (to my service fabric cluster application project that compiles to .net framework 4.5.2), it is attempting to bring down all asp.net core related binaries?

A: @LoekD's answer is absolutely correct. Here's a .NET Framework example of how to use the Microsoft Extentions Logging framework with Serilog.
public class Program
{
    private static void Main()
    {
        // instantiate and configure logging. Using serilog here, to log to console and a text-file.
        var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
        var loggerConfig = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        loggerFactory.AddSerilog(loggerConfig);

        // create logger and put it to work.
        var logProvider = loggerFactory.CreateLogger<Program>();
        logProvider.LogDebug("debiggung");

    }
}

Requires Microsoft.Extensions.Logging, Serilog.Extensions.Logging and Serilog.Sinks.File NuGet packages.

A: This means that the library 'Microsoft.Extensions.Logging' is compiled against netstandard (1.1), which means it can be used by both full framework (4.5+) applications and dotnet core applications.
Adding the net standard metapackage introduces a bunch of dependencies, but since your project is targeting the full framework, they won't actually be used by your service.


text:
Q: How To Perform Navigation In Silverlight 4.0 Using MVVM? I'm new to Silverlight and I'm having trouble understanding how to properly navigate between pages, especially when I need to pass data around.
Classic example: I have a list of People on one page, and when I click on a person in the datagrid I'd like to go to the details page and load that data. I need to pass the PersonId. More importantly, I need to know how to do this from the ViewModel.
It's easy to fire a command from the datagrid that is on the ViewModel, and the SelectedItem on the viewmodel is also bound and thus tracked, but then what? How do I get to the next page? I can't for the life of me figure this one out. This seems like it should be really easy, but so far it's been anything but easy.

A: The most basic thing to do would be to change what Application.Current.RootVisual is set to and set the appropriate DataContext. However it is much better to have some wrappers that set this up properly for you. For example in your custom view that you are navigating to you can have the view's constructor handle some of that logic for you in a nicer way. If you are using Prism then you are ultimately talking about modifying the shell, or a container within the shell.

A: In the SelectedItemChanged you could set a ViewModel property "SelectedItem" with the object that you need in the other page.  You ViewModel would need to be a Singleton.  In the other page, you need to have the DataContext set to the ViewModel and now you can bind the SelectedItem to the control that you want.
The only thing that I do not like is that you still would need to go to the code behind of the starting page, get the SelectedItem from the DataGrid and set the ViewModel with this value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use Redshift Copy command to do a merge I have a process that iterates over input and spits out data to AWS Firehose that I have configured to upload to a redshift table I created. One problem is that sometimes the rows can be duplicated because the process needs to reevaluate data.
Something like:
Event_date, event_id, event_cost
2015-06-25, 123, 3
2015-06-25, 123, 4

http://docs.aws.amazon.com/redshift/latest/dg/t_updating-inserting-using-staging-tables-.html
Looking there, I want to replace the old row with the new value, so something like:
insert into event_table_staging
select event_date,event_id, event_cost from <s3 location>;

delete from event_table
using event_table_staging
where event_table.event_id = event_table_staging.event_id;

insert into target
select * from event_table_staging;

delete from event_table_staging
select * from event_table_staging;

Is it possible to do something like:
Redshift columns: event_date,event_id,cost
copy event_table from <s3>
(update event_table
select c_source.event_date,c_source.event_id,c_source.cost from <s3 source> as c_source join event_table on c_source.event_id = event_table.event_id)
CSV

copy event_table from <s3>
(insert into event_table
select c_source.event_date,c_source.event_id,c_source.cost from event_table left outer join<s3 source> as c_source join on c_source.event_id = event_table.event_id where c_source.event_id is NULL)
CSV

A: You can't do a merge directly from COPY.
However your initial approach can be wrapped in a transaction using a temp table to stage the load data for the best performance.
BEGIN
;
CREATE TEMP TABLE event_table_staging (
     event_date  TIMESTAMP  NULL
    ,event_id    BIGINT     NULL
    ,event_cost  INTEGER    NULL )
DISTSTYLE KEY
DISTKEY (event_id)
SORTKEY (event_id)
;
COPY event_table_staging
FROM <s3 location>
COMPUDATE ON
;
UPDATE event_table
SET    event_date = new.event_date
      ,event_cost = new.event_cost
FROM        event_table         AS trg
INNER JOIN  event_table_staging AS new
        ON  trg.event_id = new.event_id
WHERE COALESCE(trg.event_date,0) <> COALESCE(new.event_date,0)
  AND COALESCE(trg.event_cost,0) <> COALESCE(new.event_cost,0)
;
INSERT INTO event_table
SELECT  event_date
       ,event_id
       ,event_cost
FROM        event_table_staging AS new
LEFT JOIN   event_table         AS trg
       ON   trg.event_id = new.event_id
WHERE trg.event_id IS NULL
;
COMMIT
;

This approach actually performs amazingly well as long as you use a transaction and the total volume of updates is relatively low (single digit %). The only caveat is that your target will need to be VACUUMed periodically - once a month is enough for us.
We do this hourly for several tables in the 100s of millions of rows range, i.e, 100s of millions of rows merged into 100s of millions of rows. User queries over the merged tables still perform well.

A: Redshift is optimize to handle massive amount of data in a cost efficient way, and you need to change some of the thinkings about the data and database that you have from other DB.
The main concept is that you shouldn't update data in Redshift. You should consider that data in Redshift as "Log". You can use functions as INSERT or UPDATE but they will limit the amount of data you can process dramatically.
You can handle duplicates in multiple ways:

*

*You can prevent from writing duplicates in the first place, by managing some in-memory lookup tables (for example in Redis on ElastiCache) of all the IDs you are processing and ignore a record if you already processed it

*You can keep duplicates inside Redshift and process these records using WINDOW functions that will take only one of the records (LAST_VALUE, for example).

*You can have the raw events in Redshift and do the aggregation in queries to the DB, instead of doing it as a preprocessing. This mode also gives flexibility in changing the way that you aggregate the data. Redshift can be very fast with these aggregation, and there is little need for pre-aggregation.
If you still want to have "clean" and aggregated data in Redshift, you can UNLOAD that data with some SQL query with the right aggregation or a WINDOW function, delete the old table and COPY the data back into Redshift.


text:
Q: Which PO editor can extract messages from twig files? There is a lot of PO editors, you can find some of them here: What good alternatives to poEdit are there?
But which one can extract messages from twig files?
{% trans %}Hello %name%{% endtrans %}

There is some way to use poedit, but I'm looking for a better way.

A: I think there is no PO editor that can parse Twig emplates. Poedit can do it with the help of Twig Gettext Extractor.
The Twig Gettext Extractor is Poedit friendly tool which extracts translations from twig templates.

A: I use the following two npm modules xgettext-template and gettext-volt. Works perfectly since Volt templates have nearly the same syntax as Twig templates.
EDIT 2021:
You could also purchase a Poedit Pro licence:

Work with Twig and Volt templates
Twig is one of the most popular templating languages for web development, used by WordPress, Craft CMS, Symfony, Drupal, or Grav; Volt is used by Phalcon. Poedit Pro supports extraction of translation strings from Twig and Volt templates out of the box.


text:
Q: Receive a task notification for any task assigned to you - your group or not Is there a general place to set up notifications on tasks so that anyone who has a task assigned to them will receive a notification - not dependant on if they have set up an alert for that list or not?
Example: Jane works in Design. She has no access to Fincance. But Finance has assigned her the task of designing a presentation. Finance has no access to Design. How would Fincance task Jane and she would receive a notification?

A: I think task lists will do this by default.  Under advanced settings there is an option to send email when ownership is assigned.  I believe this option is enabled by default.  So a user wouldn't need to setup an alert beforehand.  I do think the user would need to have access to the task list in order to receive the email.
Cool new feature in SP 2013 mysites is it will aggregate all of the tasks assigned to you in the farm (or your farm's search realm) on a page called my tasks.  Pretty cool stuff.


text:
Q: Drawing a square by dragging the mouse I am writing a Java program that closely mimics Microsoft Paint. It can draw four different shapes: Lines, Ovals, Rectangles, and Squares. I am very close to finishing this but I am stuck on the logic for drawing squares.
There are two Points involved while drawing these shapes. The first Point(point1) is when the user presses the mouse button and the second Point(point2) is while the user drags the mouse across the canvas. I believe drawing Rectangles and Squares should be quite similar but the part that has confused me is when drawing a square the sides are equal length so point2 isn't exactly where the mouse is.
Here is the fillRect() method header for reference:
fillRect(x, y, width, height)

My functioning code for drawing rectangles is as follows:
g.fillRect((((point1.x < point2.x) ? point1.x : point2.x)),
            ((point1.y < point2.y) ? point1.y : point2.y),
            Math.abs(point2.x - point1.x),
            Math.abs(point2.y - point1.y));

I tried using the same code for drawing squares except changing the height parameter to be equal to the width parameter because squares have equal length sides:
g.fillRect((((point1.x < point2.x) ? point1.x : point2.x)),
            ((point1.y < point2.y) ? point1.y : point2.y),
            Math.abs(point2.x - point1.x),
            Math.abs(point2.x - point1.x)); //same as width

I don't know what the problem is with making both width and height equal. It works when drawing downwards to the left or right but of course the shape does not expand if you pull straight down. Clicking and dragging up does not work; the square simply moves up with the mouse along the Y axis instead of expanding.
Could anyone point me in the right direction regarding the logic for drawing square from two points?
I can explain my code a bit better if need be.

A: You should do two calculations in your MouseDragged method -- first you should calculate the two corner Points of the rectangle, p1, and p2, and only then should you calculate the width. Point p1 is easy -- it's always the first Point pressed, but p2 will require a simple calculation. Once these are clarified, your calculations should fall out correctly.
i.e., something like:
  int width = Math.abs(pointA.x - pointB.x);
  int height = Math.abs(pointA.y - pointB.y);

  width = Math.max(width, height);
  height = width;

  int x = pointA.x > pointB.x ? pointA.x - width : pointA.x;
  int y = pointA.y > pointB.y ? pointA.y - width : pointA.y;

  g.fillRect(x, y, width, height);

A: If I were using a tool to draw a square, I would expect that my mouse cursor would remain on one of the sides of the square while drawing.  If you always use the x distance as the side, then if I've drawn farther down than across, the cursor will be outside the square.
I think, while the dragging is going on, the code would need to calculate whether the x distance or the y distance to the origin is the longer, and use that as the side of the square-in-progress.  Then the cursor will be on one of the sides, and that side will extend out beyond the cursor to the corner of the square-in-progress.
I don't know why the drawing is going awry -- it is difficult to be sure I understand what you say is going wrong.


text:
Q: Update DOM reference in jQuery each I am modifying an elements innerHTML property inside a $.each() loop. Now if my stack of elements contains childrens of the element where I update the innerHTML, the DOM reference of that children will get lost.
Example:
$(function(){
    $stack = $(".myelement, .myelement *");
    $stack.each(function(){
        var $this = $(this);
        var element = $(this)[0];
        console.log(element.innerHTML = element.innerHTML + " modified");
    });
});

Fiddle: https://jsfiddle.net/b0ux0v5e/
What happens is that I first modify the innerHTML of .myelement. This includes the children p. Therefore the DOM reference of this element is get lost and "modified" will not be appended.
How can such an scenario be solved without building a function that creates a unique selector for the element and re-catches it in each loop?
Note: I am not asking for specifically appending some text to nodes. This is just an example. In a real project I am replacing text in the innerHTML.

A: I guess you want to modify the text content. in this case you would like to know about .contents() method, which lets you loop through with text nodes as well:

$(function() {
  $(".myelement").contents().each(function(i, el) {
    el.textContent += " 'modified'";
  });
});

  I am the myelement

    Hello world

A: Don't modify innerHTML, it will destroy/recreate all the elements inside and force a re-render. You can use insertAdjacentHTML or jQuery's append to add to an element.
Also you do not need to do:
element = $(this)[0];

this will already be a reference to the element.

$(function(){
    $stack = $(".myelement, .myelement *");
    $stack.each(function(){
        var $this = $(this);
        //this.insertAdjacentHTML("beforeend"," modified");
        //Or
        $this.append(" modified");
    });
});

  A span

A div

a paragraph in a div

EDIT
As it seems you want to replace word(s) and not append a word, you could do a replace on the html and then reset it, but again this will destroy/recreate the elements inside, so if any of them have something like event listeners attached they will be lost
var modified = $".myelement").html().replace(/yourword/g,"modified");
$(".myelement").html(modified);

Or you could just loop over all the Text nodes and replace the word from there, this will keep the elements, their event listeners, and so on intact.

$(".myelement, .myelement *").contents().filter(function() {
  return this.nodeType == 3;
}).each(function(){
  this.textContent = this.textContent.replace(/A/g,"modified");
});

  Inside A element

  A span

A div

a paragraph in A div

A: just change
 $stack = $(".myelement, .myelement *");

to
 $stack = $(".myelement");

And you will see in your console
I am the myelement

    Hello world

 modified


text:
Q: Initialize Realm object with @PrimaryKey 0 (zero) fails on second object I'm experiencing some weird behaviour when trying to initialize a simple Realm object. I have a JSONArray which looks like that:
[{"id":0,"name":"Biatrix"},{"id":1,"name":"Bill"},{"id":2,"name":"O-ren"}]

I have the following simple Realm class:
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;

public class Assassin extends RealmObject {
    @PrimaryKey
    private int id;

    @Required
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Here is how I try to populate the class (in Kotlin):
val assassins = viperData.getJSONArray("assassins")

for (i in 0..(assassins.length() - 1)) {
    val item = assassins.getJSONObject(i)

    var assassin = realm.createObject(Assassin::class.java)
    assassin.setId(item.getInt("id"))
    assassin.setName(item.getString("name"))
}

The first item which has id=0 is created fine, but the in the second item I get an exception io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 0. Then I thought oh ya, the object is created pr. default with a id=0 and only afterwords I change the value to something else. It's failing because it allready has an item with the value 0. So I set the id=-1 in the class:
...
public class Assassin extends RealmObject {
    @PrimaryKey
    private int id = -1;
...

... but still get the same exception.
Is this a bug or am I missing something here?
Update
I removed the @PrimaryKey annotation and the class populated correctly. Just to show that the values are unique, here is a shot of the realm class containing the values (the actual values - no assassins here...):

A: From realm documentation:
When calling Realm.createObject(), it will return a new object with all fields set to the default value. In this case, there might be a conflict with an existing object whose primary key field is the default value. To avoid this, it is suggested to create a standalone object, set values of the fields, and then copy it to Realm by copyToRealm() method.


text:
Q: Autocomplete formulário dinamico Tenho um formulário que inclui linhas dinamicamente. Nesse formulário tenho um campo autocomplete onde seleciono o produto e adiciona o valor do produto em outro input. Meu problema é o seguinte: se incluo duas linhas e seleciono o produto o valor duplica no campo preço(conforme a imagem abaixo) gostaria que cada linha incluida pegasse o valor daquele produto.
Segue o codigo do autocomplete e incluir linhas:
function autoCompletar() {
    $('.produtoDesc').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '../models/retornaProduto.php',
                dataType: "json",
                data: {
                    name_startsWith: request.term,
                    type: 'produto'
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        var code = item.split("|");
                        return {
                            label: code[0],
                            value: code[0],
                            data: item
                        }
                    }));
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            var names = ui.item.data.split("|");
            $("input[name='produtoValor[]']").val(names[1]);
        }
    });
};

function adicionaLinha() {
    var addLinha = $("#qtdLinhas")["val"]();
    let novoCampo;
    let idLinha;
    for (var i = 0; i < addLinha; i++) {
        novoCampo = $("tr.linhas:first")["clone"]();
        idLinha = parseInt($("tr.linhas:last").prop("id").split("item_")[1]) + 1;
        novoCampo.find('input').val("");
        novoCampo.insertAfter("tr.linhas:last").attr("id", "item_" + idLinha).find("span").html(idLinha);
        removeLinha();
        autoCompletar();
    }
    ;
};

A: É preciso pegar o input da mesma linha onde você inseriu a informação do campo autocomplete.
Da forma que está fazendo, ele está pegando todos os elementos existentes com input[name='produtoValor[] e inserindo o valor de names[1]:
// pega todos os elementos com name produtoValor[]
$("input[name='produtoValor[]']").val(names[1]);

Altere essa linha para:
          busca por isso                             dentro disso
                 ↓                                         ↓
$("input[name='produtoValor[]']", $(event.target).closest("tr")).val(names[1]);

Assim irá buscar apenas o elemento da mesma linha
 onde está o campo do autocomplete.
Exemplo:

$( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( ".produtoDesc" ).autocomplete({
      source: availableTags,
          select: function (event, ui) {
       $("input[name='produtoValor[]']", $(event.target).closest("tr")).val("valor adicionado");
        }

    }
    );
  } );

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

           Digite Java:
           <input class="produtoDesc">

        <input name='produtoValor[]'>

           Digite Basic:
           <input class="produtoDesc">

        <input name='produtoValor[]'>


text:
Q: What produces Error 10001 in vb6 at connection string? After the last Windows/Office update Feb 2020 on some of the computers the following connection string in vb6 produces an

"Catastrophic Failure : (10001)"

ConnectionString = "provider=microsoft.ace.oledb.12.0;DataSource="+cMDBFile

After installing MicrosoftDatabaseEngine2010 (32bit) the error was gone, but only until the next Windows Restart/Windows Update.
After changing to
ConnectionString = "provider=microsoft.jet.oledb.4.0;DataSource="+cMDBFile

it seems to run.
My MDBFile Format is ACCESS2003
The connection is created as follows:
Dim objConn as ADODB.Connection
Set objConn = new ADODB.Connection

With objConn
    .ConnectionString = "provider=microsoft.ace.oledb.12.0;DataSource="+cMDBFile
    .Open
End With

The Error Occurs at .Open.
Does anybody know what happened?
The last years no error occurred (except 3420 in December of course).
Is this an error produced by Microsoft, if so, how can I tell them?

A: You connection string should according to your database type.
more likely when you are connection to mdb file, you should use
PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=


text:
Q: TraceListener headers and footers When writing a custom TraceListener how can I force the writeheader, the data/messsage, and the writefooter to be one discreet record?  Specifically the custom tracelisteners in question  write to a non file based source, such as database or event stream.   I need to either have the writeHeader, writefooter base methods in TraceListener be ignored or somehow packaged into a single write event.

A: Here is a good article on how custom TraceListeners work, which also explains when and wh WriteHeader and WriteFooter are called.  The trick to avoiding WriteHeader and WriteFooter is apparently to override the TraceData and/or TraceEvent calls.
There is also some discussion of this issue in this SO thread.
Finally, I would encourage you to take a look at Ukadc.Diagnostics it is a pretty cool library for extending System.Diagnostics and provides, among other features, a nice way to achieve some log4net/NLog-like output formatting.  There is a little bit of discussion about this library in this SO thread.
Good luck!


text:
Q: How to pass token kind with its associated information from lexer to preprocessor, then to parser I try to implement a simple C/C++ parser, which try to partially parsing C++ language. So I need to create a Lexer, a Preprocessor and a Parser class.
I'm considering what is the data type I need to pass information from those three layers. Normally, a Token class is need here, for right now, my Token class looks like below:
struct Token
{
    TokenKind id;
    std::string lexeme;
    int fileIndex;
    int line;
    int column;
}

I think the most important part is the TokenKind(it could be IDENTIFIER or CLASS_KEYWORD or any other punctuation like LPAREN), and some times, the lexeme is also important, because it usually contains the type name or variable name information.
I looked at some implementations about how the Token is passed to Parsers.
1, I see the Clang has some functions in it's Preprocessor class like Preprocessor.cpp:739
void Preprocessor::Lex(Token &Result)

You see, a reference is passed as a the function argument, and the function fill the object with the result, see another reference here on a Clang's tutorial here:Clang-tutorial/CItutorial3.cpp at master · loarabia/Clang-tutorial, here the instance tok is reused in a loop.
Token tok;
do {
    ci.getPreprocessor().Lex(tok);
    if( ci.getDiagnostics().hasErrorOccurred())
        break;
    ci.getPreprocessor().DumpToken(tok);
    std::cerr << std::endl;
} while ( tok.isNot(clang::tok::eof));

2, For some lexer generator, I see function yylex() just return an int type, which is actually a TokenKind, and the other information such as the actual lexeme string is stored in a global variables like yylval.
3, For a tiny language for GCC A tiny GCC front end – Part 3 | Think In Geek, I see the Lexer return a std::shared_ptr<Token>, that is:
  static TokenPtr
  make_identifier (location_t locus, const std::string& str)
  {
    return TokenPtr(new Token (IDENTIFIER, locus, str));
  }

The Lexer return a TokenPtr which is a smart pointer of the Token object to the Parser, so the whole Token is returned to the Parser.
4, GCC's cpp library has some interface of the cpp_get_token() function like below:
const cpp_token *token = cpp_get_token (pfile);

Then token->type is just like the TokenKind field.
So, my question is: what are the advantages and disadvantages of those kinds of implementations. Some of the mentioned methods above do not even have a preprocess layer, for me, I do need three layers(the lexer, the preprocessor and the parser).
Note that my parser won't be big enough as clang or GCC's parser. My main idea is that my parser can only parse very limited part of C++ language, and I would like to make them all hand written.
EDIT A similar question is here What should be the datatype of the tokens a lexer returns to its parser?, I also post some comments there several days ago, but that question does not involve the three layers.


text:
Q: Does the law of Universal Gravitation apply to every matter? If I have a big ball of 20,000,000kg and another of 100g, does it mean that the big ball will pull the small ball towards it?

A: The magnitude of the force for both balls is $F = G \frac{M m}{r^2}$. Here $M$ is the mass of the big and $m$ the mass of the small ball, both assumed to be point masses. As you can see the force is the same on both balls.
So $F_{Big} = F_{small}$. This leads with $F = m\cdot a $ to $m a_{small} = M a_{big}$ or in a much nicer way:
$$\frac{a_{small}}{a_{big}} = \frac M m = 200,000,000$$
As you can see both balls will move, but the smaller ball has a much bigger acceleartion. With this you can assume that the big ball stays at rest and only the small ball is moving.

A: The gravitational force between the 2 balls is $F=\frac{Gm_1m_2}{r^2}=\frac{6.6\times 10^{-11}\times 2\times 10^7\times 0.1}{r^2}=\frac{1.32\times 10^{-4}}{r^2}$
So in order that the force be of 1 N, the distance between the two masses should be about $r=1~cm$. If the density of the larger ball is $\rho=10^4~kg/m^3$, its volume is $V=2000~m^3$ which simply means that its radius is much greater than $1~cm$ and that the gravitational force in this case is much less than $1~N$ and doesn't cause any noticeable effect.

A: Both balls would exert equal and opposite attractive forces on one another. But, the motion depends on environment (other forces may affect it).
Providing there's no other force, it may look like massive ball is pulling lighter ball. Its because massive ball would offer higher resistance to other's force. This causes massive ball to accelerate slower than lighter ball.

A: In a certain sense, you are correct, "the big ball will pull the small ball towards it".
Essentially, both the big ball and the small ball will accelerate towards the center of mass of the system which, in this case, is very close to the center of the big ball.
So, from the perspective of the center of mass, the big ball barely moves while the small ball rapidly accelerates towards the big ball.


text:
Q: PHP Performance optimization I'm trying to optimise PHP code to manage code easily and to speedup page execution time. My strategy is to create a file core_functions.php and defined all functions in this file. Then include this file into every other file of the project.
I need to know is it best practice to have all function defined in one file or it is best practice to split the function into different files and include where needed.

A: What you're doing is actually going to hurt performance. In each page that loads the 6000 line file the PHP interpreter has to interpret that whole file. You'd be better of splitting your functions into modules and have each page only reference the modules it needs.
This reinterpretation of PHP files on each page load can be reduced though by using a caching mechanism that caches the compiled byte code of interpreted files.
There is a list of frameworks that do this here: http://en.wikipedia.org/wiki/List_of_PHP_accelerators


text:
Q: Changing a String in a php file on a web server with java? Basically i have these two pages... each with a string that i get with a minecraft bukkit plugin. I need to know if its possible that i can change the String in the index.php file which sits on a web server using java methods. Basically I'm too lazy to edit the files every time i release a update to my plugin. To get more info on what I'm talking about.... http://updates.milkycraft.net/ - for the version.  The source code of my plugin can be found at http://github.com/milkywayz/entitymanager/. I would probably just want to create a separate java application with swing and have that update the values. The index.php file for both strings are extremely simple, i just declared a string variable then echo'd it.

A: Of course you could change the PHP file, but it's not the best solution - it would be really error-prone. There is an other alternative: write the data to the separate file in a well-known format (XML, JSON, YAML, INI etc.) and let the PHP script read it.
Map<String, String> data = new HashMap<String, String>();
data.put("a", "value a");
data.put("b", "value b");
data.put("c", "value c");

// Convert a Map to JSON using GSON:
String data = new Gson().toJson(data);

// Write data to the file:
BufferedWriter writer = null;

try {
    writer = new BufferedWriter(new FileWriter("/path/to/file"));
    writer.write(data);
    writer.flush();
} catch ( ... ) {
   ...
} finally {
    if (writer != null) {
        writer.close();
    }
}

// Read the data
$data = json_decode(file_get_contents('/path/to/file'));

print_r($data);

A: Of course you can.
There are different approaches you can take

*

*Have a index.template where you put in a placeholder like
In java you open that file, replace the  with your value and save it as index.php

*Or you can enclose the string in the index.php with something like mystring
You then open the index.php and replace the content between START/END replace
André


text:
Q: I cannoot get my scroll bar to behave properly in react using javascript, can anyone see an issue? I am trying to make a react site (first time so forgive me if I have made dumb mistakes and am missing something obvious).
My nav bar is currently fixed at the top of my page it has some basic animations on-hover.
I want it to disappear when scrolling down and reappear when scrolling up.
Like in this youtube video tutorial https://www.youtube.com/watch?v=RYUuGgC_IY0
Here is my current Javascript
import React from 'react';
import './Header.css';

const body = document.body;
let lastScroll = 0;

window.addEventListener("scroll", () => {
  const currentScroll = window.pageYOffset;
  if (currentScroll <= 0) {
    body.classList.remove("scroll-up");
  }
  if (currentScroll > lastScroll && !body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-up");
    body.classList.add("scroll-down");
  }
  if (currentScroll < lastScroll && body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-down");
    body.classList.add("scroll-up");
  }
  lastScroll = currentScroll;
});
const Header = () => {
  return (

Home

About

Projects

Contact

  );
}

export default Header;

and here is my css
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgb(85, 85, 85);
  opacity: 0.85;
  color: white;
  font-size: 24px;
  position: fixed;
  top: 0;
  z-index: 9999;
 width: 100%;
}

.header .logo-container {
  display: flex;
 }

.header .logo-container a {
  display: inline-block;
  margin-right: 10px;
}

.header .logo-container a i {
  font-size: 50px;
  color: rgb(255, 255, 255);
  padding: 10px;
}

.header .logo-container a i:hover {
  transform: scale(1.5);
}

.header .username {
  margin-right: 20px;
}

.header nav ul {
  display: flex;
}

.header nav ul li {
  list-style: none;
  margin-left: 20px;
}

.header nav ul li a.nav-link {
  padding-right: 40px;
  font-family: 'Roboto', sans-serif;
  font-size: 30px;
  color: white;
  text-decoration: none;
}

.header nav ul li a.nav-link:hover {
  color: rgb(30, 255, 10);
  font-weight: bold;
  transform: scale(1.5) !important;
}

.header .logo-container a i.fab.fa-linkedin:hover {
  color: rgb(0, 123, 181);
}
.header .logo-container a i.fab.fa-twitter:hover {
  color: rgb(29, 161, 242);
}

.header .logo-container a i.fab.fa-github:hover {
  color: black;
}

.header .logo-container a i.fab.fa-youtube:hover {
  color: rgb(203, 32, 39);
}

/*   Scroll      */
.scroll-down header {
  transform: translate3d(0, -100%, 0);
}

.scroll-up header {
  transform: translate3d(0, 0, 0);
}

Here is my react App.js file as well
import React from 'react';
import './App.css';
import Header from './Header.js';
import Contact from './Contact.js';
import Landing from './Landing.js';
import Sidebar from './Sidebar.js';
import Main from './Main.jsx';

function App() {
  return (

        <Sidebar />
        <Landing />
        <Contact />

  );
}

export default App;

I cannot seem to get it to behave as intended, any insight would be greatly appreciated!

A: The code execution should be broken out of, from one if-condition block, if the purpose for that check is done.
window.addEventListener("scroll", () => {
  const currentScroll = window.pageYOffset;

  if (currentScroll <= 0) {
    body.classList.remove("scroll-up");
    return; // or return with a value or setup the lastScroll = currentScroll before this empty return;
  }

  if (currentScroll > lastScroll && !body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-up");
    body.classList.add("scroll-down");
    return; // or return with a value or setup the lastScroll = currentScroll before this empty return;
  }

  if (currentScroll < lastScroll && body.classList.contains("scroll-down")) {
    body.classList.remove("scroll-down");
    body.classList.add("scroll-up");
    return; // or return with a value or setup the lastScroll = currentScroll before this empty return;
  }

  lastScroll = currentScroll;

});

One other key point to note is where does the scroll-up and scroll-down function gets attached to. The position of Header component in DOM tree inside the body would matter. The code checks in body.classList.contains("scroll-down"), where as it should be known if the class-name is attached/attributed to the parent-div of the Header component?


text:
Q: Warning: DOMDocument::loadXML(): Empty string supplied as input
Warning: DOMDocument::loadXML(): Empty string supplied as input in C:\xampp\htdocs\Magento2\vendor\magento\module-config\Model\Config\Structure\Reader.php on line 132

A: I found this problem when learning to build modules. Don't pre configuring the files and folder with empty .xml files, be sure to only create an .xml file with correct content and save it. Don't just leave them empty with a view of populating later as magento's error handling will just fall-over.

A: I experienced the same kind of issues. I fixed that issue by remove spacing at start of the xml file.
don't give any space at start of the xml file

<?xml version="1.0"?>
...................
..............

it should be
<?xml version="1.0"?>
...................
..............

if it is not solve your problem, show your module.xml

A: There is an empty .xml file in you project and If you don't know where is empty file and you are using linux. Use this command to get list of empty files.
open terminal and type
find  /path/to/dest -type d -empty for dir.
and
find  /path/to/dest -type f -empty for file.

A: i just encountered this problem and it took me a couple hours for it to finally become enabled. I found that by deleting excess files from the demo file structure example and using the bare minimum for the purposes of getting things going worked for me.
like so:
app/code/Vendor/Test/etc/module.xml

                    Test/composer.json

                    Test/registration.php

While trying to work this out. I tweaked many things. In my last run before it finally worked. I made sure I changed the autoload in the composer to read "PSR-4" to read name\type(a module in this case)and the name.
like so
"Gary\\ModuleTest"

I also got rid of a line space in between
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,

in my registration.php
like so:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,

after that i enabled it and upgraded using php bin/magento setup:upgrade.

A: If this issue exists only in Internet Explorer browser, then the possible cause of this issue is due to it's Compatibility View Settings
Turn OFF "Display intranet sites in Compatibility View" under Settings > Compatibility View Settings


text:
Q: What's the difference between numpy.take and numpy.choose? It seems that numpy.take(array, indices) and numpy.choose(indices, array) return the same thing: a subset of array indexed by indices.
Are there only subtle differences between the two, or am I missing something more important? And is there a reason to prefer one over the other?

A: numpy.take(array, indices) and numpy.choose(indices, array) behave similarly on 1-D arrays, but this is just coincidence. As pointed out by jonrsharpe, they behave differently on higher-dimensional arrays.
numpy.take
numpy.take(array, indices) picks out elements from a flattened version of array. (The resulting elements are of course not necessarily from the same row.)
For example,
numpy.take([[1, 2], [3, 4]], [0, 3])

returns
array([1, 4])

numpy.choose
numpy.choose(indices, set_of_arrays) plucks out element 0 from array indices[0], element 1 from array indices[1], element 2 from array indices[2], and so on. (Here, array is actually a set of arrays.)
For example
numpy.choose([0, 1, 0, 0], [[1, 2, 3, 4], [4, 5, 6, 7]])

returns
array([1, 5, 3, 4])

because element 0 comes from array 0, element 1 comes from array 1, element 2 comes from array 0, and element 3 comes from array 0.
More Information
These descriptions are simplified – full descriptions can be found here: numpy.take, numpy.choose. For example, numpy.take and numpy.choose behave similarly when indices and array are 1-D because numpy.choose first broadcasts array.

A: They are certainly not equivalent, as you can see by giving the same arguments (switched) to both methods:
>>> a = np.array([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 11, 12],
                  [13, 14, 15, 16]])
>>> np.choose([0, 2, 1, 3], a)
array([ 1, 10,  7, 16]) # one from each row
>>> np.take(a, [0, 2, 1, 3])
array([1, 3, 2, 4]) # all from same row

I suggest you read the documentation on take and choose.

A: Explanation of np.choose() behavior in the documentation.

*

*numpy.choose(a, choices, out=None, mode='raise')[source]
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])

index array and choices
import numpy as np

print("--------------------------------------------------------------------------------")
print("Index array 'a' and array of choice(s).")
print("--------------------------------------------------------------------------------")
a = np.array([4, 3, 2, 1])
print("'a' is {} shape is {}\n".format(
    a, a.shape
))

c = np.arange(60).reshape((5, 3, 4))
_choice = c[0]
print("An example choice is \n{} \nshape is {}\n".format(
    _choice,
    _choice.shape
))

--------------------------------------------------------------------------------
Index array 'a' and array of choice(s).
--------------------------------------------------------------------------------
'a' is [4 3 2 1] shape is (4,)

An example choice is
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
shape is (3, 4)

Broadcast

Given an "index" array (a) of integers and a sequence of n arrays
(choices), a and each choice array are first broadcast, as necessary,
to arrays of a common shape; calling these Ba and Bchoices[i], i =
0,…,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for
each i.

Ba.shape == Bchoices[i].shape.
print("--------------------------------------------------------------------------------")
print("np.choose() broadcasts 'a' and 'choice' to match (here only on a)")
print("--------------------------------------------------------------------------------")
a = np.vstack([
    np.array(a) for i in range(_choice.shape[0])
])
print("Broadcast shape of 'a' is {}\n 'a' is \n{}\n.".format(a.shape, a))

--------------------------------------------------------------------------------
np.choose() broadcasts 'a' and 'choice' to match (here only on a)
--------------------------------------------------------------------------------
Broadcast shape of 'a' is (3, 4)
 'a' is
[[4 3 2 1]
 [4 3 2 1]
 [4 3 2 1]]

Choose values from choices
c[a[I]][I] for I in ndi.ndindex(a.shape)

suppose that i (in that range) is the value at the (j0, j1, …, jm)
position in Ba - then the value at the same position in the new array
is the value in Bchoices[i] at that same position;

print("--------------------------------------------------------------------------------")
print("Simulate np.choose() behavior of choosing elements c[a[I]][I]]]:")
print("np.array([ c[a[I]][I] for I in np.lib.index_tricks.ndindex(a.shape) ])")
print("--------------------------------------------------------------------------------")
result = np.array([]).astype(int)
for I in np.lib.index_tricks.ndindex(a.shape):
    print("Selecting the element {} at c[{},{}]".format(
        c[a[I]][I].astype(int), a[I], I
    ))
    result = np.concatenate([result, [c[a[I]][I].astype(int)]])
    print("chosen items: {}".format(result))

print("\nResult is \n{}\n".format(
    result.reshape(a.shape)
))

--------------------------------------------------------------------------------
Simulate np.choose() behavior of choosing elements c[a[I]][I]]]:
np.array([ c[a[I]][I] for I in np.lib.index_tricks.ndindex(a.shape) ])
--------------------------------------------------------------------------------
Selecting the element 48 at c[4,(0, 0)]
chosen items: [48]
Selecting the element 37 at c[3,(0, 1)]
chosen items: [48 37]
Selecting the element 26 at c[2,(0, 2)]
chosen items: [48 37 26]
Selecting the element 15 at c[1,(0, 3)]
chosen items: [48 37 26 15]
Selecting the element 52 at c[4,(1, 0)]
chosen items: [48 37 26 15 52]
Selecting the element 41 at c[3,(1, 1)]
chosen items: [48 37 26 15 52 41]
Selecting the element 30 at c[2,(1, 2)]
chosen items: [48 37 26 15 52 41 30]
Selecting the element 19 at c[1,(1, 3)]
chosen items: [48 37 26 15 52 41 30 19]
Selecting the element 56 at c[4,(2, 0)]
chosen items: [48 37 26 15 52 41 30 19 56]
Selecting the element 45 at c[3,(2, 1)]
chosen items: [48 37 26 15 52 41 30 19 56 45]
Selecting the element 34 at c[2,(2, 2)]
chosen items: [48 37 26 15 52 41 30 19 56 45 34]
Selecting the element 23 at c[1,(2, 3)]
chosen items: [48 37 26 15 52 41 30 19 56 45 34 23]

Result is
[[48 37 26 15]
 [52 41 30 19]
 [56 45 34 23]]

np.choose(a,c)
print("--------------------------------------------------------------------------------")
print("Run np.choose(a, c):")
print("--------------------------------------------------------------------------------")
print(np.choose(a, c))

--------------------------------------------------------------------------------
Run np.choose(a, c):
--------------------------------------------------------------------------------
[[48 37 26 15]
 [52 41 30 19]
 [56 45 34 23]]


text:
Q: clearer jquery textbox change event my apologies to ask this question as there may e answers already existing just that the weren't clear enough to me. What is the best way to apply jquery change event on an html texbox control.

A: Do you mean textarea? Something like this:
$('textarea').on('keydown', function() {
    //Do stuff
    console.log('Do something smart here!');
});

A: Can you try the below sample code.
<input type="text" class="common" />
<input type="text" class="common" />
<input type="text" class="common" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
<script type="text/javascript">
 $(document).ready(function () {
     $("input.common[type='text']").change(function () {
        var value = this.value;
        alert(value);
     });
 });

</script>

A: On modern browsers, use oninput event:
$('textarea').on('input',function(event){
   alert(this.value);
});


text:
Q: Sending email only in prodcution but not in development with Rails I have an app that sends email and I configured mandrill in my application.rb file.
config.action_mailer.smtp_settings = {
  address:              'smtp.mandrillapp.com',
  port:                 587,
  domain:               'translatr.herokuapp.com',
  user_name:            ENV["MANDRILL_USERNAME"],
  password:             ENV["MANDRILL_PASSWORD"],
  authentication:       'plain',
  enable_starttls_auto: true  }

However I don't want to send out mail during development and when testing but I do in production.Do I do this by moving this setting to production.rb?or is there another way to do it?

A: Move your settings to production.rb, then email will be sent in production only

A: You want to have this setting in production.rb only. Because there are other useful settings for the other environments:
In test.rb you will find something like:
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test

This allows you to write specs that check if a mail would have been send on production by checking if ActionMailer::Base.deliveries.size increased.
And the development environment usually should not sent an email. It just logs into development.rb what email would be send on production. Also very useful for debugging.

A: Instead of changing the setting in application.rb you can check for current rails environment. If env is production call the mail method.
      send_mail if Rails.env.production?

How to tell if rails is in production?


text:
Q: Type 'boolean' is not assignable to type 'boolean[]' I would like to create a switch between tabs based on a boolean array. However, I do not know how to replace the switchTabs function to stop this error from being displayed.
The interface is built like this:
interface IData {
    setData: boolean[];
}

My constructor looks like this:
  constructor(props: IData) {
        super(props);
        this.state = {
            setData: [true, false, false]
        }
    }

However, the method in which the error (Type 'boolean' is not assignable to type 'boolean[]') occurs looks like this:
 private switchTabs() {
        this.setState({ setData: !this.state.setData});
    }

A: per @evolutionxbox comment:

private switchTabs() {
        this.setState({ setData: this.state.setData.map( x=>!x});
    }

using .map will apply a function against each element in an array. This is nice, tidy notation.  This is inverting each boolean value in the array. I'm not exactly sure what will happen if your array contains a non-boolean element though.

A: You're denying the array of booleans !this.state.setData which evaluates to false. Thus throwing that error.
Instead you should create a copy of the array and modify the desired index
private switchTabs(tabIndex) {
        const newData = [...this.state.setData]; //copying the array
        newData[tabIndex] = !newData[tabIndex];
        this.setState({ setData: newData});
    }


text:
Q: Java 8 - Custom JavaDoc check using Doclet I'm interested in validating JavaDoc, I found this answer of customizing checks:

import com.sun.javadoc.*;

public class CheckingDoclet extends Doclet {

The problem com.sun.javadoc was removed and will be replaced only in java 9 (which means using at least java 10)

The declarations in this package have been superseded by those in the package jdk.javadoc.doclet. For more information, see the Migration Guide in the documentation for that package.

Is there any replacement using Java 8?
EDIT
I need a new check for preventing description after block tag,
In checkstyle there's no such rule and need to create a new check
In PMD there's no such rule and probably need to create a new check

A: I would suggest to use the JavaDoc checks of your ide (my is eclipse) - and also of CheckStyle and PMD.
For all three you should do your own configuration!
Within eclipse you can find the configuration for JavaDocs at Windows/Preferences/Java/Compiler/Javadoc
For the case that you have special requirements that can not be fulfilled by these tools - then forget about eclipse.
Your only chance is to write your own extensions for CheckStyle or PMD.
For example see Writing CheckStyle checks.
Btw. also it is not recommended to use java internal api's - see Stackoverflow About Java 8 Doclets. To my best knowledge these api's will vanish with Java 9/10/11+. So it's not recommended to use them.


text:
Q: Mangled member function name different during dllimport I'm getting some unresolved externals when importing a DLL of a project (Project 1) in a .exe project (Project 2) using MSVC 2013 (it compiles fine in Mingw 4.8.1):
main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: class chakra::Message * __thiscall chakra::PublisherSubscriberChannel::GetMessageA(unsigned __int64)" (__imp_?GetMessageA@PublisherSubscriberChannel@chakra@@QAEPAVMessage@2@_K@Z) referenced in function "public: virtual void __thiscall Bar2::ProcessMessages(void)" (?ProcessMessages@Bar2@@UAEXXZ)
test_wrap.obj : error LNK2001: unresolved external symbol "__declspec(dllimport) public: class chakra::Message * __thiscall chakra::PublisherSubscriberChannel::GetMessageA(unsigned __int64)" (__imp_?GetMessageA@PublisherSubscriberChannel@chakra@@QAEPAVMessage@2@_K@Z)

The function GetMessage is a member function of class PublisherSubscriberChannel of namespace chakra in Project 1.
Examined the .exp and .dll file of Project 1 using dumpbin.exe /exports and found the function to be exported as ?GetMessage@PublisherSubscriberChannel@chakra@@QAEPAVMessage@2@_K@Z whereas during importing it is looking for ?GetMessageA@PublisherSubscriberChannel@chakra@@QAEPAVMessage@2@_K@Z as per the above error.
It happens only when I #include "Ogre.h" or any of the other Ogre headers in test_wrap.cxx file (which is a SWIG generated file).
Does anyone have any idea why the function name mismatch with the extra 'A'?


text:
Q: How to show two different error messages based on a range of two dates in angular 7 and HTML? I have to validate moveindate with respect to purchase date and effective date. the condition is it should be in range between purchase date and effective date. So in my ts file I wrote this code:
moveInDateRange = [
 DateStringService.toDate(purchaseDate),
 DateStringService.toDate(policyEffectiveDate)
];

But in HTML I have to show two different error messages, in two different scenerios.

*

*move-in date must be on or after your purchase date

*move-in date must be on or before your policy effective date

so I wrote the code like this:
<div *ngIf="moveindate < finalDetails.property.Details.moveInDateRange[0].toLocaleDateString()">
                    move-in date must be on or after your purchase date

 finalDetails.property.Details.moveInDateRange[1].toLocaleDateString()">
                    move-in date must be on or before your policy effective date

But the problem is it is always showing the second error message.
can you please tell me where I am going wrong?

A: Maybe your condition is not valid since you are comparing by strings. Did you tried with Dates.compare() ?
You should find what you want here :

*

*https://www.w3resource.com/javascript-exercises/javascript-date-exercise-5.php

*https://masteringjs.io/tutorials/fundamentals/compare-dates

A: If you use reactiveForm, you can create a custom validator. You can make the custom validator over the FormControl "moveinDate", but you need remember updateAndvalidity the control when change "purchaseDate" and "policyEffectiveDate"
Here we go!
I imagine you has some like
  form = new FormGroup({
    purchaseDate: new FormControl(),
    policyEffectiveDate: new FormControl(),
    moveinDate: new FormControl(null, this.validationBetween())
  });

after create the form, we need take account when change the purchaseDate and policyEffectiveDate, we are going to use rxj operator "merge" that emit a new value when one or another FormControl change his value. But as merge only emit one value after the two FormControls change, we are going to use startWith also
  ngOnInit(){
    merge(this.form.get('purchaseDate').valueChanges.pipe(
                     startWith(this.form.value.purchaseDate)),
    this.form.get('policyEffectiveDate').valueChanges.pipe(
                     startWith(this.form.value.policyEffectiveDate))
    ).subscribe(_=>{
      this.form.get('moveinDate').updateValueAndValidity()
    })
  }

Our custom validator can return an object with the same property: "error" in both cases or with different properties if we want make differences.
  validationBetween(){
    return (control:AbstractControl)=>{
      const parent=control.parent as FormGroup
      if (parent)
      {
        const purchaseDate=parent.get('purchaseDate')
        const policyEffectiveDate=parent.get('policyEffectiveDate')
        if (!purchaseDate.value || !policyEffectiveDate.value || !control.value)
        return null;
        if (purchaseDate.value>control.value)
           return {error:"moveInDate should be greater or equal than "+purchaseDate.value}
        if (policyEffectiveDate.value<control.value)
           return {error:"policyEffectiveDate should be less or equal than "+policyEffectiveDate.value}
      }
      return null;
    }
  }

If we choose the same property we can use simply
<form [formGroup]="form">
  <input type="date" formControlName="purchaseDate">
  <input type="date" formControlName="policyEffectiveDate">
  <input type="date" formControlName="moveinDate">
  {{form.get('moveinDate').errors?.error}}
</form>

If we choose that in one case return,e.g. {errorLess:"...."} and {errorGreater:"..."} we can use some like

Error less

Error Greater

The stackblitz
NOTE: I use a input type="date", really I like more use angular material date picker or ng-bootstrap datePicker. In this case we need convert the "dates" to string in the way "yyyy-mm-dd" or use getTimer() to get the milliseconds before compare them


text:
Q: Number of components of a node in Networkx How can I compute the number of connected components surrounding a given node in a network?
Example: suppose A is connected to B. A is also connected to C and D, and C and D are connected to each other as well. In this case, node A has 2 connected components including [B] and [C,D].

A: I believe I understand your intent now.
Let's use Padgett's Florentine families as a model.

Here, of the neighbors of the Medici node, only Ridolfi and Tornabuoni are neighbors of each other.
# Setup
import networkx as nx
G = nx.florentine_families_graph()  # Or whatever else your graph is.

# Computation
node_id = 'Medici'  # Your nodes are probably identified by a number.
ego = nx.ego_graph(G, n=node_id, center=False)
components = nx.connected_components(ego)
for c in components:
    print(c)
# {'Acciaiuoli'}
# {'Ridolfi', 'Tornabuoni'}
# {'Albizzi'}
# {'Salviati'}
# {'Barbadori'}

The ego graph is all immediate neighbors of a node n. center=False excludes n from that graph. From there, we find the components.


text:
Q: ¿Por qué Google Chrome me agrega el tag tbody? Tengo dos tablas que se crean y se van llenando a través de un evento.
Tengo diseñado el estilo de la tabla para que las fila pares se pinten de blanco:
table {

border-collapse: collapse;
width: 100%;

}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}

Pero debido a que Chrome me agrega un tbody por cada tag
 en la primera tabla(back-end) no me funciona el css.
La primera tabla se llena de datos desde el back-end:
var prueba = {};
        prueba = nuevaCadena[nuevaCadena.length - 1].replace(/
/g, "").split(",");
        prueba.venta = prueba[0];
        prueba.fecha = prueba[1];
        prueba.heladeria = prueba[2];

        //prueba.base.split(",");

        //if (myElem === null) {
        var contenido = document.getElementById("contenido");
        var tr2 = document.createElement("TR");

        if (contenido.getElementsByTagName("TH").length === 0)
        {
            contenido.appendChild(tr2);
            tr2.innerHTML += "Heladeria	";
            tr2.innerHTML += "Fecha	";
            tr2.innerHTML += "ID	";

        } else {
           var template = "
{{heladeria}}	{{fecha}}	{{venta}}
";

            document.querySelector('#contenido').innerHTML +=       Mustache.render(template, prueba);

       }

Y la segunda, que funciona perfectamente, toma los datos desde el tag <select>:
var contenido = document.getElementById("contenido2");
var tr2 = document.createElement("TR");

var tr = document.createElement("TR");
if (contenido.getElementsByTagName("TH").length === 0)
{
    contenido.appendChild(tr2);
    tr2.innerHTML += "Heladeria	";
    tr2.innerHTML += "Fecha	";
    tr2.innerHTML += "Sabor	";
    tr2.innerHTML += "Cantidad	";

}

//var head = document.createElement("TH");

contenido.appendChild(tr);

//var th = document.createElement("TD");
var option = ["heladerias", "sabores"];
var valor = document.getElementById("sabor_calorias");
var fecha = document.getElementById("fecha");

for (var i = 0; i <= 0; i++) {

    var input = document.getElementById(option[i]).selectedIndex;
    var input2 = document.getElementById(option[i]).options;

    tr.innerHTML += "" + input2[input].text + "	";
    tr.innerHTML += "" + fecha.value + "	";

    for (var j = 1; j <= 1; j++) {

        input = document.getElementById(option[j]).selectedIndex;
        input2 = document.getElementById(option[j]).options;
        tr.innerHTML += "" + input2[input].text + "	";
        tr.innerHTML += "" + valor.value + "	";
        tr.innerHTML += "<input type='button' class='borrar' value='x' onclick='deleted(this)'/>";

    }

}

El resultado es el siguiente:

A: http://htmlhelp.com/reference/html40/tables/tbody.html:

El elemento TBODY define un grupo de filas de datos en una tabla. Una tabla debe tener uno o más elementos TBODY, que deben seguir por TFOOT opcional. La etiqueta final TBODY siempre es opcional. La etiqueta de inicio es opcional cuando la tabla contiene sólo un TBODY y no THEAD o TFOOT.

Osea, en simples palabras, el TBODY siempre esta ahí, aunque no lo hayas incluido. Y cuando este no se incluye el navegador debe corregirlo para poder armar el DOM.
Tomado de: https://stackoverflow.com/questions/938083/why-do-browsers-insert-tbody-element-into-table-elements
Pero ayudando a resolver el problema, te dejo este codigo, espero te sirva.

table {

border-collapse: collapse;
width: 100%;

}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}

    1

    2

3

4

5

6


text:
Q: Kernel Headers for Ubuntu 15.04 Today I upgraded by 14.10 VM to 15.04.  Since it's a virtual machine (via VirtualBox), I needed to install guest additions.  However, the installation fails saying (in /var/log/vboxadd-install.log):

Error! Your kernel headers for kernel 3.16.0-31-generic cannot be found.

So, I tried to install it in the usual way and got:

Package linux-headers-3.16.0-31-generic is not available, but is referred to by another package.  This may mean that the package is missing, has been obsoleted, or is only available from another source[.]

Having installed linux-headers-generic, which should provide the correct headers, I was confused.  This is the sort of error I would expect if 3.16.0-31 was out of date.  But . . . indeed dpkg -l | grep generic produces:

...
  ii  linux-headers-3.19.0-17-generic ...
  ...

A ha!  So it looks like the guest additions are trying to use an outdated kernel.  Maybe they use uname.  So I tried uname -r and got:

3.16.0-31-generic

My guess is that the guest additions are using uname to get the desired kernel header version, but that uname is giving the incorrect value for whatever reason.  Question: If my analysis is right, how do I fix it?  If not, what's the problem?

EDIT: After looking around, it seems that this means the running kernel is actually 3.16.0-31, while 3.19.0-17 is merely installed.  I sudo update-grubd, confirmed that 3.19 kernel is the 0th element of /boot/grub/menu.lst and rebooted, but it doesn't seem to change anything.
EDIT: While /boot/grub/menu.lst is correct (the 0th entry is 3.19), on reboot and holding Shift to get the manual menu, I do not see the 3.19 kernel, and the top entry is the 3.16 kernel.

A: It looks like upgrade process from 14.10 to 15.04 has a bug. Kernel does not install correctly. This can be fixed by running:
sudo apt-get install linux-generic

This will pull both linux-image-generic and linux-headers-generic.
These meta packages always point to the latest kernel image and headers.
This is not the first question with this kind of a problem.

A: fixed mine with:
uname -r
3.13.0-30-generic

sudo apt-get update
sudo apt-get dist-upgrade
reboot

uname -r
3.13.0-30-generic

??
sudo apt-get install linux-image-generic
sudo reboot

uname -r
3.19.0-18-generic

followed by:
sudo /etc/init.d/vboxdrv setup


text:
Q: Convert one element in XML tree to another value, inside namespaces via XSLT I'm trying to manipulate a SAML response (after validation).
The SP is trying to make use of /saml:Assertion/saml:Subject/saml:NameID/content but instead I want it to use /saml:Assertion/saml:AttributeStatement/saml:Attribute/saml:AttributeValue/content where Name is "uid".  (The reason is that the unique identifier is part of the back end attribute and not expressed as the subject, which was a created name.)
That is, inside the SAML response,
<saml:Subject>
  <saml:NameID SPNameQualifier="https://10.19.31.141:9443/sps/SimpleSAML/saml20" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">4202cf15bef783f0e85a9395eca2dc67020ed333</saml:NameID>
  <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
    <saml:SubjectConfirmationData NotOnOrAfter="2015-07-02T13:12:06Z" Recipient="https://10.19.31.141:9443/sps/SimpleSAML/saml20/login" InResponseTo="FIMREQ_4ee0b1eb-014e-1f6b-987d-b8d22c8d5967"/>
  </saml:SubjectConfirmation>
</saml:Subject>

needs conversion to
<saml:Subject>
  <saml:NameID SPNameQualifier="https://10.19.31.141:9443/sps/SimpleSAML/saml20" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">test</saml:NameID>
  <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
    <saml:SubjectConfirmationData NotOnOrAfter="2015-07-02T13:12:06Z" Recipient="https://10.19.31.141:9443/sps/SimpleSAML/saml20/login" InResponseTo="FIMREQ_4ee0b1eb-014e-1f6b-987d-b8d22c8d5967"/>
  </saml:SubjectConfirmation>
</saml:Subject>

because
<saml:AttributeStatement>
  <saml:Attribute Name="uid" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
    <saml:AttributeValue xsi:type="xs:string">test</saml:AttributeValue>
  </saml:Attribute>
</saml:AttributeStatement>

If someone can provide a magical transform I'd love it, but I think I need clues (tutorial?) to come up to speed on transformation inside namespaces.  Suggestions?

A: Thanks, Michael.  Indeed, the issue of namespace was exactly as noted: because the SAML response began
  <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"

I had to include those namespaces in the converter.
The answer turned out to be relatively simple:

*

*populate a variable by scanning the tree

*Apply the identity transformation

*Transform the one element from the preserved variable.

The solution is fairly short, so I'll paste it below as an example:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />

  <xsl:variable name="uid">
    <xsl:value-of select="/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute/saml:AttributeValue"/>
  </xsl:variable>

   <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="saml:NameID/text()">
    <xsl:value-of select="$uid"/>
  </xsl:template>

</xsl:stylesheet>


text:
Q: AWS IoT Core multiple environments Lets say I want to have a staging environment and a production environment. The application works by adding topic rules and processes the ingest with AWS lambda.
What is the best way to have multiple environments in AWS IoT Core?
I thought about doing this:

*

*Set up two accounts (not possible in my project)

*Split environments by topic prefix like dev/* or prod/*

*

*Means the device needs to know in advance where it belongs to

*Add devices to a group and do rule based filtering

*

*Is there any guidance how to do this? I know I can call a lambda function, but this seems a bad idea. It would be great to have a group based filter but afaik there is no access to the device`s groups or properties right now

I would strongly prefer 3. as it allows me to also use production devices for testing. 1. and 2. are alright but not very flexible.
Maybe there are some best practices?

A: We have experienced the stage topic prefix approach in our project for months. I think we keep doing it but there are some side effects that I have mentioned below.
STAGE AS TOPIC PREFIX
Most of the time messages will routed to IoTCore Rules and will trigger some AWS services like Lambda/S3/Dynamo etc. If you are using serverless this could achive with env variables as follows
...
custom:
  myStage: ${opt:stage, self:provider.stage}
  STAGES:
    - dev
    - prod

provider:
  name: aws
  runtime: nodejs12.x
  region: eu-central-1
  environment:
    STAGE: ${self:custom.myStage}

functions:
  someLambdaFunction:
    timeout: 180
    handler: someLambdaFunction.handler
    events:
      - iot:
          name: "iotRuleName_${self:custom.myStage}"
          sqlVersion: "2016-03-23"
          sql: "SELECT  * as data , topic() as topicName FROM '${self:custom.myStage}/room/+/temperature'"

So when you deploy to serverless app to development environment, the rule name will be iotRuleName_dev and the rule sql will be like dev/room/+/temperature
But there are some problems:

*

*As you say with this approach, endnodes should know the prefix value.

*AWS limits your topic levels as 8 -max 7 forward slashes(/) - so by adding stage as prefix to all topics you basically decrease your limit to 7 AWS IoT Core Quotas

*You still have to check for thingName collision. You cant have same thingName in multiple environments at the same time and you would not want to deal with it. Adding stage prefix to thing names could solve confusion. Something like 'DEV-Thing1'
You would also want to consider using basic ingest to reduce costs
STAGE AS REGIONS
It could also possible to split your whole application environments between AWS regions, No collision, no side effects. But you should almost split everything to sleep well in your bad at night. Because accessing different regions entities could cause a big chaos.
CUSTOM APPLICATION
Build your own IoT Core. Well, if you achive this. Do not only use it but sell it.


text:
Q: Jquery Ajax Send to plugin action WordPress I'm using ajax to send form data to a plugin action and I can't get the jQuery to link to the function. The jQuery seems to be sending the code perfectly as i can see via the headers. However the WordPress php function call isn't being actioned. Can't figure it out.
$.ajax({
        url: cjdAjax.ajaxurl,
        type: 'POST',
        action: 'cjd_send_test_email',
        data: {
            'email': email,
            'subject': subject,
            'content': content
        },
        success: function( data ) {
            console.log( data );
            $(".test-box .spinner").hide();
            $(".test-email-message").slideDown();
        }

    });

PHP code
wp_localize_script( 'cjd_admin_script', 'cjdAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

add_action( 'wp_ajax_cjd_send_test_email', 'cjd_send_email_test' );
add_action( 'wp_ajax_nopriv_cjd_send_test_email', 'cjd_send_email_test' );

function cjd_send_email_test(){
  echo $_POST['content'];
  echo $_POST['subject'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}

A: The action param should be part of the data array:
data: {
    action: 'cjd_send_test_email',
    email: email,
    subject: subject,
    content: content
},


text:
Q: Is this problem ill-defined? I am confused by a problem from Schey's Div, Grad, Curl and All That:

Use the divergence theorem to show that
  $$\iint_S\hat{\mathbf{n}}dS=0,$$ where S is a closed surface and
  $\hat{\mathbf{n}}$ the unit vector normal to the surface $S$.

The whole discussion of surface integrals in this text so far has dealt with scalar-valued integrands, like:
$$\iint_S\mathbf{F}\cdot\hat{\mathbf{n}}dS.$$
So it would seem the author is either introducing vector-valued integrands for the first time, or suggesting $\mathbf{F}=1$, which I assume is a typo.
Any ideas about how to resolve this issue? I guess I could just say that, over a closed surface, for every surface normal there will be a normal elsewhere on the surface pointing in the opposite direction so they all cancel. But this approach doesn't use the divergence theorem.

A: The approach you suggest would not work. One-by-one cancellation works with sums but in the case of integrals you'd also need to show that the contributions with opposite signs are represented with the same weight (size of a differential patch corresponding to that $\vec n$ or something).
I think they mean to show that
$$\iint_S n_j\,\mathrm{d}S = 0, \quad \forall j \in \{x,y,z\}$$
because integral of a vector, unless defined more concretely, is understood as a vector of integrals of its components, and that is zero if and only if each of the integrals is. (The other possible understanding
$$\iint_S \vec n \cdot \,\vec{\mathrm{d}S} = 0$$
could not be asked because it is not true: the value of the left-hand side is the surface area of $S$.)
In the above sense, that's not hard, because $n_j = \vec e_j \cdot \vec n$, where $\vec e_j$ is a unit vector in the $j$-th coordinate. I'm sure you can take it from there.

A: $\DeclareMathOperator{div}{div}\DeclareMathOperator{grad}{grad}$
We have
$$
\int\limits_S n \,dS
= \int\limits_S \sum_i n_i e_i \, dS
= \sum_i e_i \int\limits_S (e_i \cdot n) dS
= \sum_i e_i \int\limits_V \div e_i \, dV
= \sum_i e_i \int\limits_V 0 \, dV = 0
$$
where $e_i$ is the canonical base vector in $i$-direction: $(e_i)_j = \delta_{ij}$.


text:
Q: JEdit settings and plugins I would like to prepare a version of JEdit that my students could use right away, without having to install the necessary plugins and changing many settings.
Is there a "clean" way of doing this, i.e. something that would be cross-platform and could be distributed publicly, not just to the students?
This answer was of some help, but does not address the same need: https://stackoverflow.com/a/36683022/6771080
Thanks in advance

A: I effectively do this on every machine I use by copying the ~/.jedit  or c:/users/<username>/AppData/Roaming/jEdit folder. It includes the plugins and all the settings.


text:
Q: What would cause the speed difference between servers? I have this query on my dev server:
select
    snStudyNumber as ProjectNumber
from CDB.cdb.Quotes q
    inner join CDB.cdb.LineItems l
        on q.PK_quID=l.FK_quID
    inner join CDB.cdb.StudyNumbers s
        on l.FK_snID=s.PK_snId
    left outer join ardb.projects p
        on s.snStudyNumber=p.prProjectNumber
    left outer join b
        on s.snStudyNumber=b.studynumber
where q.quDateWon>''
    and s.snPTWCompletionDate >''
    and p.PK_prID is null
    and l.liCreationDate>'12/31/06'
    and b.studynumber is null
union all

select CAST(ProjectNumber AS int)
from history.ProjectsToProcess a
    left outer join ardb.projects p
        on a.ProjectNumber=p.prProjectNumber
where p.PK_prID is null

order by ProjectNumber desc

This used to work ok on the dev server until yesterday.  Now it's taking about 1 1/2 minutes to run.  However, it works fine on the test server.
Here's the weird part.  If i modified the query on dev to take out one of the left outer joins (either one), it would run fine (but the wrong dataset).  If i added the join back it slowed down again.
Also, the data between the servers are within 90% similarity.  Structure and amount wise.
I also tried rebooting the dev server, but that didn't fix the issue.
So, what could cause this discrepancy?  Where should I be looking?
edit-
ok, so i missed something in the execution plans.  The test server (the one that works) is on the left, the dev server on the right.

A: Sounds like your statistics are out of date.  Run UPDATE STATISTICS on the tables on the server running slow and see if that fixes the problem.


text:
Q: How to integrate Sentry with typescript in node I have one node project with typescript and firebase, now I need to add Sentry to my project.
as per the documentation,
I try to ingrate Sentry with node. but if I start my firebase function the sentry is not working and returns the following error
Error [ERR_INSPECTOR_NOT_AVAILABLE]: Inspector is not available
if I remove the sentry integration code the error is not generated and everything is working perfectly.
I am using the following plugins for Sentry integration in node
winston-transport-sentry-node
sentry/tracing
sentry/node


text:
Q: \2 mean in regular expression As of my understanding \2 represents the contents of group 2.
So, the expression r'(\w*)(\w)\2' should return the contents of group2( i.e \w)
but when we use the word having repeated characters it is returning repeated characters.
example:
re.search(r'(\w*)(\w)\2','finally').group(2) -> 'l'
re.search(r'(\w*)(\w)\2','finallyy').group(2) ->'y'

In the 1st example the output is 'l' instead of 'y'.
Can anyone tell me what exactly \2 mean in regular expression and where does my understanding is wrong.

A: This is a "reference" to the second capture group. It thus means that the content in the second capture group is repeated.
For example with this regex, 'finally' and 'finallyy' are matched as:
(\w*) (\w) \2    <rest>
fina   l   l     y
finall y   y

Since the Kleene star is greedy, it will typically eat as much characters as possible, but still matching the string.
So in short if the second capture group would match foo, then \2 has to be able to match foo as well.
Strictly speaking such constructs are not always regular expressions (at least not in the strict mathematical sense): regular expressions can only match regular languages, and regular languages should be parseable by a finite state machine. If the second group for example can match an arbitrary number of characters (for example with (\w+)\1), then one can not encode this on a finite state machine.


text:
Q: Java HTTP GET request gives 403 Forbidden, but works in browser I have some code, which is meant to send a GET request via HTTP to a server, and fetch the data there. I haven't yet coded the part that does stuff with the response, as I first wanted to test whether the GET request worked. And it didn't:
private static String fetch() throws UnsupportedEncodingException, MalformedURLException, IOException {
        // Set the parameters
        String url = "http://www.futhead.com";
        String charset = "UTF-8";

        //Fire the request
        try {
        URLConnection connection = new URL(url).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        // ^^^ I tried this, and it doesn't help!
        InputStream response = connection.getInputStream();

        HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
        httpConnection.setRequestMethod("GET");
        System.out.println("Status: " + httpConnection.getResponseCode());
        } catch (UnknownHostException e) {
            // stuff
        }
        return null;
        // ^^^ I haven't coded the fetching itself yet
    }

With that code in mind, fetch() prints Status: 403. Why is this happening? My guess is that this particular server doesn't let non-browser clients access it (because the code works with http://www.google.com), but is there a workaround?
There are some answers out there already, but some of them are either irrelevant to me (they talk about a problem with HTTPS) or incomprehensible. I've tried those that I can understand, to no avail.

A: You might have Browser Integrity Check enabled https://support.cloudflare.com/hc/en-us/articles/200170086-What-does-the-Browser-Integrity-Check-do-
I disabled Browser Integrity Check and it works fine now. Another solution would be to set User-Agent, if possible.
I experienced the problem from Scala, which eventually uses java.net.URL


text:
Q: Division with Number type I have a server call which returns values of type "Number".
This value needs to be transformed and stored.
Eg: Transformation = value/10( Here value is the response from the server)
These transformation could be different for different datapoints. For now, I consider the transformation to be (value/10)
Number modifiedValue = applyTransformation(event.getValue().getValue(),transformation);

private Number applyTransformation(Number value, String transformation) {
    Number dinominator = Integer.parseInt(transformation.substring(transformation.lastIndexOf("/")+1));

    Number modifiedValue = value/dinominator; //Produces an error

     return modifiedValue;

  }

Error : "The operator / is undefined for the argument type(s) java.lang.Number, java.lang.Number"
Any suggestions to handle this please?

A: yes divide operator not applicable for the argument java.lang.Number. But you can convert Number to java.math.BigDecimal you can apply this. Example code is below.
Output is :
5
5.0
5.0
5
public static void main(String[] args) {

    Number result = divideByNumber(10l, 2l);

    //Test data
    result = divideByNumber(10, 2l);
    System.out.println(result);

    result = divideByNumber(10.0, 2l);
    System.out.println(result);

    result = divideByNumber(10.0f, 2l);
    System.out.println(result);

    result = divideByNumber(new BigDecimal("10"), 2l);
    System.out.println(result);
}

static Number divideByNumber(Number n1, Number n2){
    return new BigDecimal(n1.toString()).divide(new BigDecimal(n2.toString()));
}

A: If you read the API docs for java.lang.Number you find

*

*it is an abstract class so has no instance state ! (so it cannot hold anything unless it is part of a class that extends from it e.g. Integer , Double Float BigDecimal e.t.c.)

*IF it genuinely exists as a number it would be best to find its actual "instantiated" sub type using tests through instanceof
(some problem with the code wrapping button in this page)
Number recieve = event.getValue().getValue();
 int recval;

 float trans;

 int transasint;

 if (recieve instanceof Integer){

 recval = ((Integer)recieve).intValue();

 trans = recval/10;

 transasint = new Float(trans).intValue();

}


text:
Q: How much room do language packs take? In order to save space, is it possible to make the CD English-only, and put the other languages only on the DVD?

A: Indeed, CDs already do not contain language packs other than English. The language choices you see on CD is just for the translations of the installation process' strings. For the actual language packs of an Ubuntu system other than English to be installed, you should either have a working internet connection during the installation or you should install from a DVD or you should install language packs later.
Its officially stated as below:

DVD downloads
Don't be confused, even though DVDs can hold far more data than the
  typical Ubuntu CD, the main benefit of
  the DVD downloads is to get access to
  all of the available language packs.
  Most people will be fine with the
  standard CD installer. There are fewer
  download locations for the DVD images
  and this list is updated less
  frequently than for the CD images.

A: Yes it'd be possible to make the CD smaller that way.  Are you worried that language packs are taking up space on the installed system?  Only the language you choose as default is installed by default.  Not all of what's on the CD ends up on the system.

A: My rough estimate is that the language data is occupying 600 MB on the DVD.
Not all files are in packages. Many are inside a squashfs as one flat file-system:

*

*On the DVD they occupy about 300 MB (which becomes 822 MB after extraction).

Packages (~ 300MB):

*

*Most of it the language related packages are of the
"localization" section (195 MB)

*Packages of the section
"translations" (55 MB)

*They depend on
spelling dictionaries and word lists
(29 MB)

Here is how I counted:
wget http://cdimage.ubuntu.com/dvd/current/maverick-dvd-amd64.iso
mkdir mnt
sudo mount -o loop ./maverick-dvd-amd64.iso ./mnt

# Flat files from Squashfs
sudo mount -o loop ./mnt/casper/filesystem.squashfs ./mnt-dvd2/
sudo find mnt-dvd2/ -type d -a \( -name '*langpack*' -prune -o -name '*language*' \) > files
du -hsc `cat files` # 822 MB uncompressed
tar czf files.tar.gz `cat files` # Very rough approximation of squashfs compression
ls -lh files.tar.gz # (305 MB)

# Localization section packages (195 MB):
for i in `find ./mnt/ -name *.deb`; do dpkg -I $i | grep -q "Section: localization" && echo $i ; done | xargs du -hsc

# Translations section packages (55 MB):
for i in `find ./mnt/ -name *.deb`; do dpkg -I $i | grep -q "Section: translations" && echo $i ; done | xargs du -hsc

# Spelling Dictionaries and Word Lists packages (29 MB):
for i in `find mnt/ -name *.deb`; do dpkg -I $i | grep Provides | egrep -q '(wordlist)|(dictionary)|(spell-)' && echo $i ; done  | xargs du -hsc

Details are here http://codepad.org/vVfI44gw

A: My rough estimate is that the language data is occupying 30 MB on the CD.
The CD does not have any .deb packages related to language, everything is in the squashfs filesystem.
Here is how I counted:
wget http://mirror.yellowfiber.net/ubuntu//maverick/ubuntu-10.10-desktop-amd64.iso

mkdir mnt-cd mnt-cd2
sudo mount -o loop ubuntu-10.10-desktop-amd64.iso ./mnt-cd/
sudo mount -o loop mnt-cd/casper/filesystem.squashfs  ./mnt-cd2/
sudo find mnt-cd2/ -type d -a \( -name '*langpack*' -prune -o -name '*language*' \) > files2

du -shc `cat files2`
149K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-en-AU@firefox-3.6.ubuntu.com
149K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-en-CA@firefox-3.6.ubuntu.com
149K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-en-GB@firefox-3.6.ubuntu.com
148K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-en@firefox-3.6.ubuntu.com
159K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-es-AR@firefox-3.6.ubuntu.com
163K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-es-CL@firefox-3.6.ubuntu.com
160K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-es-ES@firefox-3.6.ubuntu.com
161K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-es-MX@firefox-3.6.ubuntu.com
159K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-pt-BR@firefox-3.6.ubuntu.com
160K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-pt-PT@firefox-3.6.ubuntu.com
148K    mnt-cd2/usr/lib/firefox-addons/extensions/langpack-xh@firefox-3.6.ubuntu.com
5.5K    mnt-cd2/usr/lib/language-selector
1.5K    mnt-cd2/usr/share/doc/language-pack-en
1.5K    mnt-cd2/usr/share/doc/language-pack-en-base
1.5K    mnt-cd2/usr/share/doc/language-pack-es
1.5K    mnt-cd2/usr/share/doc/language-pack-es-base
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-en
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-en-base
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-es
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-es-base
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-pt
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-pt-base
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-xh
1.5K    mnt-cd2/usr/share/doc/language-pack-gnome-xh-base
1.5K    mnt-cd2/usr/share/doc/language-pack-pt
1.5K    mnt-cd2/usr/share/doc/language-pack-pt-base
1.5K    mnt-cd2/usr/share/doc/language-pack-xh
1.5K    mnt-cd2/usr/share/doc/language-pack-xh-base
14K mnt-cd2/usr/share/doc/language-selector
13K mnt-cd2/usr/share/doc/language-selector-common
1.5K    mnt-cd2/usr/share/doc/language-support-en
1.5K    mnt-cd2/usr/share/doc/language-support-writing-en
25M mnt-cd2/usr/share/gnome/help-langpack
788K    mnt-cd2/usr/share/gtksourceview-2.0/language-specs
63K mnt-cd2/usr/share/language-selector
41K mnt-cd2/usr/share/language-support
54M mnt-cd2/usr/share/locale-langpack
279K    mnt-cd2/usr/share/omf-langpack
81M total

tar czf files2.tar.gz `cat files2`
ls -lh files2.tar.gz # 32 MB


text:
Q: How to attach OSDisk and change OSProfile for Azure VM I am setting up a VM restoration pipeline. It looks like this:
I Copy the OS disk
$diskConfig = New-AzureRmDiskConfig -AccountType $storageType `
    -Location $snapshot.Location -SourceResourceId $snapshot.Id -CreateOption Copy
$disk = New-AzureRmDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName `
    -DiskName $diskName

I then Attach it to my VM like so:
$vmConfig = New-AzureRmVMConfig -VMName $virtualMachineName `
    -VMSize $virtualMachineSize
$vmConfig = Set-AzureRmVMOSDisk -VM `
    $vmConfig -ManagedDiskId $disk.Id -CreateOption Attach -Windows

However I also want to indirectly modify the OSProfile property of the VM by binding a certificate to it as I am following this guide by Microsoft. I do:
$vmConfig = Add-AzureRmVMSecret -VM $vmConfig -SourceVaultId $vaultId `
    -CertificateStore $certificateStore -CertificateUrl $certificateUrl

And now when I try to finalize the creation by
New-AzureRmVM -VM $vmConfig -ResourceGroupName $resourceGroupName -Location $location

I get an error:
New-AzureRmVM : Parameter 'osProfile' is not allowed.

I am aware that it modifies OSProfile.Secrets (that is - adds a new record to the list), but there is a restriction that I cannot edit it whatsover. I also tried doing it by creating a VM first and then adding those Secrets, but it gives me the almost the same error
Update-AzureRmVM : Changing property 'osProfile' is not allowed.

By the way, if I use FromImage instead of Attach, I get error:
New-AzureRmVM : Cannot specify user image overrides for a disk already defined in the specified image reference.

How can I solve this?

A: I ended up creating a powershell script that executes a powershell command (using Invoke-AzureRmVMRunCommand) on the VM which:

*

*Retrieves certificates
Get-AzureKeyVaultSecret -VaultName $keyVaultName -name (Get-AzureKeyVaultSecret -VaultName $keyVaultName).name

*Downloads and binds those certificates to IIS

*Creates an ssl binding and assigns it to https binding
Get-ChildItem cert:\localmachine\My | New-Item -Path IIS:\SslBindings\!443

A: Pretty sure this error means that you are trying to use existing disk to create vm. you cannot modify the os settings in this case. only when creating from new disk.

A: Provision a new VM from an image that has the closest matching osProfile that you want. Go ahead and let it create a new OS disk.
After the VM is fully provisioned, go to the VM in Azure Portal and stop the VM. Then go to the Disks settings in the VM's menu and click Swap OS Disk. Pick your desired OS disk. Note: The disk you pick might have to closely match the size and type of the existing OS disk. I didn't test that.
osProfile will remain on the VM. Worked for me at least. Hope it helps someone else.


text:
Q: ROS subscriber callback missing messages Summary: I have a node publishing messages at ~300hz, but a callback subscribing to the topic in another node only gets called at ~25hz. The spinOnce in the subscriber node is being called at ~700hz, so I don't know why it's missing messages.
Publisher node:
#include <ros/ros.h>
#include <ros/console.h>
#include <nav_msgs/Odometry.h>

...

int main(int argc, char** argv)
{
    ros::init(argc, argv, "sim_node");
    ros::NodeHandle nh;

    ...

    // Publishers
    tf::TransformBroadcaster tfbr;
    ros::Publisher odomPub = nh.advertise<nav_msgs::Odometry>("pose",10);

   ...

    ros::Rate r(300); // loop rate
    while(ros::ok())
    {
        ...

        // Publish pose and velocity
            ...
        odomPub.publish(msg);

        ros::spinOnce();
        r.sleep();
    }

    ros::waitForShutdown();
    return 0;
}

Subscriber node:
#include <ros/ros.h>
#include <ros/console.h>
#include <nav_msgs/Odometry.h>

...

std::mutex mtx1, mtx2;

class DataHandler
{
private:
    ros::NodeHandle nh;
    ros::Publisher odomPub;
    double lastTime;
    int lastSeq;

public:
    Eigen::Vector3d x, xDot, w;
    Eigen::Vector3d xDes, xDesDot, xDesDotDot, b1Des, b1DesDot;
    Eigen::Matrix3d R;

    DataHandler()
    {
        // Initialize data
        xDes = Eigen::Vector3d(1,0,1);
        xDesDot = Eigen::Vector3d::Zero();
        xDesDotDot = Eigen::Vector3d::Zero();
        b1Des = Eigen::Vector3d(1,0,0);
        b1DesDot = Eigen::Vector3d::Zero();
        x = Eigen::Vector3d::Zero();
        xDot = Eigen::Vector3d::Zero();
        R = Eigen::Matrix3d::Identity();

        odomPub = nh.advertise<nav_msgs::Odometry>("controller_pose",10);
        trajPub = nh.advertise<asap_control::DesiredTrajectory>("controller_desTraj",10);
        lastTime = ros::Time::now().toSec();
        lastSeq = 0;
    }

    // Get current pose and velocity
    void odomCB(const nav_msgs::OdometryConstPtr& odomMsg)
    {

        mtx1.lock();
        // Get data
        double time1 = ros::Time::now().toSec();
        x << odomMsg->pose.pose.position.x, odomMsg->pose.pose.position.y, ...;
        xDot << odomMsg->twist.twist.linear.x, odomMsg->twist.twist.linear.y, ...;
        R = Eigen::Quaterniond(odomMsg->pose.pose.orientation.w, odomMsg->pose.pose.orientation.x,...;
        w << odomMsg->twist.twist.angular.x, odomMsg->twist.twist.angular.y, ...;
        double time2 = ros::Time::now().toSec();

        // Time to extract data, < 1ms
        double delTproc = time2 - time1;
        std::cout << "\n\n";
        std::cout << "proc elapsed time: " << delTproc << "\n";
        std::cout << "proc frequency: " << 1.0/delTproc << "\n";

        odomPub.publish(odomMsg); // rostopic hz says this is publishing at ~25Hz

        // Time between callback calls, ~25Hz
        double timeNow = ros::Time::now().toSec();
        double delT = timeNow - lastTime;
        lastTime = timeNow;
        std::cout << "elapsed time: " << delT << "\n";
        std::cout << "frequency: " << 1.0/delT << "\n";

        // Message sequence IDs, shows 12 msgs skipped every call
        int seqNow = odomMsg->header.seq;
        int delSeq = seqNow - lastSeq;
        lastSeq = seqNow;
        std::cout << "delta seq: " << delSeq << "\n";
        mtx1.unlock();
    }

};

...

int main(int argc, char** argv)
{
    ros::init(argc, argv, "asap_control");
    ros::NodeHandle nh;

    ...

    // Publishers
    ros::Publisher outputPub = nh.advertise<geometry_msgs::WrenchStamped>("wrench_command",10);
    ros::Publisher debugPub = nh.advertise<control::ControllerSignals>("controller_debug",10);
    tf::TransformBroadcaster tfbr;

    // Subscribers
    DataHandler callbacks;
    ros::Subscriber poseSub = nh.subscribe("pose",10,&DataHandler::odomCB,&callbacks);

    // Asynchronous threads for callback handling
    //ros::AsyncSpinner spinner(2);
    //spinner.start();

    double lastTime = ros::Time::now().toSec();

    // Main loop
    ros::Rate r(700); // loop rate
    while(ros::ok())
    {
        // Data (extracted for cleanliness further down, and thread safety)
        mtx1.lock();
        Eigen::Vector3d x = callbacks.x;
        Eigen::Vector3d xDot = callbacks.xDot;
        Eigen::Matrix3d R = callbacks.R;
        Eigen::Vector3d w = callbacks.w;
        mtx1.unlock();

            ...

        // Publish
            ...
        outputPub.publish(msg);

        // Publish debug signals
        control::ControllerSignals debugMsg;
        debugMsg.x[0] = x(0);
        ...
        debugPub.publish(debugMsg);

        //double timeNow = ros::Time::now().toSec();
        //double delT = timeNow - lastTime;
        //lastTime = timeNow;
        //std::cout << "\n\n";
        //std::cout << "elapsed time: " << delT << "\n";
        //std::cout << "frequency: " << 1.0/delT << "\n";

        ros::spinOnce();
        r.sleep();
    }

    ros::waitForShutdown();
    return 0;
}

Additional info:

*

*The publisher is publishing at ~300Hz (confirmed by rostopic hz of the "pose" topic)

*The main loop in the subscriber node is running at ~700Hz (confirmed by rostopic hz of the "wrench_command" topic being published to in the loop, as well as loop timing via ros::Time::now()), and hence, spinOnce is being called at the same rate.

*The callback for the pose topic is being called at ~25 Hz (confirmed by rostopic hz of the "controller_pose" topic being published to in the callback, as well as loop timing via ros::Time::now())

*I get the same behavior even if I use the AsyncSpinner instead of spinOnce, though can only confirm using rostopic hz. Timing produces erratic output, as expected

*Increasing the subscriber queue_length to e.g., 10 increases the callback rate to ~250Hz, however, I want to keep a queue_length of 1 to get only the most recent data.

*System monitor in Ubuntu shows less than 50% cpu utilization, so I don't think it's cpu bottleneck issue.

A: I solved a similar issue transmitting odometry data a while back, where odometry data was being transmitted at 100Hz but only being received at 25 Hz. Turned out that the underlying TCP socket was buffering the data, lumping 4 messages into a single TCP packet to save on transport costs. I believe you need to set tcpNoDelay to true in the TransportHints():
node.subscribe(...,ros::TransportHints().tcpNoDelay(true));
Note that this happens on the subscription side.
http://wiki.ros.org/roscpp/Overview/Publishers%20and%20Subscribers#Transport_Hints