text:
Q: QTP - Object doesn't support this property or method error I am not sure what's wrong with the below code.
    Set obj=description.Create()

    obj("micClass").Value="Link"
    obj("name").Value="Advertising Programs"

    Set totalnobuttons=Browser("title:=.*").Page("title:=.*").ChildObjects(obj)
    totalnobuttons.highlight
    print totalnobuttons.count

    For i=0 to totalnobuttons.count-1
        print totalnobuttons(i).GetRoProperty("name")
    Next

This gives an error "Object doesn't support this property or method error" during execution. I need to highlight the "Advertising Programs" program link using the above code.

A: Your line:
totalnobuttons.highlight

is a culprit. You are trying to highlight the whole collection of Link objects. You cannot do that. Instead, remove that line and put that in your For...Loop like this:
For i = 0 to totalnobuttons.count-1
    totalnobuttons(i).HighLight
    print totalnobuttons(i).GetRoProperty("name")
Next

A: You are trying to find collection object. Return type should be always array of objects.
Try to use advanced for loop to proceed. Find the code below:
For each button in totalnobuttons
    button.HighLight
    print button.GetRoProperty("name")
Next


text:
Q: Coffeescript HTTP client I am running server.coffee from this page: https://github.com/xenph/foaas
From the command line, you can do:
curl http://localhost:5000/off/Name1/Name2
!@#$ off, Name1. - Name2

But I'm using the code from this page: http://coffeescriptcookbook.com/chapters/networking/basic-http-client
http = require 'http'

http.get { host: 'http://localhost:5000/off/Name1/Name2' }, (res) ->
    data = ''
    res.on 'data', (chunk) ->
        data += chunk.toString()
    res.on 'end', () ->
        console.log data

The error I get is:
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: getaddrinfo ENOTFOUND
  at errnoException (dns.js:37:11)
  at Object.onanswer [as oncomplete] (dns.js:124:16)

Which leads me to believe that it's not finding the url.
What can I do?

A: try
http.get 'http://localhost:5000/off/Name1/Name2', (res) ->

or
http.get { hostname: 'localhost', port: 5000, path: '/off/Name1/Name2' }, (res) ->

instead of
http.get { host: 'http://localhost:5000/off/Name1/Name2' }, (res) ->

maybe?

A: Firstly extract a little more info from exceptions:
.on('error',function(e){
   console.log("Error: " + hostNames[i] + "\n" + e.message);
   console.log( e.stack );
});

Secondly as curl is working we can assume that the service is up and accessible from localhost so there must be a deeper issue. What flavour of linux are you using? I've solved similar issues before by disabling firewall (iptables) and selinux.
Also double check to make sure that you have dns configured and that it will return 127.0.0.1 for localhost. Use nslookup.

redpajama_set_name: RedPajamaStackExchange


text:
Q: error creating reference from interface that extends crudrepo Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoB2a': Invocation of init method failed; nested exception is java.lang.IllegalAccessError: tried to access class org.springframework.beans.PropertyMatches from class org.springframework.data.mapping.PropertyReferenceException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:736)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:140)
    at org.springframework.context.support.FileSystemXmlApplicationContext.<init>(FileSystemXmlApplicationContext.java:84)
    at test.Main.main(Main.java:28)
Caused by: java.lang.IllegalAccessError: tried to access class org.springframework.beans.PropertyMatches from class org.springframework.data.mapping.PropertyReferenceException
    at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
    at org.springframework.data.mapping.PropertyReferenceException.<init>(PropertyReferenceException.java:59)
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:235)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:373)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:353)
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:87)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:61)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:95)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:73)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:416)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:206)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:251)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:237)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    ... 12 more

@Component("test")
public class JpaConfig {

@Autowired
daoB2a dao;

public daoB2a getDao() {
    return dao;
}

public void setDao(daoB2a dao) {
    this.dao = dao;
}

}

<jpa:repositories base-package="com.company.springdata.daos" />
<context:property-placeholder location="src/main/resources/application.properties"/>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${db.drivermanager}"/>
    <property name="url" value="${db.url}"/>
    <property name="password" value="${db.password}"/>
    <property name="username" value="${db.username}"/>
</bean>

<bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="showSql" value="true"/>
    <property name="generateDdl" value="true"/>
    <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.mycompany.springdata.entities"/>
    <property name="jpaVendorAdapter" ref="hbAdapterBean"/>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<context:component-scan base-package="com.mycompany.springdata.entities"/>

public class Main {

public static void main(String[] args) {
    ApplicationContext app = new FileSystemXmlApplicationContext("src/main/resources/beans.xml");
    System.out.println("read successfuly");

     //        JpaConfig user = (JpaConfig) app.getBean("test");
     //        System.out.println("user is    "+user);
    //  System.out.println(""+user.getDao().save(new User("dskds", "sds",          "dsds", "dsddskd")));

}
}

A: make sure you inject daoB2a bean in your xml file
;


text:
Q: react setState() from external? New to Reactjs, I have followed a tut or 2 to build a relatively simple app, that sends queries to Mongodb and renders the results. Although I am yet to render them. I can pass the find() through and get back results that I like, and log them to the console, but for the life of me I cannot figure out how to get the results into "state", or anywhere else in the app. It's likely a very simple mistake somewhere. But I don't have enough knowledge of react to figure it out.
Here is the (small) App.js file in it's entirety, I thought it easier than trying to pick through it and make a valid sample.
// /client/App.js
import React, { Component } from 'react';
import axios from 'axios';
import * as PropTypes from "prop-types";
import {useEffect, useState} from "react";

function View(props) {
  return null;
}

View.propTypes = {children: PropTypes.node};

function Text(props) {
  return null;
}

function MyForm() {
  const [user_search, setName] = useState("");

  const handleSubmit = async (event) => {
    event.preventDefault();

    console.log(`The Search you entered was: ${user_search}`);

    let felcher = user_search.split(/[ ,]+/);
    let search_obj = {}
    for (let i in felcher) {
      search_obj[i] = felcher[i]

    }
    axios.post('http://localhost:3001/api/searchData', {
      search_obj
      }
    ).then(resp => {
      console.log("RESPONSE FROM POST", resp['data'])

    });

  }

  return (
      <form onSubmit={handleSubmit}>
        Enter Search Terms:
          <input
              type="text"
              value={user_search}
              onChange={(e) => setName(e.target.value)}
          />

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

  )
}

let formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',})

Text.propTypes = {children: PropTypes.node};

class App extends Component {
  // initialize our state
  state = {
    data: [],
    _id: 0,
    ticker: '',
    primary_share: [],
    title: null,
    document_date: null,
    release_date: null,
    search_text: null,
    url: null,
    result_state: null,

  };

  componentDidMount() {
    this.getDataFromDb();
    if (!this.state.intervalIsSet) {
      let interval = setInterval(this.getDataFromDb, 1000);
      this.setState({ intervalIsSet: interval });
    }
  }

  componentWillUnmount() {
    if (this.state.intervalIsSet) {
      clearInterval(this.state.intervalIsSet);
      this.setState({ intervalIsSet: null });
    }
  }

  getDataFromDb = () => {
    fetch('http://localhost:3001/api/getData')
      .then((data) => data.json())
      .then((res) => this.setState({ data: res.data }));
  };

  render() {
    const { data } = this.state;
    return (

        <MyForm />

        {/*
*/}
        {/*  {data.length <= 0*/}
        {/*    ? 'Getting Results......'*/}
        {/*    : data.map((dat) => (*/}
        {/*
*/}
        {/*           Ticker:  {dat.ticker}
*/}
        {/*           Release Date:  {dat.release_date}
*/}
        {/*           Document Title: {dat.title}
*/}
        {/*           Document URL: {dat.url}
*/}
        {/*
*/}
        {/*      ))}*/}
        {/*
*/}

    );

  }
}

export default App;

The area I am struggling with is where print the results to the console here ...
console.log("RESPONSE FROM POST", resp['data'])
In the "MyForm()" function. I feel if I could setState() there, but it appears to not work.
But I can't do anything else that gets them over to render. HELP!!!!

A: SetState is a hook that returns two items: the state and setter (or the function to set the state). In your case you will have a setState at the top of your function:
const [data, setData] = useState([]) // what ever you put as an argument will be the default data until it is set
const [err, setErr] = useState(null) // this will be our error state

In your axios request you will use:
axios
    .post('http://localhost:3001/api/searchData', { search_obj })
    .then(resp => {
        setData(resp['data']) // see here we call the state function
    })
    .catch(err => {
        setErr(err) // and here for our error
    })

Then in our return we can use the data any way we like:
return (
  <>

{data}</data>

{err ? err : 'no errors'}

  </>
)

Does that make sense? (Code not tested)


text:
Q: Ansible loop and print dictionary variable Can anyone help with this basic question?  I have a dictionary variable and I'd like to print it.
dict_var:
  - key1: "val1"
  - key2: "val2"
  - key3: "val3"

Is it possible to loop and print its content in a playbook?

A: Q: "Loop and print variable's content."
A: The variable dict_var is a list. Loop the list, for example
- hosts: localhost
  vars:
    dict_var:
      - key1: "val1"
      - key2: "val2"
      - key3: "val3"
  tasks:
    - debug:
        var: item
      loop: "{{ dict_var }}"

gives (abridged)
    "item": {
        "key1": "val1"
    }

    "item": {
        "key2": "val2"
    }

    "item": {
        "key3": "val3"
    }

Q: "Loop and print dictionary."
A: There are more options when the variable is a dictionary. For example, use dict2items to "loop and have key pair values in variables" item.key and item.value
- hosts: localhost
  vars:
    dict_var:
      key1: "val1"
      key2: "val2"
      key3: "val3"
  tasks:
    - debug:
        var: item
      loop: "{{ dict_var|dict2items }}"

gives (abridged)
    "item": {
        "key": "key1",
        "value": "val1"
    }

    "item": {
        "key": "key2",
        "value": "val2"
    }

    "item": {
        "key": "key3",
        "value": "val3"
    }

