text:
Q: Terminology and intuition about valuation When I first heard the term "valuation", I imagined something like evaluating polynomials in $k[X]$ or functions in $C(\mathbb{R})$ at some fixed point $a$. Valuations in a Dedekind ring $R$ (almost?) correspond bijectively to prime ideals, and I've heard that in modern number theory people think of elements in $R$ as functions on the spectrum $\text{Spec}(R)$, whose points are the prime ideals, so that strengthened by previous belief. However I just realized that the map $e:k[X]\rightarrow k,f(x)\mapsto f(a)$ is far from being a valuation. Here are my questions.

*

*So why do we call them "valuations"? Because of the Dedekind ring example? But very few maps $\text{Spec}(R)\rightarrow\mathbb{Z}$ come from some element in $R$.

*Is there any connection between valuations and the map $f(x)\mapsto f(a)$?

*Another important example of valuation is the map that sends $f(x)=a_nx^n+\cdots+a_kx^k$ (where $a_k\neq 0$) to $k$. Is it still possible to think of this as "valuating a map at some point"?

A: There is in fact a connection between valuations and evaluation maps, in that you can sometimes think of valuations as measuring the "order of vanishing" of a function at a specific point.  For instance, your last example that sends a polynomial $f(x)$ to the exponent on the lowest power of $x$ appearing in it can be thought of as the "order of vanishing" of $f$ at $0$.  This is related to evaluation at $0$ in that the order of vanishing is positive iff $f(0)=0$, and more generally the order of vanishing measures "how strongly" $f(0)$ is $0$.  Similarly, any nonzero prime ideal $p$ in a Dedekind domain $R$ corresponds to a valuation, and that valuation can be thought of as measuring the "order of vanishing" at $p$ when you think of elements of $R$ as functions on $\operatorname{Spec} R$.
From an etymological perspective, though, this connection is entirely coincidental: the term "valuation" is not used because it is similar to "evaluation".  There is really not any particular reason the word "valuation" is used instead of any other and you should not try to read any special meaning into the word.  The way I understand the motivation behind it is that you are sort of assigning a "value" to elements in the sense of somehow measuring their "size" or "how much" of something they have (e.g., how many factors of $p$ they have, for the $p$-adic valuation).  Like much of mathematical terminology, though, the choice of specific word is rather arbitrary.  The notion of a "valuation" is not modeled on evaluation maps and you should not try to understand it as a generalization of evaluation maps.


text:
Q: How to make linked list function return specific class object instead of "Object" in Java? I'm new to java. unvisited and visited are linked lists with elements that are Node class objects, how can I make this method return a Node class object instead of an "Object"? I need to be able to use the output from this function to move onto the next unvisited puzzle state but I can't access the puzzle state within the Node class, and if I try to make the function return a Node it says it's a type mismatch (even though every single element in the list is a Node...). Please help, thank you.
/**
 * Removes last visited puzzle state from unvisited queue and adds it to the visited list.
 * Returns next puzzle state to visit from unvisited queue.
 */
public Object nextState() {
    // if unvisited is empty, return null (no solution)
    if (unvisited.size() == 0) {
        return null;
    }
    // remove visited node from unvisited list & add to beginning of visited list
    visited.addFirst(unvisited.removeFirst());
    // visit next unvisited node
    Object first = unvisited.getFirst();
    return first;
}

A: change the return type of the function to Node instead of object like so
public Node nextState() {
// if unvisited is empty, return null (no solution)
    if (unvisited.size() == 0) {
        return null;
    }
    // remove visited node from unvisited list & add to beginning of visited list
    visited.addFirst(unvisited.removeFirst());
    // visit next unvisited node
    Node first = unvisited.getFirst();
    return first;

A: public Node nextState() {
// if unvisited is empty, return null (no solution)
    if (unvisited.size() == 0) {
        return null;
    }
    // remove visited node from unvisited list & add to beginning of visited list
    visited.addFirst(unvisited.removeFirst());
    // visit next unvisited node
    Object first = unvisited.getFirst();
    if(first instance of Node){
        return (Node) first;
    }
    return null;
}

The problem is your unvisited.getFirst() is returning an object of type Object. So you need to cast it to Node type and return it. 'instance of' is a preventive measure, you can avoid it if you think it always returns an objet of type Node

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to populate an HTML datalist from an array of JSON objects? I'm using React, Node, Express, Postgres. I have a component that is a datalist whose options are to be populated from a database table. My table query returns an array of json objects, and I want to iterate through this array to populate my datalist.
React Component
import React, { Fragment, useState, useEffect } from "react";

const DataList1 = () => {

    const [suppliers, setSuppliers] = useState([]);

    //Search query for list of supplier names and their ids

    const getSuppliers = async () => {
        try {

            const response = await fetch("http://localhost:5000/supplier");
            const jsonData = await response.json();

            setSuppliers(jsonData);
            console.log(jsonData);

        } catch (err) {
            console.log(err.message);
        }
    }

    useEffect(() => {
        getSuppliers();
    }, []);

    return <Fragment>
        <button  className="btn btn-danger" onClick={getSuppliers}></button>

        <label htmlFor="SupplierDatalist">Choose a supplier:</label>
        <input list="SupplierDatalist" id="SupplierDatalist"/>

        <datalist id="SupplierDatalist">
            {suppliers.map(suppliers => (
                <option key={suppliers.supplier_id} value={suppliers.supplier_name} />
            ))}
        </datalist>
    </Fragment>
}

export default DataList1;

And this is how my array looks as an example:
Array(8) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]

0: Object { supplier_id: "2", supplier_name: "Sup1" }

1: Object { supplier_id: "3", supplier_name: "Sup2" }

2: Object { supplier_id: "4", supplier_name: "Sup3" }

...

To add a little context what I'm trying to do here, each datalist selection will need to take as parameter either the id/name to update some other selection

A: You can map through the array and create option for datalist.
<datalist id="SupplierDatalist">
  {suppliers.map(supplier => (
    <option key={supplier.supplier_id} value={supplier.supplier_name} />
  ))}
</datalist>


text:
Q: How to plot polygons on leaflet using R? I have a simple problem that I am facing while in try to plot a SpatialPolygonsDataFrame on top of Leaflet using R. My code is as below:
leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%
    setView(lng = -80.8858673, lat = 41.1450276, zoom = 5) %>%
    addPolygons(data = SPDF, weight = 2, color = ~colorQuantile("red", SPDF$id)(id))

Where SPDF is my SpatialPolygonsDataFrame.
When I execute this code it "PLOTS NOTHING" but only the base map. I have been searching around and this question is similar but it doesn't have this issue.
In order to plot the polygons I have been following this link.
The problem seems to be simple but it has consumed allot of time for me. Looking forward for the suggestions. Thanks for the time.

NOTE: SPDF contains data exported from OSM, which means the coordinates (of POLYGONS) are without the decimal points as it is in the OSM data.

A: Finally, I have been able to figure out the problem myself. The problem is in projections and the CRS (Coordinate Reference System).
Default proj4string was not properly set at the first place and in result of which the coordinates were not realistic (without the decimal point). Therefore, first I set the default proj4string of my SpatialPolygonsDataFrame(SPDF):
SPDF@proj4string <-CRS("+init=epsg:3857")

After setting this I provided the projection as following:
SPDF <- spTransform(SPDF,  CRS("+ellps=WGS84 +proj=longlat +datum=WGS84 +no_defs"))

And now when I execute the following leaflet lines of code, it works perfectly.
leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%
    setView(lng = -80.8858673, lat = 41.1450276, zoom = 5) %>%
    addPolygons(data = SPDF, weight = 2, color = ~colorQuantile("red", SPDF$osm_id)(osm_id))

In order to solve this I followed the discussion on this page.
I hope this works for others who are facing the same problem. Though still I am not an expert of projections and cartography, therefore, it would be great if someone may recommend some necessary information to understand such issues. Thanks all for the time.
PS: Make sure you have included the necessary packages such as leaflet, sp, magrittr etc.


text:
Q: Does autowiring a derived class also ensures the base class is setup? 3 classes Test, Base, Derived
In the Base class I have a a few fields (say A and B) which are Autowired and also a constructor.
In the Derived I have the implementation of the abstract methods.
When I autowire the Derived class in Test will the fields of the Base class (A and B) be setup? Will the constructor of the Base class be called?
Test() {
   @Autowired
   Derived derived;
}

@Component
Base() {
  @Autowired
  A a;
  B b;

  public Base() {
     //Do Something
  }
}

@Service
Derived() extends Base {

}

A: Firstly I'm not a Spring IOC user, I'm a guice IOC user. So if you'll allow me to make some reasonable assumptions about Spring, and assuming your example simply contains some clerical errors
If you had
class Base{
    @Autowired A a;
    @Autowired B b;

    public Base(){
        // doConfigurationOfOtherFields
    }
}

@Service
class Derived extends Base{
    //as per the language spec, if you don't include a constructor
    //one is effectively auto-generated for you.
    //and if you have a superclass it's param-free ctor will be called automatically
    //meaning regardless of whether or not you typed this in source code
    //effectively you get
    Dervied(){
        super();
    }
}

Derived instance = iocContainer.resolve(Derived.class);

Then yes, both a and b instances should be created and set by Spring. and the constructor of Base will be called as the first action taken by the (implicit) Derived constructor.
I do not believe spring will set assign values to a and b before the constructor is called (unless its using obgenisis), so those values will be assigned after the constructor is called.


text:
Q: rails: how to solve that difficult query within rails I have a query for my Rails environment, which I don't really know how to solve...:
I have users and products where any user owns multiple products:

users m:n products

I solved that with a sales table. for any product a user owns there is a more specific table

sales 1:1 individualspecifications

I need to get all the products from a certain user where the individualspecifications are nil...
Thanks in advance
Markus

A: I think you basically want to do this. In your case, it might be something like:
ids = a_user.products.map(&:id)
Products.find(:all, :conditions => ["id not in (?)", ids])

This assumes a user has many products through sales, which you may or may not have defined.

A: The question is a little ambiguous. So this solution is based on my interpretation, and feel free to comment if I got it wrong.
The way I understand your database, you have a many to many relationship between users and products through the sales table. And there is a one to one relationship between sales and individual specifications.
In ActiveRecord terms that means your four models are probably set up like this:
class User < ActiveRecord::Base
  has_many :sales
  has_many :products, :through => sales
end

class Sale < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
  belongs_to :individual_specifications
end

class Product < ActiveRecord::Base
  has_many :sales
  has_many :users, :through => sales
end

class IndividualSpecifcation < ActiveRecord::Base
  has_one :sale
end

