text:
Q: Window Crypto Subtle : How we can use encrypt / decrypt method if we generate public private key with "RSASSA-PKCS1-v1_5" algo? I want to use the same public-private key to do some encryption/decryption at the code level and want to send encrypted data to the backend along with my public key which I am appending inside of my JWT AUTH Token.
So pls help me to encrypt / decrypt with that approach if possible, as I can't change this code due to reusability
      const keyDetails = await window.crypto.subtle.generateKey(
          {
              name: 'RSASSA-PKCS1-v1_5',
              modulusLength: 2048,
              publicExponent: new Uint8Array([1, 0, 1]),
              hash: { name: 'SHA-256' },
          },
          true,
          ['verify', 'sign']
      );

I tried that way but got an error.
Also, I want to use my exported public and private keys which I am doing with that approach
const publicKey: any = await window.crypto.subtle.exportKey('jwk', keyDetails.publicKey);
const privateKey: any = await window.crypto.subtle.exportKey('jwk', keyDetails.privateKey);

      const enc = new TextEncoder();
      const encodedText = enc.encode("testing 1234");

      const encryptedText = await window.crypto.subtle.encrypt({
        name: "RSASSA-PKCS1-v1_5"
      },
      publicKey,
      encodedText
    )
    console.log(encryptedText);
    const decryptedText = await window.crypto.subtle.decrypt({
        name: "RSASSA-PKCS1-v1_5"
      },
      privateKey,
      encryptedText
    )

TypeError: Failed to execute 'encrypt' on 'SubtleCrypto': parameter 2 is not of type 'CryptoKey'.

A: RSASSA-PKCS1-v1_5 is a padding that is applied during signing/verification. It cannot be used for encryption/decryption. The padding for encryption/decryption is RSAES-PKCS1-v1_5, but this is not supported by WebCrypto API. WebCrypto only supports RSAES-OAEP for encryption/decryption. See RFC8017 and WebCrypto API for more details.
Also, the exported JWK keys must first be adapted for encryption/decryption. Then the keys must be imported before they can be used in encryption/decryption.
The following example demonstrates this: First, a key pair for signing/verifying with RSASSA-PKCS1-v1_5 is generated. Both keys are exported as JWK. Then the key_ops and alg parameters are adjusted. Afterwards, the modified keys are re-imported and used for encryption/decryption with RSAES-OAEP:

(async () => {

// Generate
const keyDetails = await window.crypto.subtle.generateKey(
    {
        name: 'RSASSA-PKCS1-v1_5',
        modulusLength: 2048,
        publicExponent: new Uint8Array([1, 0, 1]),
        hash: { name: 'SHA-256' },
    },
    true,
    ['verify', 'sign']
);
console.log(keyDetails)

// Export
const publicKey = await window.crypto.subtle.exportKey('jwk', keyDetails.publicKey);
const privateKey = await window.crypto.subtle.exportKey('jwk', keyDetails.privateKey);
console.log(publicKey)
console.log(privateKey)

// Adapt parameters and import
publicKey.key_ops = ['encrypt'];
privateKey.key_ops = ['decrypt'];
publicKey.alg = 'RSA-OAEP-256';
privateKey.alg = 'RSA-OAEP-256';
const publicKeyReloaded = await window.crypto.subtle.importKey("jwk", publicKey, {name: "RSA-OAEP", hash: {name: "SHA-256"}}, true, ["encrypt"]);
const privateKeyReloaded = await window.crypto.subtle.importKey("jwk", privateKey,{name: "RSA-OAEP", hash: {name: "SHA-256"}}, true, ["decrypt"]);
console.log(publicKeyReloaded)
console.log(privateKeyReloaded)

// Encrypt/Decrypt
const enc = new TextEncoder();
const encodedText = enc.encode("testing 1234");
const encryptedText = await window.crypto.subtle.encrypt({name: "RSA-OAEP"}, publicKeyReloaded, encodedText)
console.log(ab2b64(encryptedText));
const dec = new TextDecoder();
const decryptedText = await window.crypto.subtle.decrypt({name: "RSA-OAEP"}, privateKeyReloaded, encryptedText)
console.log(dec.decode(decryptedText));

// Helper
function ab2b64(arrayBuffer) {
    return window.btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
}

})();

Note that in general the same key pair should actually be used for either signing/verifying or encrypting/decrypting, not for both together, see here.
WebCrypto API provides some protection against this misuse by binding the purpose of the key to it (however, this protection can be circumvented all too easily, as shown above).

A: Well, the answer is already provided by @topaco.
now I Just want to add one more approch here. If someone wants to Encrypt and Decrypt sensitive data with help of [JSON Web Encryption - Ciphertext] JOSE npm lib.  with that public/ private key which is generated for sign/ verify only!
const jose = require('jose'); // npm i jose
async encryptDecryptLogic(data: string): Promise<any>{

    const keyDetails = await window.crypto.subtle.generateKey(
          {
              name: 'RSASSA-PKCS1-v1_5',
              modulusLength: 2048,
              publicExponent: new Uint8Array([1, 0, 1]),
              hash: { name: 'SHA-256' },
          },
          true,
          ['verify', 'sign']
      );

       // updating operation from sign-varify to encrypt-decrypt.
       // As that private/ public key is generated for sign and verification purposes only but here we extended its purpose. So we need to update a few properties to do encryption/decryption

        publicKey.key_ops = ['encrypt'];
        privateKey.key_ops = ['decrypt'];

        // updating algo from sign-varify[RS256] to encrypt-decrypt[RSA-OAEP]
        // Defines the algorithm used to encrypt the Content Encryption Key (CEK). This MUST be set to "RSA-OAEP".

        publicKey.alg = 'RSA-OAEP';
        privateKey.alg = 'RSA-OAEP';

 const encodedText =  await this.jose.jwe.encrypt(publicKey, "lets encrypt me!!")
        console.log('encodedText', encodedText);

 const decodedText =  await this.jose.jwe.decrypt(privateKey, encodedText)
        console.log('decodedText', decodedText);
}


text:
Q: Repairing a corrupt postgresql database This is what happens when postgresql tries to start after a power failure:
2012-01-27 18:00:44 MSK LOG:  database system was interrupted while in recovery at 2012-01-27 18:00:16 MSK
2012-01-27 18:00:44 MSK HINT:  This probably means that some data is corrupted and you will have to use the last backup for recovery.
2012-01-27 18:00:44 MSK LOG:  database system was not properly shut down; automatic recovery in progress
2012-01-27 18:00:44 MSK LOG:  consistent recovery state reached at 17/762C39B8
2012-01-27 18:00:44 MSK LOG:  redo starts at 17/761F6A40
2012-01-27 18:00:44 MSK FATAL:  invalid page header in block 311757 of relation base/26976/27977
2012-01-27 18:00:44 MSK CONTEXT:  xlog redo insert: rel 1663/26976/27977; tid 311757/44
2012-01-27 18:00:44 MSK LOG:  startup process (PID 392) exited with exit code 1
2012-01-27 18:00:44 MSK LOG:  aborting startup due to startup process failure

I know I'm not out of luck and there is a command I can use to repair the database in this situation. It doesn't matter if the last few hours of transactions disappear, as long as the database becomes consistent.
Please advice me on what to do in this situation.

A: I fixed it using below commands:
mkdir -p /var/run/postgresql/9.6-main.pg_stat_tmp

sudo service postgresql-9.6 restart

change filename/versions as shown in error message.

A: Depends on how much you're willing to give up on data side.
You can set zero_damaged_pages to on in your postgresql.conf configuration file and then give it a try - but that will cause data loss. It might work or might not work.
If you want to try that, always start by shutting down the postgres database and taking a full filesystem copy of it (e.g. tar). Because it might still be the least broken version you have. Then once you've set it, run a pg_dump right away, wipe the cluster, and restore the dump. And absolutely do not run the new cluster with zero_damaged_pages on by default, remember to turn it back off!
And then set up proper Point-In-Time Recovery backups for the new cluster.

A: Restore from the last backup, then reapply the logs from there.
Unless you have the last backup and all logs since then, you're screwed.

A: In my case, I was getting the following error:
LOG:  could not open directory "pg_tblspc/ui6h1i/PG_13_202007201/pgsql_tmp": Not a directory
LOG:  could not open directory "pg_tblspc/ui6h1i/PG_13_202007201": Not a directory

It turned out that /var/lib/postgresql/data/pg_tblspc/ui6h1i was actually an executable instead of a directory. I made a backup of the data folder, then deleted ui6h1i. Postgres was then able to start up, and seems to be working.
(using postgres 13)

redpajama_set_name: RedPajamaStackExchange


text:
Q: decrease time execution of a python code how can i decrease the time execution of this code:
tab_voyelle is a table of 2669433 different words
for elem in tab_voyelle:
 words_match = []
 elem = elem.strip()
 Tab_elem_out = CheckImpli(elem,tab_voyelle)
if len(Tab_elem_out) != 0:
 MonFichINImpli = open('/home/user/Bureau/MesTravaux/MatchingCorpus/in_imply_result.txt','w')
 for i in range(len(Tab_elem_out)):
  MonFichINImpli.write(elem + ' ' + Tab_elem_out[i] + '\n')
  MonFichINImpli.close()
  subprocess.call(['java', '-jar', '/home/user/Bureau/MesTravaux/MatchingCorpus/dist/ImpliMorphVer4.jar','-i', 'in_imply_result.txt','-o','Result_Impli.txt'])
words_match = MatchingArabicWords('Result_Impli.txt','in_imply_result.txt')
if len(words_match) != 0 :
 MonFichierResultat.write('<mot id="'+elem+'">'+'\n')
 for valeur in words_match:
    valeur = valeur.strip()
    MonFichierResultat.write('<val>'+valeur+'</val>'+'\n')
    t = tab_voyelle[tab_voyelle.index(valeur)]
    del tab_voyelle[tab_voyelle.index(valeur)]
 MonFichierResultat.write('</mot>' + '\n')
if len(words_match) == 0:
 MonFichierResultat.write('<mot id="'+elem+'">'+'\n'+'<val></val>\n'+'</mot>' + '\n')
MonFichierResultat.write('</matching>' + '\n')
MonFichierResultat.close()


text:
Q: input type submit vs input type button I have been trying to solve an annoying behavior with PHP (I think..). Maybe some of you have encountered the same and have some ideas. I have an html form and I use an  element with the onClick event that calls a javascript function. Once the script's content has been processed, I execute the form.submit() directive. It basically checks common things like length of fields, etc.
Now my problem is, when I use input type button, I set its name to submit1, and just to run a small test, I set the <form id="register" action="<?php echo($PHP_SELF) ?>" method="post">
I then put:
        <?php

if (isset($_POST["submit1"])) {
    echo "Submit button was pressed";
    die();

}

?>