The next option is to loop the list of the dictionary's keys. For example
    - debug:
        msg: "{{ item }} {{ dict_var[item] }}"
      loop: "{{ dict_var.keys()|list }}"

gives (abridged)
    "msg": "key1 val1"

    "msg": "key2 val2"

    "msg": "key3 val3"

A: If all you want to do is printing the dictionary items, you can do:
  - debug: msg="{{ item }}"
    with_items: "{{ dict_var | dict2items }}"


text:
Q: How to skip fingerprint checking when "sudo ssh localhost"? When first enter a sudo ssh localhost we always get a note like:

The authenticity of host 'localhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:u0q6ow7gfu4IvqfGOytZB6MKjO479AUr9hulSqO/dy4.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

And I want to skip this step.
I have try follow(with sshpass):
ssh-keygen -t rsa -P '' -f ~/.ssh/deploy_rsa<<<y
cat ~/.ssh/deploy_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
sudo ssh-keyscan localhost>>~/.ssh/known_hosts

Well it seems just works in ssh localhost, but not in sudo ssh localhost.
So is there any reliable way to access my goal?

A: ssh -o StrictHostKeyChecking=no localhost
Or for something more permanent, create or modify your ~/.ssh/config with this:
Host localhost
    StrictHostKeyChecking no

Also you should know that this process opens you up to MITM attacks (not on localhost obviously) and shouldn't be done on any important server.


text:
Q: Matching documens with text2vec -- scaling problems I am having a few issues with scaling a text matching program.  I am using text2vec which provides very good and fast results.
The main problem I am having is manipulating a large matrix which is returned by the text2vec::sim2() function.
First, some details of my hardware / OS setup:  Windows 7 with 12 cores about 3.5 GHz and 128 Gb of memory.  Its a pretty good machine.
Second, some basic details of what my R program is trying to achieve.
We have a database of 10 million unique canonical addresses for every house / business in address. These reference addresses also have latitude and longitude information for each entry.
I am trying to match these reference addresses to customer addresses in our database. We have about 600,000 customer addresses. The quality of these customer addresses is not good.  Not good at all! They are stored as a single string field with absolutely zero checks on input.
The techical strategy to match these addresses is quite simple.  Create two document term matrices (DTM) of the customer addresses and reference addresses and use cosine similarity to find the reference address which is the most similar to a specific customer address.  Some customer addresses are so poor that will result in a very low cosine similarity -- so, for these addresses a "no match" would be assigned.
Despite being a pretty simple solution, the results obtained are very encouraging.
But, I am having problems scaling things....? And I am wondering if anyone has any suggestions.
There is a copy of my code below. Its pretty simple. Obviously, I cannot include real data but it should provide readers a clear idea of what I am trying to do.
SECTION A - Works very well even on the full 600,000 * 10 million input data set.
SECTION B - the text2vec::sim2() function causes R studio to shut down when the vocabulary exceeds about 140,000 tokens (i.e columns).  To avoid this, I process the customer addresses in chunks of about 200.
SECTION C - This is the most expensive section. When processing addresses in chunks of 200, SECTION A and SECTION B take about 2 minutes.  But SECTION C, using (what I would have thought to be super quick functions) take about 5 minutes to process to process a 10 million row * 200 column matrix.
Combined, SECIONS A:C take about 7 minutes to process 200 addresses.  As there are 600,000 addresses to process, this will take about 14 days to process.
Are they are ideas to make this code run faster...?
rm(list = ls())
library(text2vec)
library(dplyr)

# Create some test data

# example is 10 entries.
# but in reality we have 10 million addresses
vct_ref_address <- c("15 smith street beaconsfield 2506 NSW",
"107 orange grove linfield 2659 NSW",
"88 melon drive calton 3922 VIC",
"949 eyre street sunnybank 4053 QLD",
"12 black avenue kingston 2605 ACT",
"5 sweet lane 2004 wynyard NSW",
"32 mugga way 2688 manuka ACT",
"4 black swan avenue freemantle 5943 WA",
"832 big street narrabeet 2543 NSW",
"5 dust road 5040 NT")

# example is 4 entries
# but in reality, we have 1.5 million addresses
vct_test_address <- c("949 eyre street sunnybank 4053 QLD",
"1113 completely invalid suburb with no post code QLD",
"12 black road kingston 2605 ACT",
"949 eyre roaod sunnybank 4053 QLD" )

# ==========================
# SECTION A ===== prepare data
# A.1 create vocabulary
t2v_token <- text2vec::itoken(c(vct_test_address, vct_ref_address),  progressbar = FALSE)
t2v_vocab <- text2vec::create_vocabulary(t2v_token)
t2v_vectorizer <- text2vec::vocab_vectorizer(t2v_vocab)
# A.2 create document term matrices dtm
t2v_dtm_test <- text2vec::create_dtm(itoken(vct_test_address, progressbar = FALSE), t2v_vectorizer)
t2v_dtm_reference <- text2vec::create_dtm(itoken(vct_ref_address, progressbar = FALSE), t2v_vectorizer)

# ===========================
# SECTION B ===== similarity matrix
mat_sim <- text2vec::sim2(t2v_dtm_reference, t2v_dtm_test,  method = 'cosine', norm = 'l2')

# ===========================
# SECTION C ===== process matrix
vct_which_reference <- apply(mat_sim, 2, which.max)
vct_sim_score <- apply(mat_sim, 2, max)

# ============================
# SECTION D ===== apply results
# D.1 assemble results
df_results <- data.frame(
test_addr = vct_test_address,
matched_addr = vct_ref_address[vct_which_reference],
similarity =  vct_sim_score )

# D.2 print results
df_results %>% arrange(desc(similarity))

A: The issue in step C is that mat_sim is sparse and all the apply calls make column/row subsetting which are super slow (and convert sparse vectors to dense).
There could be several solutions:

*

*if mat_sim is not very huge convert to the dense with as.matrix and then use apply

*Better you can convert mat_sim to sparse matrix in a triplet format with as(mat_sim, "TsparseMatrix") and then use data.table to get indices of the max elements. Here is an example:
library(text2vec)
library(Matrix)
data("movie_review")
it = itoken(movie_review$review, tolower, word_tokenizer)
dtm = create_dtm(it, hash_vectorizer(2**14))

mat_sim = sim2(dtm[1:100, ], dtm[101:5000, ])
mat_sim = as(mat_sim, "TsparseMatrix")

library(data.table)

# we add 1 because indices in sparse matrices in Matrix package start from 1
mat_sim_dt = data.table(row_index = mat_sim@i + 1L, col_index = mat_sim@j + 1L, value = mat_sim@x)

res = mat_sim_dt[,
        { k = which.max(value); list(max_sim = value[[k]], row_index = row_index[[k]]) },
        keyby = col_index]
res

Also as a side suggestion - I recommend to try char_tokenizer() with ngrams (for example of the size c(3, 3)) to "fuzzy" match different spelling and abbreviations of addresses.


text:
Q: PyQt4 : Module not foundError I am trying to run a Python file that references PyQt4 using PyCharm. I get the following error message:

from PyQt4 import QtCore, QtGui
ModuleNotFoundError: No module named 'PyQt4'

I am running a virtual environment and I tried installing PyQt4 in the venv's site-packages directory using the following command:
pip install pyqt4

However, the CMD window returns that it cannot return a version that satisfies the requirement pyqt4.
I checked the vendor's website and it states that in order to use the PyQt4, I need to install the SIP package and I did. But that didn't solve it either.

A: Use
PyQt5 or PySide2 or PySide6

like previously advised.


text:
Q: Can an HTTP proxy handle inbound CONNECT requestd over HTTP/2? AFAIK, HTTP proxy CONNECT HTTP/1.1 requests tunnel a single TCP connection. After any TCP connection is closed, both upstream and downstream connections are closed. Connection reuse isn't possible. Is it possible to make HTTP/2 requests to a proxy to mux multiple tunneled over a single TCP (upstream) connection to avoid the cost of TCP handshake? Does the HTTP/2 standard allow the CONNECT method?

A: Yes, in HTTP/2 the CONNECT method exists too:
"In HTTP/2, the CONNECT method is used to establish a tunnel over a single HTTP/2 stream to a remote host for similar purposes"


text:
Q: why php results in HTML are undefined when using JavaScript I need to get the IP of the client. I am able to get it through PHP variable
"$_SERVER['REMOTE_ADDR']". I get this ip from server side php to html page through AJAX request but when I want to use this IP value in JavaScript it is showing that the value is undefined.
any solution?
PHP code:
<?php echo $_SERVER['REMOTE_ADDR'];?>

HTML CODE:

JavaScript code:
function ip() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ip").innerHTML =
        this.responseText;
    }
  };
  xhttp.open("POST", "ip.php");
  xhttp.send();
}

function ip2() {
  setTimeout(function () {
    var ip = document.getElementById("ip").value;
    alert(ip);
  }, 1000);
}

A: First of all you should validate that you are getting the right response from your AJAX request by check that the result is certainly written to the element with id attribute "ip", and than instead of using:
var ip = document.getElementById('ip').value;

You should use Node.textContent to get the text content:
var ip = document.getElementById('ip').textContent;

Code example (without AJAX request):

function ip() {
  document.getElementById('ip').innerHTML = '127.0.0.1';
}

function ip2() {
  setTimeout(function () {
    var ip = document.getElementById('ip').textContent;
    console.log(ip);
  }, 1000);
}

A: You want your Ip Address in java script , so have to put ip address in that tag i think.
<?php $ip_address =  $_SERVER['REMOTE_ADDR'];?>

<?php echo $ip_address; ?>

A: <?php echo $_SERVER['REMOTE_ADDR'];?>

run this code you might found what is the problem.


text:
Q: Allocate more resources to EC2 service on demand I'm trying to get my service to scale with the load. It's possible to configure all these capacities and values. In that case, AWS will spawn new instances of your service. You'll have multiple instances running at the same time.
https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-capacity-limits.html
Is it possible to have it increase resources for a single instance instead? For example, add more RAM, when RAM usage is high.