With this relationship, you could write a simple named scope in Product to get the job done.
class Product < ActiveRecord::Base
  has_many :sales
  has_many :users, :through => sales

  named_scope :missing_specification, :joins => :sales,
    :conditions => {:sales => {:individual_specification_id => nil}}

end

Now you can just do @user.products.missing_specification to get a list of products that for a certain user that are missing specification.
If I got the has_one/belongs_to relationship between sales and individual specifcation backward then the scope gets a much more complicated:
named_scope :missing_specification,
  :joins => "JOIN sales ON sales.id = products.id " +
     "LEFT OUTER JOIN individual_specifications is ON is.sale_id = sales.id",
  :conditions => "is.id is NULL"


text:
Q: Why are static and dynamic imports in node.js treated differently wrt read-only? Why would node.js 15.4.0 treat static and dynamic imports differently wrt to their read-only behavior?
I have a file test.mjs which reads
let a = {x: 1};
export default a;

When i use this in a dynamic import:
async function run () {
  var m = await import ("./test.mjs");
  m.d=45;
  console.log (m);
}
run();

it complains that the object is not extensible (and this conforms to my reading of the standard that imports provide read-only bindings).
However, when I use this statically as in
import m from './test.mjs';
m.d = 44;
console.log (m);

this works nicely and outputs {x:1, d:44}.
Why does this work? Is this not in violation of the standard?
The question is of particular importance for a design decision to be taken now and I am afraid eventually node would also treat static imports as read-only.

A: The same assignment works for the dynamic import:
(async function() {
  const { default: m } = await import("./test.mjs");
//      ^^^^^^^^^^^^^^
  m.d = 45;
  console.log(m);
})();

You need to add the property to the default-exported object, not to the immutable namespace.
You'd get the same error when using a static namespace import:
import * as m from './test.mjs';
m.d = 44;
//  ^ ReferenceError


text:
Q: Elegant way to set values in a nested json in python I am setting up some values in a nested JSON. In the JSON, it is not necessary that the keys would always be present.
My sample code looks like below.
if 'key' not in data:
    data['key'] = {}
if 'nested_key' not in data['key']:
    data['key']['nested_key'] = some_value

Is there any other elegant way to achieve this? Simply assigning the value without if's like - data['key']['nested_key'] = some_value can sometimes throw KeyError.
I referred multiple similar questions about "getting nested JSON" on StackOverflow but none fulfilled my requirement. So I have added a new question. In case, this is a duplicate question then I'll remove this one once guided towards the right question.
Thanks

A: Please note that, for the insertion you need not check for the key and you can directly add it.  But, defaultdict can be used. It is particularly helpful incase of values like lists.
from collections import defaultdict

data = defaultdict(dict)
data['key']['nested_key'] = some_value

defaultdict will ensure that you will never get a key error. If the key doesn't exist, it returns an empty object of the type with which you have initialized it.
List based example:
from collections import defaultdict

data = defaultdict(list)
data['key'].append(1)

which otherwise will have to be done like below:
data = {}
if 'key' not in data:
    data['key'] = ['1']
else:
    data['key'].append('2')

Example based on existing dict:
from collections import defaultdict

data = {'key1': 'sample'}
data_new = defaultdict(dict,data)
data_new['key']['something'] = 'nothing'

print data_new

Output:
defaultdict(<type 'dict'>, {'key1': 'sample', 'key': {'something': 'nothing'}})

A: You can write in one statement:
data.setdefault('key', {})['nested_value'] = some_value

but I am not sure it looks more elegant.
PS: if you prefer to use defaultdict as proposed by Jay, you can initialize the new dict with the original one returned by json.loads(), then passes it to json.dumps():
data2 = defaultdict(dict, data)
data2['key'] = value
json.dumps(data2)    # print the expected dict


text:
Q: why does my substr not work properly in javascript? I wrote the following code:
var serverTime ="October 01, 2015 18:39:21 +0900";
var timezone = serverTime.substr(serverTime.length-5,serverTime.length-1);
alert(timezone);

and I want to display +09, however in a return I get the full string +0900. Why does my substr function not return the correct value?
http://jsfiddle.net/8ej2kwte/

A: From MDN substr()

str.substr(start[, length])
Parameters
start
Location at which to begin extracting characters. If a negative number
  is given, it is treated as strLength + start where strLength is the
  length of the string (for example, if start is -3 it is treated as
  strLength - 3.)
length Optional.
The number of characters to extract.

With substr, the second parameter is the length of the string to extract, not the end position. So you should be using 3 as the second parameter. Also look into substring() which uses indexes.

A: The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
var serverTime ="October 01, 2015 18:39:21 +0900";
var timezone = serverTime.substr(serverTime.length-5,3);
alert(timezone);


text:
Q: CNN classification input shape The train shape is: (985039, 8) and after reshaping is : (985039, 1, 8)
My code is:
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (train_X.shape[0], train_X.shape[2], 1)))
model.compile(optimizer='adam', loss=['binary_crossentropy'], metrics=['accuracy'])
history = model.fit(train_X, y_train, epochs=7, batch_size=72, validation_data=(test_X, y_test))

Now the error is:

ValueError: Error when checking input: expected conv2d_38_input to have 4 dimensions, but got array with shape (985039, 1, 8)

I changed the input_shape in different ways but not solved.
Can anyone know how to solve?


text:
Q: iReport CSV preview - where does the CSV get saved? I'm running iReport on ubuntu. When I choose the CSV preview from the Build menu and choose Build -> execute (with active connection) a message is displayed in the console saying "Exporting Report". But nothing happens afterwards. Where does the CSV file get saved?
PS:- When choosing JRViewer preview things work fine

A: The files were in the bin directory of the root iReport directory.


text:
Q: How to arrange css priority in ODOO, when installing modules? Odoo version: 9 community
I defined style for "#o_shop_collapse_category li a" but, it's not loading last, the style loaded is the one defined in "/website_sale/static/src/css/website_sale.css".
When I defined my module, it depends of website_sale, so.... my module is installed last, and the css file is defined with last() so my style should be last defined in the website.assets_frontend.0.css
My style is the following:
#o_shop_collapse_category li a{
    border: 1px solid #ccc;
    padding: 6px 4px 6px 20px;
    margin-bottom: 5px;
}

and it is load like this
<template id="celuphone_style" name="Celuphone style" inherit_id="website.assets_frontend">
    <xpath expr="link[last()]" position="after">
        <link rel="stylesheet" href="/client_CELUPHONE/static/less/style.less" type="text/less"/>
    </xpath>
</template>

The question is how Odoo define modules priorities at the time to compile less files
Thanks!

A: Maybe you should just add priority to template definition?
<template id="celuphone_style" name="Celuphone style" inherit_id="website.assets_frontend" priority="999">
    <xpath expr="link[last()]" position="after">
        <link rel="stylesheet" href="/client_CELUPHONE/static/less/style.less" type="text/less"/>
    </xpath>
</template>


text:
Q: Scripting a MySQL query in Unix using daemon in PHP I'm trying to make an "at" job work at a given time, for testing purposes I'm using $time but this will be a datetime that I get from a separate MySQL query.  In the command line I go like this:
echo "mysql -e 'UPDATE admin SET row1=row2 WHERE id=1;'" | at now

And I get a "job 36 at 2010-10-28 15:05".  in PHP I tried going like this:
exec("\"mysql -e 'UPDATE admin SET row1=row2 WHERE id=1'\" | at $time");

But the query doesn't run.  Worse, I have no idea what is happening.
echo exec('whoami');