However, I never see the message even though my input button's name is submit1. I then changed the input type to submit, and I click submit, I'll see the message but the only problem is that even if my javascript function finds any errors in the form, after clicking okay on the alert box, the form continues regardless. It only does this on submit type=submit.
If anyone is interested,
my buttons:
1st try:
<input type="button" name="submit1" class="submit" value="Register"
onclick="validateFields()"  />

2nd try:
<input type="submit" name="submit1" class="submit" value="Create Account!"
onclick="validateFields()"  />

A: To submit your form, the input field must be of the type submit, not button.
<input type="submit" name="submit1" class="submit" value="Create Account!"
onclick="validateFields()"  />

You can also do:
<button type="submit" name="submit1" class="submit" onclick="validateFields()">
Create Account! </button>

And, to avoid your form from being submitted if there are errors, you can return false:
function validateFields() {
    //do validation
    if(failed) {
        return false;
    }
}

A: For the java script problem may be you haven't put return false that's why form is submitting in any way.
if(a.value == ""){
alert("Name is empty");
return false; // this will prevent your form to be submit if condition fails
}

Whereas the difference between button and submit is that the submit is submitting the form(posting form) so PHP is eligible to get via $_POST but in button case the form isn't submitting so you cant get the values on other page rather than using Ajax.
Similar Question here

A: Thank you everyone, I fixed it :).
I changed the input type into button, and changed my onclick="function(); return false"
And in my original JS code, I added: document.getElementById('myFormId').submit();
Now my JS code runs and it doesn't submit it until all the errors are fixed. Thank you. Silly mistake on my part.


text:
Q: HTML- How can I insert the contents of a .txt file into a variable to use .innerHTML to change the contents of ? Im trying to create an automated system for HTML page handling where I will be able to change the contents
of a
 inside  by writing into an external .txt file and uploading it to the server. Im still an early student in university
and I havent learned PHP and JQuery yet. So I am trying to accomplish this by using only Javascript and HTML.
I just need a way for whatever I write inside the .txt file to be written again inside the
 which is inside the  automatically. Any thoughts and suggestions are greatly appreciated!

A: You can solve your problem by using the FileReader.
Have a look to
this answer.

function readSingleFile(e) {
    var file = e.target.files[0];
    if (!file) {
        return;
    }
    var reader = new FileReader();
    reader.onload = function (e) {
        var contents = e.target.result;
        displayContents(contents);
    };
    reader.readAsText(file);
}

function displayContents(contents) {
    var element = document.getElementById('target');
    element.textContent = contents;
}

document.getElementById('file-input')
    .addEventListener('change', readSingleFile, false);

    <input type="file" id="file-input" />

Contents of the file:

A: You can make an AJAX call for the text file and take the response from that call and set that as the .textContent of the div. Here's an example (see comments inline):

const output = document.getElementById("output");

// Create XHR object
var xhr = new XMLHttpRequest();

// Configure the request (substitute a URL
// to the file below)
xhr.open("GET", filePathHere, false);

// Set up the callback for when the response has
// been recieved
xhr.onreadystatechange = function (){
 if(xhr.readyState === 4) {
   // Was the request successful?
   if(xhr.status === 200 || xhr.status == 0) {
     // Populate the
 with the response text
     output.textContent = xhr.responseText;
   }
 }
}
xhr.send(null);  // Make the call


text:
Q: Setting a variable - constructor/get/set C# i haven programmed in a while so i forgot something.
ive got a "Kunde" class. with some variables:
class Kunde
{
    private string _navn;
    private string _adresse;
    private int _postnr;
    private string _by;
    private int _telefonnr;
    private int _mobil;
    private string _email;
    private string _land;
    private string _oplysning;
    private int _kundenr;
    //Erhverv:
    private int _cvr;
    private string _firmanavn;
    private string _kontaktperson;

    //Tom konstruktør
    public Kunde()
    {
    }

    //privat
    public Kunde(string navn, string adresse, int postnr, string by, int telefonnr, int mobil, string email, string land, string oplysning, int kundenr)
    {
        _navn = navn;
        _adresse = adresse;
        _postnr = postnr;
        _by = by;
        _telefonnr = telefonnr;
        _mobil = mobil;
        _email = email;
        _land = land;
        _oplysning = oplysning;
        _kundenr = kundenr;
    }
}

}
my question is.. ive got a winform with some text fields, but not every field has to be filled with data..
should a make a get/set on every variable to be able to set the variable from another class - or a constructor for each option?
whats the best way to do this?

A: Just provide a Get and optionally a Set accessor for each member.
You'll have to pick some form of DataBinding + Validation to work from your Form. But a Customer class has its own design and its own logic.

A: In C# 4.0, you can specify values for properties when calling a constructor.
var kunde = new Kunde()
{
    Navn = navn,
    Adresse = adresse,
    // all your properties
};

Create get/set accessors for each of your fields and then you can specify whichever properties you want to set as above.

A: You'd better keep default constructor only and create public property for each data you need to read or set.
You may keep your constructor with parameters - but only with those that are really mandatory to be filled for each of your Kunde-n.
If you plan to bind your Kunde object-s directly to some BindingSource and display them e.g. in some sort of grid/list and/or treeview you may also consider implementing some of the related interfaces: System.ComponentModel.IdataErrorInfo; System.ComponentModel.INotifyPropertyChanged;
and you may cosider apply Attribute-s to your public properties - such as System.ComponentModel.DisplayNameAttribute; - it can define fixed name of headers in the DataGrid orit might be localized for different languages

A: public string Adresse { get; private set; } etc. and you have an automatic variable which is read-only except inside the class.


text:
Q: Dynamically Resize Table Based on Text in Cell I have a dynamic table that changes size based on slicer selection, so sometimes the table may consist of 4 rows, sometimes, 7, sometimes 15, etc.
Regardless of the size of the table, the last row in column A will always equal "Retail Total".
My table looks essentially like this:
+--------------+------+------+------+------+------+------+
|     ColA     | ColB | ColC | ColD | ColE | ColF | ColG |
+--------------+------+------+------+------+------+------+
| Row1         | B2   | C2   | D2   | E2   | F2   | G2   |
| Row2         | B3   | C3   | D3   | E3   | F3   | G3   |
| Row3         | B4   | C4   | D4   | E4   | F4   | G4   |
| Retail Total | B5   | C5   | D5   | E5   | F5   | G5   |
+--------------+------+------+------+------+------+------+

What I would like to do is have some VBA code that will resize the table depending on wherever "Retail Total" occurs.
Here is my code so far:
Private Sub Worksheet_Calculate()
Dim ws As Worksheet
Dim ob As ListObject
Dim Lrow1 As Long

Set ws = ActiveWorkbook.Worksheets("Sheet1")
Set ob = ws.ListObjects("Table6")

With Sheets("Sheet1")

    Lrow1 = .Cells(.Rows.Count, "G").End(xlUp).Row
    Do While .Cells(Lrow1, "A").Value = "Retail Total"
        Lrow1 = Lrow1 - 1
    Loop

End With

ob.Resize ob.Range.Resize(Lrow1)

End Sub

This code doesn't seem to work. The table keeps growing and does not stop at "Retail Total", so I was hoping for some assistance.

A: I ran this code and it worked, except for an off-by-one error. I fixed it with:
ob.Resize ob.Range.Resize(Lrow1 + 1)

You should verify that the cell that contains "Retail Total" actually contains that verbatim phrase and not any leading or trailing spaces. You can test by putting this code in your immediate window and see if it comes up true:
? range("A5").Value = "Retail Total"

Replace A5 with whatever cell happens to contain "Retail Total" at the moment.


text:
Q: Switching foreign keys of two rows I am working on a site where users can trade items with other users. Upon completion of a trade, I need to change the owner of the items.
My 'items' table has a foreign key referencing the user. Given two item id's, how can I switch the foreign keys with each other?
I've tried something like this...
UPDATE items
SET user_id = (
  SELECT users.id FROM items
  INNER JOIN users
  ON users.id = items.user_id
  WHERE items.id = $1
)
WHERE id = $2;

UPDATE items
SET user_id = (
  SELECT users.id FROM items
  INNER JOIN users
  ON users.id = items.user_id
  WHERE items.id = $2
)
WHERE id = $1;

This doesn't work because after the first UPDATE is performed, the user_id is updated, so the second SELECT statement does not work as intended.

A: You should do that in a single query, use with statement.
The pairs query links items (given as parameters) with users and switches the linked values by aggregating them in opposite orders.
with params(param) as (
    values ($1), ($2)
),

pairs(i_id, u_id) as (
    select i_id, u_id
    from (
        select
            array_agg(param order by user_id) as i_arr,
            array_agg(user_id order by user_id desc) as u_arr
        from items
        join params on param = id
    ) s,
    unnest(i_arr, u_arr) as u(i_id, u_id)
)

update items
set user_id = u_id
from pairs
where id = i_id;