A: No, you cant scale vertically (bigger instance) on demand. You should build infrastructure that scales horizontally (more instances).

A: Yes, it's possible but it will require stopping and terminating EC2 instances.
AutoScaling will perform a rolling replacement.


text:
Q: Appending HTML string to the DOM How to append a HTML string such as
var str = '
Just some text here
';

to the
 with the id test?
(Btw div.innerHTML += str; is not acceptable.)

A: Performance
AppendChild (E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML(F) is fastest on firefox. The innerHTML= (B) (do not confuse with += (A)) is second fast solution on all browsers and it is much more handy than E and F.
Details
Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)

*

*on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest

*on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k)  slowest is A(466)

*on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)

You can replay test in your machine here

function A() {
  container.innerHTML += '
A: Just some text here
';
}

function B() {
  container.innerHTML = '
B: Just some text here
';
}

function C() {
  $('#container').append('
C: Just some text here
');
}

function D() {
  var p = document.createElement("p");
  p.innerHTML = 'D: Just some text here';
  container.appendChild(p);
}

function E() {
  var p = document.createElement("p");
  var s = document.createElement("span");
  s.appendChild( document.createTextNode("text ") );
  p.appendChild( document.createTextNode("E: Just some ") );
  p.appendChild( s );
  p.appendChild( document.createTextNode(" here") );
  container.appendChild(p);
}

function F() {
  container.insertAdjacentHTML('beforeend', '
F: Just some text here
');
}

A();
B();
C();
D();
E();
F();

This snippet only for show code used in test (in jsperf.com) - it not perform test itself.

A: The right way is using insertAdjacentHTML. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment if your str contains no script tags.
If your str contains script tags, you need to remove script elements from the fragment returned by createContextualFragment before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML marks scripts unexecutable.)

A: Use insertAdjacentHTML which is supported in all current browsers:
div.insertAdjacentHTML( 'beforeend', str );

The position parameter beforeend will add inside the element, after its last child.
Live demo: http://jsfiddle.net/euQ5n/

A: Is this acceptable?
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle.
But, Neil's answer is a better solution.

A: Quick Hack:

Use Cases:
1: Save as .html file and run in chrome or firefox or edge. (IE wont work)
2: Use in http://js.do
In Action:
http://js.do/HeavyMetalCookies/quick_hack
Broken down with comments:

Reason Why I posted:
JS.do has two must haves:

*

*No autocomplete

*Vertical monitor friendly

But doesn't show console.log messages.
Came here looking for a quick solution.
I just want to see the results of
a few lines of scratchpad code, the
other solutions are too much work.

A: The idea is to use innerHTML on an intermediary element and then move all of its child nodes to where you really want them via appendChild.
var target = document.getElementById('test');
var str = '
Just some text here
';

var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
  target.appendChild(temp.firstChild);
}

This avoids wiping out any event handlers on div#test but still allows you to append a string of HTML.

A: This can solve
 document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '
<input type="text" name="" value="" class="" />
');

A: InnerHTML clear all data like event for existing nodes
append child with firstChild adds only first child to innerHTML. For example if we have to append:

text1

text2

only text1 will show up
What about this:
adds special tag to innerHTML by append child and then edit outerHTML by deleting tag we've created. Don't know how smart it is but it works for me
or you might change outerHTML to innerHTML so it doesn't have to use function replace

function append(element, str)
{

  var child = document.createElement('someshittyuniquetag');

  child.innerHTML = str;

  element.appendChild(child);

  child.outerHTML = child.outerHTML.replace(/<\/?someshittyuniquetag>/, '');

// or Even child.outerHTML = child.innerHTML

}

This text is inside the div
<button onclick="append(document.getElementById('testit'), '<button>dadasasdas</button>')">To div</button>
<button onclick="append(this, 'some text')">to this</button>

A: Why is that not acceptable?
document.getElementById('test').innerHTML += str
would be the textbook way of doing it.