returns "daemon" though.  How can I echo whatever response I'm getting from the exec command? ideally I guess it would say "job 36 at 2010-10-28 15:05" or something similar.
Also, I have a .my.cnf file in my dir that specifies the db, login and password to use, does the daemon need to have one also for these to work?
[from the answers I can tell I wasn't clear about what I am trying to do.  I need to

*

*A. Run a mySQL query to get a date/time and an id

*B. Schedule an update to take place to rows that match the id at the date/time

I'd already done "A" and was using "1" for the id and "now" for the time while testing.  I'll look into PDO.

A: I'm not that familiar with the at command, but it seems to help run commands at a certain time.
If you're trying to write a scheduled script in PHP there are better ways to do it. Just write a CLI script and use the cron to schedule it. As Svisstack notes, if you're running MySQL queries use an in-built function such as PDO rather than system commands.
If you're just running systems commands, I'm not sure why you're using PHP ;)

A: Are you perhaps in safe_mode? If yes then your | is getting escaped automatically. Per the manual:

With safe mode enabled, the command
  string is escaped with
  escapeshellcmd(). Thus, echo y | echo
  x becomes echo y \| echo x.

A: You can get more information by using the other parameters for the exec command.  Try running this and see the output.
$output = array();
$return = false;
$last_line = exec("\"mysql -e 'UPDATE admin SET row1=row2 WHERE id=1'\" | at now", $output, $return);

var_dump($last_line);
var_dump($output);
var_dump($return);

Also, it looks like when you ran it at the command line, you echo'ed the MySQL command, but when you put it in the PHP code, it's not doing the echo anymore.  I'm not sure if that makes a difference since I'm not to familiar with at, but I thought that I could offer some troubleshooting help.
$last_line = exec("echo \"mysql -e 'UPDATE admin SET row1=row2 WHERE id=1'\" | at now", $output, $return);

A: A missing echo in your second statement / exec? (and I'd rather use popen / proc_open the at $time, and fwrite the command for at to execute (after which you close the input stream, then the program. Use atq to verify wether it worked, and be aware the current use may be disallowed at jobs (normally found in files like /etc/at.allow or /etc/at.deny)


text:
Q: Converting numerical bar (column) graph axis to Text Axis VBA Hi so I wrote this today to create a bar graph based on some data in my sheet but it is treating my column of months as numbers (instead labeling the x axis with 1-12). Is there a way to manipulate it to take the column as text and therefore make the axis "January, February, Etc."
This could also apply to names of binned data I suppose.
'Create Range for Y
   Dim rng1Y As Range, rng2Y As Range
   Dim Y_Range As Range

With ThisWorkbook.Sheets("Graphs")
Set rng1Y = .Cells(1, A + 7)

' Prevents Crashing if no data is in column
    If Cells(1, A + 7) = "" Then

    Else

    Set rng2Y = .Cells(1, A + 7).End(xlDown)

    Set Y_Range = .Range(rng1Y.Address & ":" & rng2Y.Address)
    Y_Range.Select

    End If

'Adds a second Series if needed
If Cells(2, A + 8) = "" Then

Else

 'Create Range for X
    Dim rng1X As Range, rng2X As Range
    Dim X_Range As Range

With ThisWorkbook.Sheets("Graphs")
Set rng1X = .Cells(1, A + 8)

'prevents crashing if no data is in column
If Cells(2, A + 8) = "" Then

Else

Set rng2X = .Cells(1, A + 8).End(xlDown)

Set X_Range = .Range(rng1X.Address & ":" & rng2X.Address)
X_Range.Select

End If

 ' Creates full range for Bar graph
Set Total_Range = .Range(Y_Range.Address & ":" & X_Range.Address)

Total_Range.Select

End With
'-------------------------------------------------------------------------

'Build chart

Dim Sh As Worksheet
Dim chrt As Chart

Set chrt = Nothing
Set Sh = ActiveWorkbook.Worksheets("Graphs")
Set chrt = Sh.Shapes.AddChart.Chart
With chrt

    'Titles
    .HasTitle = True
    .ChartTitle.Characters.Text = Cells(i + 12, 2).Value
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Title Here X"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Title here Y"
    .Axes(xlCategory).HasMajorGridlines = True
    .HasLegend = True

    End With
End If

End With
End Sub


text:
Q: character space of a non unital abelian c*-algebra is locally compact I would like to know why character space of a unital abelian c*-algebra is compact, while the charecter space of a non unital is locally compact.
Why do we add 0 to character space of a non unital one? Why do not we add another point of unit ball A* to character space to make it compact?

A: By the Banach-alaoglu theorem, the character space is a subset of a compact space (the closed unit ball of the dual space). Now suppose that $A$ is not unital, and let $B$ be the standard unitisation of $A$. Then the map which sends the unit in $B$ to 1 and is identically zero on $A$ is a character. This corresponds to the zero character on $A$. The addition of this character gives the one point compactificaton of the character space of $A$.


text:
Q: How to use the geometry package with newlfm documents? I am using the newlfm letter documentclass, and try loading the geometry package. This returns the following error:
! LaTeX Error: Command \geometry already defined.

What I want to do is put more space (margin) between the text and the top of the page. A MWE is provided below:
\documentclass{newlfm}
\usepackage[margin=0mm, top=2mm]{geometry}

\begin{document}
\begin{letter}{Recipient Company\\ Recipient Address}

\opening{Dear Sir or Madam,}

Here goes the letter content

\end{letter}
\end{document}

What am I doing wrong?

A: (Too long for a comment)
From the user guide of the newlfm document class:

geometry is no longer used for dimension setting. Rather, all dimensions are set internally. This is done using a combination of default values, header and footer sizes and values input from the user. These include primarily the page size commands leftmarginsize, textwidthsize and rightmarginsize.

I guess the implication of this passage is that if you're going to use this document class for letters, faxes, and memos, you should try not to use the geometry package and its methods; instead, try using the parameters provided by the newlfm document class directly. Conversely, even though you may be able load the geometry package after all -- see @HarishKumar's answer -- by first undefining the \geometry command, you may find that the page-related parameters won't work the way you might expect them to work in, say, the article document class.
Addendum: Here's a quick example of how you could proceed if you wanted the left and right margins to be 1.5" wide each:
\leftmarginsize{1.5in}
\rightmarginsize{1.5in}

The text block's width would then be calculated as <paperwidth>-2*1.5"; if the paper happens to be "US Letter"-size (8.5"x11"), the text block would end up being 5.5" wide. Other page-related parameters will, in general, be determined by the options you provide as arguments to the \documentclass[...]{newlfm} command.

A: The command \geometry, it seems, is already defined by the class  newflm. If you do not want that default page setting put
\let\geometry\relax

just below \documentclass{newlfm}
Your file becomes:
\documentclass{newlfm}
\let\geometry\relax
\usepackage[margin=0mm, top=2mm]{geometry}

\begin{document}
\begin{letter}{Recipient Company\\ Recipient Address}

\opening{Dear Sir or Madam,}

Here goes the letter content

\end{letter}
\end{document}

Update Ignoring the commands defined by the document class will certainly cause trouble at some point of time (Agreeing with @Mico). Hence it is always better to use these commands. This MWE shows how to play with different margins using the built-in commands of the newlfm class itself.
\documentclass[a4paper]{newlfm}
%% to change margins-----------------------
\leftmarginsize{0in}
\rightmarginsize{0in}
\topmarginsize{2mm}
\topmarginskip{0in}
\headermarginsize{0in}
\headermarginskip{0in}
%%-----------------------------------------
\usepackage{lipsum} %% to add dummy text
%%-----------------------------------------
\nameto{George Bush} \addrto{\parbox{2in}{The White House \\ Washington, DC}}
\namefrom{Paul Thompson} \addrfrom{\parbox{2in}{The Pink House \\ Belleville, IL}}
%%-----------------------------------------
\begin{document}
\closeline{Sincerely yours,} \greetto{Dear Mr. Bush,}
\begin{newlfm}
How are the azaleas?

\lipsum[5]
\end{newlfm}
\end{document}

For more details one may run texdoc newlfm from from the command prompt and the details of these lengths can be found in page 8 of the manual. I am attaching a screen shot of the same.


text:
Q: Automatically go to a Class in eclipse from Instance Is there a way to automatically go to a Class in eclipse from an instance of it.
Foo foo = new Foo();
// lots of lines of code
foo.some();   // from foo I want to go to the Class Foo direcly with a key press.

I received some answers but that is not what I was looking for. Sometime I don't call a method, I just have reference foo only, e.g when calling other method :
method(foo, bar);

A: Hold down control and click on the class name.
You can also go to specific methods from method calls by using the "Open Declaration" functionality. So hold down control and click on some() and it will take you to that method's declaration in the Foo class. (Or hit F3, or right-click and choose "Open Declaration.")
Or you can use the constructor in the line: Foo foo = new Foo(); to jump to the class' constructor, which will also take you to the class.

A: You can ctrl-click on the variable name and you get to the variable declaration. And then you can ctrl-click on the type to get to the class definition.


text:
Q: Voltage present, even without fuse in DC distribution panel I have an AC and DC distribution panel installed in my cargo trailer. And I think I have an issue with my DC side of the panel.
This is my first electrical work of any sort and thought it was going well until I checked voltage at the end of one of my circuits. I had 12v.  But no fuses in the distribution panel. I was expecting nothing.  I did wire up a small LED light and there was a faint amount of light coming from it.  If I put in the fuse, LED lights up with the expected brightness.
Are my expectations about having no voltage incorrect?
If they aren't incorrect, what are some troubleshooting steps I should start with?
The specific panel I am using is a Arterra WF-8930/50NPB Black RV Generator and Component (Distribution Center 30 Or 50 Amp Ac Service - 15 Dc Circuits -) and the manual is here.

A: Wait, it's on the DC or AC panel?
On the AC panel it would be normal to have a voltage (in a no-load condition) due to capacitive coupling, even if the breakers were open.
You could measure that voltage with a multimeter and it would be usually a small fraction of the full voltage, but possibly approaching the full voltage depending on the situation.
However, as soon as any load was plugged in this voltage would disappear.
But you said it was on the DC side and you said "fuses", so you're talking about the DC side only, right?
Cause there's no capacitive coupling for DC.
Then something else is happening.

A: The manual states that the panel has "blown fuse indicators" - red LEDs that will light when the fuse is blown.
The simplest way to do this is to connect an LED and current-limiting resistor in parallel with the fuse.  With a blown fuse (or no fuse) this would allow a small current to flow in the circuit - probably enough to light your test light dimly.


text:
Q: Setting state of javascript function not saving I am trying to create a new function, MyNs.MyObj(), call a method on it that modifies a 'private' variable, 'prop1', and the next time I access the public accessor, 'Prop1' that it retrieves the saved variable.
After running the below code, the output is still, '2' (the initial value).  Can someone help me understand why calling the Method function does not udpate the Prop1 variable the way I expect?
var MyNs = MyNs || {};

(function( o ){
    o.MyObj = function (options) {
        var prop1 = options;

        var obj = {
            Prop1: prop1,
            Method: function() {
                prop1 = "abc";
            }
        };

        return obj;
    };
})(MyNs);

var s = new MyNs.MyObj(2);
s.Method();

console.log(s.Prop1);

A: When you do this
var prop1 = options;

var obj = {
    Prop1: prop1
};

You've set Prop1 to the value of prop1 at that time, changing prop1 later will not update Prop1.
You can easily test this with something like
var a = 'abc'; // set a value on 'a'
var b = a;     // set 'b' to equal 'a', as it's a string, it's passed directly

a = 'bca';     // set a new value for 'a'

alert(b);      // still outputs 'abc'

FIDDLE
This means you have to update the property, not the variable, and you'd do that like so
var MyNs = MyNs || {};

(function( o ){
    o.MyObj = function (options) {
        var prop1 = options;

        var obj = {
            Prop1: prop1,
            Method: function() {
                this.Prop1 = "abc";
            }
        };

        return obj;
    };
})(MyNs);

var s = new MyNs.MyObj(2);
s.Method();

console.log(s.Prop1);

FIDDLE


text:
Q: C++ templates and runtime I want to create a template factory class such that given an int i, it will create an instance of the i'th class in its parameter list; and i has to be a runtime variable.  The idea starts as follows: Let's say we have types A, B. We can create the class below easily:
class factory{
  void* create(size_t i) {
    return (i==0) new A() : (i==1 ? new B() :nullptr);
  }
};

We have to use void* as return type but this works.  Now how can we expand it with templates such that we can do:
auto f = factory<A,B,C,D,E,F>();
A* a = f.create(0);
E* e = f.create(4);

I've already spent a solid 10 hours on this and came up with a solution that works if i is known at compile time.  Here it is:
template <size_t i, class first, class... rest>
struct choose: public choose<i - 1, rest...> {};

template <class first, class... rest>
struct choose<0, first, rest...> {
    using type = first;
};

template<class... cls>
class factory {
public:
    template <size_t j, typename... ArgTypes>
    inline typename choose<j, cls...>::type* create(ArgTypes... args) {
        using f = typename choose<j, cls...>::type;
        return new f(args...);
    }
};

The problem is that variable j needs to be known at compile time, which is not something I want.
I also don't want to create the objects, put them into an array and then just get it from the array. I understand that would make my pain go away, but the purpose of this exercise is to learn templates.

The Context of this code is for a simple web framework I am making using c++.  I want to have Controller classes and an Application class:
class Controller {
   virtual get(params) =0;
   virtual post(params) =0;
};
class ControllerA: Controller {
public:
   constexpr static char route[] = "/home";  //this controller handles this route
   // virtual implementation
};
class ControllerB: Controller {
public:
   constexpr static char route[] = "/user";
   // virtual implementation
};

template<class... controllers>
class Application {
  factory<controllers...> f;
public:
  Application() {
    //create router and give it all of the routes from the controllers in the template.
  }
  dispatchPostRequest(request) {
    int i = doRounting(request.route); //router returns a number that specifies the
    //index of controller in the template parameter pack.
    f.create(i) -> post()
  }
};

To me this seems like a simple concept. Java/JS/Python implementation would have taken me 20 minutes each.  I do not understand why I'm having such a tough time with it in C++.

A: You should specify the function with <typename HEAD, typename... TAIL>. This may be a private function that is used as an utility:
template<class... cls>
class factory {
private:
    template <typename Head, typename... Tail>
    void* create_impl(size_t i) {
        if (i == 0)
            return new Head;
        else
            return create_impl<Tail...>(i - 1);
    }
public:
    void* create(size_t i) {
        return create_impl<cls...>(i);
    }
};

So you have a runtime parameter i plus compile time template arguments Head and 'Tail'. Tail is a variadic. Whenever the runtime parameter is 0, you retuen Head. Otherwise you employ recursion.
I'm using void* for simplicity, you may have a more complicated hierarchy.
Upd.
Ok, another approach on top of the first one. You may implement a function that should be called once, and that would create a table of other functions that should be called based on the index.
template<class... cls>
class factory {
private:
    template <typename Head, typename... Tail>
    void* create_impl(size_t i) {
        if (i == 0)
            return new Head;
        else
            return create_impl<Tail...>(i - 1);
    }

    function<void*()> make_func(size_t i) {
        return make_func_impl(i);
    }

    template <typename Head, typename... Tail>
    function<void*()> make_func_impl(size_t i) {
        if (i == 0)
            return create<Head>;
        else
            return make_func_impl<Tail...>(i - 1);
    }

    template <typename Class>
    Class* create() {
        return new Class;
    }

    vector<function<void*()>> m_table;
public:
    factory() {
        m_table.reserve(sizeof...(cls));
        for (int i = 0; i < sizeof...(cls); ++i) {
            m_table[i] = make_func(i);
        }
    }

    void* create(size_t i) {
        return m_table[i]();
    }
};

This still may require linear recursion, but this will be performed once. You may use m_table as a precomputed table of functions based on runtime index.

A:
I also don't want to create the objects, put them into an array [...]

That can be the basis for a possible solution; though you won't add objects into that array, but creator functions.
However already your very simple piece of code showed up a memory leak:
f.create(i) -> post();

When gets the object deleted again??? So make the creator functions safe by returning a smart pointer!
Going via void* is never safe either (apart from preventing smart pointers – you cannot delete void pointers!), you can just far too easily apply a bad cast then:
std::string* s = static_cast<std::string*>(create<std::string, std::complex<double>, std::vector<int>>(1));

See the problem? But with your Controller base class, you have already all the necessary infrastructure you need to keep that factory function (or class) safe! So a possible solution might look like this:
template <typename T>
std::unique_ptr<Controller> makeT()
{
    return std::make_unique<T>();
}

template <typename ... Types>
std::unique_ptr<Controller> create(size_t index)
{
    static std::unique_ptr<Controller>(*creators[])() =
#if 0
    { &std::make_unique<Types> ... };
#else
    { &makeT<Types>... };
#endif
    return creators[index]();
}

Unfortunately, we cannot use std::make_unique directly, as each instantiation has a different return type (of unique_ptr of the specific class!), thus we get incompatible pointers. So we need that intermediate function...
Due to smart pointer (avoiding the necessity for explicit deletion) and polymorphism (avoiding the need for correct cast), the call above now is safe.

A: I came up with this two liner too:
template <class... cls>
Controller* (*creator_array[sizeof...(cls)])() = {[]{return dynamic_cast<Controller*>(new cls());}...};

It creates an array of creator functions, similar to the answer above. So you can do:
Controller* (*arr[2])() = creator_array<ControllerA, ControllerB>;
arr[0]() //creates new ControllerA
arr[1]() //create new ControllerB


text:
Q: How to make this discriminated union work? Trying to create a simple table component, but having a bit of trouble with making the typings work as I want.
TL;DR How do write the type for Column3 in this Playground Link so that the 2 errors go away?
This works
So given the following common stuff:
type Data = { id: number, name: string };
const data: Data[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
]

type Header = { header: string };

Here's a variant that makes you supply a typesafe field name, and optionally a formatting function for the value of that field:
type Value1<Row> = {
  [Key in keyof Row]: {
    field: Key;
    format?: (value: Row[Key]) => string;
  };
}[keyof Row];

type Column1<Row> = Header & Value1<Row>;

const makeTable = <R>(r: R[], c: Column1<R>[]) => {}
makeTable(data, [
  { header: 'Id', field: 'id' },
  { header: 'Name', field: 'name', format: value => value.toUpperCase() },
])

Here's a variant that makes you only supply a formatting function, and instead of a value you get the row object:
type Value2<Row> = {
  format: (row: Row) => string;
};

type Column2<Row> = Header & Value2<Row>;

const makeTable = <R>(r: R[], c: Column2<R>[]) => {};
makeTable(data, [
  { header: 'Id', format: row => row.id.toString() },
  { header: 'Name', format: row => row.name.toUpperCase() },
])

This does not...
The issue comes when I would like to combine these two, because for some columns the first variant makes sense, and for others the second one does.
I figured I could do it as follows, but Typescript is not happy...
type Column3<Row> = Header & (Value1<Row> | Value2<Row>); // <-- Non-working discriminated union?

const makeTable = <R>(r: R[], c: Column3<R>[]) => { };
makeTable(data, [
  { header: 'Id', field: 'id' },
  { header: 'Name', field: 'name', format: value => value.toUpperCase() },
  { header: 'Test', format: row => `${row.id} : ${row.name}` },
])

Apparently the type of data is now incorrect, and also that row in the third column for some reason is implicitly any, which it of course shouldn't be.
I can "fix" the type of data by being explicit about the generic Row type:
makeTable<Data>(data, [
  { header: 'Id', field: 'id' },
  { header: 'Name', field: 'name', format: value => value.toUpperCase() },
  { header: 'Test', format: row => `${row.id} : ${row.name}` },
])

But row is still implicitly any, and it really shouldn't be necessary to be explicit here, so something is definitely not right here... but... I don't understand what's going on here.
What am I misunderstanding here?

A: So, let's chalk the wrong type on data up to generic default types (because Row is never defined as an actual type, I think Typescript defaults it to string at some point for purposes of type resolution (I may be wrong on this)).
The type of row being any in the format functions is due to Typescript not inferring types for function arguments.  That thread has a lot of good discussion as to why.  In fact, at one point in the discussion, it is mentioned that

there's nothing in TypeScript today that infers information about a variable from its usage.

For a short example of the complexities that can develop, what is the type of row in  z.format?
type t = { format: (row: string) => string } | { format: (row: number) => number }
const z: t = {format: row => row }

Without additional annotation during usage:
const z: t = {format: (row: number) => row}

The compiler cannot easily tell what shape row is supposed to be.  Unfortunately, this forces us to be explicit at times that we wouldn't expect to have to be.
To 'fix' the type for Column3, you just have to be a little more explicit in your usage:
type Column3<Row> = Header & (Value1<Row> | Value2<Row>);
type R = Data
(<R>(r: R[], c: Column3<R>[]) => {})(data, [
  { header: 'Id', field: 'id' },
  { header: 'Name', field: 'name', format: value => value.toUpperCase() },
  { header: 'Test', format: (row: R) => `${row.id} : ${row.name}` },
])

A: Format is ambigeous as defined in both Value1 and Value2
The compiler cannot tell row's type between Row[Key] //Value1 and Row //Value2
I suggest you to switch the format of both Value1 and Value2 :
type Value1<Row> = {
  [Key in keyof Row]: {
    field: Key;
    format_field?: (value: Row[Key]) => string;
  };
}[keyof Row];

type Value2<Row> = {
  format_row: (row: Row) => string;
};

(<R>(r: R[], c: Column3<R>[]) => {})<Data>(data, [
  { header: 'Id', field: 'id' },
  { header: 'Name', field: 'name', format_field: value => value.toUpperCase() },
  { header: 'Test', format_row: row => `${row.id} : ${row.name}` },
]) //No more ambigeous


text:
Q: What happen to this v-for directive I wanted to make some object like below

So, at first I wrote code below

    <button class="text-white w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-yellow-400 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-orange-400 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-green-800 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-sky-500 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-red-500 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-purple-600 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-gray-300 w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>
    <button class="text-black w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue"></button>

But, yes.. it's not efficient. So, I thought I can use v-for directive to make this code simply. like below.
in template

    <button v-for="level in LevelList" :key="level" :class="`text-${level} w-7 border-2 border-BgLightBlue rounded-full hover:border-primary hover:bg-BgLightBlue`"></button>

in script
export default {
    setup() {

        const LevelList = ['white', 'yellow-400', 'orange-400', 'green-800', 'sky-500', 'red-500', 'purple-600', 'gray-300', 'black']

        return {
            LevelList,
        }
    }
}

However, result was no same. after wrote code, when I activated 'npm run dev' the result show like below.

what am I missing something?

A: by analyzing it seems like this problem is happening with all element of LevelList which have dash in their name.
it might be possible that javascript is treating for example yellow-400 as arithmetic expression (value of yellow) - 400 rather than a simple string
try renaming your multi-word elements and see if it works out !


text:
Q: Where clause with conditionals in stored procedure I have the following query in my stored procedure (SQL Server):
SELECT
    ea.attendanceid,
    ea.employeeid,

    FROM employee_attendance ea

    WHERE
    ea.masterentity = @masterentity
    AND ea.employeeid = @employeeid

    -- here I need to know what value @type is and then create my conditionals
    AND (ISNULL(@type,'') = '' OR
        .......

My parameter @type has diferent string values:

*

*IL = Internal Lunch

*EL = External Lunch

*L = All Lunch

*N = Only Normal

*R = Especial

And depending on the value is the column that I have to filter:
If `@type='IL'` then I have to filter: `AND ea.lunchtype = 'C'`
If `@type='EL'` then I have to filter: `AND ea.lunchtype = 'CI'`
If `@type='L'` then I have to filter: `AND ea.islunch = 1`
If `@type='N'` then I have to filter: `AND ea.islunch = 0`
If `@type='R'` then I have to filter: `AND (ea.ismanual = 1 AND ea.lunchtype = 'K')`

Any clue on how to accomplish this?

A: You need to translate into SQL in the similar way
AND (
ISNULL(@type, ' ') = ' '
OR ( @type='IL' AND ea.lunchtype = 'C' )
OR ( @type='EL' AND ea.lunchtype = 'CI' )
OR (@type='L' AND ea.islunch = 1   )
OR (@type='N' AND ea.islunch = 0    )
OR (@type='R'  AND (ea.ismanual = 1 AND ea.lunchtype = 'K')
)
)

A: Use a CASE statement.
CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.
MSDN CASE (Transact-SQL)
Refer to the examples on this page on howto.


text:
Q: I cannot delete div element using filter() in React I was able to add div element  with delete button. I want to delete each div element when I click the delete button.
How can I achieve this, I used the filter method but still missing something
import React, {useState, useEffect} from "react";

function App() {
  const [task, setTask] = useState("")
  const [errorMessage, setErrorMessage] = useState("")
  const [todos, setTodos] = useState([])

  function createTodo(){
    if(todos.find(todo => todo["name"] === task)){
      setErrorMessage(`${task} already exists`)
      return true;
    }
    else {
      setTodos(oldTodos => {
        return [...oldTodos, {"name":task, "id": oldTodos.length}]
      })
      setTask("");
      return false;
    }

      //console.log(`Task Value: ${task}`)
  }

  //delete task
  function deleteTask(taskID){
      setTodos(oldTodos =>  oldTodos.filter(todo => todo !==taskID))
      //console.log(taskID);
  }
  return (

This is the Best ToDO app Ever

      <input type="text" value={task} onChange={event => {setTask(event.target.value)
      }}
      onKeyPress={(ev) => {
        if (ev.key === "Enter") {
          ev.preventDefault();
          createTodo();
        }
      }}
      />
       <button onClick={createTodo}> Create Todo </button>

            {todos.map(todo => {
                return  <div key={`${todo["name"]}-${todo["id"]}`}>

{todo["name"]}

                <button onClick={() => deleteTask(todo["id"])}>Delete</button>

            })}

          {errorMessage}

  )
}

export default App;

A: You are equaling a string to a number, so it will never be true. Use this:
setTodos(oldTodos =>  oldTodos.filter(todo => todo.id !== taskID))


text:
Q: Console.ReadKey() produces Exception I have created a Windows Forms Application. In special situations, I open a Console-Window with
    public static void CreateConsole() {
        AllocConsole();
    }

    [DllImport("kernel32")]
    private static extern bool AllocConsole();

When I after call Console.ReadKey() i get an InvalidOperationException:
Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
When I use Console.Read() it will not work. No keystroke is recognized.
Can someone help me, whats the problem here? Thank you.

A: As you might see, your output goes to Visual Studio console, not opened one. To fix that issue you need to reopen console output stream:
if (AllocConsole())
{
    var outHandle = CreateFile("CONOUT$",
        (uint)(FileConsts.FILE_GENERIC_WRITE | FileConsts.FILE_GENERIC_READ),
        (uint)(FileConsts.FILE_SHARE_WRITE | FileConsts.FILE_SHARE_READ),
        0,
        FileConsts.OPEN_EXISTING,
        FileConsts.FILE_ATTRIBUTE_NORMAL, 0);

    var inHandle = CreateFile("CONIN$",
        (uint)(FileConsts.FILE_GENERIC_WRITE | FileConsts.FILE_GENERIC_READ),
        (uint)(FileConsts.FILE_SHARE_WRITE | FileConsts.FILE_SHARE_READ),
        0,
        FileConsts.OPEN_EXISTING,
        FileConsts.FILE_ATTRIBUTE_NORMAL, 0);

    if (!SetStdHandle(STD_OUTPUT_HANDLE, outHandle))
        throw new Exception("Can't set std handle");

    if (!SetStdHandle(STD_INPUT_HANDLE, inHandle))
        throw new Exception("Can't set std handle");

    //Just for handle .Dispose();
    var fileStream = new FileStream(new SafeFileHandle(outHandle, true), FileAccess.Write);
    var fileStreamRead = new FileStream(new SafeFileHandle(inHandle, true), FileAccess.Read);

    ConsoleKey read;
    while ((read = Console.ReadKey().Key) != ConsoleKey.Escape)
    {
        Console.WriteLine($"Printed {read}");
    }

    Console.WriteLine("Escape Pressed, exiting");

    SetStdHandle(STD_INPUT_HANDLE, IntPtr.Zero);
    SetStdHandle(STD_OUTPUT_HANDLE, IntPtr.Zero);
    fileStream.Dispose();
    fileStreamRead.Dispose();
    FreeConsole();
}

Note, that new FileStream("CONOUT$", ...) and Console.OpenStandardInput() won't work.
I've just tested it with Windows.Forms application. Console.ReadKey works correctly for me.
Create file and constants is from kernel32.dll


text:
Q: Which is the correct usage - " the line is breaking off " or " the line is breaking up"? When you are having a conversation over the phone and the voice keeps getting cut off because of poor signal strength, what is the appropriate term for it?

A: When the other person's voice is affected by poor signal, we use 'the line is breaking up'.
If the the call is unintentionally ended because of poor signal, we use 'the line has cut off' (you could say 'the line has broken off', but idiomatically it's better to use 'cut off').
It may be helpful to think about an actual line, drawn on a piece of paper. If the line is 'breaking up', there are still little pieces of the line left, because we are in the process of breaking. If the line has 'broken off', then the process of breaking is completed - the line has reached a premature end and there are no more pieces left.


text:
Q: Using data from WorkbookQuery directly in vba I have an existing data connection in my excel work book.
I have come across code that can query against that data connection while loading it to a worksheet:
With currentSheet.ListObjects.Add(SourceType:=0, Source:= _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _
        , Destination:=Range("$A$1")).QueryTable
        .CommandType = xlCmdDefault
        .CommandText = Array("SELECT * FROM [" & query.Name & "]")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = False
        .Refresh BackgroundQuery:=False
    End With

source https://gallery.technet.microsoft.com/office/VBA-to-automate-Power-956a52d1
via How to automate a power query in VBA?
And also this from the same source, which is essentially the same thing:
Sub LoadToWorksheetAndModel(query As WorkbookQuery, currentSheet As Worksheet)
    ' Let's load the query to the Data Model
    LoadToDataModel query

    ' Now we can load the data to the worksheet
    With currentSheet.ListObjects.Add(SourceType:=4, Source:=ActiveWorkbook. _
        Connections("Query - " & query.Name), Destination:=Range("$A$1")).TableObject
        .RowNumbers = False
        .PreserveFormatting = True
        .PreserveColumnInfo = False
        .AdjustColumnWidth = True
        .RefreshStyle = 1
        .ListObject.DisplayName = Replace(query.Name, " ", "_") & "_ListObject"
        .Refresh
    End With
End Sub

Sub LoadToDataModel(query As WorkbookQuery)

    ' This code loads the query to the Data Model
    ThisWorkbook.Connections.Add2 "Query - " & query.Name, _
        "Connection to the '" & query.Name & "' query in the workbook.", _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _
        , """" & query.Name & """", 6, True, False

End Sub

But this loads the data to a worksheet, rather than keeping the data in a VBA object.
I would like to efficiently query against this connection and load the result to a variable for further use in VBA without it ever touching a worksheet.
Specifically, I would like to be able to do things like pull all unique values from a column in the data connection into a variable. And I would like to further filter the data in the connection before writing it to a worksheet (while preserving the original data so it can be re-queried).


text:
Q: errno: 34, code: 'ENOENT' I tried to run my project , but it gave me the ENOENT error somewhere along the way. Yes I have looked at this similar question, but its solution doesn't work for me.
PROJECTS.JS::CREATED 542a78fcaa50f4260d1e52a5
{ [Error: ENOENT, mkdir '/home/haint/avs3_tmp/html5-videoEditor-master/modules/..                      /public/projects/ca62a6012db5454fb0ba41d35f61afe6']
errno: 34,
code: 'ENOENT',
path: '/home/haint/avs3_tmp/html5-videoEditor-master/modules/../public/projects                    /ca62a6012db5454fb0ba41d35f61afe6' }
{ [Error: ENOENT, mkdir '/home/haint/avs3_tmp/html5-videoEditor-master/modules/..                /public/projects/ca62a6012db5454fb0ba41d35f61afe6/assets/']
errno: 34,
code: 'ENOENT',
path: '/home/haint/avs3_tmp/html5-videoEditor-master/modules/../public/projects                /ca62a6012db5454fb0ba41d35f61afe6/assets/' }
{ [Error: ENOENT, mkdir '/home/haint/avs3_tmp/html5-videoEditor-master/modules/..                /public/projects/ca62a6012db5454fb0ba41d35f61afe6/compositions/']
errno: 34,
code: 'ENOENT',
path: '/home/haint/avs3_tmp/html5-videoEditor-master/modules/../public/projects                /ca62a6012db5454fb0ba41d35f61afe6/compositions/' }
PROJECTS.JS::FOUND 542a78fcaa50f4260d1e52a5
PROJECTS.JS::LIBRARY SERVED WITH 0 ASSETS
PROJECTS.JS::COMPOSITIONS SERVED WITH 0 COMPS.

how can i fix it

A: Check your path. If you were making multiple levels of directories, you will usually get this.
For example. if you need to mkdir('public/projects'), make sure you mkdir('public') first then mkdir('public/projects')
Just some sample scripts to demo:

var fs = require('fs');

var f = '/css/colors';

var dirs = f.split('/');

var newDir = __dirname;

for (var i = 0; i < dirs.length; i++) {
  newDir += dirs[i] + '/';
  console.log(newDir);

  if (!fs.exists(newDir)) {
    fs.mkdir(newDir, function(error) {
      console.log(error);
    })
  }
}

A: Probably you are on the wrong path.
picture the follow path:

/git/react/my-react-app

if you are on the react folder and try to run a npm start to start up your application, it will prompt an ENOENT.


text:
Q: Recyclerview selected view null on Scroll I apply own logic on single select item on recyclerview. when i select item and scroll to last position and select new item and remove background last selected  item then shows error

java.lang.NullPointerException: Attempt to read from field 'android.view.View android.support.v7.widget.RecyclerView$ViewHolder.itemView' on a null object reference

My logic is:
recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(SubServicesActivity.this, recyclerViewSubServices ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {

                        String selectedName = serviceLists.get(position).getServiceTitleEnglish();

                        RecyclerView.ViewHolder viewHolder = recyclerViewSubServices.findViewHolderForPosition(position);
                        FrameLayout serviceImageBackground = (FrameLayout) viewHolder.itemView.findViewById(R.id.image_back_layout);

                        if(!select) {
                            serviceImageBackground.setBackground(getResources().getDrawable(R.drawable.selection_border_tick_rec));
                            select = true;
                            selectedPosition = position;
                        }else{

                           RecyclerView.ViewHolder viewHolderselect = recyclerViewSubServices.findViewHolderForPosition(selectedPosition);
                                FrameLayout serviceImageSelect = (FrameLayout) viewHolderselect.itemView.findViewById(R.id.image_back_layout);
                                serviceImageSelect.setBackgroundColor(getResources().getColor(R.color.material_grey_200));
                                serviceImageBackground.setBackground(getResources().getDrawable(R.drawable.selection_border_tick_rec));
                                selectedPosition = position;
                        }
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        // do whatever
                    }
                })
        );

Adapter Class:
public class SubServicesAdapter extends RecyclerView.Adapter<SubServicesAdapter.ServiceViewHolder>  {

    List<ServiceList> subServiceModels;
    Context context;

    public class ServiceViewHolder extends RecyclerView.ViewHolder{

        TextView textViewSubServiceName;
        ImageView imageViewSubServiceIcon;
        FrameLayout imageBacklayout;
        CheckBox selectSubServiceCheckBox;

        public ServiceViewHolder(View itemView) {
            super(itemView);
            this.textViewSubServiceName = (TextView) itemView.findViewById(R.id.sub_service_title_textview);
            this.imageViewSubServiceIcon = (ImageView) itemView.findViewById(R.id.sub_service_icon_imageview);
            this.imageBacklayout = (FrameLayout) itemView.findViewById(R.id.image_back_layout);
            this.selectSubServiceCheckBox = (CheckBox) itemView.findViewById(R.id.select_sub_service_checkbox);

        }
}

    public SubServicesAdapter(Context _context, List<ServiceList> _subServiceModels) {
        this.subServiceModels = _subServiceModels;
        this.context = _context;

    }

    @Override
    public ServiceViewHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.sub_service_card_layout, parent, false);

        ServiceViewHolder myViewHolder = new ServiceViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(ServiceViewHolder holder, int position) {

        final ServiceList serviceItem = subServiceModels.get(position);

        TextView textViewSubServiceName = holder.textViewSubServiceName;
        ImageView imageViewSubServiceIcon = holder.imageViewSubServiceIcon;
        FrameLayout imageBackground = holder.imageBacklayout;
        final CheckBox checkBox = holder.selectSubServiceCheckBox;

        textViewSubServiceName.setText(subServiceModels.get(position).getServiceTitleEnglish());
        Picasso.with(context)
                .load(subServiceModels.get(position).getImageURL())
                .resize(150, 150)
                .centerCrop()
                .into(imageViewSubServiceIcon);
       // imageViewSubServiceIcon.setImageResource(icons[position]);
    }

    @Override
    public int getItemCount() {
        return subServiceModels.size();
    }
}

A: I also face the same issue I was resolved the following way.
I just created the model class for maintaining the selected values. So when we scrolled "onBindViewHolder" will be called so we just check the selected position and set the background.
The problem is Recyclerview reuse the viewholder and if it is not laid down the view then it returns the null.
 public void onBindViewHolder( ViewHolder holder, int position) {

                File file =new File(imageUrlList.get(position));
                View v=null;
                if(file.length()>0 ){
                    Glide.with(mContext).load(imageUrlList.get(position)).into(holder.imageView);

                    holder.imagePath=imageUrlList.get(position);
                   // Get the Selected Item from model class and set the background.
    **ArrayList<Integer>selectedImages=GalleryHelper.getInstance().getSelectedImagePositions();

                    if(selectedImages!=null && selectedImages.contains(position)){

                        Drawable highlight=mContext.getResources().getDrawable(R.drawable.image_border);
                         v=  holder.itemView;

                        v.setBackground(highlight);
                    }else {
                        v=  holder.itemView;
                        v.setBackground(null);
                    }

                }else{
                    Log.i(TAG," This file is Empty : "+imageUrlList.get(position));
                }**

            }


text:
Q: Android Studio 4.1 Stuck at loading screen in Mac My Android Studio has been stuck at loading screen since yesterday. X_X

What I have tried:

*

*Restarting computer.

*Clearing junk files and logs.

*Completely uninstall and then Reinstalling AndroidStudio.

*Followed many different solutions (e.g: one of it is here). But still doesn't work. Excerpt from the solution:

*

*Open file Android Studio setup directory/bin/idea.properties

*Add disable.android.first.run=true to end

*Restart Android Studio

*When I deleted the SDK it worked, but then after I let it download the SDK again, it opens for that session, then stuck again on the next session.

Well, I don't want to always delete and re-download the SDK every time I open Android Studio. So does anyone have any solution to this?
Thanks
More Info:
Android Studio 4.1
Build #AI-201.8743.12.41.6858069, built on September 23, 2020
Runtime version: 1.8.0_242-release-1644-b3-6222593 x86_64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.6
GC: ParNew, ConcurrentMarkSweep
Memory: 4029M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: org.jetbrains.kotlin, Dart, io.flutter

My jave -version
openjdk version "14.0.1" 2020-04-14
OpenJDK Runtime Environment (build 14.0.1+14)
OpenJDK 64-Bit Server VM (build 14.0.1+14, mixed mode, sharing)

My /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java -version
java version "1.8.0_271"
Java(TM) SE Runtime Environment (build 1.8.0_271-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.271-b09, mixed mode)

My studio.vmoption:
-Xms1G
-Xmx4G
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-XX:CICompilerCount=2
-Dsun.io.useCanonPrefixCache=false
-Djdk.http.auth.tunneling.disabledSchemes=""
-Djdk.attach.allowAttachSelf=true
-Dkotlinx.coroutines.debug=off
-Djdk.module.illegalAccess.silent=true
-Djna.nosys=true
-Djna.boot.library.path=
-Didea.vendor.name=Google
-XX:+UseCompressedOops
-Dfile.encoding=UTF-8

-XX:ErrorFile=$USER_HOME/java_error_in_studio_%p.log
-XX:HeapDumpPath=$USER_HOME/java_error_in_studio.hprof

My idea.properties:
idea.max.intellisense.filesize=2500
idea.cycle.buffer.size=1024
sun.java2d.d3d=false
idea.dynamic.classpath=false
idea.no.launcher=false
idea.xdebug.key=-Xdebug
sun.java2d.uiScale.enabled=true
swing.bufferPerWindow=true
idea.fatal.error.notification=disabled
javax.swing.rebaseCssSizeMap=true
idea.max.content.load.filesize=20000
idea.popup.weight=heavy
sun.java2d.pmoffscreen=false
CVS_PASSFILE=~/.cvspass
com.apple.mrj.application.live-resize=false
java.endorsed.dirs=
idea.smooth.progress=false
apple.laf.useScreenMenuBar=true
apple.awt.fileDialogForDirectories=true
apple.awt.graphics.UseQuartz=true
apple.awt.fullscreencapturealldisplays=false
idea.jre.check=true
disable.android.first.run=true

A: found the answer in https://stackoverflow.com/questions/54806995/android-studio-corrupt-installation/61701185#61701185
I just delete the folder
MacOS: ~/Library/Application Support/Google/AndroidStudio4.1
and it works.

A: When running from terminal you can see the error causing it to enter a restart loop.
My fix was to just re-install using JetBrains Toolbox.
2021-04-09 17:47:38,379 [  45709]  ERROR - llij.ide.plugins.PluginManager - Android Studio 4.1.3  Build #AI-201.8743.12.41.7199119
2021-04-09 17:47:38,444 [  45774]  ERROR - rationStore.ComponentStoreImpl - Android Studio 4.1.3  Build #AI-201.8743.12.41.7199119
2021-04-09 17:47:38,444 [  45774]  ERROR - rationStore.ComponentStoreImpl - JDK: 1.8.0_242-release; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o
2021-04-09 17:47:38,444 [  45774]  ERROR - rationStore.ComponentStoreImpl - OS: Mac OS X
2021-04-09 17:47:38,444 [  45774]  ERROR - llij.ide.plugins.PluginManager - JDK: 1.8.0_242-release; VM: OpenJDK 64-Bit Server VM; Vendor: JetBrains s.r.o
2021-04-09 17:47:38,445 [  45775]  ERROR - llij.ide.plugins.PluginManager - OS: Mac OS X
2021-04-09 17:47:38,444 [  45774]  ERROR - rationStore.ComponentStoreImpl - Last Action:
2021-04-09 17:47:38,445 [  45775]  ERROR - llij.ide.plugins.PluginManager - Last Action:
2021-04-09 17:47:38,445 [  45775]  ERROR - llij.ide.plugins.PluginManager - Could not initialize class com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
java.lang.NoClassDefFoundError: Could not initialize class com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
  at com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector.onError(LifecycleUsageTriggerCollector.java:123)
  at com.intellij.diagnostic.DefaultIdeaErrorLogger.canHandle(DefaultIdeaErrorLogger.java:62)
  at com.intellij.diagnostic.DialogAppender.appendToLoggers(DialogAppender.java:85)
  at com.intellij.diagnostic.DialogAppender.lambda$queueAppend$0(DialogAppender.java:58)
  at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
  at java.awt.EventQueue.access$500(EventQueue.java:98)
  at java.awt.EventQueue$3.run(EventQueue.java:715)
  at java.awt.EventQueue$3.run(EventQueue.java:709)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
  at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
  at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:974)
  at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:847)
  at com.intellij.ide.IdeEventQueue.lambda$null$8(IdeEventQueue.java:449)
  at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:741)
  at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:448)
  at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:831)
  at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:502)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
  at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