text:
Q: How to add/remove a group of fields using jQuery in a multi-step Rails 3 form? I have a Rails 3 app with a multi-step form that I developed using this railscast: http://railscasts.com/episodes/217-multistep-forms
In the 3rd step(not the last step) of my form, I have a group of fields, called "Audience", which contains 4 select boxes.
Using Jquery, I have "add" and "remove" links next to this group of fields, so that I can have multiple "Audiences" in the form.
So for example, I start off with 1 Audience. If I click "add", then I have another Audience for a total of 2 Audiences (2 groups of fields). However, if I click on "remove", then that Audience will be removed from the form, and I'll be left with 1 Audience (1 group of fields) again.
This Audience form is nested. I used the nested form gem for this: https://github.com/ryanb/nested_form/
My problem is that no matter what I try, this Audience portion of the form never seems to work correctly. Right now, when the Audience form page first loads, the "remove" link doesn't appear at all, and every time I click the "add" link, 2 groups of fields are added instead of just 1. When I go to another page, and then come back to the Audience form again, then the "remove" link reappears, but the "add" link still does the same thing. Every time I go back to the page, more fields are added without me even clicking on the "add" link. In addition, I set a limit to the number of fields, but that doesn't work either.
I've spent the better part of a week on this problem, and I still can't figure it out. My Jquery skills are not wonderful, but I can do the basics. I've repeatedly asked for suggestions, but they never work. I'm desperate at this point...I already started banging my head against the wall a few days ago.
I have a good demonstration of what I want here, just replace "beets" with a group of fields: http://jsfiddle.net/beehive/8zJr6/
Any suggestions for a solution to this would be greatly appreciated. Maybe I should just go with a different approach entirely?
application.js
$(document).ready(function() {

    // Nested Audience form
    var x = $('#audiencefields');
    var i = $('#audiencefields p').size() + 1;

    $('#addlink').live('click', function() {
        if ($(".item", x).length < 3) {
            $('
beets '+ i +'#removelink').appendTo(i);
            i++;
        }
        return false;
    });

    $('#removelink').live('click', function() {
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });

});

_audience_step.html.erb

select your audience

            <%= f.fields_for :audiences do |audience_form| %>

                    <%= audience_form.label :number_of_people, "Size" %>

                    <%= audience_form.collection_select :number_of_people, Audience::PEOPLE, :to_s, :to_s, :include_blank => true %>

                    <%= audience_form.label :gender %>

                    <%= audience_form.collection_select :gender, Audience::GENDERS, :to_s, :to_s, :include_blank => true %>

                    <%= audience_form.label :age %>

                    <%= audience_form.collection_select :age, Audience::AGES, :to_s, :to_s, :include_blank => true %>

                    <%= audience_form.label :ethnicity %>

                    <%= audience_form.collection_select :ethnicity, Audience::ETHNICITIES, :to_s, :to_s, :include_blank => true %>

                <%= audience_form.link_to_remove "Remove this audience", :id => "removelink" %>
           <% end %>

<%= f.link_to_add "Add another audience", :audiences, :id => "addlink" %>

audience.rb
class Audience < ActiveRecord::Base
  attr_accessible :age, :ethnicity, :gender, :number_of_people

  belongs_to :upload

  #validates_presence_of :age, :ethnicity, :gender, :number_of_people

  PEOPLE = ['5', '10', '25', '50', '75', '100']
  GENDERS = ['Male', 'Female']
  ETHNICITIES = ['Caucasian/White', 'African-American/Black', 'Latin/Hispanic', 'Asian', 'Indian', 'Middle-Eastern', 'Native American']
  AGES = ['0-2', '3-5', '6-12', '13-17', '18-29', '30-39', '40-49', '50-59', '60+']
end


text:
Q: R Webscraping RCurl and httr Content I'm learning a bit about webscraping and I'm having a little doubt regarding 2 packages (httr and RCurl), I'm trying to get a code from a magazine (ISSN) on the researchgate website and I came across a situation. When extracting the content from the site by httr and RCurl, I get the ISSN in the RCurl package and in httr my function is returning NULL, could anyone tell me why this? in my opinion it was for both functions to be working. Follow the code below.
library(rvest)
library(httr)
library(RCurl)

url <- "https://www.researchgate.net/journal/0730-0301_Acm_Transactions_On_Graphics"

########
# httr #
########

conexao <- GET(url)
conexao_status <- http_status(conexao)
conexao_status

content(conexao, as = "text", encoding = "utf-8") %>% read_html() -> webpage1

ISSN <- webpage1 %>%
  html_nodes(xpath = '//*/div/div[2]/div[1]/div[1]/table[2]/tbody/tr[7]/td') %>%
  html_text %>%
  str_to_title() %>%
  str_split(" ") %>%
  unlist
ISSN

########
# RCurl #
########

options(RCurlOptions = list(verbose = FALSE,
                            capath = system.file("CurlSSL", "cacert.pem", package = "RCurl"),
                            ssl.verifypeer = FALSE))

webpage <- getURLContent(url) %>% read_html()

ISSN <- webpage %>%
  html_nodes(xpath = '//*/div/div[2]/div[1]/div[1]/table[2]/tbody/tr[7]/td') %>%
  html_text %>%
  str_to_title() %>%
  str_split(" ") %>%
  unlist
ISSN

sessionInfo() R version 3.5.0 (2018-04-23) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows >= 8 x64 (build
    9200)

Matrix products: default
locale: [1] LC_COLLATE=Portuguese_Brazil.1252
  LC_CTYPE=Portuguese_Brazil.1252    LC_MONETARY=Portuguese_Brazil.1252
  [4] LC_NUMERIC=C                       LC_TIME=Portuguese_Brazil.1252
attached base packages: [1] stats     graphics  grDevices utils
  datasets  methods   base
other attached packages:  [1] testit_0.7      dplyr_0.7.4
  progress_1.1.2  readxl_1.1.0    stringr_1.3.0   RCurl_1.95-4.10
  bitops_1.0-6     [8] httr_1.3.1      rvest_0.3.2     xml2_1.2.0
  jsonlite_1.5
loaded via a namespace (and not attached):  [1] Rcpp_0.12.16
  bindr_0.1.1       magrittr_1.5      R6_2.2.2          rlang_0.2.0
  tools_3.5.0        [7] yaml_2.1.19       assertthat_0.2.0
  tibble_1.4.2      bindrcpp_0.2.2    curl_3.2          glue_1.2.0
  [13] stringi_1.1.7     pillar_1.2.2      compiler_3.5.0
  cellranger_1.1.0  prettyunits_1.0.2 pkgconfig_2.0.1

A: Because the content type is JSON and not HTML, you can't use read_html() on it:
> conexao
Response [https://www.researchgate.net/journal/0730-0301_Acm_Transactions_On_Graphics]
Date: 2018-06-02 03:15
Status: 200
Content-Type: application/json; charset=utf-8
Size: 328 kB

Use fromJSON() instead to extract issn:
library(jsonlite)
result <- fromJSON(content(conexao, as = "text", encoding = "utf-8") )
result$result$data$journalFullInfo$data$issn

result:
> result$result$data$journalFullInfo$data$issn
[1] "0730-0301"


text:
Q: React D3 x-axis text tilt - how to access transform property? tickFormat? I am using the Bar Chart in React-D3 :
My x-axis labels are slamming into each other, and I want to rotate them for readability,
an issue solved here for D3 without React rendering:
http://www.d3noob.org/2013/01/how-to-rotate-text-labels-for-x-axis-of.html
How do I fit this solution into the React-D3 package?
Where can I access the 'transform' property on 'text' or 'tick'?
I tried to pass in a prop as 'xAxisTransform' on BarChart.js, but it wasn't registering.
Should I use the tickFormat function to change the text on the ticks, if so, how?
Can/should ticks be manipulated from /common/axes/AxisTicks.js ?
https://github.com/esbullington/react-d3/issues/162

A: In node_modules/react-D3/common/axes/AxisTicks.js
there's a switch statement (depending on where axis ticks are located on graph) where
transform = rotate(-65)
can be added.
Make sure to declare transform as a variable:
render:function() {
    var props = this.props;

    var tr,
        ticks,
        scale,
        adjustedScale,
        textAnchor,
        transform,
        tickFormat,
        y0, y1, y2, dy, x0, x1, x2, dx;

and at bottom where the element is created by React and returned add it to the style object:
React.createElement("text", {
      strokeWidth: "0.01",
      dy: dy, x: x1, y: y1,
      style: {stroke:props.tickTextStroke, fill:props.tickTextStroke},
          textAnchor: textAnchor,
          transform: transform
      }

This solves the immediate problem, however, hacks the shared/common attributes for all D3 chart axis ticks.
If there is a better way, please post!


text:
Q: Auto-login on a Remote Desktop session after reboot We have an application which performs some logging and reporting, and it has to stay running continually in order to function (the developers haven't heard of Windows services, evidently). Normally we just leave them running in a disconnected Remote Desktop session so that we can connect remotely to check stats, reports, etc. It works well enough.
When the server reboots, however, these applications aren't automatically started. This can be a problem, since the data that's being logged is highly temporal in nature, and comes from a different server. Is there some way to have this logging server automatically log in to a disconnected RDP session at startup? I've done automatic console logins before, but never RDP. If that's possible, then I can just put the necessary programs into Startup.
Edited to add:
One of the various application-to-service conversion wrappers might work, but we specifically want to keep the interface available for whenever somebody connects to work with the program. It's just that it also has to stay open even when nobody is actively using it, and when the server reboots, such as to apply OS updates, the program isn't restarted automatically.

A: Google for something like "run program as service windows 2008" and you'll find a number of programs that will run an executable as a service. It may be clunky and you'll have to test it to see if it's compatible with your application, though, since the your program was designed to run like that. No telling how it'll react to not having a console to display to...but if it will run as a service it's probably better than leaving an RDP session running.
Really you're kind of trying to crowbar something to fit into a function it wasn't designed for; Windows wasn't meant to run RDP sessions just to run a particular application when starting the session, and to my knowledge there isn't a way to get it to do so.
Another alternative would be to have a monitoring program running on another system that could "ping" the server for the existence of a particular service, or have a batch/script file run at bootup time that would send an alert that the server restarted so someone can log in and start up the RDP session. If you have system monitoring services in place that can detect uptime or the existence of a particular process on the server that may be your best workaround.

A: You could try creating an automated task with Task Scheduler.  Under the Trigger tab, you could choose "At Startup".  Also, under the General tab, you can choose which user the process will run as.
Another thing you could try is under the Settings tab, you have the option if restarting the task if it fails.

A: One of the elements of our phone system has a very similar issue.
Assuming 2008 is like 2003 You can do an automatic console login to start your applications and connect to that existing session via RDP remotely once it is running. Not ideal but functional.
@Bart's solution is really the best route to go if you can make it happen. The phone system issue I mentioned had some weird GUI hook issues that stopped that from working in my case.

A: I would try FireDaemon!  http://www.firedaemon.com/

A: We do this on a clients server running win 2008r2 and have no problems. Its virtualized so getting to the console it pretty easy. The app has to run interactively and doesn't work as a service at all... for one thing it doesn't respond to normal windows shutdown instructions and will block a system shutdown until you intervene manually.
MS have a tool called autologon.exe available from www.sysinternals.com
It works fine. After you autologon you just have a normal entry in the startup folder.
I have to agree with the above comment that this is not a great idea - but when you are faced with an app which has to be open to work then you don't have much alternative. Best you can do is complain about it to the developers.

A: Have a look at Autologon from Sysinternals:
http://technet.microsoft.com/en-us/sysinternals/bb963905


text:
Q: Why this happens all the time? Solr OutOfMemoryError GC overhead limit exceeded I am doing a load test for my Solr application. The index has more than 200 million documents. I use the default Jetty server and set up the maximal JVM memory as 4GB. To test my app, I make up 5000 text queries and issue them to Solr one by one. However, after about 110 queries, the Jetty container throws an exception.
Why does this happen? How can I solve it?
SEVERE: java.lang.OutOfMemoryError: GC overhead limit exceeded
    at org.apache.lucene.util.AttributeImpl.clone(AttributeImpl.java:196)
    at org.apache.lucene.util.AttributeSource$State.clone(AttributeSource.java:116)
    at org.apache.lucene.util.AttributeSource$State.clone(AttributeSource.java:119)
    at org.apache.lucene.util.AttributeSource.captureState(AttributeSource.java:349)
    at org.apache.solr.highlight.TokenOrderingFilter.incrementToken(DefaultSolrHighlighter.java:595)
    at org.apache.lucene.search.highlight.OffsetLimitTokenFilter.incrementToken(OffsetLimitTokenFilter.java:43)
    at org.apache.lucene.analysis.CachingTokenFilter.fillCache(CachingTokenFilter.java:78)
    at org.apache.lucene.analysis.CachingTokenFilter.incrementToken(CachingTokenFilter.java:50)
    at org.apache.lucene.search.highlight.Highlighter.getBestTextFragments(Highlighter.java:225)
    at org.apache.solr.highlight.DefaultSolrHighlighter.doHighlightingByHighlighter(DefaultSolrHighlighter.java:468)
    at org.apache.solr.highlight.DefaultSolrHighlighter.doHighlighting(DefaultSolrHighlighter.java:379)
    at org.apache.solr.handler.component.HighlightComponent.process(HighlightComponent.java:116)
    at org.apache.solr.handler.component.SearchHandler.handleRequestBody(SearchHandler.java:194)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129)
    at org.apache.solr.core.SolrCore.execute(SolrCore.java:1368)
    at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:356)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:252)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
    at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
    at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)

A: Obviously 4Gb RAM is very low to handle load test on 200M index. We made performance testing for Solr 4.2 on 300M documents with average document size of 1K. The goal was  to figure out minimal machine configuration on which we can have stable response time < 3 sec for non-faceted queries. For 100 concurrent queries our result showed minimal machine configuration was 8 CPU cores / 15Gb RAM. Of course results will vary depending on many factors, however you can use this as rule of thumb for your machine sizing.


text:
Q: I need to show Div result of HTML/Js page in bar chart? I need to show the result of below mention code in bar chart.Is it possible to show the result of below code for survey to show in bar chart ?So i put the code here as suggested by few mate.You can see in code i am printing survey result but what i wanted to show the spider chart also but i am not know how to proceed.
You can check code in this question
Js file :-
function displayRadioValue() {

let section1 = document.querySelectorAll('.section-1 > input[type="radio"]')
let section2 = document.querySelectorAll('.section-2 > input[type="radio"]')
let section1Total = 0
let section2Total = 0
let section1Question = 0
let section2Question = 0
let finalResults = document.querySelector('.final-results')
let result1 = ''
let result2 = ''
finalResults.innerHTML = ''

//Section 1
section1.forEach(function(radio, index) {
if (radio.checked) {
  section2Question++
  section1Total += +radio.value
 }
})

//Section 2
section2.forEach(function(radio, index) {
if (radio.checked) {
  section1Question++
  section2Total += +radio.value
}
})

//Final Results and validation
if (section1Total > 0 && section2Total > 0) {
finalResults.innerHTML += genTable(section1Question, section1Total, 1)
finalResults.innerHTML += genTable(section2Question, section2Total, 2)
} else {
finalResults.innerHTML = 'Snap! Please select the atleast one survey   question from each section '}
document.getElementById("control").style.display = "block";
document.getElementById("toemail").href +=   document.getElementById("final-results").innerText;

}

Html file :-

Select a radio button and click on Submit.

Section 1

question 1:
<input type="radio" name="question1" value="1">1
<input type="radio" name="question1" value="2">2
<input type="radio" name="question1" value="3">3

 question 2:
<input type="radio" name="question2" value="1">1
<input type="radio" name="question2" value="2">2
<input type="radio" name="question2" value="3">3

 question 3:
<input type="radio" name="question3" value="1">1
<input type="radio" name="question3" value="2">2
<input type="radio" name="question3" value="3">3

Section 2

question 1:
<input type="radio" name="question4" value="1">1
<input type="radio" name="question4" value="2">2
<input type="radio" name="question4" value="3">3

 question 2:
<input type="radio" name="question5" value="1">1
<input type="radio" name="question5" value="2">2
<input type="radio" name="question5" value="3">3

 question 3:
<input type="radio" name="question6" value="1">1
<input type="radio" name="question6" value="2">2
<input type="radio" name="question6" value="3">3

 question 4:
<input type="radio" name="question7" value="1">1
<input type="radio" name="question7" value="2">2
<input type="radio" name="question7" value="3">3

<button type="button" onclick="displayRadioValue()">
  Submit
 </button>

Send to
  email&nbsp<button onclick="window.print();">Send to PDF</button>.

css file :-
@media print {
body * {
visibility: hidden;
 }
.final-results * {
visibility: visible;
 }
 .final-results {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
 }
}

table,
 table tr th,
table tr td {
 border: 1px solid black;
 }

A: Here is working simple bar chart for you. You can use chartJS library to achieve the results you are after.
First, we need to define the chart options and in those options you can load your data dynamically which come from the results.
I have made two sections which show Total Scored and Percentage of each section as well. The Bar Chart will appear just below the final-results table
The chart data will change accordingly to the results and question scores when you click on Show Results button. The chart also appears in your PDF as well.
Live Demo:

function displayRadioValue() {
  let section1 = document.querySelectorAll('.section-1 > input[type="radio"]')
  let section2 = document.querySelectorAll('.section-2 > input[type="radio"]')
  let fullName = document.querySelector('#fullName').value
  let email = document.querySelector('#email').value
  let age = document.querySelector('#age').value
  var ctx = document.querySelector('#resultsChart').getContext('2d');
  let section1Total = 0
  let section2Total = 0
  let section1Question = 0
  let section2Question = 0
  let finalResults = document.querySelector('.final-results')
  let result1 = ''
  let result2 = ''
  finalResults.innerHTML = ''

  //Section 1
  section1.forEach(function(radio, index) {
    if (radio.checked) {
      section2Question++
      section1Total += +radio.value
    }
  })

  //Section 2
  section2.forEach(function(radio, index) {
    if (radio.checked) {
      section1Question++
      section2Total += +radio.value
    }
  })

  var options = {
    type: 'bar',
    data: {
      labels: ["Section 1", "Section 2"],
      datasets: [{
          label: 'Total Scored',
          data: [section1Question, section2Question, 30],
          backgroundColor: '#E91E63',
          borderWidth: 1
        },
        {
          label: 'Percentage %',
          data: [((section1Total / (section1Question * 3)) * 100).toFixed(2), ((section2Total / (section2Question * 3)) * 100).toFixed(2), 30],
          backgroundColor: '#004D40',
          borderWidth: 1
        }
      ]
    },
    options: {
      scales: {
        responsive: true,
        yAxes: [{
          ticks: {
            reverse: false
          }
        }]
      }
    }
  }

  //Final Results and validation
  if (fullName.value != '' && email.value != '' && age.value != '') {
    if (section1Total > 0 && section2Total > 0) {
      finalResults.innerHTML += genDetails(fullName, email, age)
      finalResults.innerHTML += "
Results
"
      finalResults.innerHTML += genTable(section1Question, section1Total, 1)
      finalResults.innerHTML += genTable(section2Question, section2Total, 2)
      finalResults.innerHTML += "
Chart Results
"
      document.getElementById("control").style.display = "block";
      document.getElementById("resultsChart").style.display = "block";
      document.getElementById("toemail").href += document.querySelector(".final-results").innerText;
      new Chart(ctx, options); //show chart
    } else {
      finalResults.innerHTML = 'Snap! Please select the atleast one survey question from each section '
    }
  } else {
    finalResults.innerHTML = 'Snap! Please enter your name, emial, age in the first section '
  }
}

function genDetails(name, email, age) {
  var result = "
Personal Info
"
  result += "Full name: " + name + "
"
  result += "Email name: " + email + "
"
  result += "Age:  " + age + "
"
  return result
}

function genTable(ques, total, section) {
  var result = "Section " + section + ":
"
  var tr = "
" + total + "	" + ((total / (ques * 3)) * 100).toFixed(2) + "
"
  result += "

Total Score	Percentage

" + tr + "

"
  return result
}
canvas {
  display: none
}

@media print {
  body * {
    visibility: hidden;
  }
  canvas {
    visibility: visible;
    margin-top: 30%;
  }
  .form-control {
    visibility: visible;
  }
  .final-results * {
    visibility: visible;
  }
  .final-results,
  .form-control {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
}

table,
table tr th,
table tr td {
  border: 1px solid black;
}
<!DOCTYPE html>

  <title>Survey Question</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

Survey

Personal Info

Section 1

Section 2

Results

              Full Name address
              <input type="email" class="form-control" id="fullName" aria-describedby="nameHelp" placeholder="Enter full name">
              Please enter your full name.

              Email address
              <input type="email" class="form-control" id="email" aria-describedby="email" placeholder="Enter email">
              Please enter your valid email address.

              Password
              <input type="number" class="form-control" id="age" aria-describedby="age" placeholder="Age">
              Please enter your age in number.

              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 1:</legend>

                      <input class="form-check-input" type="radio" name="question1" id="gridRadios1" value="1">

                              1

                      <input class="form-check-input " type="radio" name="question1" id="gridRadios2" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question1" id="gridRadios3" value="3">

                              3

              </fieldset>
              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 2:</legend>

                      <input class="form-check-input" type="radio" name="question2" id="gridRadios4" value="1">

                              1

                      <input class="form-check-input" type="radio" name="question2" id="gridRadios5" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question2" id="gridRadios6" value="3">

                              3

              </fieldset>
              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 3:</legend>

                      <input class="form-check-input" type="radio" name="question3" id="gridRadios7" value="1">

                              1

                      <input class="form-check-input" type="radio" name="question3" id="gridRadios8" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question3" id="gridRadios9" value="3">

                              3

              </fieldset>

              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 4:</legend>

                      <input class="form-check-input" type="radio" name="question4" id="gridRadios10" value="1">

                              1

                      <input class="form-check-input" type="radio" name="question4" id="gridRadios11" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question4" id="gridRadios12" value="3">

                              3

              </fieldset>
              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 5:</legend>

                      <input class="form-check-input" type="radio" name="question5" id="gridRadios13" value="1">

                              1

                      <input class="form-check-input" type="radio" name="question5" id="gridRadios14" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question5" id="gridRadios15" value="3">

                              3

              </fieldset>
              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 4:</legend>

                      <input class="form-check-input" type="radio" name="question6" id="gridRadios16" value="1">

                              1

                      <input class="form-check-input" type="radio" name="question6" id="gridRadios17" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question6" id="gridRadios18" value="3">

                              3

              </fieldset>
              <fieldset class="form-group">

                  <legend class="col-form-label col-sm-2 pt-0">Question 4:</legend>

                      <input class="form-check-input" type="radio" name="question7" id="gridRadios19" value="1">

                              1

                      <input class="form-check-input" type="radio" name="question7" id="gridRadios20" value="2">

                              2

                      <input class="form-check-input" type="radio" name="question7" id="gridRadios21" value="3">

                              3

              </fieldset>

            <canvas id="resultsChart"></canvas>

            <button type="button" class="btn btn-success" onclick="displayRadioValue()">
                        Show Results
                    </button>

              Send to
                        email <button onclick="window.print();" class="btn btn-warning">Send to PDF</button>


text:
Q: Не работает react production build Делаю проект с фронтом на React и бэком на Express (связывалось при помощи добавления "proxy" в package.json клиента). В dev-режиме все работает как надо. Решил попробовать захостить проект. Для этого выполнил "npm run build", а в server.js дописал:
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '/client/build/index.html'))
});