A: The answer to my Question was just this; a simple Map with an empty value; and all I can get is a very heavy answer and not precise. I wonder who closed my question... didn't even bother to read
"use strict"
try{
  const fruits = new Map([["Banana",""],["Apples", ""], ["Orange"," "]]);

let text = "
Fruits
" + "
";

fruits.forEach(function(value, key){
  text += "
" + key + value + "
" + "
" });

text +="
 ";

document.getElementById('demo').innerHTML = text;
}
catch(err){
 document.getElementById('theError').innerHTML = err;
}

A: Shortest - 18 chars (not confuse += (mention by OP) with = more details here)
test.innerHTML=str

var str = '
Just some text here
';

test.innerHTML=str


text:
Q: Passing List of Exception Types as type parameter to generic method I'm trying to write a generic helper method that'd call methods and handle exceptions if any.
The method should be able to accept a List of acceptable Exception types, and handle them in a specific way. For other type of exceptions, it'll handle differently.
This is a very simplified version of the method
public static TResult InvokeMethod<TResult, TAllowedException>
                (Func<TResult> func) where TAllowedException : Exception
{
    try
    {
        return func();
    }
    catch (Exception ex)
    {
        if (ex is TAllowedException) //do something
            return default(TResult);
        else //do something else
            throw;
    }
}

Here I'm specifying the allowed Exception Type as TAllowedException. This works fine. But, this accepts only a single Exception_Type. How can I pass a List<Exception_Type> instead?

A: You cannot pass a list of types as type arguments to a generic method.
Why not simply pass a collection of types as a regular parameter?
public static TResult InvokeMethod<TResult>
        (Func<TResult> func, ICollection<Type> ignoredExceptions)
{
    try
    {
        return func();
    }
    catch (Exception ex)
        when (ignoredExceptions != null &&
              ignoredExceptions.Any(t => t.IsAssignableFrom(ex.GetType())))
    {
        return default(TResult);
    }
}

If someone passes a Type that is not an exception, nothing bad will happen. In my opinion there is no need to validate it. The method will still work correctly - the exceptions in the collection will be ignored.
What is the expected behavior of calling InvokeMethod(func, new Type[] { typeof(Int32) })? The func will be executed, and if it throws an exception that is an Int32, the default result will be returned. func will never throw an Int32 exception, so it already works like that without validating ignoredExceptions.
BTW passing arg as a parameter is not necessary. You can use a lambda to capture arg in a closure - () => func(arg). And this will work with any number of arguments.
Edit
If you really want to restrict the types at compile time, you'd have to create your own collection, with a bit weird generic Add method:
public class ExceptionCollection : IEnumerable<Type>
{
    private readonly List<Type> _exceptions = new List<Type>();

    public void Add<T>() where T : Exception => _exceptions.Add(typeof(T));
    public IEnumerator<Type> GetEnumerator() => _exceptions.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_exceptions).GetEnumerator();
}

The biggest disadvantage of this class is that it doesn't work with collection initializers.
There is a way to make it work with collection initializers too. The initializers require an Add method taking one parameter, but they will happily work with a generic Add<T>(T item) method.
public void Add<T>(T item) where T : Exception => _exceptions.Add(typeof(T));

Using it is a bit tricky too. We could of course pass instances of exceptions, but it's pointless to create an instance only to get its type. We can pass a strongly-typed null instead, using a cast or default(T):
new ExceptionCollection { default(ArgumentNullException), default(ArgumentException) };

I still think that in this particular case it's not necessary to validate the collection of types. There might be other cases when a constrained collection of types is necessary - then the above solution is quite ok.


text:
Q: Perl Programming in Shell My Expectation:
I have to use the following command to send the value of first argument to all the files calling perl.pl file.
./perl.pl 1

The one is read using the following file: (perl.pl)
#!/usr/bin/perl
package Black;
use strict;
use warnings;

#subroutines
sub get_x();

#variables
our $XE = -1;

  my ($param1, $param2, $param3) = @ARGV;
  my $x = get_x();

  sub get_x()
  {
  $XE = $param1;
  return $XE;

  }

exit;

Then I wrote another script which performs some code base on the input to perl.pl (0 or 1).
The file is ./per.pl and I invoke in from linux terminal like this: ./per.pl
Here is the code I wrote for it:
#!/usr/bin/perl

require "perl.pl";

my $xd = Black::get_x();
if ($xd ==1){
print $xd;}
else {
print "5";
}

exit;
But this is what I get when I write these commands:
./perl.pl 1

I tried to print it and it prints 1...removed the print like from the code in this case
./per.pl

And now I get nothing. I would like the 1 getting printed out but no it doesn't
Thanks in Advance

A: Before we get started, you cannot possibly get the output you say you get because you tell the process to exit when the module is executed by require, so Black::get_x() is never reached. Change exit; to 1;.

Now on to your question. If I understand correctly, you want to pass a value to one process via its command line, and fetch that value by executing the same script without the parameter.
You did not even attempt to pass the variable from one process to another, so it shouldn't be a surprise that it doesn't work. Since the two processes don't even exist at the same time, you'll need to store the value somewhere such as the file system.
#!/usr/bin/perl

use strict;
use warnings;

my $conf_file = "$ENV{HOME}/.black";
my $default = -1;

sub store {
    my ($val) = @_;
    open(my $fh, '>', $conf_file) or die $!;
    print $fh "$val\n";
    return $val;
}

sub retrieve {
    open(my $fh, '<', $conf_file)
        or do {
            return $default if $!{ENOENT};
            die $!;
        };

    my $val = <$fh>;
    chomp($val);
    return $val;
}

my $xd = @ARGV ? store($ARGV[0]) : retrieve();
print("$xd\n");


text:
Q: Gradle build failed While creating new Jetpack compose project Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2/7.3.0-8691043/aapt2-7.3.0-8691043.pom'. Received status code 405 from server: Method Not Allowed
got this error in androi build gradle while creating and starting new jetpack compose project


text:
Q: Form field validation issue I want to highlight the form fields that are empty and prompt the end-user to fill in the missing fields before submitting a form.
Currently when I click the submit button, it is highlighting the empty fields but then it bypasses the prompt and submitting the form anyway. Is there a way to make sure that the user fills in the form first before submitting the form? Also do I need to combine the following functions as they appear to be operating separately.
See the code snippet below:
//JS

****

****

// HTML

<form name="onlinepensionform" action="onlinepensionform_submit.asp" id="onlinepensionform_submit.asp" method="post">

Financial Institution:
      <input name="FinancialInstitutionName" type="text"  id="FinancialInstitutionName" value="" />

 Account name:
        <input name="AccountName"  type="text"  id="AccountName" value="" />

 BSB Number:
                       <input name="BsbNumber"  type="text"  id="BsbNumber" value="" />

  Account Number:
        <input name="AccountNumber"  type="text"  id="AccountNumber" value="" />

<input type="button" onclick="myFunction(); formcheck(); return false" value="Submit form">

</form>

A: Do what @FrankerZ said if you would like to stay with the current code.
Alternatively :
You can use required tag from HTML5 and not worry about that. It will look something like this :
<input type="text" name="firstName" required>

learn more here:
http://www.w3schools.com/tags/att_input_required.asp


text:
Q: "make install" - Changing output destination for all builds I am doing Linux development on a few machines, mainly Slackware 13.37 and Ubuntu 12.04. I am testing and validating the results of a few simple makefiles, and want to confirm the output of make install. However, before I go ahead testing this, I want to know if there is a portable means of changing the default output destination for make install for any makefile.
I would prefer if I could somehow stage my output, so all output goes to, for example:
/test/bin
/test/lib
/test/usr/bin

instead of:
/bin
/lib
/usr/bin

I know that in QNX development environments, for example, I can set environment variables like QCONF_OVERRIDE and INSTALL_ROOT_nto, and guarantee that no makefile is able to install anywhere other than a subdirectory of /test for example. Is there a similar mechanism for GCC on Ubuntu that just requires setting some environment variables in my ~/.bashrc file? I do all my work via command-line and VIM anyways, so I'm not worried about the case where a pretty IDE doesn't understand these environment variables due to them not being in a .kderc, .gnomerc, or equivalent.
Thank you.

A: Short answer: no.
Long answer:
There isn't a way to set the output destination for any Makefile; the Makefile or some other part of the build system has to be designed to make it possible.  make is a very simple tool because it's intended to function identically across a wide variety of platforms.  Consequently, it doesn't really use environment variables that aren't present in the Makefile itself.  This is good in terms of environment pollution and for keeping things less magic, but bad for achieving your desired goal.
A bit of context: things are a bit more complicated in part because, unlike the QNX development environment (a largely homogeneous cross-compilation environment), a large portion of software that uses make (I'm assuming GNU make but this applies to other versions as well) to build is written for a heterogeneous build and run environment—it may be designed to be able to build for different distributions, operating systems (Linux, MS Windows, Mac OS X, FreeBSD, etc.), and even hardware architecture (x86, arm, mips, power, sparc, sh, etc.).  Sometimes you're building for the same system and sometimes for a different one.  Unsurprisingly, there isn't really a standard way to define an install path across such a variety of systems.
Basile mentioned in his answer that for programs that use the GNU build system, you can use ./configure --prefix=/test.  This will typically work for simple programs that use Autotools.  For more complicated programs using GNU Autotools, there are usually complications if more diverse options are available:

*

*cross-compiling?  You might want your prefix to be set to where it's going to be installed on the target system (maybe /usr/local), and to use make install DESTDIR=/test.

*Does your build system expect dependencies in the prefix directory, but you want to find them elsewhere?  Better run ./configure --help to see what other options there are for providing alternate paths (often --with-foo=/prefix/of/foo)

I'm sure there's more that I'm forgetting right now, but I think you get the picture.
Keep in mind that only applies to projects that use Autotools.  Other projects may have other systems (perhaps naming a variable or editing a configuration file), so ultimately your best bet is to read the project documentation, and failing that, the Makefile.  Fun, eh?
P.S. Having variables defined in the environment is different than passing them as a command argument to make, i.e. SPAM="alot" make target is different from make target SPAM="alot"—the latter will override makefile variables.  See the GNU make docs on Variables from the Environment.

A: Just change prefix variable in makefile
prefix=/test

then run
 make install

also you can run following command for installing binaries
make prefix=/test install

Refer http://www.gnu.org/prep/standards/html_node/Directory-Variables.html

A: At least for GNU software (using autotools)  you should configure your software with
./configure --prefix=/test

just using (without a specific --prefix to configure before)
make prefix=/test install

usually won't work correctly, because some of the files are builtin for the program so their path becomes a constant inside it.
You could also use make install DESTDIR=/tmp/dest and then copy /tmp/dest to /test but it won't work correctly neither
For example, my /usr/local/bin/emacs binary has /usr/local/share/emacs/24.3.50/lisp as some string (checked with strings /usr/local/bin/emacs command) and the /usr/local/ part of that path is the configure-d prefix.
BTW, you could have a chroot-ed environment to test your applications for various distributions.


text:
Q: Protect a directory with regular Laravel Auth I have a secondary application that drops new folders into my Laravel application on a daily basis. The contents of the folder need to be publicly accessible because they're flash files with a number of assets placed in each day's folder, alongside static .html pages, .jpgs, and .swfs. These links are part of the secondary application's vendor-coded framework.
Moving the files from a non-web accessible folder using php doesn't seem like a good option. I've tried using readfile() and considered .htaccess, but I don't want a secondary login for my users.
Only users who have logins with my Laravel application should have access to these files. Is there some way I can protect access to any request inside this folder with Laravel's Auth system, not basic auth? With the understanding that the page requests inside that folder vary?

A: From extensive searching, I've found that Laravel cannot handle the protection of public folders with static assets. This is a web server configuration issue.
One solution would be to set a cookie that gets read by the web server and bounces the user if the cookie value does not match a predetermined value. But Laravel encrypts cookies and disposes of cookies not encrypted on each load. So that solution would only work if you use App::filter to process the cookie using php setcookie().


text:
Q: Reloading a page won't work after calling a javaScript alert in PHP I have a contact-us page in my site.
When user submits a form it will go to  mailIt.php and do the necessary to send that mail. After sending that it will refresh the code.
Since I wanted to add notification kinda thing to notify the user that the mail has been sent, I changed the code to display a javaScript alert in the page. But after that alert will be shown and the page loading will stop and it will remain in the mailIt.php page (with inout text).
@mail($email_to, $email_subject, $email_message, $headers);
?>
    <script type="text/javascript">
        alert("Thank you for contacting us!");
    </script>
<?php
echo("in");
header('Location: /contact_us.html');
echo("out");

The only part I added is  the,
?>
    <script type="text/javascript">
        alert("Thank you for contacting us. We will be in touch with you very soon !");
    </script>
<?php

Why is this happening ? How can I prevent that ?

A:
Remember that header() must be called before any actual output is sent
  http://php.net/manual/en/function.header.php

You are sending the javascript pop up before you call the header() function.
A solution would be to print the javascript popup and then load the contents of ./contact_us.html and print that to your page, like so:
echo '<script type="text/javascript">
alert("Thank you for contacting us!");
</script>';

$html = file_get_contents('./contact_us.html');
echo $html;

And if you want to be sure the mail has been sent, you should put the mail() function in a if() statement. mail() returns a bool: true if succeeded and false if failed.
if(mail($email_to, $email_subject, $email_message, $headers)){
    echo '<script type="text/javascript">
    alert("Thank you for contacting us!");
    </script>';

    $html = file_get_contents('./contact_us.html');
    echo $html;
}
else{
    echo 'Oops, something went wrong!';
}


text:
Q: javascript typeError: cannot read property of undefined I'm attempting to create a stack class in Javascript, but I keep getting variations of the above error. I know that it is the constructor, but I just can't find where the problem is. Here's my class:

"use strict"

class Stack {
    constuctor() {
        this.items = [];
    }

    emptyArray() {
        if (this.items === 0) {
            this.error = "The stack is empty";
        }
        return this.error;
    }

    isEmpty() {
        return this.items === 0;
    }

    push(x) {
        return this.items.push(x);
    }

    pop() {
        if (this.items >= 1) {
            return this.items.pop();
        }
        else {
            throw new emptyArray();
        }
    }

    size() {
        return this.items.length;
    }

    peak() {
        let el1 = this.items.pop();
        let el2 = this.items.pop();
        this.items.push(el2);
        this.items.push(el1);
        return el2;
    }
}

new Stack().size();

A: constructor is misspelled:
constuctor() {
    this.items = [];
}


text:
Q: Ternary plot - scaling opacity across groups I am trying to make a contour ternary plot, with two groups,
where the opacity (alpha) of the contours is a function of
the density of the points (e.g. more points tightly clustered = less opaque).
I am stuck on one point.
My two groups (here A and B) have unequal group sizes (A = 150 obs, B = 50 obs),
this means points in one group are frequently alot more clustered,
when this is the case the opacity of group B should be much higher relative to
group A, since points in group B are much less dense. But it looks like opacity is scaled within groups instead of across groups.
My Question: is it possible to scale opacity to the density of points, where density is relative across both groups?
An example:
library(ggtern)

set.seed(1234)

# example data
df <- data.frame(X = c(runif(150, 0.7, 1),runif(50, 0, 0.3)),
                 Y = c(runif(150, 0, 0.3),runif(50, 0, 0.3)),
                 Z = c(runif(150, 0, 0.5),runif(50, 0.5, 1)),
                 D = c(rep("A", 150), rep("B", 50)))

# ternary plot
ggtern(df, aes(x = X,y = Y, z = Z, color = D)) +
  stat_density_tern(aes(alpha = ..level.., fill = D),
                    geom = 'polygon',
                    bins = 10,
                    color = "grey") +
  geom_point(alpha = 0.5) +
  scale_colour_manual(values = c("tomato3", "turquoise4"))

# points are only displayed to show densities, I don't plan on showing
# points in the final plot

Given group B points are much less dense I would expect the contours
to be more opaque than group A.
Another option would be to use scale_colour_gradient(), but I can't
see how to get two separate gradients (one for each of A and B) on a
single plot.

A: I wished I would have an easier answer for you, but alas, I have not. However, I've found a quite hacky solution to your problem, by making a new stat and predefining breaks. Disclaimer: I don't use ggtern myself, so I don't know much about the specifics. The problem in general seems to be that the density is computed per group and the integral of densities are generally set to 1. We can solve this by adding a new stat that scales this for us.
The solution then seems deceivingly simple: multiply the calculated densities by the number of datapoints in the group, to get a density scaled to reflects group sizes. The only drawback would be that we have to change bins = 10, which is calculated per group, with breaks = seq(start, end, by = somenumber) to have absolute instead of relative breaks for the contours.
However, ggtern is quite the complicated package with it's own peculiarities that make it difficult to write a new stat function to work. There exists a list with 'approved stats' and ggtern will remove any layers that don't have their approval.
ggtern:::.approvedstat

             identity            confidence          density_tern           smooth_tern
       "StatIdentity"  "StatConfidenceTern"     "StatDensityTern"      "StatSmoothTern"
                  sum                unique      interpolate_tern          mean_ellipse
            "StatSum"          "StatUnique" "StatInterpolateTern"     "StatMeanEllipse"
             hex_tern              tri_tern
        "StatHexTern"         "StatTriTern"

So the first order of business would be to add an entry for our own stat (which we'll call StatDensityTern2) to the approved stat list, but since this .approvedstat is in the package namespace, we'll have to be a bit hacky to do this:
approveupdate <- c(ggtern:::.approvedstat, "density_tern2" = "StatDensityTern2")
assignInNamespace(".approvedstat", approveupdate, pos = "package:ggtern")

Now we can write our own StatDensityTern2, that inherits functionality from StatDensityTern, with a small update in how groups are computed. While writing this new stat, we need to take care that we load necessary packages and refer to internal functions correctly. We'll largely copy-paste from the existing StatDensityTern$compute_group, but make a small adjustment to change z = as.vector(dens$z) to z = as.vector(dens$z) * nrow(data) before passing on the data to the contour function.
library(compositions)
library(rlang)

StatDensityTern2 <-
  ggproto(
    "StatDensityTern2",
    StatDensityTern,
    compute_group = function(
      self, data, scales, na.rm = FALSE, n = 100, h = NULL,
      bdl = 0, bdl.val = NA, contour = TRUE, base = "ilr", expand = 0.5,
      weight = NULL, bins = NULL, binwidth = NULL, breaks = NULL
    ) {
      if (!c(base) %in% c("identity", "ilr"))
        stop("base must be either identity or ilr", call. = FALSE)
      raes = self$required_aes
      data[raes] = suppressWarnings(compositions::acomp(data[raes]))
      data[raes][data[raes] <= bdl] = bdl.val[1]
      data = remove_missing(data, vars = self$required_aes, na.rm = na.rm,
                            name = "StatDensityTern", finite = TRUE)
      if (ggplot2:::empty(data))
        return(data.frame())
      coord = coord_tern()
      f = get(base, mode = "function")
      fInv = get(sprintf("%sInv", base), mode = "function")
      if (base == "identity")
        data = tlr2xy(data, coord, inverse = FALSE, scale = TRUE)
      h = h %||% ggtern:::estimateBandwidth(base, data[which(colnames(data) %in%
                                                      raes)])
      if (length(h) != 2)
        h = rep(h[1], 2)
      if (base != "identity" && diff(h) != 0)
        warning("bandwidth 'h' has different x and y bandwiths for 'ilr', this may (probably will) introduce permutational artifacts depending on the ordering",
                call. = FALSE)
      data[raes[1:2]] = suppressWarnings(f(as.matrix(data[which(colnames(data) %in%
                                                                  raes)])))
      expand = if (length(expand) != 2)
        rep(expand[1], 2)
      else expand
      rngxy = range(c(data$x, data$y))
      rngx = scales:::expand_range(switch(base, identity = coord$limits$x,
                                 rngxy), expand[1])
      rngy = scales:::expand_range(switch(base, identity = coord$limits$y,
                                 rngxy), expand[2])
      dens = ggtern:::kde2d.weighted(data$x, data$y, h = h, n = n, lims = c(rngx,
                                                                   rngy), w = data$weight)

# Here be relevant changes ------------------------------------------------

      df = data.frame(expand.grid(x = dens$x, y = dens$y),
                      z = as.vector(dens$z) * nrow(data),
                      group = data$group[1])

# Here end relevant changes -----------------------------------------------

      if (contour) {
        df = StatContour$compute_panel(df, scales, bins = bins,
                                       binwidth = binwidth, breaks = breaks)
      }
      else {
        names(df) <- c("x", "y", "density", "group")
        df$level <- 1
        df$piece <- 1
      }
      if (base == "identity")
        df = tlr2xy(df, coord, inverse = TRUE, scale = TRUE)
      df[raes] = suppressWarnings(fInv(as.matrix(df[which(colnames(df) %in%
                                                            raes)])))
      df
    }
  )

Now that we've written a new stat and have approved of the stat ourselves, we can use it in the following manner:
set.seed(1234)

# example data
df <- data.frame(X = c(runif(150, 0.7, 1),runif(50, 0, 0.3)),
                 Y = c(runif(150, 0, 0.3),runif(50, 0, 0.3)),
                 Z = c(runif(150, 0, 0.5),runif(50, 0.5, 1)),
                 D = c(rep("A", 150), rep("B", 50)))

ggtern(df, aes(x = X, y = Y, z = Z, color = D)) +
  geom_polygon(aes(alpha = ..level.., fill = D),
               stat = "DensityTern2",
               breaks = seq(10, 150, by = 10),
               color = "grey") +
  geom_point(alpha = 0.5) +
  scale_colour_manual(values = c("tomato3", "turquoise4"))

Which gave me the following plot:

Hope you found this useful!


text:
Q: When to import csv data through php get "?" I am trying to import this csv:
enter image description here
I get the following array:
CSV Object
(
    [columns] => Array
        (
            [0] => numero
            [1] => nombre_pila
            [2] => apellido_1
            [3] => apellido_2
            [4] => direccion
            [5] => localidad
            [6] => codigo_postal
            [7] => provincia
            [8] => nif_pasaport
            [9] => telefono_1
            [10] => movil
            [11] => email
            [12] => fecha_nacimiento
            [13] => codigo_country
            [14] => pais
        )

    [rows] => Array
        (
            [0] => Array
                (
                    [numero] => 1
                    [nombre_pila] => To?o d'angelo
                    [apellido_1] => Iba?ez C?rdenas
                    [apellido_2] => Fuentes
                    [direccion] => C/ Playa de la Jara, n? 200 La carlota
                    [localidad] => La Algaba
                    [codigo_postal] => 8396
                    [provincia] => La Coru?a
                    [nif_pasaport] => 28.612.567-S
                    [telefono_1] => 987654123
                    [movil] => 690864186
                    [email] => jorge43722@gmail.com
                    [fecha_nacimiento] => 4/3/72
                    [codigo_country] => 196
                    [pais] => Espa?a
                )

        )

    [delimiter] => ,
    [closing] => "
)

As you will see, the symbol "?" and it should come out:
[nombre_pila] => Toño d'angelo
[apellido_1] = > Ibañez Cárdenas
[direccion] => C/ Playa de la Jara, nº 200 La carlota
[provincia] => La Coruña
[pais] => España

I am using the following:
Route::get('clients', function(){

    header('Content-Type: text/html; charset=UTF-8');

    $path_to_file = path('public') . '/files/clientes.csv';

    $csv = CSV::from_file($path_to_file, ';');

    echo "<pre>".print_r($csv,true).'</pre>';
});

Where the "from_file" method is as follows:
public static function from_file($path, $delimiter = ',', $enclosure = '"')
    {
        // fix mac csv issue
        ini_set("auto_detect_line_endings", true);

        // open file...
        if ($input = @fopen($path, 'r'))
        {
            $columns = array();
            $rows = array();

            // spin rows...
            $row = 1;
            while ($fields = fgetcsv($input, 0, $delimiter, $enclosure))
            {
                // if first row...
                if ($row === 1)
                {
                    // spin headers...
                    $count = 0;
                    foreach ($fields as $field)
                    {
                        // get column name
                        $name = $field;

                        // check exists...
                        if (in_array($name, $columns))
                        {
                            $count++;
                            $name .= '_'.$count;
                        }

                        // save column name
                        $columns[] = $name;
                    }
                }

                // if NOT first row...
                else
                {
                    // combine
                    $temp = array_combine($columns, $fields);

                    // if no error...
                    if ($temp)
                    {
                        // add to rows
                        $rows[] = $temp;
                    }
                    else
                    {
                        // do not add row
                        #die(var_dump($fields));
                    }
                }
                $row++;
            }

            // close file
            fclose($input);

            // build object
            $class = __CLASS__;
            $object = new $class;
            $object->columns = $columns;
            $object->rows = $rows;
            return $object;
        }
        else
        {
            return false;
        }
    }

I have done everything but I do not get the above, I hope you can help me, thanks.


text:
Q: Pasar datos de javascript a php Estoy intentando pasar algunos datos de un formulario pasándolos por ajax pero por alguna razón a la página que se envían los datos no llega nada. Este es mi código javascript:
        </script>

Y este es mi código php:
<?php
if(isset($_POST['telefono'])){
echo "Llegó";
$nombre=$_POST['nombre'];
$telefono = $_POST['telefono'];
$comentario = $_POST['comentario'];

$resultado = $nombre=$_POST['nombre'] .  $telefono = $_POST['telefono'] .  $comentario = $_POST['comentario'];
$json = json_encode($resultado);
echo $json;
}

else {
    echo "No ha llegado";
}
?>

Agrego además el HTML, este dispara un modal:

        <form id="formUser" name="formUser" method="post"  class="col-md-4 control-label">

             Nombre:
                <input type="text" id="nombre" name="nombre" class="form-control" autofocus>

             Telefono:
                <input type="tel" id="telefono" name="telefono" class="form-control">

             Comentario:

            <textarea  id="comentario" name="comentario" class="form-control" rows="4" cols="5" maxlength="100" placeholder="Agrega información adicional de lo que quieres que hablemos."></textarea>

                <input type="button" id="envio" value="Enviar">
        </form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

El ajax no me lanza ningún error pero al carga la página "form.php" el echo disparado es "No ha llegado".
Yo no veo el error. ¿Qué podría ser?

A: ya entendi tu problema lo que sucede es que cuando el ajax te devuelve la respuesta tu la redireccionas comenta la linea de
location.href ="http://localhost/a/form.php";

y coloca un alert en la funcion sucsess con la variable data asi
alert(data);

asi veras la respuesta que te devuelve tu php


text:
Q: Como setar dados no localStorage Tenho o seguinte código:
$scope.loginUser = function (user) {
    console.log(user);
    $http.post("admin/php/login.php", user).then(function(response){

    if(typeof(Storage) !== "undefined") {
            localStorage.setItem("chave", "valor - algum conteudo aqui");
            var valor = localStorage.getItem("chave");
            console.log(valor);
        } else {
            console.log("Desculpe, mas o navegador nao possui suporte a Web Storage.");
        }
        $window.localStorage.setItem("idUsuarios",idUsuarios);
        $window.localStorage.setItem("nome",nome);
        $window.localStorage.setItem("email",email);

        //console.log(response);
        $location.path('admin/views/painel');

    })
}

Como devo setar os dados para quem fiquem armazenadas em localStorage?
$window.localStorage.setItem("idUsuarios",?);

PHP:
<?php
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$senha = $data->senha;

$sql = mysqli_query($con, "SELECT * FROM usuarios WHERE email='$email' AND senha='$senha' ");

$return = array();

while($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)){
      $return = $row;
}

echo json_encode($return);

A: localStorage grava somente textos, sendo assim é necessário ter a informação em formato texto que pode ser obtido com o JSON.stringify caso necessário.
var test = ["Hello", "World", "Item 3", 5];

if (typeof(Storage) !== "undefined") {

    //Gravando no localStorage
    localStorage.setItem("Teste", JSON.stringify(test));
    //

    //lendo do localStorage
    var itens = JSON.parse(localStorage.getItem("Teste"));
    //

    for (var s of itens) {
      var node = document.createElement("LI");
      node.innerHTML = s;
      document.getElementById("result").appendChild(node);
    };
} else {
    var node = document.createElement("LI");
    node.innerHTML = "'localStorage' Não suportado";
    document.getElementById("result").appendChild(node);
}

Segue exemplo no JSFiddle

A: Primeira coisa adicione uma condição para verificar se o navegador possui suporte, depois utilize o setItem() para inserir um item no localStorage, esta função aceita dois parâmetros, que são chave e valor.
Exemplo:

var id = 1;
var nome = "Gabriel";
var email = "gabriel@gmail.com";
if (typeof(Storage) !== "undefined") {
  localStorage.setItem("id", id);
  localStorage.setItem("nome", nome);
  localStorage.setItem("email", email);
  print("id");
  print("nome");
  print("email");
} else {
  console.log("Desculpe, mas o navegador nao possui suporte a Web Storage.");
}

function print(key) {
  document.getElementById("result").innerHTML += localStorage.getItem(key) + "
";
}

Veja funcionando no jsfiddle


text:
Q: How is the work done to push a planet over 1m with 1N the same as pushing a feather over 1m with 1N? Assume there are no other forces acting and the rocket+fuel described do not weigh anything. Also, by rocket I mean engine/thruster, not space shuttle.
Suppose you have a planet, say of mass 1,000,000,000 kg and you push it with a rocket which exerts a force of 1 N. This will accelerate the planet by $10^{-9}\, m/s^2$.
Then, suppose you have a feather of mass 0.005 kg and push it with the same rocket which exerts a force of 1 N, accelerating it by $200\, m/s^2$.
It follows that the feather will traverse a distance of 1 m much faster than the planet and thus spend much less rocket fuel to do so. So, the energy used to propel the planet must be much more than the energy used to propel the feather.
But, work done = force × distance, $1 \times 1 = 1\, J$ for both the planet and the feather. I think I have misunderstood something. How is this possible?

A: The work done on the planet (or feather) is equal to the change in KE of the planet (or feather). This is the work-energy theorem.
If they start from rest, they will both have the same KE after the 1m of pushing. The planet will have a huge mass and very small speed. The feather small mass and large speed. The KE will be the same.
The way you "produced" the force doing the work does not enter into the work-energy theorem. You can use more or less energy depending of your "machine", the system doing the work. But this does not affect the change in KE of the system your machine does work on.

A:
So, the energy used to propel the planet must be much more than the energy used to propel the feather.

Yes. But that is because the rocket is a special thing. See below.

It follows that the feather will traverse a distance of 1m much faster than the planet [...]

Work is not about duration. It does not depend on time or on how fast. Pushing with 1 N and moving the planet 1 m requires the same work by the force regardless of it taking 1 hour or 1 year or 1000 years.
This might not seem very intuitive at first. If it takes a long time, isn't more energy then spent since the force must be upheld longer?
The answer is no. Think of a table holding up an apple with it's normal force. No energy whatsoever is spent by the table to uphold this force. It can do this forever. Force does not require energy - apart from in specific special "machines".
And that's the thing. The root of your confusion, if I'm right. A rocket propulsion engine (most types of engines to be fair) is such a kind of machine. It takes energy to create the force it exerts. It takes fuel. Fuel is burned at a never-zero rate and so the energy consumption of a rocket does depend on time.
The human body with its contracting and expanding muscle fibres is such a kind of machine as well. Eventually you will get tired of pushing, but the wall doesn't.
When thinking of the work formula $W=\int\vec F\cdot d\vec x$, I like to compare a wall with a balloon (essentially what you are doing, but in a slighty simpler setup):

*

*Pushing on a wall doesn't really make any difference even when pushing hard. Nothing moves. No work is done, you are just wasting your time.

*Pushing on a balloon is easy - it moves far. But it was so easy that no one would say that you did any significant effort. We wouldn't say that you did any significant work to move it.

The first example is your situation.

A: Let's take a Closer Look at the Whole System: It consists of the Planet / Feather (the accelerated object), the engine / thruster, and (and this is important) particles acellerated by the thruster in direction reverse to the pushing force acting on the planet.
Your massless engine, however it works, uses the energy of the massless fuel to accelerate a) The Planet / Feather, and b) some other particles (usualy the burned fuel) in order to satisfy conservation of momentum.
The whole Energy of the System is given by:
$$
E = E_{planet} + E_{burned fuel} + E_{fuel}
$$
The whole momentum is given by
$$
P = P_{planet} + P_{burned fuel}
$$
To make it short: On your one meter acceleration way, the energy that the planet and the feather get are the same. This isn't true however for momentum: The planet will carry more momentum --> There will be more "burned-fuel-particles" carrying more momentum, and thus also carrying more energy. And that's the energy that is missing in your equation. The whole energy of the system will be conserved.
To look at it more detailed:
Force is the time derivative of momentum. The thruster pushing the planet / feather with one 1 N means, that every second there is generated a backward flying "burned-fuel-particle" carrying 1 kg $\frac{m}{s}$ momentum. Since the planet takes (as you noticed) more time to move 1 m, the there will be more particles accellerated backwards. They carry most of the energy that is provided by the fuel.