2021-04-09 17:47:38,446 [  45776]  ERROR - rationStore.ComponentStoreImpl - Conflicting component name 'UsagesStatistic': class com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent and class com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent (componentManager=Application (containerState=ACTIVE) )
java.lang.Throwable: Conflicting component name 'UsagesStatistic': class com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent and class com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent (componentManager=Application (containerState=ACTIVE) )
  at com.intellij.openapi.diagnostic.Logger.error(Logger.java:146)
  ...
  at com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent.getInstance(UsageStatisticsPersistenceComponent.java:54)


text:
Q: Solving quadrature differential equation I am trying to solve the velocity as a function of the time:
$$
ma=F_\text{Thrust}-F_\text{Drag}\Leftrightarrow m \frac {\rm d}{{\rm d}t} v(t) = \frac p {v(t)} - k\cdot(v(t))^2
$$
where
 $m$ is the mass [kg], $k$ is the drag coefficient and $p$ is the power [W]
I wonder if it is even possible to solve it analytical? If possible, how do I approach it?

A: Rewrite it as $m\dfrac{v}{p - kv^3} \dfrac {{\rm d}v}{{\rm d}t}= 1$, decompose $\dfrac{v}{p - kv^3}$ into partial fractions, and integrate.


text:
Q: Is it possible to access resources inside a jar through their path? I have a SoapUI project running through a java project that is all packaged into a jar. The project runs fine unpackaged through my IDE, but it encounters problems when running the jar through the command line. Here is the code that is causing the problem:
SoapUITestCaseRunner runner = new SoapUITestCaseRunner();
ClassLoader cl = MyClass.class.getClassLoader();
runner.setProjectFile(cl.getResource("project.xml").getFile());
runner.run();