(Вот структура проекта)

Но работает не так как должно.
Пример как было при разработке(так должно работать):

вот что получается на деле:

то бишь не работают либо какие-то скрипты. И вот такие ошибки выдает консоль:

Первый раз делаю production build, поэтому даже не понимаю в чем ошибка и вообще правильно ли я делаю. Очень надеюсь на вашу помощь!


text:
Q: PowerShell remote execution between two Linux servers I have the PowerShell scripts (.ps1) on my Centos server. I can successfully execute them locally, but don't know how I can execute these scripts remotely from another Centos server.
I've tried to execute scripts after connecting over SSH and I'm getting errors
-command not found and -syntax error.
How to run PowerShell scripts on Linux remotely from another Linux box?

A: Here is the solution that I'm using:

*

*ssh to the server: ssh user@server_name

*navigate to the scripts directory

*run pwsh script_name.ps1
I don't need to connect with PowerShell session and didn't do any configuration on PowerShell server. Hope it helps.

A: You can simply ssh to the PowerShell server and run your .ps1 scripts from the console like this: pwsh your_script.ps1


text:
Q: Anyone Know How to Calculate the Area/Perimeter/Height of a Triangle? I'm a newbie to Python and I came across this question somewhere:
"Produce a programme that can calculate the perimeter of the triangle, the area of the triangle and the height of the triangle from the length of the three sides of a triangle. If the three lengths of the sides of the triangle do not define a valid triangle, a message should be displayed stating that this is not a valid calculation and the process should be terminated."
Anyone know how this could be solved? It's probably easy, but I'm a newbie so yeah
This is what I've got so far:
a = float(input('Please Enter the First side of a Triangle: '))