A: You might find this a bit simplistic, but I just wondered if maybe it helps you if I highlight some basics you may already be aware of...
that work is done to change velocity (accelerate), and an object continues at constant velocity unless work is done to it.
Work achieves a speed, not a distance.  If an object has a non zero speed and no external forces interfere then it will continue to travel until it eventually achieves a great distance.
Compared to the motion subject to friction and air resistance that we typically experience on earth motion in vacuum can intuitively seem "a bit of a freebie". It is indeed cheaper.


text:
Q: Can code stored in a table be used to dynamically fill an unbound textbox in an Access report I have an access table that I want to use to make a dynamic template for building a report. How do I use the values stored in that table in the report? As the programmer, I know how to manually write the code in the report...BUT...I want to store the information in a table instead of hard coding it, to give the USER the ability to modify the template of the report, long after I've gone.
Specifically:

*

*Enter this in table: 1. The person of interest is [First] [Last]

*I will use code to modify the user entered value as: "1. The person of interest is " & [First] & " " & [Last]

*In the Report, I want the unbound textbox to pull the information stored in the table to change the ControlSource so that when the report runs you get the desired outcome: 1. The person of interest is John Doe
I have tried using MyText.ControlSource = [TemplateField], but all this does is makes the report show the contents of the text field. I'm guessing I need to escape the code in some way so that the report reads the items in "[  ]" as code vice text, but I can't figure out how to do that while storing it at the same time.