The problem occurs on the run method when it tries to read in the xml file from the jar. Is it possible for me to get a path that I can input to the setProjectFile method from the jar? I've seen other answers say to use a stream, but this method only accepts strings.
Here is the stack trace:

2014-07-23 12:03:58,384 ERROR [errorlog] com.eviware.soapui.support.SoapUIException: Failed to load project from file [file:/C:/temp/MyJar.jar!/project.xml]
  com.eviware.soapui.support.SoapUIException: Failed to load project from file [file:/C:/temp/MyJar.jar!/project.xml]
    at com.eviware.soapui.impl.wsdl.WsdlProject.loadProject(WsdlProject.java:315)
    at com.eviware.soapui.impl.wsdl.WsdlProject.(WsdlProject.java:231)
    at com.eviware.soapui.impl.wsdl.WsdlProjectFactory.createNew(WsdlProjectFactory.java:41)
    at com.eviware.soapui.impl.wsdl.WsdlProjectFactory.createNew(WsdlProjectFactory.java:28)
    at com.eviware.soapui.tools.SoapUITestCaseRunner.runRunner(SoapUITestCaseRunner.java:329)
    at com.eviware.soapui.tools.AbstractSoapUIRunner.run(AbstractSoapUIRunner.java:188)
    at CommercialTests.ComTest.doTest(ComTest.java:14)
    at CommercialTests.ServiceTests.main(ServiceTests.java:8)
  Caused by: java.io.FileNotFoundException: C:\temp\MyJar.jar!\project.xml (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.(Unknown Source)
    at java.io.FileInputStream.(Unknown Source)
    at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    at com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.handleFile(UrlWsdlLoader.java:180)
    at com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.load(UrlWsdlLoader.java:116)
    at com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader.load(UrlWsdlLoader.java:96)
    at com.eviware.soapui.impl.wsdl.WsdlProject.loadProject(WsdlProject.java:297)
    ... 7 more

A: For something like this I normally do:
URL res = getClass().getResource("/project.xml")    // is it at the root of your jar?!?!
File f = new File(res.getFile())
runner.setProjectFile(f.getCanonicalPath());

SoapUI, depending on how it accesses the file, might need it in the "real" world. Below is a much more resource-intensive version of the above.
// locate your file in the jar resources
URL res = getClass().getResource("/project.xml")    // is it at the root of your jar?!?!
// locate the resource in the filesystem
File f = new File(res.getFile())
// copy the file out into the real filesystem
File target = new File(System.getProperty("java.io.tmpdir") + File.separator + f.getName())
java.nio.file.Files.copy(f.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)
runner.setProjectFile(target.getCanonicalPath())


text:
Q: Python Beautiful Soup and Dealing with a Non-Existent Table (for Dynamic Webpages) I'm using the following commands to successfully scrape data from a table on multiple webpages through an iteration function:
 Sales = soup.find('table', id="tblSales")
 SaleData = Sales.find_all('tr')
    for tr in SaleData:
        td = tr.find_all('td')
        SaleData = [i.text for i in td]
        print(SaleData)

The issue is that sometimes the table doesn't exist on the page (there are no "sales" so there is no table inserted into the page). So python throws an error and stops. When the table doesn't exist, the webpage has the following html:

No Sales Information Available

Is there a way to deal with non-existent tables in the soup?

A: The simplest way is to just check if Sales exists
if Sales := soup.find('table', id="tblSales"):
    SaleData = Sales.find_all('tr')
        for tr in SaleData:
            td = tr.find_all('td')
            SaleData = [i.text for i in td]
            print(SaleData)

OR (essentially same thing)
Sales = soup.find('table', id="tblSales")
if Sales:
    SaleData = Sales.find_all('tr')
        for tr in SaleData:
            td = tr.find_all('td')
            SaleData = [i.text for i in td]
            print(SaleData)


text:
Q: Java Synth: Making a Test Tone I've been looking at people's Java synth but can't make out how to produce a simple version of their program. My goal is to create a simple test tone in java, which the user will be able to alter by pressing certain keys. For example pressing "r" will raise the amplitude, or "f" will increase the frequency. I would just like to know: where to get started on creating this?

A: See Beeper for an example of generating a tone.

A: I have a Theremin that runs via Java:
http://www.adonax.com/blog/?p=187
http://www.hexara.com/VSL/JTheremin.htm
Since I'm using a wavetable to generate the data, the pitch is determined by the rate at which the cursor progresses through the table. I use linear interpolation when the cursor lands between table elements. Thus, if a 1024 element table describes a single sine wave, going through it one element at a time is one speed, going through it 1.2 elements at ta time (with linear interpolation to get the intermediate values) is a bit faster and a higher pitch.

A: Well, it would be unpleasant, but the simplest approach would be to create a square wave.
Depending on whether you're creating a file with signed or unsigned amplitudes, you'll need to work out whether to oscillate between 0 and amplitude, or -amplitude and +amplitude.
The frequency will determine how many samples to create at each value before switching.
It's hard to hlep more without any more details about what output format you're trying to create, etc - but that may help you to start with. Create a sine wave for a rather nicer tone :)