b = float(input('Please Enter the Second side of a Triangle: '))

c = float(input('Please Enter the Third side of a Triangle: '))

if  a + b >= c and b + c >= a and c + a >= b:

# calculate area and height here

Perimeter = a + b + c

s = (a + b + c) / 2

Area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print("\n The Perimeter of Triangle = %.2f" %Perimeter);

print(" The Area of a Traiangle is %0.2f" %Area)
else:
print('Not a valid triangle')

I still have to calculate the height. Everything else seems to be working now :D

A:
In mathematics, the triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side.

a, b, c = 1, 1, 1 # sides of a triangle
if a + b >= c and b + c >= a and c + a >= b:
    # calculate area and height here
else:
    print('Not a valid triangle')


text:
Q: building boost with visual studio 2012, what to provide as toolset?
*

*When building boost using Visual studio 2012 what should I provide as toolset?

*

*msvc-10.0

*msvc-11.0 (does it exist?)

*msvc (autodetect?)

*What would be recommended string to build boost x64 with Visual studio 2012?

A: I have been involved in programming a graphical tool that builds boost for you: http://vertexwahn.de/bluego.html

A: You can just use bootstrap; b2 which will automatically choose for you. Refer to boost installation guide.
Building boost on Windows

A: asking my question myself. providing msvc works fine.


text:
Q: Contain image inside div jquery I have a small problem with containing an image in a container. When the image is dragged beyond the container the image hides what I want is for the image to not hide beyond the container I want the image to stop at the container how can I make that possible here is a script.

$('img').on('click', function() {
    $('#fotos').append('

');
    $('.imgdrag').draggable();
    $('#fotos').droppable();
    $('.modal-content').resizable();

    $(".download").attr("href", $(this).attr('src'));
    $(".download").show();
  });

});
.container5 {
  background-color: transparent;
  width: 220px;
  height: 320px;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  border: 1px solid red;
  position: absolute;
  overflow: hidden;
}

$(".bananas").appendTo( $( ".container5" ) );

A: Check out the containment option of the draggable jQuery UI widget.
Here, I baked a fiddle just for you.
JS
$(function(){
    $('img').draggable({
    containment: '.container'
  });
});


text:
Q: Microsoft Bot Framework 500 Internal server Error when System.Data Namespace Used I'm trying to use  System.Data.DataTable to Parse the Excel Document attached during conversation and copy it to DataTable for further processing using the BotFramefork Dialogs .
There is an "500 InternalServerError" When "System.Data" Namespace used and failing to send message.
I've tried on below sample from Github to run it local with Emulator
https://github.com/jamesemann/intro-to-botframework5-dialogsrefactored
For the same sample if "System.Data.DataTable" is included ,There is an 500 Internal Server Error in Emulator.
[Serializable]
public class AdditionDialog : IDialog<object>
{
    protected int number1 { get; set; }

   /* Error When Included Below line*/
System.Data.DataTable dt = new System.Data.DataTable();

    public async Task StartAsync(IDialogContext context)
    {

        await context.PostAsync("Provide number one:");

        context.Wait(MessageReceivedAddNumber1);
    }

    public async Task MessageReceivedAddNumber1(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var numbers = await argument;
        // number one is persisted between messages automatically by bot framework dialog
        this.number1 = int.Parse(numbers.Text);
        await context.PostAsync("Provide number two:");

        context.Wait(MessageReceivedAddNumber2);
    }

    public async Task MessageReceivedAddNumber2(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var numbers = await argument;
        var number2 = int.Parse(numbers.Text);
        await context.PostAsync($"{this.number1} + {number2} is = {this.number1 + number2}");

        context.Done<object>(new object());
    }

Can anyone suggest if i'm missing anything here.

A: The problem is that DataTable is not serializable and thus you cannot hold a reference in the dialog for something that cannot be serialized, because in every interaction the dialog state is being serialized.
If you add the [NonSerialized] attribute you will see that the dialog execute just fine, however that will have other implications.
[NonSerialized]
System.Data.DataTable dt = new System.Data.DataTable();

Not sure why you are trying to use DataTable in a dialog, but my recommendation would be to encapsulate that into a service you can own and make sure that service is serializable a that you don't hold references to things cannot be serialized.
Check this for more info about dealing with non-serializable services.


text:
Q: How to prevent CSS Flex / Grid layouts to be reversed on dir="RTL" I have a simple div (grid layout but the same would apply to flexbox), which shows three different text elements.
The problem is that whenever my html's dir attribute is set to rtl, the order of the grid items changes, and I'd like to be able to prevent that change in that specific case (where content order is not based on writing direction, but for semantic value.
For example's sake, here's what my items look like:

let direction = 'rtl';
document.getElementById('toggle-direction').addEventListener('click', () => {
  direction = direction === 'rtl' ? 'ltr' : 'rtl';

  document.documentElement.setAttribute('dir', direction);
});
.container {
  display: grid;
  grid-template-rows: 1fr;
  grid-template-columns: repeat(3, 1fr);
  border-radius: 5px;
  padding: 10px;
}

.left-arrow {
  grid-column: 1 / 2;
  grid-row: 1 / 2;

  margin-inline-end: auto;
}

.center-content {
  grid-row: 1 / 2;
  grid-column: 2 / 3;
  text-align: center;
}

.right-arrow {
  grid-row: 1 / 2;
  grid-column: 3 / 4;

  margin-inline-start: auto;

}

#toggle-direction {
  grid-row: 2 / 3;
  grid-column: 1 / 4;
}

  <
  Center content
  >
  <button id="toggle-direction">Toggle direction</button>

PS: I could add direction: ltr; to the .container selector, but that would create an undesired styling, since I want to use inline-oriented styling.

A: Is my understanding you only want the arrows to keep their orientation.
So you should isolate and wrap the elements you want the direction to consistent in containers with consistent flow direction (and put everything you want to update outside that containers) like so :

let direction = 'rtl';
document.getElementById('toggle-direction').addEventListener('click', () => {
  direction = direction === 'rtl' ? 'ltr' : 'rtl';

  document.documentElement.setAttribute('dir', direction);
});
.container {
  display: grid;
  grid-template-rows: 1fr;
  grid-template-columns: repeat(3, 1fr);
}

.ltr {
  direction: ltr;
 }

.left-arrow {
  grid-column: 1 / 2;
  text-align: center;
}

.center-content {
  grid-column: 2 / 3;
  text-align: center;
}

.right-arrow {
  grid-column: 3 / 4;
  text-align: center;
}

#toggle-direction {
  grid-column: 1 / 4;
}

Left arrow

Center content

Right arrow

  <button id="toggle-direction">Toggle direction</button>

Edits done: wrapped the first row you had inside the container in another container (class="colum rtl") that always has a direction.
Small css updates to keep the view.
Alternatively you could place the arrows container inside the container with the button. But in order to have consistent rtl direction you will need to wrap them there in a container (with class="rtl") and you need a little more updates to your css to keep the aspect.
Alternatively if there is really no way for you to isolate all the components you need to have consistent direction you could for some specific cases create a class class="inherit-direction" (for example) and in your js, when you change the direction of the document, change the containers direction with that class as well (document.getElementsByClassName("inherit-direction") and iterate trough them).
But I would strongly advise to use this last option only as last measure and limit the number of uses as much as possible.


text:
Q: Upon double clicking a cell, copy cell value to another cell on that same row This VBA code does what I need but only on one row:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("C1:H1")) Is Nothing Then
    Cancel = True

    If Application.CountIf(Sheets("Sheet2").Range("B:B"), Target.Value) = 0 Then
        Range("B1").Value = Target.Value
    End If
End If
End Sub

I have on my Excel worksheet:
A    B   C    D    E   F   G   H
MAN     NN   NNP  JJ  POS
CAN     MOD  NN   VV   JJ  RB  NON
...     ...

up to 300,000 data.
I want when I double click any cell in C:H range, its value will be copied to B. The above code handles one row only. If I change C1:H1 to C2:H2 and B1 to B2, it will handle the second row.
How do I make it work for all rows?

A: I think the following change will work (not tested, on iPhone):
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    If Not Intersect(Target, Range("C:H")) Is Nothing Then
        Cancel = True

        If Application.CountIf(Sheets("Sheet2").Range("B:B"), Target.Value) = 0 Then
            Cells(Target.Row, 2).Value = Target.Value
        End If
    End If

End Sub


text:
Q: AJAX response match any status I have the following code:
    $.ajax(
        {
            url:        "control/" + id + ".php",
            data:       $("auth-form").serialize(),
            statusCode:
            {
                200: function( response )
                {

                },
                401: function( response )
                {

                },

                401: function( response )
                {

                },
            }
        }
    );

I need to set callback to 'any' status, whether it's 200 or 404 I need it to trigger the same callback function, something like this:
            $.ajax(
        {
            url:        "control/" + id + ".php",
            data:       $("auth-form").serialize(),
            response = function( r )
            {
                alert('got ' + r.status);
            }
        }
    );