text:
Q: Determining convergence/divergence of a series All terms are real numbers.
$$c_0+c_1+\cdots+c_{100}=0,\ c_0\neq0$$
$$a_n=c_0\sqrt{n}+c_1\sqrt{n+1}+\cdots+c_{100}\sqrt{n+100}$$
$$b_n=\sqrt[4]{n^3}$$
The question is to determine convergence/divergence of
$$\sum_{n=1}^\infty \frac{a_n}{b_n}.$$
So far I have shown that $\sum_{n=1}^\infty a_n$ is convergent:
\begin{align*}
    \sum_{n=1}^\infty a_n&=(c_0+c_1\sqrt{2}+\cdots+c_{100}\sqrt{101})+(c_0\sqrt{2}+c_1\sqrt{3}+\cdots+c_{100}\sqrt{102})+\cdots\\
    &=c_0+\sqrt{2}(c_0+c_1)+\sqrt{3}(c_0+c_1+c_2)+\cdots+\sqrt{100}(c_0+c_1+\cdots+c_{99})+\sqrt{101}(c_0+c_1+\cdots+c_{100})+\cdots\\
    &=c_0+\sqrt{2}(c_0+c_1)+\sqrt{3}(c_0+c_1+c_2)+\cdots+\sqrt{100}(c_0+c_1+\cdots+c_{99})+(c_0+c_1+\cdots+c_{100})\sum_{n=101}^\infty\sqrt{n}\\
    &=c_0+\sqrt{2}(c_0+c_1)+\sqrt{3}(c_0+c_1+c_2)+\cdots+\sqrt{100}(c_0+c_1+\cdots+c_{99}).