text:
Q: Trying to loop non-contiguous rows in a range I am trying to write something that will loop through a range of non-contiguous rows in a table, and change column data in each row ... for example, ClearContents. The range will be dynamic, and the rows I want to loop through will all be "Selected."
I tried the following, but it stopped after the first row. I am pretty sure the problem is that the next row is non-contiguous to the first row:
 For Each b In a.Rows
 mainTasks.DataBodyRange(Range("mainTasks[Status]").Column).ClearContents
 Next b

Then I had the bright idea to write something that works only the "selected" column cells. I tried using If ... .Value = Selected and that didn't work.
Am I trying to do something that Excel 2016 VBA can't do? That is, loop through non-contiguous rows in a range? I've been researching and tried several other things that don't work. Can you tell me if I am going down the wrong rabbit hole?

A: You don't have any variables in your loop.
It will just the clear the one column repeatedly in the loop. You need to somehow reference b in the loop to have a different outcome in each loop.

A: This works too (i think)
Dim selectedRange As Range

Set selectedRange = Application.Selection

For Each Row In selectedRange.Rows
    Debug.Print Row.Address
Next Row

A: I tried to simplfy your code in the comments for testing purpose, but the following code should help,
Dim x As Integer
Dim myrange As Range
For x = 1 To 30
   If (mainTasks.Cells(x, 2) = "completed" Or mainTasks.Cells(x, 2) = "Dismissed") And mainTasks.Cells(x, 3) <> "" Then
      If myrange Is Nothing Then
         Set myrange = mainTasks.Cells(x, 2)
      Else
         Set myrange = Union(myrange, mainTasks.Cells(x, 2))
      End If
    End If