Closest solution I found was using success/fail, but I need to combine them somehow. Any suggestions? Thanks!

A: Try with complete:
    $.ajax({
        url: "control/" + id + ".php",
        data: $("auth-form").serialize(),
        complete: function( r ) {
            alert('got ' + r.status);
        }
    }
);


text:
Q: Computing Paired Samples (pre/post) Effect Size with Limited Information I'm conducting a meta-analysis using the Hedge's g effect size statistic. Many of the studies are only reporting:

*

*pre-treatment mean score

*pre-treatment standard deviation

*post-treatment mean score

*post-treatment standard deviation

*sample size

With this information, is it possible to derive either:

*

*standard deviation of the difference (gain scores), or

*the paired group t-value

If not, is there any other way to compute the paired samples effect size/standard error with the aforementioned limited information?

A: Unfortunately, if that really is all the information you have, then there is no way to get either #1 or #2 -- one way or another you need to know (or be able to deduce) the correlation between pre-test and post-test scores.

A: Yes, as others have mentioned, you will need to know the correlation between pre- and post-test scores to calculate an effect size.
However, this correlation value can be imputed to obtain reasonable results, especially if you can draw upon previous research and/or have a strong theoretical rationale for the particular value. After an initial effect size estimate is calculated from the imputed correlation, sensitivity analyses (within a reasonable range of imputed values) should be conducted . If they result in similar final aggregate/omnibus estimates you can (usually) have greater confidence in those initial estimates.

A: I am also working with a similar meta-analysis.
SDd can be imputed by several methods.
1. Taking it from other studies. Use maximum of observed from other studies.
2. If any of other studies have reported r, use it. Base it on maximum of observed r values.
3. If any of other studies in your meta-analysis is has mentioned, SE or 95% CI or P-value all these could be used to derive your SD for mean change.
Here is a good paper that addresses all these with formulas.
Fu R, Vandermeer BW, Shamliyan TA, O'Neil ME, Yazdi F, Fox SH,
Morton SC. Handling Continuous Outcomes in Quantitative Synthesis. Methods Guide for Comparative Effectiveness Reviews.


text:
Q: Android app rejected due to background Location I  have submit my android app 2 time in play store.But app is rejected with Reason of your app use BACKGROUND_LOCATION.After first rejection i removed the BACKGROUND_LOCATION permission from Android-manifest file.Again i submitted the app in play store than again rejected with same reason and Not meet with privacy policy.
App used  these permission
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I removed this permission

So this is Again and again happening please suggest me what i can do.
Thanks & Regards
Umesh sharma

A: *

*if you are uploading it to some other channel at Google Play Console (e.g. alpha, beta, test), You need to upload the build to production channel and wait for google to review your build, also see Pre-Launch Report Overview section for errors if their remains some (possibly).

*And to resolve Background location permission issue you need to do the following steps as suggested by Android Developer Officials:

*

*If you find that your app accesses location in the background, consider taking the following actions:

*

*Evaluate whether background location access is critical to the core functionality of the app.
If you don't need location access in the background, remove it.

*If your app targets Android 10 (API level 29) or higher, remove the ACCESS_BACKGROUND_LOCATION permission from your app's manifest. When you remove this permission, all-the-time access to location isn't an option for the app on devices that run Android 10.

*Make sure the user is aware that your app is accessing location in the background. This is especially important for cases that aren't obvious to users.

*If possible, refactor your location access logic so that you request location only when your app's activity is visible to users.

Reference


text:
Q: Create virtual directory in IIS 6 and IIS 7/7.5 using C# I have installer that will create virtual directory.
It works fine on IIS 6.
But if I try on IIS 7.5 it crashes.
Then i tried using Microsoft.Web.Administration class
But now it will work only on IIS 7 and IIS 7.5
Can anyone help me out so that my code works for both IIS 6 and IIS 7.5?

A: If you want to use the same code to create websites on both IIS6 and IIS7 (which I suspect is using the System.DirectoryServices namespace) then you need to install the IIS6 Management Compatibility features. You can do this by adding this as a Role Service to the Web Server role in Server Manager (under Administrative Tools).
Alternatively you can use the command line on Windows 2008 and Windows 2008R2 (run as Administrator):
Windows 2008/2008R2 -
servermanagercmd -i Web-Mgt-Compat -a
Windows 2008R2 -
ServerManagerCmd.exe is deprecated and you are advised to use the ServerManager PowerShell module:

import-module ServerManager
add-windowsfeature Web-Mgt-Compat -includeallsubfeature

A: Finally I have created 2 separate classes for managing IIS6 and IIS7.5.
And its working fine.


text:
Q: Understanding Jquery-Cropper units I'm making a project using jquery-cropper (https://fengyuanchen.github.io/jquery-cropper/).
I need to get the coordinates of the crop rectangle. The method getCropBoxData() return those coordinates, but I can't get what units it's using, and the documentation doesn't mention them.
Check the picture of the demo page I'm attaching. The fields at the right show the current position of the crop in pixels, but if you press [Get Crop Box Data], you get totally different values at the bottom. Any ideas?

A: I will answer my question. For this specific issue, I found that getData method returns the crop coordinates in pixels, the same values that appear at the right in the demo page. This should be useful for anybody that need to get the crop info. About getCropBoxData, still not sure what units are those.


text:
Q: No output when running C++ applications via Eclipse CDT IDE Eclipse can build my applications for me so far, and I can execute them directly (via Windows 7 Explorer), but I get no results when I use the run command via the CDT perspective. The console tab only tells me that the application terminated, even with a console app with input (cin >> and so forth). Win32 apps don't execute either. Once again I can execute them directly via the debug folder, so this must be an IDE issue. Is this normal? Or are there settings I could change to make it work?
Thanks for any advice!

A: Solved it! It's because my workspace was in the "Program Files" directory, which has a space in it. Probably a MinGW issue.
Thanks to Keith Thompson for the help though!


text:
Q: Not getting proper status from CrossGeofences.Current.RegionStatusChanged in Xamarin forms I am using CrossGeofences Plugin For Xamarin forms
Here is the example:
https://github.com/aritchie/geofences/blob/master/README.md
But The Enter/Exit status is not proper
here is my code
For starting Geofence:
GeofenceRegion region = new GeofenceRegion("Vejdhaba", new Plugin.Geofencing.Position(Convert.ToDouble(Latitude), Convert.ToDouble(Longitude)),
                                Distance.FromMeters(150));
                        CrossGeofences.Current.StartMonitoring(region);

And Inside the App.xaml.cs
CrossGeofences.Current.RegionStatusChanged += (sender, args) =>
            {
                var region = args.Region;
                var status = args.Status;

                if (args.Status == GeofenceStatus.Entered)
                {
                    DependencyService.Get<IFClass>().SendNotification("Status", "Entered to geofence");
                }
                if (args.Status == GeofenceStatus.Exited)
                {
                    DependencyService.Get<IFClass>().SendNotification("Status", "geofence Exited");
                }
                if (args.Status == GeofenceStatus.Unknown)
                {
                    DependencyService.Get<IFClass>().SendNotification("Status", "geofence Unknown");
                }
            };

the status is not getting properly
how to solve this?


text:
Q: Is the highest photon energy currently possible a Planck photon or based on space-time quantinization? It makes sense that there could be an upper limit to the frequency/energy for individual photons if the universe as we know it is quantized.
But, the highest energy photons I've heard about have a frequency between $10^{20} \ \text{Hz}$ to $10^{30} \ \text{Hz}$. A Planck photon however would have around $10^{35} \ \text{Hz}$. If we assume a cosmological model wherein space-time is quantized to a fundamental metric such as
a Planck length, is there any reason to think the highest possible energy of a photon would be higher or lower than that?

A: There are two issues here. Physics does not set an upper limit to photon energy, although at high energy particle antiparticle pair creation will in practice be limiting. If the universe is finite, then it has a finite energy that obviously cannot be exceeded by a photon.

A: You seem to refer to in your question to quantum foam/quantum gas models which posit that QFT is an epiphenomenon of an underlying physics which is discrete and/or statistical-mechanical at the Planck scale, or below.
In such models the foam/gas is usually assumed to be randomly distributed (e.g. Poisson distributed), because Poisson distribution provides Lorenz invariance to a high accuracy over large scales (not necessarily absolutely, but exceeding the current bounds of our ability to measure).
In discrete fluid models (e.g. gas-like "hard sphere" models) we should expect fundamental limit to the wavelength of a photon in the same way as there is an upper frequency limit (lower wavelength limit) to sound waves in a gas. As the wavelength approaches the mean free path (in this case usually assumed to be  around the Planck scale) we would expect "something different" to happen.
What exactly will happen will depend very much on the properties of the fluid.
By way of example, consider a classical ideal gas in which the wave velocity (speed of sound/light) is $c$ and the mean free path is $\ell_P$  (the Planck length).
In monatomic gases such as helium, neon, xenon etc attenuation is insignificant at low frequencies, but rises with the square of the frequency. At some point where the wavelength approaches the mean free path length (average distance between collisions) the contribution to the kinetic energy of atoms due to the wave becomes much larger than variance in the distribution of kinetic energy due to the thermal motion of the atoms. Therefore we expect that the random thermal motion of the atoms will tend to quickly disperse the wave energy as heat.
Very roughly, if we take the "square of frequency" seriously, we might say that  a wavelength of $\lambda = \ell_P $ will attenuate in about $1 \ell_P $,  and a wavelength of $2 \ell_P $ will attenuate in about $4 \ell_P $. Again roughly, the attenuation distance will be proportional to the $\lambda^2/\ell_P$ . To put it another way, the attenuation distance is roughly proportional to $\lambda  \frac{\lambda}{\ell_P}$ (i.e. the wavelength, multiplied by the ratio of the wavelength to the mean free path length, the Planck length in this example).
Some rough examples follow:

*

*For a 1m radio wave, the vacuum attenuation distance would be proportional to $10^{35}$ metres, or a trillion times the diameter of the observable universe.

*For the CMBR, about 1mm wavelength, the vacuum attenuation distance would be proportional to $10^{-6}/10^{-35} = 10^{29}$ metres, about a million times the diameter of the observable universe.

*1000nm infra-red light (wavelength $10^{-6}$ metres) would attenuate over $10^{-12}/10^{-35} = 10^{23}$ metres, or about the diameter of the universe or so.

*A 0.1nm x-ray laser (10^-10 metres) would attenuate over $10^{-20}/10^{-35} = 10^{15}$ metres or 0.1 light year.

*A $10^{20}$Hz photon has a wavelength about $10^{-13}$ and would attenuate after about $10^9$ metres - a million kilometres, or about 3 seconds.

*A $10^{30}$Hz photon has a wavelength about $10^{-23}$ metres and would attenuate after about $10^{-12}$ metres ($10^{-21}$ seconds).