\end{align*}
but I am lost after this since I cannot apply the direct comparison test.
Edit: The rearrangement above doesn't work by Riemann series theorem

A: Hints:

*

*Show that since $b_n = n^{3/4}$, if $|a_n| < C n^{-1/4 - \epsilon}$ for some constant $C$ and $\epsilon > 0$, then the sequence converges.

*Show that $ |a_n | < ( \frac{1}{2} \sum |c_i| ) ( \sqrt{n+100} - \sqrt{n}) < C n^{-1/2}$ for large enough $n$, and some constant $C$.

*Hence, the series converges.


text:
Q: PyQt5 to make subplots (upto 10 graphs) in the same widget I have developed an UI to read large CSV file and plot. The problem is I can only plot one graph at a time. I need to select upto 10 variable and plot it in the same widget.
My UI should look like this
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from PyQt5 import QtCore, QtGui, QtWidgets
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QFileDialog
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as Navi
from matplotlib.figure import Figure
import seaborn as sns
import pandas as pd
import sip # can be installed : pip install sip
from datetime import datetime
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import *
import sys

# We require a canvas class
from mpldatacursor import datacursor
class MatplotlibCanvas(FigureCanvasQTAgg):
    def __init__(self,parent=None, dpi = 120):
        fig = Figure(dpi = dpi)
        self.axes = fig.add_subplot(111)
        super(MatplotlibCanvas,self).__init__(fig)
        fig.tight_layout()

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1440, 1000)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)

        self.label_1 = QtWidgets.QLabel(self.centralwidget)
        self.label_1.setObjectName("label_1")

        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")

        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setObjectName("label_3")

        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)

        self.comboBox_1 = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox_1.setObjectName("comboBox_1")

        self.comboBox_2 = QtWidgets.QComboBox(self.centralwidget)
        self.ComboBox_2 = CheckableComboBox()
        self.comboBox_2.setObjectName("comboBox_2")
        self.comboBox_2.setEditable(True)
        #self.comboBox_2.setFocusPolicy( Qt.StrongFocus )
        #self.comboBox_2.lineEdit().setMaxLength(45)
        #self.comboBox_2.setReadOnly(True)
        #self.comboBox_2.textChanged.connect(self.doSomething)

        self.radioButton = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton.setObjectName("radioButton")

        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)

        self.horizontalLayout.addItem(spacerItem)
        self.horizontalLayout.addWidget(self.label_1)
        self.horizontalLayout.addWidget(self.comboBox_1)
        self.horizontalLayout.addWidget(self.label_2)
        self.horizontalLayout.addWidget(self.comboBox_2)
        self.horizontalLayout.addWidget(self.label_3)
        self.horizontalLayout.addWidget(self.radioButton)

        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout.addItem(self.spacerItem1)
        self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionOpen_csv_file = QtWidgets.QAction(MainWindow)
        self.actionOpen_csv_file.setObjectName("actionOpen_csv_file")
        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.menuFile.addAction(self.actionOpen_csv_file)
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.filename = ''
        self.canv = MatplotlibCanvas(self)
        self.df = []

        self.toolbar = Navi(self.canv,self.centralwidget)
        self.horizontalLayout.addWidget(self.toolbar)

        self.themes = ['bmh', 'classic', 'dark_background', 'fast',
        'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright',
         'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark',
         'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook',
         'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk',
         'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn',
         'Solarize_Light2', 'tableau-colorblind10']

        self.comboBox.addItems(self.themes)
        self.comboBox_1.addItems(['Select horizontal axis here'])
        self.comboBox_2.addItems(['Select vertical axis here'])

        self.pushButton.clicked.connect(self.getFile)
        self.comboBox.currentIndexChanged['QString'].connect(self.Update)
        self.comboBox_1.currentIndexChanged['QString'].connect(self.selectXaxis)
        self.comboBox_2.currentIndexChanged['QString'].connect(self.selectYaxis)
        self.actionExit.triggered.connect(MainWindow.close)
        self.actionOpen_csv_file.triggered.connect(self.getFile)
        self.radioButton.clicked.connect(self.vsAll)
        self.dataset={}
        self.x_axis_slt=None
        self.y_axis_slt=None
        self.vsall = False

    def vsAll(self):
        """
        This function will be called upon triggering the radio check button. If set to True, all the columsn in the csv
        will be plotted against the x-axis column. Please note that vs all means versus all, so that whatever value is
        selected as the x-axis, it wont be plotted against itself in this mode. Moreover, the time series data will be
        dedicated for the datetime x-axis and it wont be displayed in the vs all contents.

        """
        if self.vsall==False:
            self.vsall=True
        else:
            self.vsall=False
        self.Update(self.themes[0])

    def selectXaxis(self,value):
        """
        This function will update the plot according to the data of x axis selected from combo box

        """
        self.x_axis_slt=value
        self.Update(self.themes[0])

    def selectYaxis(self,value):
        """
        This function will update the plot according to the data of y axis selected from combo box

        """
        self.y_axis_slt=value
        self.Update(self.themes[0])

    def Update(self,value):

        """
        This function will input the value of theme and accordingly plot the data, if the data is relative, i.e., x verus y-axis
        then the user can assign x and y axis from the combo box. If all data should be plotted in paraller then leave,
        the combo boxes of axis selections to their default starting location.

        """
        plt.clf()
        plt.style.use(value)
        try:
            self.horizontalLayout.removeWidget(self.toolbar)
            self.verticalLayout.removeWidget(self.canv)

            sip.delete(self.toolbar)
            sip.delete(self.canv)
            self.toolbar = None
            self.canv = None
            self.verticalLayout.removeItem(self.spacerItem1)
        except Exception as e:
            print(e)
            pass
        self.canv = MatplotlibCanvas(self)
        self.toolbar = Navi(self.canv,self.centralwidget)

        self.horizontalLayout.addWidget(self.toolbar)
        self.verticalLayout.addWidget(self.canv)

        self.canv.axes.cla()
        ax = self.canv.axes

        try:

            if self.vsall:
                for k,v in self.dataset.items():

                    if k!=self.x_axis_slt and type(v[0])!=datetime:
                        lines = ax.plot(self.dataset[self.x_axis_slt],v,label=k)
                        datacursor(lines)

                legend = ax.legend()
                legend.set_draggable(True)
                ax.set_xlabel(self.x_axis_slt)
                ax.set_ylabel('ALL OTHERS')
                ax.set_title(self.Title)
                #plt.setp(ax.xaxis.get_majorticklabels(), rotation=25)  # uncomment if you want the x-axis to tilt 25 degree

            else:

                lines = ax.plot(self.dataset[self.x_axis_slt],self.dataset[self.y_axis_slt],label=self.y_axis_slt)
                datacursor(lines)
                legend = ax.legend()
                legend.set_draggable(True)
                ax.set_xlabel(self.x_axis_slt)
                ax.set_ylabel(self.y_axis_slt)
                ax.set_title(self.Title)
                #plt.setp(ax.xaxis.get_majorticklabels(), rotation=25)  # uncomment if you want the x-axis to tilt 25 degree

        except Exception as e:
            print(e)
            try:
                lines = self.df.plot(ax = self.canv.axes)
                datacursor(lines)
                legend = ax.legend()
                legend.set_draggable(True)

                ax.set_xlabel('X axis')
                ax.set_ylabel('Y axis')
                ax.set_title(self.Title)
            except Exception as e:
                print(e)
                pass
            pass

        self.canv.draw()

    def getFile(self):
        """ This function will get the address of the csv file location
            also calls a readData function
        """
        try:
            self.filename = QFileDialog.getOpenFileName(filter = "csv (*.csv)")[0]
            self.readData()
        except Exception as e:
            print(e)
            pass

    def getDataset(self,csvfilename):
        """
        This function will convert csv file to a dictionary of dataset, with keys as the columns' names and
        values as values. The datatime format should be one of the standard datatime formats. Before plottting
        we need to convert the string of data time in the csv file values to datatime format.
        """
        df = pd.read_csv(csvfilename,sep=';')
        LIST_OF_X_COLUMNS = ['Time[s]']
        LIST_OF_Y_COLUMNS = df.columns
        dataset={}
        # time_format = "%d/%m/%Y %H:%M:%S"
        # time_format =  "%m/%d/%Y"
        # time_format = "%d/%m/%Y"
        # time_format = "%m-%d-%Y"
        # time_format = "%d-%m-%Y"
        # time_format = "%H:%M:%S"
        # time_format = "%M:%S"
        # time_format = '%d/%m/%Y %H:%M%f'
        #time_format = '%Y-%m-%d %H:%M:%S.%f'

        for col in LIST_OF_Y_COLUMNS:
            dataset[col]  =  df[col].iloc[0:].values
            try:
                dataset[col] = [datetime.strptime(i) for i in df[col].iloc[0:].values]
            except Exception as e:
                pass
                print(e)
        return dataset, LIST_OF_X_COLUMNS, LIST_OF_Y_COLUMNS

    def readData(self):
        """ This function will read the data using pandas and call the update
            function to plot
        """
        import os
        self.dataset={}
        self.x_axis_slt=None
        self.y_axis_slt=None

        base_name = os.path.basename(self.filename)
        self.Title = os.path.splitext(base_name)[0]

        self.dataset, LIST_OF_X_COLUMNS, LIST_OF_Y_COLUMNS = self.getDataset(self.filename)
        chunksize = 10 ** 6
        self.df = pd.read_csv(self.filename,sep=';',chunksize = chunksize)

        self.Update(self.themes[0]) # lets 0th theme be the default : bmh
        self.comboBox_1.clear()
        #self.comboBox_2.clear()

        self.comboBox_2.addItems(['Select vertical axis here'])
        self.comboBox_1.addItems(LIST_OF_X_COLUMNS)
        self.comboBox_2.addItems(LIST_OF_Y_COLUMNS)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "Select Theme"))
        self.label_1.setText(_translate("MainWindow", "X-axis"))
        self.label_2.setText(_translate("MainWindow", "Y-axis"))
        self.label_3.setText(_translate("MainWindow", "vs all"))
        self.pushButton.setText(_translate("MainWindow", "Open"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.actionOpen_csv_file.setText(_translate("MainWindow", "Open csv file"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))

if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        ui = Ui_MainWindow()
        ui.setupUi(MainWindow)

        MainWindow.show()
        sys.exit(app.exec_())

This is what I have and the output looks like. But, I need to get the output as shown in picture 1.
I'm very new to PyQt5. So, could anyone please help me with this. Thanks in advance.
Output from UI I have develop


text:
Q: Attribute References in Python I do Java programming and recently started learning Python via the official documentation.
I see that we can dynamically add data attributes to an instance object unlike in Java:
class House:
  pass

my_house = House()
my_house.number = 40
my_house.rooms = 8
my_house.garden = 1

My question is, in what situations is this feature used? What are the advantages and disadvantages compared to the way it is done in Java?

A: It can also be used when dynamically creating classes; see for instance this tutorial:
http://onlamp.com/pub/a/python/2003/04/17/metaclasses.html?page=1
or this one on Mix-ins, a programming technique that uses this capability to provide better encapsulation and modularity to object oriented code:
http://www.linuxjournal.com/article/4540
The first tutorial uses setattr(classname, "propertyname", value) instead of the classname.property = value syntax, but they are the same.

A: It's not often done from outside of the class unless the object is being used as a bucket of sorts. It's done an awful lot inside __init__() of course, to provide values to attributes that will be used elsewhere.
Oh, and speaking of Java...


text:
Q: How would I handle saving child objects along with their parent object in JSData? If I had an object
DS.defineResource({
    name : 'parent',
    relations : {
        hasMany : {
            child : {
                localField : 'children',
                foreignKey : 'parentId'
            }
        }
    }
})
DS.bindOne('parent', 1, $scope)

and I make a change to an attribute on a child parent.children[4].name='joey', how can I include that change as part of a save:
$scope.parent.DSSave();

How can I do that?

A: The reason this doesn't work in JSData 2.x is that the relation getters are non-enumerable, and thus aren't picked when the record is serialized and sent to the adapter. You'd have to manually construct the payload to send relations to the adapter:
const payload = {};
Object.keys(parentRecord).forEach((key) => payload[key] = parentRecord[key]);
payload.childRecords = parentRecord.childRecords;
DS.update('parent', parentRecord.id, payload)

In JSData v3 it would be something like this:
store.update('parent', parentRecord.id, { with: ['childRecords'] })


text:
Q: Intent chooser is created exactly three times in UncaughtException I am creating my own UncaughtException behavior. I want to send an email with the report so when the UncaughtException is handled, I want to create a chooser and let the user choose their email client.
When I do this, after calling the Intent, I have to kill the process. But killing the process makes the Intent chooser to be created three times instead of just once. What should I do differently?
public class BaseActivity extends AppCompatActivity implements Thread.UncaughtExceptionHandler {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread thread, Throwable ex) {
    MyLog.w("[BaseActivity]::[uncaughtException]");
    ex.printStackTrace();

    StringWriter errors = new StringWriter();
    ex.printStackTrace(new PrintWriter(errors));
    final String message = errors.toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"my@email.address"});
    intent.putExtra(Intent.EXTRA_SUBJECT, "ERROR: Controller");
    intent.putExtra(Intent.EXTRA_TEXT, message);

    try {
        MyLog.i("[starting chooser]::[%s]",System.currentTimeMillis());
        startActivity(Intent.createChooser(intent, getString(R.string.msg_send_action_msg)));
    } catch (ActivityNotFoundException ex1) {
        Toast.makeText(getApplicationContext(), R.string.msg_err_no_email_client, Toast.LENGTH_LONG).show();
    }

    android.os.Process.killProcess(android.os.Process.myPid());

}

}