Next x
myrange.ClearContents

I tried it out and it works Ok given the way I set it up.  Hope it helps!
You will also have to add the code to copy the data, I am clearing the contents in this one, given that was your original question


text:
Q: Balances AccountStore definition in substrate runtime In the balances pallet, the config trait has one item that is defined like type AccountStore: StoredMap<Self::AccountId, AccountData<Self::Balance>>;. This was a bit strange to me as I was expecting a normal storage map to store a mapping from AccountId to AccountData but after I looked at the docs for StoredMap I realised that it's a trait implemented on StorageMaps as well. That makes more sense now, so I go on to look at how the runtime defines this field, and to my surprise I find this in the runtime/src/lib.rs : type AccountStore = System;. Now I've never seen a runtime definition like this before because if I'm correct, System is supposed to represent the frame_system pallet. So I go to look at frame_system::Config for Runtime and I find this defintion :
type AccountData = pallet_balances::AccountData<Balance>;.
Now I don't know how these definitions are getting into pallet_balances' Config impl, but I can see that System contains both ingredients namely : one type AccountData and one AccountId. So at the end my two questions that stand are

*

*What are the reasons for such a convulting design?

*How does type AccountStore = System; figure out the concrete types?

A: *

*Storing account balances in the system pallet also maintains some other frame_system information that may be important to keep around for a certain runtime configuration. But having consumers, providers and sufficients inside a runtime with multiple pallets and potentially interacting with other runtimes becomes quite crucial.

*AccountStore defines where this balance is going to be stored, for this case is frame_system::Pallet<Runtime>. If we follow the lead and check the configuration of frame_system we will see that the type for AccountData is defined as

type AccountData = pallet_balances::AccountData<Balance>

Good, now we know that the AccountData stored in frame_system will be the one defined in pallet_balances.
So the information living in system concerning accounts will end up looking like the following:
/// Information of an account.
#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo)]
pub struct AccountInfo<Index, AccountData> {
    /// The number of transactions this account has sent.
    pub nonce: Index,
    /// The number of other modules that currently depend on this account's existence. The account
    /// cannot be reaped until this is zero.
    pub consumers: RefCount,
    /// The number of other modules that allow this account to exist. The account may not be reaped
    /// until this and `sufficients` are both zero.
    pub providers: RefCount,
    /// The number of modules that allow this account to exist for their own purposes only. The
    /// account may not be reaped until this and `providers` are both zero.
    pub sufficients: RefCount,
    /// The additional data that belongs to this account. Used to store the balance(s) in a lot of
    /// chains.
    pub data: AccountData,
}

Where AccountData fits the previous mentioned definition in pallet_balances.
Please, check this commit too for further information on how this may be tweaked -> https://github.com/paritytech/substrate/commit/31d90c202d6df9ce3837ee55587b604619a912ba