*Highest energy photon candidate observed according to https://arxiv.org/abs/0903.1127 is on the order of $10^{19}ev$, or $10^{-25}$ metres and would attenuate after $10^{-50}/10^{-35} = 10^{-15}$ metres, or about the diameter of a proton.
Very probably I have made several errors above. The general point is when the frequency is small (wavelength is large), attenuation is close to zero. As frequency rises, attenuation will at some point become observable and this will cast light on the underlying physics (if any).
TL;DR: There are many theories for what the New Physics will turn out to be. Good search terms include "Stochastic quantization", "Spin foam", "zitterbewegung".

A: Due to Lorentz invariance, the spectrum of photon energy does not cut off, but goes all the way to infinity. So, photons much higher than the Planck energy would be possible.
Update: So, the notion of quantized spacetime is of course speculative at this point. It implies that there may be different ways in which one can try to do it. However, it needs to be consistent with our current understanding, which has been tested and shown to be working. One of these requirements is Lorentz invariance. So, unless we through out Lorentz invariance, any scheme to quantize spacetime that implies a violation of Lorentz invariance would not be correct.
Considering the role of photons in mediating force among particles, one can use the tried-and-tested quantum field theory calculations. Here one finds that integrals over what effectively comes down to the photon energy need to extend to infinity. If one were to introduce a cut-off for such an integral, the cut-off scale would appear explicitly in the result. If the cut-off is the Planck scale, the contribution of the Planck scale may be so small that it would not make an observable difference in observations that we are currently able to make. However, at the same time it also shows that there is no reason to introduce such a scale in the first place to match experimental observations. By implication, the Planck scale is at present only a hypothetical scale, one that cannot at present be observed in any experiments.
As a result, it becomes rather difficult to predict what the effect of some hypothetical scheme to quantized spacetime would be at some hypothetical scale. Our current understanding does not allow arbitrary modifications to the theories, unless we suspect that something is wrong somewhere.
Not sure if this addresses your concern.


text:
Q: no funciona wifi linux mint 18.1 serena tengo un problema con el wifi. No me sale ninguna opcion para poder conectarme a una red, solamente por cable usb o el cable de red me permite tener acceso. Uso Linux Mint 18.1 Serena 64-bit
Intente varias cosas pero sin exito.
Se que el problema es por driver que no logro de instalarlo en forma correcta.
datos:

colocando el comando
"inxi -Fxzc0"   en la parte de network me sale esto

Colocando el comando "iwconfig" ; me sale

no se si es suficiente informacion con las cosas que brinde, en todo caso si hace falta mas me piden.
Saludos, espero que alguno me pueda ayudar.

A: Actualiza los repositorios de tu S.O
Utilizas:
sudo apt-get update

luego
sudo apt-get install r8168-dkms

Ese es el driver que necesitas, luego reinicias los servicios
service networking restart
service network-manager restart

Si no funciona simplemente reinicia y listo.


text:
Q: Get finger x-axis position using jquery /js I would like to get the finger position of the x-axis on ipad . I will capture 2 time, compare the difference and find out whether the user is scrolling right or left. However, my code can only capture the first x-position but not the second one, how to fix that problem? Thanks
$('#all_pages').bind('scrollstart', function(event) {
var e = event.originalEvent;
var beforeX = e.targetTouches[0].pageX;
var afterX = 0;
setTimeout(function(){afterX = e.targetTouches[0].pageX},200);
alert(beforeX + ',' + afterX);
});


text:
Q: Select a State with RxJS in Angular 6 doesn't work In a web app I'm using Angular and RxJS 6. The application has a login, the response of the login is a token so, after the login, I save the token in the sessionStorage and then I decode the token to save the current logged in user. This is the state after the login:

I'm trying to develop this behaviour: if the user go to page "..login" (so in login.components.ts) and if he is already logged in, the application will redirect to the home page.
This is my code inside ngOnInit() in login.component.ts:
  ngOnInit() {
   this.store.select('auth')
     .pipe(take(1),
       map((authState: fromAuth.State) => {
         console.log('test');
         if (authState.authenticated) {
           this.router.navigate(['/home']);
         }
      }));
}

This is the Interface of AppState:
export interface AppState {
  user: fromProfile.State,
  auth: fromAuth.State,
  core: fromCore.State
}

Testing it, I login, I go to home, then I go to login page, I put a breakpoint in the console.log() but it doesn't reach the breakpoint, it doesn't even enter it, and so it doesn't redirect to home page. Why?
* UPDATED *: this is the screen of debug

A: The select() function returns an Observable so you have to .subscribe() to it in order the pipe to be called.


text:
Q: C# factory pattern with dependency injection I have some data that I need to load asynchronously in my class. Since I cannot have an async constructor, I have tried to implement the factory pattern like this:
public class MyClass
{
  private string someData;
  private readonly IMyDependency md;

  public MyClass(IMyDependency md)
  {
    this.md = md;
  }

  public async Task<MyClass> MyClassFactory()
  {
    string data = await LoadData();
    return new MyClass(data);
  }

  private MyClass(string data) { someData = data; }

  private async Task<string> LoadData()
  {
    await md.GetSomeData();
  }
}

I understand that formally, the factory pattern assumes that my MyClassFactory() is static and that I call it explicitly to create MyClass objects.
My problems with this are the following:
Firstly, MyClass is a dependency for other modules and I am using ASP.NET Core's DI to inject it where it's necessary. This means that I never explicitly create objects of this class, the DI framework does it.
Secondly, I have this MyDependency which I need to inject into MyClass and I'm using it in the LoadData() method, which would prevent the LoadData(), and consequently the MyClassFactory() to be static.


text:
Q: Javascript: Loop Through every child node so for example i have a brunch of pages create by easytab which looks like below in HTML

//something

//something

//something

//something

And I'd like to add something in to the contents so i created a function like below
$(".identify").html("123");

I know i can do something like to add something in the last child but i'd like to add 123 in every child how may i do it?
$(".identify:last-child").html("123");

A:
And I'd like to add something in to the contents
but i'd like to add 123 in every child how may i do it?

You can use .html(function) to add new html to existing html content.

$(".identify").html(function(index, html) {
  return html + 123
})

//something

//something

//something

//something

A: You can use the .each function to iterate each found node and perform a function:
$(".identify").each(function(){
    $(this).html("123");
});

Example JSFiddle

A: You don't need a loop to achieve this.Check it

//something

//something

//something

//something

<button id="btn">Do it</button>

A: use the append to add something to the existing content:
$(".identify").each(function(){
    $(this).append("123");
});


text:
Q: Calling angularjs controller from websocket event handlers I'm new to angularjs and can use some guidance on the design of an app which uses a WebSocket connection to a backend. When the socket gets an onmessage event, it should load a dynamic view. Prior to loading the view, the model needs to be constructed based on some of the message parameters.
So, is it an acceptable angular solution to call a controller function from the onmessage event handler or is there a more angular way of doing things? If it is acceptable, how can I accomplish this? Should I call a route and pass in the route parameters to the controller? Thanks.

A: If onmessage event is a websocket server response to client request, you can use promise/deferred implementation using angular service $q. Here is a good explanation: http://clintberry.com/2013/angular-js-websocket-service/
If onmessage event is push data from websocket server, you can use $broadcast to broadcast onmessage event and $on in controller to listen the broadcast event.
I have code that may help you. It is angular service for xively.com REST API using websocket: https://github.com/mgalela/ngxively

A: You will not call a controller. You will just change the route to the view and run the initialization logic there.
This could be done in few ways. If the data that you need to initialize the view is small you could have it as a route parameter (aka state parameter).
The URL will look something like this:
http://yoursite.org/theView/theParameter

If the data large you could have a service that both controllers will inject to share data.


text:
Q: how to reformat a dict python I'm stuck on an issue with trying to re-format a dict
Here's my code that is writing the dict:
deLimit = "**"
hashKey = item1 +deLimit+ item2 +deLimit+ item3 +deLimit+ item4

mydict[hashKey] = {
   "key": currentTotal + 1
                    }

with open(file,'a') as newfile:
    print "heading1 heading2 heading3 heading4 heading5"
    for key, val in myDict.iteritems():
       print(repr((key.split('**'), val)))

Results in:
heading1 heading2 heading3 heading4 heading5
(['item1', 'item2', 'item3', 'item4'], {'key': 1})
(['item1', 'item2', 'item3', 'item4'], {'key': 1})
(['item1', 'item2', 'item3', 'item4'], {'key': 1})

I know that repr makes a nice format of my dict. But how do I re-format the output?
What I'm looking to achieve is:
heading1 heading2 heading3 heading4 heading5
item1 item2 item3 item4 keyValue
item1 item2 item3 item4 keyValue
item1 item2 item3 item4 keyValue
item1 item2 item3 item4 keyValue
item1 item2 item3 item4 keyValue
…

But I'm not sure how to re-format this output
(['item1', 'item2', 'item3', 'item4'], {'key': 1})

Thanks

A: You can use something like this:
for key, val in myDict.iteritems():
    print (key.replace('**', ' ') + ' ' + str(val['key']))

A: for key, val in mydict.items():
    print(",".join(key.split('**')),val['key'],sep=",")


text:
Q: Problemas para buscar los datos a través de la fecha Tengo un problema con este código debido a que no me reconoce estas 2 variables y lo que necesito es convertirlas de String a Date, lo intentado de varias alternativas pero no me las reconoce y la idea es que me busque los datos en el formato a traves del formato mysql ya que tiene que buscarlas en Date

        <link href="../css/style.css" rel="stylesheet" type="text/css"/>

                Listado por Sensor
                Listado Por Fechas
                Listado Mensual
                Exportar a Excel

        <input type="button"  value="Mostrar" onclick="mostrar('bn')">

A: No necesitas parsear las fechas en el cliente, eso debes hacerlo en el backend. Envía las fechas como string por ajax ya que estás consultando una API; no puedes enviar un objeto por URL.
.getJSON("graficoEntreFechas.php?fe=graficoBuscarSensor&desde="+strFecha, function (result) {
  for (var i = 0; i < result.length; i++) {
    data.push({
      x: new Date(result[i].FECHA),
      y: parseInt(result[i].Cantidad)
    });
  }
 chart.render();
});


text:
Q: How to get around "name 'row' is not defined" error when row in question doesn't exist? I am getting a "name 'row' is not defined" error when I run a particular piece of code (see below). This only happens when my input layer has one entry instead of two. So when the attribute query is run to find a second row there is no row to find and hence the error appears.
The aim of my overall script mean this will happen from time to time, what I am looking for is a way to accommodate this error and either avoid this section of script when an error is likely to occur or continue with the script even if this error pops up. I have tried to incorporate a 'try' and 'except' statement into the loop but have been unsuccessful. Would this work? if so how? If anyone has an idea on how to get around this problem please let me know.
import arcpy
from arcpy import env