A: call finish() after startActivity


text:
Q: Swift Decoding JSON from Amadeus I have a problem with decoding JSON from API.
I get JSON:
{
  "meta": {
    "count": 1,
    "links": {
      "self": "https://test.api.amadeus.com/v1/reference-data/locations?subType=AIRPORT&keyword=barcel&sort=analytics.travelers.score&view=LIGHT&page%5Boffset%5D=0&page%5Blimit%5D=10"
    }
  },
  "data": [
    {
      "type": "location",
      "subType": "AIRPORT",
      "name": "AIRPORT",
      "detailedName": "BARCELONA/ES:AIRPORT",
      "id": "ABCN",
      "self": {
        "href": "https://test.api.amadeus.com/v1/reference-data/locations/ABCN",
        "methods": [
          "GET"
        ]
      },
      "iataCode": "BCN",
      "address": {
        "cityName": "BARCELONA",
        "countryName": "SPAIN"
      }
    }
  ]
}

My code looks like this:
struct Airport: Decodable {
    let meta: MetaAirport
    let data: AirportInfo
}
struct Address: Decodable{
    let countryName: String
    let cityName: String
}

struct AirportInfo: Decodable{

    let address: Address
    let subType: String
    let id: String
    let type: String
     let detailedName: String
     let name: String
     let iataCode: String

}

struct MetaAirport : Decodable{
    let count: Int
    let links: Links
}

struct Links : Decodable{
    let info: String

    private enum CodingKeys : String, CodingKey {
           case info = "self"
       }
}

I'm trying to decode json using JSONDecoder on an AirportInfo object
              do {
                let airport = try JSONDecoder().decode(Airport.self, from: data!)
                    print(airport.data.name)
                }
                catch let err {
                    print(err)
                }

I get an error

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil)], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

What am I doing wrong?

A: In json data, address is a object. Change your code:
let address: [Address] -> let address: Address

A: I see you have edited your question from the original, so it feels hard to correctly identify at a given moment in time where the issue is.
However, Codable is great and one easy way for you to work through it is by constructing your object little by little. There is no requirement for an object to identically represent your JSON IF you make things optional. So when debugging this kind of issues, make different properties optional and see what got parsed. This would allow you to identify little by little where you're doing things wrong, without causing crashes and keeping the correctly formatted parts.
Also, pro tip: If you plan to keep this code for anything more than 1 week, stop using force unwrapping ! and get used to handle optionals correctly. Otherwise this is a hard habit to stop and others will hate the code you've created ;)

A: Your Model should be like that to parse
struct DataModel: Codable {
    let meta: Meta?
    let data: [Datum]?
}

struct Datum: Codable {
    let type, subType, name, detailedName: String?
    let id: String?
    let datumSelf: SelfClass?
    let iataCode: String?
    let address: Address?

    enum CodingKeys: String, CodingKey {
        case type, subType, name, detailedName, id
        case datumSelf = "self"
        case iataCode, address
    }
}

struct Address: Codable {
    let cityName, countryName: String?
}

struct SelfClass: Codable {
    let href: String?
    let methods: [String]?
}

struct Meta: Codable {
    let count: Int?
    let links: Links?
}

struct Links: Codable {
    let linksSelf: String?

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
    }
}


text:
Q: How to plot the graph of this expression which involves Dirac delta function? I was doing a problem on electrostatics which required finding the charge density from the given electric field and then plot a graph of the charge density. I was able to find the charge density which is
$$\rho=\frac {-Ab \epsilon_0}{r^2} \cdot e^{-br}+4 \pi \epsilon_0 A \delta(r)$$
but was not able plot it. When i looked the solution i was not able to understand it.

The reason for my confusion is the point $r=0$ where the left term is minus infinity and the right term is plus infinity. Can any one help me?

A: You are right that the function cannot be plotted, in the sense that your graph cannot stretch all the way to infinity. The behaviour near the origin is such that as $r$ gets smaller the function goes more and more negative as long as $r > 0$, and then it shoots off to $+\infty$ at $r=0$. This is because the singular behaviour of the delta function is sharper than the $1/r^2$ function.
No physical density will really be infinite in practice; the point charge and the Dirac delta function are mathematically convenient ways to deal with a charge whose spatial extent is negligible compared to other distances in the problem.

A:
When i looked the solution i was not able to understand it.

$\let\d=\delta \def\vr{\vec r}$
No wonder. Nobody can understand it. A "$\delta$-function" cannot be plotted, since it is no function. At best you can plot something which "approximates"a $\d$.
But the very "solution" you report is worse. You didn't give us the problem text, and we can only back-engineer it from its solution. However, if the $\d(r)$ is meant to represent a point charge in the origin, it is wrong. It should have been
$\d^{(3)} (\vec r)$.
Can you see the difference? And why $\d^{(3)}(\vr)$ is meaningful, whereas $\d(r)$ is meaningless in present context?


text:
Q: FreeCodeCamp: Iterating Through All an Array's Items Using For Loops I've got this working block of code from the freecodecamp hint
  function filteredArray(arr, elem) {
  let newArr = [...arr];

  for(let i = 0; i < newArr.length; i++) {
    for(let j = 0; j < newArr[i].length; j++) {
      if(newArr[i][j] == elem) {
        newArr.splice(i,1);
        i--;
        break;
      }
    }
  }

  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

I understand most part of it but not
i--;
break;
I really need an explanation as to why i--; break; was used.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops/

A: This is a common question when a developer says, this code is skipping indexes.
You are altering the original array and removing the index. So think about it like a stack of blocks. You remove one, all of the ones above it drop down one.
So you are removing an item with splice, so you need to reduce the index by one so you do not skip over the item that fills in the gap.
A [B] C D E <-- before
   ^
A [C] D E   <-- after

This is why people normally loop from the end to the start to avoid this.