text:
Q: customising matplotlib figure I am using matplotlib.pyplot for a little module I am developing (code appended). However, I can't work out how to customise the figure (increas figure size, change background canvas colour). How do I do this. I have tried fig = plt.figure(figsize=(16,8)) after self.fig, self.ax = plt.subplots() and this does increase the figure size and add my buttons but shows my plot on a seperate figure. What is my simple mistake?

    # Setup the axes.
    self.fig, self.ax = plt.subplots()
    self.slider_ax    = self.fig.add_axes([0.2, 0.03, 0.65, 0.03])
    self.delete_ax    = self.fig.add_axes([0.85, 0.84, 0.1, 0.04])
    self.register_ax  = self.fig.add_axes([0.85, 0.78, 0.1, 0.04])
    self.add_ax       = self.fig.add_axes([0.85, 0.72, 0.1, 0.04])
    self.save_ax      = self.fig.add_axes([0.85, 0.66, 0.1, 0.04])
    self.reset_ax     = self.fig.add_axes([0.85, 0.16, 0.1, 0.04])
    self.quit_ax      = self.fig.add_axes([0.85, 0.1,  0.1, 0.04])

    # Make the slider
   ! self.slider = Slider(self.slider_ax, 'Frame', 0, 1,
                        valinit=0, valfmt='%1.2f', closedmin=True,
                        closedmax=False)
    self.slider.on_changed(self.update)

    #Make the buttons
    self.del_button = Button(self.delete_ax, 'Delete')
    self.del_button.on_clicked(self.delete)
    self.reg_button = Button(self.register_ax, 'Register')
    self.reg_button.on_clicked(self.register)
    self.add_button = Button(self.add_ax, "Add")
    self.add_button.on_clicked(self.add)
    self.save_button = Button(self.save_ax, "Save")
    self.save_button.on_clicked(self.save)
    self.quit_button = Button(self.quit_ax, "Quit")
    self.quit_button.on_clicked(self.quit)
    self.reset_button = Button(self.reset_ax, "Reset")
    self.reset_button.on_clicked(self.reset)

    # Plot the first slice of the image
    self.im = self.ax.imshow(np.array(raw_dicom_stack[0]), cmap = cm.gray)

A: plt.subplots has **fig_kw that contains all the keyword arguments that can be sent to the figure (see figure doc). One of them is figsize. You can do
self.fig, self.ax = plt.subplots(figsize=(16,8), ...)

otherwise you can use figure methods once the figure is created
self.fig.set_size_inches(16,8, forward=True)

If you call self.fig = plt.figure() after subplots, correctly, a second figure shows up. And as you add all the buttons to self.fig, they all go to the last defined.
At last: it would be probably better to create self.ax with add_axes, to be more coherent with all the other axes and have more control on his positioning
edit
(elaborate the last sentence)
self.ax is a matplotlib.axes.AxesSubplot object (the same that you would get from e.g. plt.subplot(111), while all the buttons are added tomatplotlib.axes.Axesobjects (created withadd_axes`).
Putting axes and subplots together can give problems with the relative position of the plot with respect to the buttons and slider if the figure size is changed or the window resized.
I think that a consistent division of the space in the figure canvas, either using axes or subplots, would be better to avoid such possible problems. So I suggest either to create the plotting axes as self.ax = fig.add_axes(...) or to use something like gridspec.

A: Each call to plt.figure will create a new figure instance. What you want to do is modify an existing figure. You can do this with the methods available on your figure instance. The two directly relevant to this question are set_figwidth, set_figheight and set_facecolor.
HTH


text:
Q: How can I change the UIActivityIndicatorView to set a custom image? Well, I am looking for a way to change my spinner image and use a custom image
Any suggestion?

A: I have created a subclass of UIActivityIndicatorView that allows you to set a custom image.

A: You could simply use a UIImageView and add an animation that rotates the view's layer indefinitely. You can achieve this using CoreAnimation. There are plenty of tutorials for this out there.
If you wish to start and stop the animation you can create a simple subclass of UIImageView that adds and removes said animation.
Here's a link for the animation: Basic keyframe animation (rotation)


text:
Q: Idiomatic Kotlin for Level Order Traversal of BST Following is my implementation of Level Order Traversal of a BST:
fun levelOrder(): Iterable<Pair<Key, Int>> {
    class InternalNode(val node: Node<Key>, val level: Int)

    val yetToVisit = emptyQueue<InternalNode>()
    val visited = emptyQueue<Pair<Key, Int>>()

    root?.also { yetToVisit.enqueue(InternalNode(it, 1)) }

    while (!yetToVisit.isEmpty) {
        do {
            val node = yetToVisit.dequeue().also { visited.enqueue(it.node.key to it.level) }
            listOf(node.node.left, node.node.right)
                    .filter(Objects::nonNull)
                    .map { InternalNode(it!!, node.level + 1) }
                    .forEach(yetToVisit::enqueue)
        } while (!yetToVisit.isEmpty && yetToVisit.peek().level == node.level)
    }

    return visited
}

I'm wondering if the above can be implemented in a more idiomatic/functional manner without using while and do-while. Ideas?

A: Yes you can, by using a sequence (say, generateSequence):
fun levelOrder(): Iterable<Pair<Key, Int>> {
    class InternalNode(val node: Node<Key>, val level: Int)

    val yetToVisit = emptyQueue<InternalNode>()
    val visited = emptyQueue<Pair<Key, Int>>()
    fun peek() = yetToVisit.dequeue()
            .also { visited.enqueue(it.node.key to it.level) }

    root?.also { yetToVisit.enqueue(InternalNode(it, 1)) }
    if (yetToVisit.isEmpty) return visited
    generateSequence(peek()) { node ->
        if (!yetToVisit.isEmpty && yetToVisit.peek().level == node.level) peek()
        else null
    }.forEach { node ->
        listOfNotNull(node.node.left, node.node.right)
                .map { InternalNode(it, node.level + 1) }
                .forEach(yetToVisit::enqueue)
    }

    return visited
}

And BTW you may use listOfNotNull or listOf().filterNotNull to replace filter(Objects::nonNull).
Note I've just syntaxically refactored your code but since I cannot compile your code I can't verify the correctness of it. If it's not working as expected please leave a comment.


text:
Q: Loop to Find Sum of Digits I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
    //loops through all numbers whose sum of digits is 11
    for(int number = 29; number < 1000; number++) {
        //checks the values of the 100,10,and 1 position
        int hPlace = number / 100; number = number - (hPlace * 100);
        int tPlace = number / 10;  number = number - (tPlace * 10);
        int oPlace = number;
        //sum of digits
        int i = hPlace + tPlace + oPlace;

        //prints if sum of digits is 11
        int count = 0;
        if (i == 11) {
            count++;
            System.out.print(i + " ");
        }

        //new line after every 10 numbers -- just for formatting
        if (count % 10 == 0) {
            System.out.println("");
        }
      }

A: You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
                           ---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
                           ---------------------------------

A: Don't do this
number = number - (hPlace * 100);

when your condition is dependent on number
for(int number = 29; number < 1000; number++)

A: because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
        for(number = 29;number < 930;number++) {

A: //loops through all numbers whose sum of digits is 11
    for(int number = 29; number < 1000; number++) {
        //checks the values of the 100,10,and 1 position
        int hPlace = number / 100;
        **number** = number - (hPlace * 100);     // PROBLEM!!!
        int tPlace = number / 10;
        **number** = number - (tPlace * 10);     // PROBLEM!!!
        int oPlace = number;
        //sum of digits
        int i = hPlace + tPlace + oPlace;

        //prints if sum of digits is 11
        int count = 0;
        if (i == 11) {
            count++;
            System.out.print(i + " ");
        }

        //new line after every 10 numbers -- just for formatting
        if (count % 10 == 0) {
            System.out.println("");
        }
      }

A:
if(count>500){break;} to halt it after the loop counter reaches 500....still nothing

This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
 int hPlace = number / 100; number = number - (hPlace * 100);
 int tPlace = number / 10;  number = number - (tPlace * 10);

Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.

A: Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.

A: import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SumDigits
{
public static void main(String args[])throws Exception
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter a Number:");
    String string=br.readLine();
    System.out.println("length of Number:"+string.length());
    int sum=0;
    int number=0;
    for(int i=0;i<=string.length()-1;++i)
    {
        char character=string.charAt(i);
        number=Character.getNumericValue(character);
        sum=sum+number;
    }//for
    System.out.println("Sum of digits of Entered Number:"+sum);
    }//main()
}//class


text:
Q: Chamar ion-view em função Estou iniciando em Ionic e AngularJS, já googlei bastante e não achei nada a respeito desta simples duvida.
consigo navegar de boa entre as ion-view "Page1" e "Page2" utilizando os botões:

<ion-view view-title="Page1">
  <ion-content>

Page 1

    Page 2
  </ion-content>
</ion-view>

<ion-view view-title="Page2">
  <ion-content>

Page 2

    Page 1
  </ion-content>
</ion-view>

Porem gostaria de executar isso através de uma função:

function EventoTal(){

      carregue("page2");

}

Sem a necessidade de clicar no botão.
Em jQuery $(elemento).show();

A: Não se irá funcionar com Ionic, mas como ele é baseado em Web, podemos tentar o seguindo que é o código equivalente ao que o Page 2 faz:
location.hash = "/app/page2";

Ou assim para manter o histórico da pilha de paginas:
if(history.pushState) {
    history.pushState(null, null, '#/app/page2');
}
else {
    location.hash = '#/app/page2';
}


text:
Q: React Native:Why does the child component have access in a variable which is inside the useEffect in a parent component? i have the following code.I can't understand why the "TestA" component has access to the "s" variable  which is inside the useEffect in "Test" component.
import React, {useEffect, useState} from 'react';
import {View, Text} from 'react-native';

const Test = ({children}) => {
  const [init, setInit] = useState(0);
  useEffect(() => {
    setInit(1);
  }, []);
  useEffect(() => {
    s = {
      example: 'www',
    };
  }, []);
  // console.log(s);
  return init > 0 ? <View>{children}</View> : <Text>Noooo</Text>;
};
const TestA = () => {
  console.log(s); -->why this has access inside the useEffects' variable "s"???
  return (
    <View>
      <Text>Hello {s.example}</Text>
    </View>
  );
};
const App = () => {
  return (
    <>
      <Test>
        <TestA />
      </Test>
    </>
  );
};

export default App;

I notice this happen only for ReactNative.In React something like that doesn't work.Is something that babel does in react native.Here is my package.json file:
{
  "name": "exampleNative",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.11.0",
    "react-native": "0.62.2"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.58.0",
    "react-test-renderer": "16.11.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

A: I think this is happening because the child functional component has access to the scope of the parent functional component because it has been defined inside it. It is a concept in JavaScript called 'Closures'. You can read more about it in this blogpost (not mine). https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4


text:
Q: Android - OneBusAway: translate message for succesfully sent problems I need trying to change/translate the message shown in the OneBusAway Android app after sending with success a report about an arrival time or a bus stop.
The dialog shows the message "Your issue has been successfully reported", plus an "Ok" button:

The message shown does not depend on the language of the operating system. I looked in the whole code for that string, and for substrings, without beeing able to find anything.
More, debugging step-by-step it seems the dialog is originated from some Android library.
Any idea on how to approach the problem in order to change and/or translate the message?