env.workspace = "C:\MyArcGIS\EDRN_Shp"

arcpy.env.overwriteOutput = True

join110 = "C:\\MyArcGIS\\EDRN_Shp\\join110.shp"
joinField = "LCC_DRN_ID"
query1 ='"FID" = 1'

arcpy.MakeFeatureLayer_management(join110, "feature_layer12")
arcpy.SelectLayerByAttribute_management ("feature_layer12", "NEW_SELECTION", query1)

rows = arcpy.SearchCursor("feature_layer12")
for row in rows:
    if row.getValue("edrn_in") >= "E":
        arcpy.JoinField_management("feature_layer10", joinField, "feature_layer12", joinField, "edrn_in")
    if row.getValue("edrn_out") >= "E":
        arcpy.JoinField_management("feature_layer10", joinField, "feature_layer12", joinField, "edrn_out")

del row, rows

A: I would try using with instead, and also for performance switching to da search cursors
import arcpy
from arcpy import env

env.workspace = "C:\MyArcGIS\EDRN_Shp"

arcpy.env.overwriteOutput = True

join110 = "C:\\MyArcGIS\\EDRN_Shp\\join110.shp"
joinField = "LCC_DRN_ID"
fc = r"C:\Shapefile\featurelayer12.shp"
fields = ["erdn_in", "erdn_out"]
query1 ='"FID" = 1'

arcpy.MakeFeatureLayer_management(join110,fc)
arcpy.SelectLayerByAttribute_management (fc, "NEW_SELECTION", query1)

with arcpy.da.SearchCursor (fc, fields) as cursor:
    for row in cursor:
        if row[0] >= "E":
            arcpy.JoinField_management("feature_layer10", joinField, "feature_layer12", joinField, "edrn_in")
        elif row[1] >= "E":
            arcpy.JoinField_management("feature_layer10", joinField, "feature_layer12", joinField, "edrn_out")
        else:
            pass

This should work in 10, what I think was happening is you didn't initially define your field names, therefore getValue wouldn't work.
import arcpy
from arcpy import env

env.workspace = "C:\MyArcGIS\EDRN_Shp"

arcpy.env.overwriteOutput = True

join110 = "C:\\MyArcGIS\\EDRN_Shp\\join110.shp"
joinField = "LCC_DRN_ID"
fc = r"C:\Shapefile\featurelayer12.shp"
erdn_in = "erdn_in"
erdn_out = "erdn_out"
query1 ='"FID" = 1'

arcpy.MakeFeatureLayer_management(join110,fc)
arcpy.SelectLayerByAttribute_management (fc, "NEW_SELECTION", query1)

rows = arcpy.SearchCursor(fc)
row = rows.next()
while row:
    if row.getValue(erdn_in) >= "E":
        arcpy.JoinField_management("feature_layer10", joinField, "feature_layer12", joinField, "edrn_in")
    elif row.getValue(erdn_out) >= "E":
        arcpy.JoinField_management("feature_layer10", joinField, "feature_layer12", joinField, "edrn_out")
    else:
        pass
    row = rows.next()


text:
Q: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop | Redux Forms I want to create a simple form that takes in an email adress and later adds it to our database. I went with React Forms, because it facilitates the whole development process and reduces the amount of time.
However, when I'm trying to POST my form I'm getting this error: Uncaught Error: You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop
Here's my AddUserForm.js:
import React from 'react'
import { Field, reduxForm } from 'redux-form'

const AddUserForm = ({ handleSubmit }) => {
  return (
    <form onSubmit={handleSubmit}>

        <Field name="email" component="input" type="email" />

      <button type="submit">Bjud in</button>
    </form>
  )
}
export default reduxForm({
  form: 'addUser'
})(AddUserForm)

Here's my addUserAction:
import axios from 'axios'
import settings from '../settings'

axios.defaults.baseURL = settings.hostname

export const addUser = email => {
  return dispatch => {
    return axios.post('/invite', { email: email }).then(response => {
      console.log(response)
    })
  }
}

And here's my AddUserContainer.js:
import React, { Component } from 'react'
import { addUser } from '../../actions/addUserAction'
import AddUserForm from './Views/AddUserForm'
import { connect } from 'react-redux'

class AddUserContainer extends Component {
  submit(values) {
    console.log(values)
    this.props.addUser(values)
  }

  render() {
    return (

Bjud in användare

        <AddUserForm onSubmit={this.submit.bind(this)} />

    )
  }
}

function mapStateToProps(state) {
  return { user: state.user }
}

export default connect(mapStateToProps, { addUser })(AddUserContainer)

I am really grateful for all the answers! Stay awesome!

A: In your AddUserForm.js
Here you have to add onSubmitHandler as a prop for taking in the submit function that's suppose to run on form submit. You then have to pass the onSubmitHandler to handleSubmit()
import React from 'react'
import { Field, reduxForm } from 'redux-form'

const AddUserForm = ({ handleSubmit, onSubmitHandler }) => {
  return (
    <form onSubmit={handleSubmit(onSubmitHandler)}>

        <Field name="email" component="input" type="email" />

      <button type="submit">Bjud in</button>
    </form>
  )
}
export default reduxForm({
  form: 'addUser'
})(AddUserForm)

In your AddUserContainer.js
Change onSubmit={this.submit.bind(this)} to onSubmitHandler={this.submit.bind(this)}

A: Not 100% this is your problem but I would recommend against trying to bind on the form or whatever. Assuming you're storing the input in the state's user object, then you just want to define a submit method, and call it with this.state.user. That method should basically just call your api method.
import React, { Component } from 'react'
import { addUser } from '../../actions/addUserAction'
import AddUserForm from './Views/AddUserForm'
import { connect } from 'react-redux'

class AddUserContainer extends Component {
  submit(values) {
    console.log(values)
    this.props.addUser(values)
  }

  render() {
    return (

Bjud in användare

        <AddUserForm onSubmit={this.submit(this.state.user)} />

    )
  }
}

function mapStateToProps(state) {
  return { user: state.user }
}

export default connect(mapStateToProps, { addUser })(AddUserContainer)


text:
Q: igraph spatial distance edge attribute based on edge match? I'm building a spatial network where edges represent the movement between two locations in real world terms, the weight of edges in the number of times the movement occurred, and the nodes are the points in space.
For instance, consider airports. Where nodes are the airports, and edges are the number of flights between the airports, and each edge has an attribute distance (i.e. km between airports). My hope is to then use the distance in some downstream analyses (not sure if they're going to be useful).
Anyway, I'm not quite sure how to integrate the spatial information into the graph layer (i.e. attributing distance to the edges). Typically, if working in dataframes I would do a join, but given the igraph object structure I'm not sure how to do this. Doing it manually, by setting attributes in the order of the igraph edges is unfeasible given the sheer amount of data I have.
Here is a small reproducible example. In real terms, I calculate edges from large adjacency matrices in which I have rows that represent departures (from) and arrivals are (to). I can calculate distances using coordinates associated to the spatial points at an earlier time, but how do I then integrate everything in igraph?
library(igraph)

g = make_graph(c("Paris", "Amsterdam", "Amsterdam",
"London", "Milan", "Paris", "Dublin", "London"), directed = TRUE)

g

#> IGRAPH 3c2accf DN-- 5 4 --
#> + attr: name (v/c)
#> + edges from 3c2accf (vertex names):
#> [1] Paris    ->Amsterdam Amsterdam->London    Milan    ->Paris
#> [4] Dublin   ->London

The data from which the edges are created looks like the following. It's in tibble format, then is converted using xtabs into structure needed by igraph to make graph layer.
edges = tibble(from = c("Paris","Amsterdam","Milan","Dublin"), to = c("Amsterdam","London","Paris","London"))

edges = xtabs(~ from + to, edges)

edges
#>            to
#> from        Amsterdam London Paris
#>   Amsterdam         0      1     0
#>   Dublin            0      1     0
#>   Milan             0      0     1
#>   Paris             1      0     0

I'm guessing there is some easy way how to associate specific edges to a specific attribute by matching strings, but just not sure how to do it. Ultimately, all I want to achieve is to have an edge attribute that describes the distance between the two airports in question.
Thank you.

A: I guess you can use as_adjacency_matrix with attr =  enabled, e.g.,
edges %>%
  mutate(xfrom = c(48.87, 8.87, 45.49, 53.34), yfrom = c(2.30, 2.30, 9.17, -6.26), xto = c(52.36, 51.48, 48.87, 51.48), yto = c(4.87, -0.10, 2.30, -0.10)) %>%
  mutate(distance_km = geosphere::distHaversine(cbind(xfrom, yfrom), cbind(xto, yto)) / 1000) %>%
  select(from, to, distance_km) %>%
  graph_from_data_frame(directed = FALSE) %>%
  as_adjacency_matrix(attr = "distance_km")

and you will obtain
5 x 5 sparse Matrix of class "dgCMatrix"
             Paris Amsterdam    Milan  Dublin   London
Paris       .       481.8386 851.3811   .        .
Amsterdam 481.8386    .        .        .     4749.576
Milan     851.3811    .        .        .        .
Dublin      .         .        .        .      716.185
London      .      4749.5765   .      716.185    .


text:
Q: Unable to install texlive on Impish When I try to install the texlive distribution using:

sudo apt install texlive

I get the following output:

Reading package lists... Done Building dependency tree... Done Reading
state information... Done Some packages could not be installed. This
may mean that you have requested an impossible situation or if you are
using the unstable distribution that some required packages have not
yet been created or been moved out of Incoming. The following
information may help to resolve the situation:
The following packages have unmet dependencies:  texlive : Depends:
texlive-latex-base (>= 2019.20200218) but it is not installable
texlive-base : Depends: texlive-binaries (>= 2019.20190605)
texlive-latex-recommended : Depends: texlive-binaries (>=
2019.20190605)
Depends: texlive-latex-base (>= 2019.20200218) but it is not installable E: Unable to correct problems, you have held broken packages.

I have no idea what this means or how to fix it. Any gurus out there please help. I have run apt-get update successfully already.

A: Once you have run sudo apt update to update the software database, install TeXLive with
sudo apt install texlive-full


text:
Q: AIR File.upload() doesn't work the very first time have a strange bug in an AIR project that uploads video files to aserver. The simplified code is
var file:File = new File();
file.addEventListener(Event.SELECT, onSelect);
file.browse();

private function onSelect(e:Event):void
{
   trace(e.target.nativePath);
}

In my onSelect handler I get a reference to the File object (in this case my video file) and then use File.upload() to upload to the server url.
The very first time I browse to a file and select it, nothing happens, no error is thrown. My file upload method is called but then nothing!.
All subsequent attempts work. It's almost as if the application needs to be initialized with a first file selection. Has anyone encountered this?