text:
Q: How to tell Alexa to punctuate user responses properly. Please see the use case I am sorry if this looks like a stupid question!
My skill is recording user responses in the database.  This part is working fine. But my concern is Alexa is not punctuating the response at all. Here is an example:
User: The loading speed of the website is very slow (a few milliseconds of pause) can't we make it faster (vocal tone was used in such a way so that Alexa can understand that this part is a question)
Recorded: the loading speed of the website is very slow can't we make it faster
Expected: the loading speed of the website is very slow. can't we make it faster?
Is there any way to accomplish this? Because it is very important to have correctly punctuated responses to be stored in the database. as this skill will be used for project management purpose.

A: I am afraid it's not possible with Alexa. However you can use AWS Transcribe Service - build an app for the mobile/web and send recorded audio to the service. According to their docs:

Easy-to-Read Transcriptions
Amazon Transcribe automatically adds punctuation and formatting so that the output closely matches the quality of manual transcription at a fraction of the time and expense.


text:
Q: How to cleanup Excel.AppEvents AdviseSinks? SO I ran into a problem using the WorkbookOpen event when in an ole embedded scenario: its a well documented issue:

*

*https://blogs.msdn.microsoft.com/mshneer/2008/10/18/com-interop-handling-events-has-side-effects/

*https://blogs.msdn.microsoft.com/rcook/2008/10/30/iconnectionpoint-and-net-or-how-i-learned-to-stop-worrying-and-love-managed-event-sinks-part-1/
reading this blog post
https://blogs.msdn.microsoft.com/vsofficedeveloper/2008/04/11/excel-ole-embedding-errors-if-you-have-managed-add-in-sinking-application-events-in-excel-2/
I not only need an IConnectionSink but also call Marshal.ReleaseComObject on each workbook object passed as a parameter.
public class ExcelAppEventSink : Excel.AppEvents
{
... other functions ...

public void WorkbookOpen(Excel.Workbook Wb)
{
  <-- operate on workbook -->
  Marshal.ReleaseComObject(Wb);
}

... other functions ...
}

But another blog post from microsoft posted 2 years later claims Marshal.ReleaseComObject is dangerous.
https://blogs.msdn.microsoft.com/visualstudio/2010/03/01/marshal-releasecomobject-considered-dangerous/
since I just need to release the RCWs would it be safer in 2016 to call
CleanupUnusedObjectsInCurrentContext at the end of the function call instead?
extra reading material:

*

*https://blogs.msdn.microsoft.com/vcblog/2006/09/19/mixing-deterministic-and-non-deterministic-cleanup/

A: So this answer was really good: https://stackoverflow.com/a/349202/ Don't like to have to specify using for every COM object but other than that the code is pretty clean.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React - Form keeps re-rendering component while I type This function renders a modal that shows a login form. As I type, the whole component is re-rendering, and I can only type 1 or 2 letters before it resets. I've never seen this kind of problem before.
I've tried factoring out the "opts" object, in case that was forcing the re-render. It did not change anything.
import React, {useState} from 'react';
import useApi, {IPayload} from './hooks/useApi';
import Modal from 'react-modal'
import './modal.css';
Modal.setAppElement('#root')

interface IProps {
  payload:IPayload|null,
  closeAction?:()=>void,
}

const defaultProps:IProps = {
  payload:null,
  closeAction: ()=>null,
}

function Auth(props:IProps):JSX.Element{

  const [auth, updateAuth] = useState<boolean>(false)
  const [authModalIsOpen, setAuthModal] = useState(true)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const opts = {
    username: username,
    password: password,
    fail: forceLogin,
  }

  const defaultPayload:IPayload = {
      path:'notes/validateAuth/',
      method: 'GET',
      body: null,
      callback: loginAction
  }

  const [payload, setPayload] = useState(defaultPayload)
  if(props.payload!==null){

    setPayload(props.payload)
  }
  // console.log(_payload)
  // useApi(opts, payload)

  function forceLogin(){
    setAuthModal(true)
    updateAuth(false)
  }

  function closeAuthModal(){
    if(auth){ setAuthModal(false) }
  }

  function SubmitLogin(){
    setPayload(defaultPayload)
  }

  function loginAction(res:any){
    updateAuth(true)
    setAuthModal(false)
    setUsername(res.auth)
  }

  function LoginWindow(){
    return(
      <Modal
        isOpen={authModalIsOpen}
        onRequestClose={closeAuthModal}
        className='SearchModal'
        overlayClassName='SearchOverlay'
        >

        <form onSubmit={(e)=>{
          e.preventDefault()
          SubmitLogin()
        }}>
            <input name='username' className='greenput_narrow' onChange={(e)=>{
              setUsername(e.target.value)
            }}/>

            <input type="password" name='password' className='greenput_narrow' onChange={(e)=>{
              setPassword(e.target.value)
            }}/>

            <button className='greenput_narrow' type="submit">Login</button>
          </form>

NullDisk

Military Grade Encryption

Zettelkasten Schema

VIM Keybindings

        </Modal>
    )
  }

  return(
    <LoginWindow/>
  )
}

Auth.defaultProps = defaultProps
export default Auth;

How do I fix this?

A: Your function LoginWindow() is another component inside function Auth(props:IProps). All your setStates happens in your parent component as you type. In React any change in the Parent component will trigger a re-render of child components.
If you really wanted to keep a separate child component, you had to pass all those set methods you are using in LoginWindow as props. Then you will have to wrap your methods that are passed into your child component in a useCallback so every time your parent re-renders due to the state update your functions will not regenerate as new objects. That's a path you don't need for such a small component I believe.
I don't know why you are using a component inside another component in the wrong way. Why don't you directly return your JSX like,
import React, { useState } from 'react';
import useApi, { IPayload } from './hooks/useApi';
import Modal from 'react-modal';
import './modal.css';
Modal.setAppElement('#root');

interface IProps {
  payload: IPayload | null;
  closeAction?: () => void;
}

const defaultProps: IProps = {
  payload: null,
  closeAction: () => null
};

function Auth(props: IProps): JSX.Element {
  const [auth, updateAuth] = useState < boolean > false;
  const [authModalIsOpen, setAuthModal] = useState(true);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const opts = {
    username: username,
    password: password,
    fail: forceLogin
  };

  const defaultPayload: IPayload = {
    path: 'notes/validateAuth/',
    method: 'GET',
    body: null,
    callback: loginAction
  };

  const [payload, setPayload] = useState(defaultPayload);
  if (props.payload !== null) {
    setPayload(props.payload);
  }
  // console.log(_payload)
  // useApi(opts, payload)

  function forceLogin() {
    setAuthModal(true);
    updateAuth(false);
  }

  function closeAuthModal() {
    if (auth) {
      setAuthModal(false);
    }
  }

  function SubmitLogin() {
    setPayload(defaultPayload);
  }

  function loginAction(res: any) {
    updateAuth(true);
    setAuthModal(false);
    setUsername(res.auth);
  }

  return (
    <Modal
      isOpen={authModalIsOpen}
      onRequestClose={closeAuthModal}
      className="SearchModal"
      overlayClassName="SearchOverlay"
    >

          <form
            onSubmit={e => {
              e.preventDefault();
              SubmitLogin();
            }}
          >
            <input
              name="username"
              className="greenput_narrow"
              onChange={e => {
                setUsername(e.target.value);
              }}
            />

            <input
              type="password"
              name="password"
              className="greenput_narrow"
              onChange={e => {
                setPassword(e.target.value);
              }}
            />

            <button className="greenput_narrow" type="submit">
              Login
            </button>
          </form>

NullDisk

Military Grade Encryption

Zettelkasten Schema

VIM Keybindings

    </Modal>
  );
}

Auth.defaultProps = defaultProps;
export default Auth;

A: Had a similar issue here: in the input that you want to focus on put autofocus:

 <input style={{width: "50%"}}maxLength="8" autoFocus value={inputValue} onChange={customTextChange.bind(this)} className={styles.patternSelector} />

You many want to conditionally add it based on an onChange event


text:
Q: excel datasource returning nulls with sql command I'm reading excel sheet that has a column formated as number but every now and then contains letters. These are returned as NULLS. I need the values. I added IMEX=1 and that did not help. Changing Values in the registry is not an option. the columns are fixed so is there a way to manually set them to string?
I also tried changing it from advance editor and they go back to the default that is double float.
I am getting the data with an SQL command. Is there a way to force the column to be a type with cast or convert from here? I tried with cast and I keep getting an error.

A: Try reading in the columns as varchar, then either use a data conversion or derived column transformation within the SSIS package, or update the data once read into the db using cast or convert.

A: I have found out that cast and convert does not work in this context. I used CSTR(). I was getting error displaying this cell in the preview but the end product was good.


text:
Q: Is it possible to repeat getopt I'm trying to create a basic shell with builtin commands, and I'm having some issues with getopt. Here is the output (using valgrind):
$ mkdir -p foo/bar
mkdir
-p
foo/bar
FLAGON
$ mkdir -p foo/test
mkdir
-p
foo/test
==15377== Invalid read of size 1
==15377==    at 0x5201BBE: _getopt_internal_r (in /usr/lib/libc-2.17.so)
==15377==    by 0x5202CEA: _getopt_internal (in /usr/lib/libc-2.17.so)
==15377==    by 0x5202D37: getopt (in /usr/lib/libc-2.17.so)
==15377==    by 0x40351A: shell_ns_cmd_mkdir (shell.c:542)
==15377==    by 0x403AB4: normal_shell_cb (shell.c:610)
==15377==    by 0x402E8E: shell_mainloop (shell.c:402)
==15377==    by 0x401B67: main (main.c:52)
==15377==  Address 0x54e0912 is 2 bytes inside a block of size 3 free'd
==15377==    at 0x4C2AD3C: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15377==    by 0x402C93: shell_mainloop (shell.c:384)
==15377==    by 0x401B67: main (main.c:52)
==15377==
$

And here is the source (clipped):
for (i = 0; i < argc; i++) {
    puts(argv[i]);
}
while ((c = getopt(argc, argv, "p")) != -1) {
    switch (c) {
        case 'p':
            puts("FLAGON");
            mkparents = true;
            break;
        case '?':
            fprintf(stderr, "invalid option -- %c", optopt);
            ret = 127;
            goto end;
            break;
    }
}

So the first time it runs it (mkdir -p) recognizes it (-p) and the second time it runs, it doesn't. Any ideas?

A: If you want to scan multiple vectors you need to reset getopt by setting optind to 1.

The variable optind is the index of the next element of the argv[]
  vector to be processed. It shall be initialized to 1 by the system,
  and getopt() shall update it when it finishes with each element of
  argv[].

If setting optind to 1 doesn't work, also try 0, I think I remember reading about that somewhere.


text:
Q: How to "denormalize" a pytorch tensor? I would like to normalize the labels for my neural network but also be able to reverse the normalization process, so that I can scale my prediction outputs back to the original size.
My labels are of the form:
[[ 2.25, 2345123.23],
 [ 1.13, 234565.11],
 ...
 [0.12, 990232.98]]

Now I would like to normalize each column such that the values range from 0 to 1.
I found that pytorch has the torch.nn.functional.normalize function which allows me to normalize along a specific dimension using whichever p-norm I desire.
Is there an existing inverse function that allows me to scale my normalized values?
Currently, I am using a custom function that performs feature scaling as follows which scales both columns together, however, I wanted to make sure I am not creating a function that already exists in the torch library before rewriting it.
 A = lbl_min
 B = lbl_max
 a = lower_bound
 b = upper_bound
 self.labels = a*np.ones(shape) + (self.labels - A*np.ones(shape))*(b-a)/(B-A)

Additional information:
I am using a regression model to output continuous real world values. I need to "denormalize" my predictions in order to validate them against the true values. Also, if I were to use my model in a practical application, I would need my output back in its original units.

*

*My neural network predicts multiple values at once that are in very different ranges.

*The two values have different distributions but can be predicted from the same input.

*My input is an image into two CNN layers that then are fed into two fully connected layers

A: This is a trick question right.
It has no sense to denormalize your values.
Why? Because once you normalize them, the neural net should learn to create the predictions based on your normalized values.
So you are safe.
BTW, you will typically use mean and std of your data to normalize.

In case of the regression problems it is the same. At least the architectures I created so far. For instance: Create the model M1 to learn sum + operation.
You provide pair of values a,b and you set the sum c as prediction.
In case you train another model M2 with a/10, b/10 and you again provide the c as prediction, this means you normalize the input.
All you have to do in the inference phase is to normalize your inputs (divide by 10) and you get the correct output.


text:
Q: Scala for comprehension with Map iteration I gone through a bunch of codes and tutorials and i still don't understand how to iterate the Map through the for comprehension.
For example : I have a Map. Key as a string (student name) and the value as student details. I wants to iterate the student Map as each key and value. How can i achieve this through for comprehension.
Here's the code i tried but i failed to understand
for {
  studentMap <- studRepo.getAllStudent()// returns a map
  result1 <- performSomeOper(studentMap.key) // I'm not getting an option to access the key/value
  result2 <- performSomeOper(studentMap.value)
} yield performYieldOps(result1, result2)

What i'm doing wrong here ? Do i needs to keep the studentMap outside the for comprehension? Please feed me your input.

A:   for {
    (key, value) <- studRepo.getAllStudent()
    res1 <- performSomeOper(key)
    res2 <- performSomeOper(value)
  } yield ...

You can map key, value from Map.
and for comprehension actual is equal to flatMap, so for the above equal to:
  m.flatMap {
    case (key, value) => ...
  }


text:
Q: Standardized residuals of a Tobit model in R  Does anybody know why it is not possible to compute standardized residuals when estimating a Tobit model?
Here is a short example of what I am talking about:
> require(AER)   # for tobit estimation commands
> require(MASS)  # for computing standardized residuals
> numberofdrugs <- rpois(84, 5)+1
> healthvalue <- rpois(84,5)
> tob <- tobit(healthvalue ~ numberofdrugs)
> residuals(tob) # works fine
> stdres(tob)    # doesn't work fine

Where is the problem?

A: The problem is in assuming that stdres() will work for a tobit regression. The reason resid() works for tob is that the type of object returned by tobit() inherits from class "survreg":
R> class(tob)
[1] "tobit"   "survreg"

and there is a special residuals() method for objects of that class:
R> methods(residuals)
 [1] residuals.breakpointsfull* residuals.coxph*
 [3] residuals.coxph.null*      residuals.coxph.penal*
 [5] residuals.default          residuals.glm
 [7] residuals.HoltWinters*     residuals.isoreg*
 [9] residuals.lm               residuals.loglm*
[11] residuals.nls*             residuals.smooth.spline*
[13] residuals.survreg*         residuals.survreg.penal*
[15] residuals.tukeyline*

   Non-visible functions are asterisked

("survreg" is there as number 13.)
stdres() is (or at least appears to me to be) limited to the linear model case, and one could argue that a tobit model is not a linear regression. From ?stdres we have:
Arguments:

  object: any object representing a linear model.

That this is the case is seen more clearly when one looks at lmwork(), the function that does the work in stdres(), which on the second line of the code for that function, lm.influence() is called, and that is where stdres() is failing (output from debugging lmwork() and calling stdres(tob):
Browse[2]> n
debug: resid <- object$residuals
Browse[2]>
debug: hat <- lm.influence(object, do.coef = FALSE)$hat
Browse[2]>
Error in if (model$rank == 0) { : argument is of length zero

I'm not familiar with survival models nor tobit regression. Read ?residuals.survreg and see if that is doing the right thing regarding standardising the residuals (there is something in there about using sigma). otherwise you might have to cook this yourself or contact the author of the survival package for suggestions as to how to compute the standardised residuals that you want.


text:
Q: Any lexicon for age, gender and ocuupation to extract from tweets in R? There is lexicon available for sentiment.Likewise any lexicon for age, gender, and occupation that can be used in R and extract relevant demographics data from tweets.
Any function related to gender, age and occupation in R.

A: You will need to do some reading, it is not a simple plug and play thing yet, but there is solid work for Facebook & Twitter demographic work.
This is the link to the ZIP of the lexicon:
2004 Age & Gender Lexica
Here is a link to a paper (it is academic and heavy) it explains the limit and scope of accuracy for this lexicon:
Paper on this lexicon and how it was developed and tested
Here is some guidance in getting started with this type of analysis:
Age Gender Tutorial Video
ANd some information on how to bring it together with other demography including occupation.
Demography and Twitter
It is not a simple ANSWER, because we are not yet at the stage with this yet. But this should get you going!


text:
Q: Self joining a table n times I'm trying to find a biological "find core genome of a given set of organisms" problem. Essentially, given a list of organisms, find all genes that are common to them. To abstract away biology, you can think of find all colours that are favourite amongst a list of people (one person can have multiple favourite colours).
Database table would look like:
name | fav_colour
john | red
john | blue
john | green
jason | red
jason | blue
matt | red
matt | teal

User can specify a set of names like [john, jason] to get out [red, blue], or [john] to get [red, blue, green], or [john, jason, matt] to get [red].
I'm trying to solve this by doing n number of self joins where n is the number of names supplied.
Is there any way for me to do n number of self joins of tables to solve this problem for any number of names supplied? I tried to look for a way to do this via Postgres functions but can't figure out the n number of self joins part... any help or pointers towards the correct direction would be appreciated.
And no, unfortunately I can't change the schema to do these type of queries easier.

A: I don't think you need self-joins for this.  You can use aggregation and a HAVING clause:
with t(name, fav_colour) as (
      values ('john', 'red'),
             ('john', 'blue'),
             ('john', 'green'),
             ('jason', 'red'),
             ('jason', 'blue'),
             ('matt', 'red'),
             ('matt', 'teal')
     )
select fav_colour
from t
where name in ('john', 'jason')
group by fav_colour
having count(*) = 2;

The value "2" is the number of names in the list.  Changing the IN list and the count are the only changes you need.


text:
Q: Hawtio not recognizing Jboss EAP I have downloaded latest hawtio and deployed in my Jboss EAP 6.2
I followed the instructions here to make the hawtio war compatible with jboss eap.
However, I found that hawtio web app was up but was not showing local jboss server mbeans on which it was deployed.
Can you please point out what I am missing here.

A: You may want to take a look at wildfly-camel module that ships with hawtio supported out of the box. This module is intended of EAP / wildfly containers

*

*https://github.com/wildfly-extras/wildfly-camel

*http://wildflyext.gitbooks.io/wildfly-camel/content/features/hawtio.html


text:
Q: Summing the result of a query Ok, so I know what this query should give, it should give the sum of the total it is outputting. I am having trouble figuring out how to sum the results. The database i am using is the publishers database
Here is my query
SELECT DISTINCT authors.state, qty*price as total
from authors
JOIN titleauthor on titleauthor.au_id = authors.au_id
JOIN titles on titles.title_id = titleauthor.title_id
JOIN sales on sales.title_id = titles.title_id
JOIN stores on stores.stor_id = sales.stor_id
WHERE authors.state LIKE stores.state

and Here is the output it gives
CA 104.6500
CA 299.8000
CA 299.8500
CA 1000.0000

A: The joins give you duplicates because they include more than one table representing a many-to-many relationship and the filtering is not sufficient to preclude the many-to-many tables from returning more than one row based on the given join conditions.
You could avoid duplicates by introducing a semi-join in the form of an EXISTS predicate and subsequent moving some of the tables there. Here's one possible way of using EXISTS in your situation:
SELECT
  stores.state,
  SUM(qty * price)
FROM sales
INNER JOIN stores ON sales.stor_id  = stores.stor_id
INNER JOIN titles ON sales.title_id = stores.title_id
WHERE EXISTS (
  SELECT *
  FROM authors a
  INNER JOIN titelauthor ta ON a.au_id = ta.au_id
  WHERE ta.titel_id = titles.title_id
    AND a.state LIKE stores.state
)
GROUP BY
  stores.state

The central table is most likely sales, it's where the figures come from. Therefore, the query is being built around sales. Other tables are joined explicitly (using a JOIN clause) as long as they return only one row for every row of sales. Once a table is going to return more than one row, it gets moved to EXISTS.
There's one more thing. While working on this query, I noticed that one join may be redundant (in your query as well as in mine). The table is titles. If your foreign keys are in order, you shouldn't need to join to titles, as titleauthor could be joined directly to stores on title_id. (Even if you don't have the corresponding foreign keys, you still don't have to include titles, as any possible non-existent titles referenced by either titleauthor or sales would be filtered out either way.)
So the final query might look like this:
SELECT
  stores.state,
  SUM(qty * price)
FROM sales
INNER JOIN stores ON sales.stor_id  = stores.stor_id
WHERE EXISTS (
  SELECT *
  FROM authors a
  INNER JOIN titelauthor ta ON a.au_id = ta.au_id
  WHERE ta.titel_id = sales.title_id
    AND a.state LIKE stores.state
)
GROUP BY
  stores.state

A: SELECT DISTINCT authors.state, sum(qty*price) as total
from authors
JOIN titleauthor on titleauthor.au_id = authors.au_id
JOIN titles on titles.title_id = titleauthor.title_id
JOIN sales on sales.title_id = titles.title_id
JOIN stores on stores.stor_id = sales.stor_id
WHERE authors.state = stores.state
group by authors.stat


text:
Q: Vertical align of text in CSS I am trying to align a Fontawsome Icon (http://fortawesome.github.io/Font-Awesome/) with some text next to it. In this case a phone number next to a - you guessed it - phone icon.
HTML

    111 222 333

CSS
.phone {
    font-size: 1.5em;
    vertical-align: middle;
}

http://jsfiddle.net/ypLN5/
I tried several things playing around with line-height and vertical-align: middle but I haven't come up with a solution.
May you help please?

A: There is a very very easy way of doing this:
i, span{
    vertical-align:middle;
}

Demo fiddle

A: SW4's answer is correct.
Although if you are looking to center inside of a bigger element using display: table-cell and will solve your problem:
http://jsfiddle.net/3U2Vj/1/


text:
Q: Oracle.EntityFrameworkCore 5.12.3 - CLOBs are returned as null How can I read a CLOB column using Oracles Entity Framework core (latest version)?
I have tried this (from https://docs.oracle.com/en/database/oracle/oracle-data-access-components/19.3/odpnt/EFCoreLargeCharacter.html):
modelBuilder.Entity<Email>()
            .Property(a => a.Body)
            .HasColumnName("BODY")
            .IsUnicode(false)
            .HasColumnType("CLOB");

and this:
[Column("BODY", TypeName = "CLOB")]

It always returns null!  How can I populate the CLOB?
var emails = await context.Emails.ToListAsync();
context: public DbSet<Email> Emails { get; set; }


text:
Q: ListAddapter in FragmentList Why are these errors appearing?
04-10 17:07:57.880: E/AndroidRuntime(917): Process: com.example.programming_fragments, PID: 917
04-10 17:07:57.880: E/AndroidRuntime(917): java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.ListFragment.ensureList(ListFragment.java:344)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.ListFragment.onViewCreated(ListFragment.java:145)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:925)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.os.Handler.handleCallback(Handler.java:733)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.os.Handler.dispatchMessage(Handler.java:95)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.os.Looper.loop(Looper.java:136)
04-10 17:07:57.880: E/AndroidRuntime(917):  at android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 17:07:57.880: E/AndroidRuntime(917):  at java.lang.reflect.Method.invokeNative(Native Method)
04-10 17:07:57.880: E/AndroidRuntime(917):  at java.lang.reflect.Method.invoke(Method.java:515)
04-10 17:07:57.880: E/AndroidRuntime(917):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 17:07:57.880: E/AndroidRuntime(917):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 17:07:57.880: E/AndroidRuntime(917):  at dalvik.system.NativeStart.main(Native Method)

Code:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="schemas.android.com/apk/res/android"; android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffeeeeee" android:gravity="center" android:orientation="vertical" > <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>

A: Your content must have a ListView whose id attribute is android.R.id.list. So go to your xml that contains your listview and add the id so it looks something like:
<ListView android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

You can, of course, have a custom list, but I am going to assume you are using a simple list adapter based on your question, so this should work for you.

A: Issue is with the layout you have set in onCreateView().
If you override the onCreateView in your custom ListFragment , you need to inflate a layout which has a ListView in it, with id android:id="@android:id/list".
If you really want to have a different layout than the default one used in ListFragment , then only override the onCreateView() , else use the default layout.
This is what the code in ListFragment,. You can look at the default layout (R.layout.list_content) and see if you really need to override this layout
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(com.android.internal.R.layout.list_content,
            container, false);
}


text:
Q: How to redirect to different URLs when we click on each row in the table i.e, click on each row element must redirect to different URLs? How to redirect to different URLs when we click on each row in the table i.e, click on each row element must redirect to different URLs?
I am working on Mustache Spring MVC framework where the entire data from MOngodb is retrieved onto a placeholder in the view page.So, now I need to be make this data click enable and each data row when clicked need to redirect to different URLs
This is my table

    Book Name
    Description

  {{#books}}

    {{book_name}}

    {{book_details}}

  {{/books}}

Output looks like list of books and its description
Now when I click on book1 it should go to some other URL and when I click on book2 it must go to another URL and so on

A: This must be a quick solution

                Book Name
                Description

            {{#books}}

                {{book_name}}

                {{book_details}}

            {{/books}}

A: You can try something like this. Here each url will be like some_url/book_name.

      {{book_name}}

   {{book_details}}

A: if I understood your problem correctly this will solve your problem
Add a field bool_url ( say bookUrl java specific ) to your Book bean.
While adding book to database you need to specify that book_url too.
then following will work for you

        Book Name
        Description

    {{#books}}

            {{book_name}}
            {{book_details}}

    {{/books}}


text:
Q: Unable to customize user registration with djoser I have being using djoser with django to handle register and login. I have no issue configuring the default register field (username, email, password and re_password).
But now I want to customize the register field and add gender and hobby. However, I keep getting the following error when I try to register another user with these additional fields that djoser
does not provide by default.
user = User.objects.create_user(**validated_data)
TypeError: UserManager.create_user() missing 2 required positional arguments: 'gender', 'hobby'

The error is coming from the function in models.py file for creating new user shown below:
class UserManager(BaseUserManager):
    def create_user(self, username, email, gender, hobby, password=None, **extra_fields):
        if username is None:
            raise ValueError(_('Username is required'))
        if email is None:
            raise ValueError(_('Enter a functional email address'))

        if gender is None:
            raise ValueError(_('Provide your gender'))

        if hobby is None:
            raise ValueError(_('Enter hobby'))

        user = self.model(email=self.normalize_email(email) **extra_fields)
        user.username=username
        user.gender=gender,
        user.hobby=hobby
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self,username, email, gender, hobby, password=None):
        if password is None:
            raise ValueError(_('Please enter your password'))

        user = self.create_user(email=self.normalize_email(email))
        user.username=username
        user.gender=gender,
        user.hobby=hobby
        user.is_superuser = True
        user.is_staff = True
        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=25, unique=True, default='')
    email = models.EmailField(max_length=255, unique=True)
    gender = models.CharField(max_length=50, null=True, blank=True)
    hooby = models.CharField(max_length=50, null=True, blank=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def __str__(self):
        return self.username

serializers.py

class UserCreateSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = (
            'id',
            'username', 'email',
            'gender', 'hobby',
            'password'
            )

settings.py
djoser = {
'SERIALIZERS': {
        'user_create': 'accounts.serializers.UserCreateSerializer',
        'user': 'accounts.serializers.UserCreateSerializer',
        'current_user': 'accounts.serializers.UserCreateSerializer',
        'user_delete': 'djoser.serializers.UserDeleteSerializer',
    }
}

I have gone through the code several times I still can't find why I'm getting the error

A: I had the same problem. added the field into the REQUIRED_FIELDS in the User model and problem solved.
just add gender and hobby into the REQUIRED_FIELDS

A: one problem is for sure that you have "hooby" as field


text:
Q: Forcing viewDidLoad to be called again after pushing to a new UIViewController I have a tabbar controller with 2 tabs in it.
Tab 1 gets started and I click on tab 2. In the UIViewController inside of Tab2 is a button that gets pushed with a UINavigationController. This all worrks fine. But when I hit back I want to force TabBarController class to call viewDidLoad again.
How do I accomplish that?

A: You can't.
If you want to do something each time tab 1 is shown you have to use viewWillappear or viewDidAppear.
Check Responding to View Events on Apple documentation.


text:
Q: Unable to see Xamarin insight events I've setup Xamarin Insights, and was able t catch 2 exceptions. I added some Xamarin.Insights.Track(...... statements to track some functionality.
However I can not see this on the web portal. The overview displays 5 users 80+ sessions and 2 open issues (the exceptions). Is the Tracking/event feature a special paid feature or?

A: (While this response is bit late, maybe it's still useful?)
Short version: Insights Event tracking is a paid feature.
Longer version: In order to gain access to Insights Event tracking you would need to upgrade your Insights subscription tier to an Enterprise level (which I'm not sure is possible post-merge).  At this point you would benefit more by migrating your app to utilize HockeyApp (if you haven't already).  I suppose if you absolutely need this functionality, perhaps you could write into Xamarin support or sales.
Old Xamarin Insights tier page via web.archive.org (https://web.archive.org/web/20160304014709/http://xamarin.com/insights#pricing)


text:
Q: Error exportando datos a Excel desde C# Necesito exporter los datos de un DataGriedView a una hoja de Excel. Tengo el siguente código:
public void exportar(DataGridView dgv)
{
    try
    {
        SaveFileDialog fichero = new SaveFileDialog();
        fichero.Filter = "Excel (*.xlsx)|*xlsx";
        fichero.FileName = "ArchivoExportado";
        if (fichero.ShowDialog() == DialogResult.OK)
        {
            Microsoft.Office.Interop.Excel.Application aplicacion;
            Microsoft.Office.Interop.Excel.Workbook libro;
            Microsoft.Office.Interop.Excel.Worksheet hoja;

            aplicacion = new Microsoft.Office.Interop.Excel.Application();
            libro = aplicacion.Workbooks.Add();
            hoja = (Microsoft.Office.Interop.Excel.Worksheet)libro.Worksheets.get_Item(1);

            for (int i = 0; 1 < dgv.Rows.Count - 1; i++)
            {
                for (int j = 0; 1 < dgv.Columns.Count; j++)
                {
                    if ((dgv.Rows[i].Cells[j].Value == null) == false)
                    {
                        hoja.Cells[i + 1, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
                    }
                }
            }
            libro.SaveAs(fichero.FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
            libro.Close(true);
            aplicacion.Quit();
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error"+ex.ToString());
    }
}

Cuando doy clic en el boton Exportar me muestra un error:

La línea 551 es el if: if ((dgv.Rows[i].Cells[j].Value == null) == false)
No sé cuál es el problema.

A: No hagas uso del for para recorrer las rows del grid usa el foreach
int i = 1;
foreach (var row in dgv.Rows)
{
    int j = 1;
    foreach(var col in dgv.Columns)
    {
        if (row.Cells[col.Index].Value != null)
        {
            hoja.Cells[i, j] = row.Cells[col.Imdex].Value.ToString();
        }
        j++;
    }
    i++;
}

Tambien recomendaria que evites de usar las librerias de interop del office para exportar a excel, usa unas basadas en open xml como ser
ClosedXML - The easy way to OpenXML
de esta forma no tendras problemas con COM y no requieres office instalado para poder exportar


text:
Q: C++ Queue from Linked List Good evening. I have been trying to implement a Queue class in C++, taking a previously created Linked List class as a base.
Linked Linked List:
#include <cstddef>
#include <iostream>
#include <cstdio>

using namespace std;

template <class T>
class LinkedList {

public:
    LinkedList() {
        head = NULL;
    }
    ~LinkedList() {
        MakeEmpty();
    }

    struct Node {
        T value;
        Node *next;
    };

    Node* getHead() {
        return head;
    }

    void Print();
    void Insert();
    void MakeEmpty();

private:
    Node *head;     // Head of the linked list.
};

Queue class:
#include "LinkedList.h"

template <class T>
class Queue {

public:
    Queue() {
        LinkedList<T>::Node *tnode = Q.getHead();
    }

    ~Queue() {
        Q.MakeEmpty();
    }

    void Enqueue( T x ) {
        LinkedList<T>::Node *cnode = Q.getHead();

        //Find the last element of Q
        while( cnode -> next != NULL ) {
            cnode = cnode -> next;
        }
        //Add x to the end of the queue
        Q.Insert( x );
    }

    void Dequeue() {
        LinkedList<T>::Node *hnode = Q.getHead();
        //Rest of function
    }

    void Print() {
        Q.PrintList();
    }

private:
    LinkedList<T> Q;
};

As you probably noticed, I am making them template classes. When compiling, I am told that tnode (found in the constructor of the Queue class) has not been declared in the scope. Any suggestions on how to fix this?
EDIT 1: The error message that I am getting is:

RCQueue.h: In constructor 'Queue::Queue()':
  RCQueue.h:8:28: error: 'tnode' was not declared in this scope
         LinkedList::Node *tnode = Q.getHead();

The main purpose of my constructor is to initialize the "head" pointer from the LinkedList class as NULL. I was also curious as to how one could go about declaring a variable of a structure that was declared in another template class.

A: Enqueue Algorithm :
1. Create a newNode with data and address.
2. if queue i.e front is empty
i.  front = newnode;
ii. rear  = newnode;
3. Else
i.rear->next = newnode;
ii.rear = newnode;

Dequeue Algorithm :
1. if queue is i.e front is NULL      printf("\nQueue is Empty \n");
2. Else next element turn into front
i.  struct node *temp = front ;
ii. front = front->next;
iii.free(temp);

C++ implementation :
     #include <bits/stdc++.h>
      using namespace std;

      struct node
      {
        int data;
        node *next;
      };

      node *front = NULL;
      node *rear =NULL;

     void Enque(int data)
     {
           node *newnode = new node;
           newnode->data = data;
           newnode ->next = NULL;

           if(front==NULL)
           {
               front=newnode;
               rear=newnode;
           }

           else
           {
              rear->next = newnode;
              rear = newnode;
           }
      }

    void Deque()
    {
       struct node *temp;

       if (front == NULL)
       {
         printf("\nQueue is Empty \n");
         return;
       }

       else
       {
           temp = front;
           front = front->next;
           if(front == NULL)  rear = NULL;
           free(temp);
       }
     }

    void display()
    {
        node *temp=front;
        if(front==NULL)
        {
          printf("\nQueue is Empty \n");
        }

        else
        {
            while(temp != NULL)
            {
                cout<<temp->data<<" ";
                temp = temp->next;
            }
        }
        cout<<endl;
    }

A: You need typename in front of every use of the Node type in LinkedList that you reference within Queue because its dependent on the template parameter T. In specific,
template <class T>
class Queue {

public:
    Queue() {
        typename LinkedList<T>::Node *tnode = Q.getHead();
    }

    ~Queue() {
        Q.MakeEmpty();
    }

    void Enqueue( T x ) {
        typename LinkedList<T>::Node *cnode = Q.getHead();

        //Find the last element of Q
        while( cnode -> next != NULL ) {
            cnode = cnode -> next;
        }
        //Add x to the end of the queue
        Q.Insert( x );
    }

    void Dequeue() {
        typename LinkedList<T>::Node *hnode = Q.getHead();
        //Rest of function
    }

    void Print() {
        Q.PrintList();
    }

private:
    LinkedList<T> Q;
};

Notice the addition of typename before the uses of LinkedList<T>::Node.
Of course you'll also hear complaints about the missing definition of MakeEmpty() within LinkedList that is called in your Queue class, so just add a definition for it.
For more information on why typename is needed, this post explains its pretty clearly.


text:
Q: Three.js: Scaling issue when drawing earth with an image as surface texture I am trying to draw earth with a bunch of satellites and users on earth and lines pointing from satellite to users but I am completely failing.
Scaling issue:

And when I zoom out a little:

import React, { useRef } from "react";
import { useLoader, useFrame } from "@react-three/fiber";
import { TextureLoader } from "three";
import { OrbitControls, Stars } from "@react-three/drei";
import * as THREE from "three";
import data from "../data.json";

import EarthDayMap from "../assets/img/earth_texture_map_1000px.jpg";

const COLORS = {
  0: 'white',
  1: 'lightgrey',
  2: 'orange',
  3: 'pink'
};

const EARTH_RADIUS = 4000;

export function Earth(props) {
  const [colorMap, normalMap, specularMap, cloudsMap] = useLoader(
    TextureLoader,
    [EarthDayMap]
  );

  const earthRef = useRef();
  const cloudsRef = useRef();
  const satellitesRef = useRef([]);
  const usersRef = useRef([]);

  useFrame(({ clock }) => {
    const elapsedTime = clock.getElapsedTime();

    earthRef.current.rotation.y = elapsedTime / 24;
    cloudsRef.current.rotation.y = elapsedTime / 24;
  });

  return (
    <>
      <ambientLight intensity={1} />
      <pointLight color="#f6f3ea" position={[5000, 0, 5]} intensity={1.2} />
      <Stars
        radius={30000}
        count={20000}
        factor={7}
        saturation={0}
        fade={true}
      />
      <mesh ref={cloudsRef} position={[0, 0, 0]}>
        <sphereGeometry args={[0, 32, 32]} />
        <meshPhongMaterial
          map={cloudsMap}
          opacity={0.1}
          transparent={true}
          side={THREE.DoubleSide}
        />
      </mesh>
      <group>
        {data.satellites.map(({ coordinate: { x, y, z }, id }, i) => <mesh
          key={id}
          ref={el => satellitesRef.current[i] = el}
          position={[x, y, z]}>
          <sphereGeometry args={[100, 32, 32]} />
          <meshPhongMaterial
            color='red'
            side={THREE.DoubleSide}
          />
        </mesh>)}
      </group>
      <group>
        {data.satellites.map(({ coordinate: { x, y, z }, id }, i) => <mesh
          key={id}
          ref={el => usersRef.current[i] = el}
          position={[x, y, z]}>
          <sphereGeometry args={[100, 32, 32]} />
          <meshPhongMaterial
            color='green'
            side={THREE.DoubleSide}
          />
        </mesh>)}
      </group>
      <group>
        {data.mappings.map(({ satellite: satelliteId, user: userId, color }, id) => {

          const satellite = data.satellites.find(s => s.id === satelliteId);
          const user = data.users.find(u => u.id === userId);

          return <line key={id}
            points={[
              [satellite.coordinate.x, satellite.coordinate.y, satellite.coordinate.z],
              [user.coordinate.x, user.coordinate.y, user.coordinate.z]
            ]}
            color={COLORS[color]}
          />
        })}
      </group>
      <mesh ref={earthRef} position={[0, 0, 0]}>
        <sphereGeometry args={[EARTH_RADIUS, 256, 256]} />
        <meshPhongMaterial specularMap={specularMap} />
        <meshStandardMaterial
          map={colorMap}
          normalMap={normalMap}
          metalness={0.4}
          roughness={0.7}
        />
        <OrbitControls
          enableZoom={true}
          enablePan={true}
          enableRotate={true}
          zoomSpeed={0.6}
          panSpeed={0.5}
          rotateSpeed={0.4}
        />
      </mesh>
    </>
  );
}

Repository

A: Your Earth radius seems to be 4000 units. The Perspective camera by default has a near and far range of 0.1 to 2000, so most of the sphere is probably outside the camera's frustum. You'll have to adjust these values. I'd try camera.near = 100 and far at 10000, for starters.
https://threejs.org/docs/?q=camer#api/en/cameras/PerspectiveCamera.far


text:
Q: How to write numbers in the language of first-order set theory. I saw this Numberphile video (link at bottom), and at around 10:10 they talk about writing numbers in the language of first-order set theory. For example, to write $0$, it showed the empty set:
$$\exists x_1\neg\exists x_2(x_2\in x_1)$$
And to write $1$, it said: $$\exists x_1\forall x_2(x_2\in x_1\leftrightarrow(\neg\exists x_3(x_3\in x_2)\vee\forall x_3(x_3\in x_2\leftrightarrow\neg\exists x_4(x_4\in x_3))))$$

Edit: An answer has corrected this and showed that the above formula is for $2$, not $1$. I have left the above as this is what the video showed.

The video then alluded to writing other numbers, saying that it takes less symbols as the numbers get larger.
This made me curious and I wanted to find out more about this topic.
I have done research and tried to find how to write other numbers in the language of first-order set theory, but I haven't been able to find anything.

Question
Does anyone know any resources/websites with information on how to write numbers in the language of first-order set theory? I have searched the internet many times but I haven't been able to find this.

Or is it just that there are no websites about this because there is no use for them and nobody really cares about them?
Thanks.
Numberphile video-The Daddy of Big Numbers (Rayo's Number)-Numberphile https://youtu.be/X3l0fPHZja8

A: The logical formulas you have written describe the Von Neumann Ordinals for 0 and 1. This is one particular encoding of numbers in terms of sets, which can be easily turned into numbers in terms of logical formulas by writing a sentence saying explicitly what is in that set (this describes the set uniquely by extensionality).
For instance, to say $0 = \emptyset$, which it is, we would instead say $\forall x . x \not \in 0$. That formula forces $0 = \emptyset$. The formula you've written says "the number $0$ exists".
Similarly, $1 = \{ \emptyset \}$. So we can express in the language of logic by writing
$\forall x . x \in 1 \leftrightarrow x = 0$. If we want to be purists, and avoid using the defined symbol $0$:
$$ \forall x . x \in 1 \leftrightarrow (\forall y . y \not \in x)$$
The second formula you've written is actually the number $2$. Well, it's the formula saying "the number $2$ (which it is calling $x_1$) exists", but they're very similar ideas.
If you want a reference for this material, any decent book on set theory will do. In fact, just knowing that these are called "von Neumann Ordinals" will help tremendously. Good luck!
Edit:
The sentence you have written is quite long, so I'll color code it for ease of reference. Each part of this says something that points towards "$x_1 = 2$". Let's break it down:
$$
\exists x_1 \forall x_2
(
  x_2 \in x_1 \leftrightarrow
  (
    \color{blue}{\lnot \exists x_3 (x_3 \in x_2)}
    \lor
    \color{green}{\forall x_3 (x_3 \in x_2 \leftrightarrow}
    \color{red}{\lnot \exists x_4 (x_4 \in x_3)}\color{green}{)}
  )
)
$$
This says:

*

*there exists a set $x_1$ (which we will soon see to be $2$) such that

*$x_2 \in x_1$ iff some condition holds on $x_2$.

*

*remember, we want this condition to be "$x_2 = 0 \lor x_2 = 1$"

*the blue part of this condition says $x_2 = \emptyset$, so $x_2 = 0$

*the green part says the only thing in $x_2$ has a unique element, colored red

*

*notice the red part says "$x_3 = \emptyset$", or, $x_3 = 0$

*so the green part says $x_2 = \{ \emptyset \}$, equivalently, $x_2 = 1$

*so the blue and green parts together say $x_2 = 0 \lor x_2 = 1$

*this is exactly what we wanted, and $x_1 = \{0, 1\} = 2$

I hope this helps ^_^


text:
Q: How to transmit files between two AVDs using TCP? I have established two AVDs and would like to transfer files between them using TCP ; How do I establish this ?

A: Since your AVDs are running locally, they can be binded to localhost on different ports, and you can take use of Sockets.
Sockets:
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
You might need to setup some forwarding stuff like below:
How can I forward my localhost IP-Address to an Android Emulator?


text:
Q: Sequence generator warning in JPA Application after upgrading to hibernate 5 I faced following issues after upgrading to hibernate 5  in JPA Application.
HHH90000015: Found use of deprecated [org.hibernate.id.MultipleHiLoPerTableGenerator] table-based id generator; use org.hibernate.id.enhanced.TableGenerator instead.

and
HHH90000014: Found use of deprecated [org.hibernate.id.SequenceGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead.

The entities are annotated like this:enter code here
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="TB_SEQ_GEN")
private long id;

and
@Id
@GeneratedValue
private long id;`

persistence.xml:`
<shared-cache-mode>NONE</shared-cache-mode>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"></property>
<property name="hibernate.show_sql" value="false"></property>
<property name="hibernate.hbm2ddl.auto" value="update"></property>
<property name="hibernate.id.new_generator_mappings" value="true">
</property>

orm.xml:
<table-generator name="TB_SEQ_GEN" table="SEQUENCE_GENERATOR" schema="tb" pk-column-name="SEQ_NAME" value-column-name="NEXT_VAL" pk-column-value="TB" initial-value="1000" allocation-size="1000">

A: Try to change mapping to something like this:
@Id
@GenericGenerator(
        name = "myTableGenerator",
        strategy = "org.hibernate.id.enhanced.TableGenerator",
        parameters = {
                @Parameter(name = "table_name", value = "MY_SEQUENCES")
        }
)
@GeneratedValue(generator = "myTableGenerator")
private long id;

and:
@Id
@GenericGenerator(
        name = "mySequenceGenerator",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "MY_SEQUENCE"),
                @Parameter(name = "initial_value", value = "1000"),
                @Parameter(name = "increment_size", value = "1")
        }
)
@GeneratedValue(generator = "mySequenceGenerator")
private long id;


text:
Q: Why Are My Random List Items Always Identical? I have a list and then two randomly selected items from them.
But those two items are always the same. Why?
\documentclass{article}

\usepackage{pgf}
\usepackage{pgffor}
 \pgfmathsetseed{\number\pdfrandomseed}

\newcommand{\InitVariables}
{%
\pgfmathdeclarerandomlist{List}{{2}{3}{4}{5}{6}{7}{8}{9}}
\pgfmathrandomitem{\VarA}{List}
\pgfmathrandomitem{\VarB}{List}
}

\begin{document}

ATTEMPT ONE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

ATTEMPT TWO
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

ATTEMPT THREE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

\end{document}

A: \pgfmathrandomitem doesn't actually define \varA to be a randomly selected item, it defines it to choose such an item, and then \VarB gets the same definition, both are defined to be
> \VarB=macro:
->\csname pgfmath@randomlist@List@\pgfmath@randomtemp \endcsname .

as shown by the \show.
Here as the items are unexpandable you cansimply edef expand the definitions to get the actual values into the macros, as shown by the 2nd and 4th \show.
> \VarA=macro:
->5.

example document:
\documentclass{article}

\usepackage{pgf}
\usepackage{pgffor}
 \pgfmathsetseed{\number\pdfrandomseed}

\newcommand{\InitVariables}
{%
\pgfmathdeclarerandomlist{List}{{2}{3}{4}{5}{6}{7}{8}{9}}
\pgfmathrandomitem{\VarA}{List}
\show\VarA
\edef\VarA{\VarA}
\show\VarA
\pgfmathrandomitem{\VarB}{List}
\show\VarB
\edef\VarB{\VarB}
\show\VarB
}

\begin{document}

ATTEMPT ONE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

ATTEMPT TWO
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

ATTEMPT THREE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

\end{document}


text:
Q: Is completion block syntax for MFMailComposeViewController mailComposeDelegate possible? I would like to use the MFMailComposeViewController mailComposeDelegateproperty with completion block syntax, but not sure if that is possible.  Something similar to how the TWTweetComposeViewController completionHandler property works:
TWTweetComposeViewController __weak *twee = tweeter;
tweeter.completionHandler = ^(TWTweetComposeViewControllerResult result) {
    // code here
};

The code I have creates the MFMailComposeViewController, but then has to save a reference my viewController parameter, since this "share via email" functionality is not in a UIViewcontroller, but a custom MYSharing class.
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
// more code here
_viewController = viewController;
picker.mailComposeDelegate = self;
[viewController presentModalViewController:picker animated:YES];

The mailComposeController:didFinishWithResult:error: from MFMailComposeViewControllerDelegate uses that _viewController to dismiss the modal.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    [_viewController dismissModalViewControllerAnimated:YES];
}

Not understanding blocks very well, is there some syntax that look like this?
picker.mailComposeDelegate = ^(???)(??? ??? ???) {
    [viewController dismissModalViewControllerAnimated:YES];
}

I did find MFMailComposeViewController(BlocksKit) (which has source on github), but even with that, the syntax conversion trips me up.

A: No completion handler for MFMailComposeViewController now.
if you want to reference the view controller who presented the MFMailComposeViewController, code like below, use presentingViewController property.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    [controller.presentingViewController dismissModalViewControllerAnimated:YES];
}

A: Why don't you just call [self dismissModalViewControllerAnimated:YES]; from the MFMailComposeViewControllerDelegate method?


text:
Q: python Argumentparser. executable file and source-code file as arguments I can't figure out how to pass arguments from the command line properly. I want to pass an executable program and a source code file as arguments. It seems to be working well until I try to open the source code file. What am I doing wrong?
Command line:
$ my_script.py  my_executable  source_code.fe

Code:
import sys, argparse
def main():

    parser = argparse.ArgumentParser(description='Description of program')

    parser.add_argument('exe', type=argparse.FileType('r'))
    parser.add_argument('src_file', type=argparse.FileType('r'))

    #args = vars(parser.parse_args())
    args = parser.parse_args()

    infile = open(args.src_file)
    #child = subprocess.run( [exe], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=infile)

   if __name__ == "__main__":

A: FileType essentially produces a wrapper around open. The attribute in the value returned by parse_args is a file-like object already.
parser = argparse.ArgumentParser(description='Description of program')

parser.add_argument('exe', type=argparse.FileType('r'))
parser.add_argument('src_file', type=argparse.FileType('r'))

args = parser.parse_args()

infile = args.src_file

At its simplest, you could define FileType yourself as
def FileType(*args, **kwargs):
    def _(fname):
        return open(fname, *args, **kwargs)
    return _

The real definition handles - as an alias for standard input or standard output as appropriate for the given mode, as well as better error handling.


text:
Q: Convert node.js HTTP response function (using "request" library) to use streams I'm using the request library in node.js, which downloads an HTML body response, but does so in chunks. Currently I'm just concatenating them into a dataChunks variable and using a hacked-together test to see when it's all downloaded. However, I've skim-read the Stream Handbook, and this seems like a case where it might be appropriate to use a stream to get the data chunks. I don't fully understand how I'd do this though, so would appreciate any help. The relevant code is below:
var dataChunks = "";

request.get({ url: baseUrl + path })
            .on("error", function(err) { throw new Error(err); })
            .on("response", function(res) {
                if (res.statusCode === 200) {
                    res.on("data", function(data) {
                        var dataString, dt;

                        dataChunks += (dataString = data.toString());

                        if ((dt = dataString.slice(-100).trimRight()).lastIndexOf("</html>") === dt.length - 7) {
                            // do stuff with dataChunks
                        }
                    });
                }
            });

Thank you in advance for any help.

A: You don't need a stream for that.  From the request Readme:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
 }
})

Stream example:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))


text:
Q: Return the value from Task.Run I am loading an XML file using async/await but cannot work out how to return the value 'xe' from the Task.Run. How do I return this value from within the task shown in the code below?
 try
        {
            Exception exceptionOut = null;

            await Task.Run(() =>
            {
                //inside
                try
                {

                    XElement xe = XElement.Load(filePath);
                }
                catch (Exception exceptionIn)
                {
                    exceptionOut = exceptionIn;
                }
            });

            if (exceptionOut != null)
            {
                throw exceptionOut;
            }
        }
        catch (Exception ex)
        {
            //show the error
            MessageBox.Show(ex.Message);
        }

A: I suppose this is what you want:
try
{
    XElement xe = await Task.Run(() =>
    {
        return XElement.Load(filePath);
    });
}
catch (Exception ex)
{
    //show the error
    MessageBox.Show(ex.Message);
}


text:
Q: C-Style Unions in C# I apologize for the naming of these fields, but I'm have to block out things like field names based on an NDA.
So basically I am in C# and I am using Interop to communicate with an external library, which requires specific structures to be passed by reference, one of which uses a union.  This is the struct that seems to be giving me a headache, because I have found a few references online on how to union two data types but not two structs together.  Here are the basics of the two struct
struct datatype1
{
    char field1;
    char field2;
    char field3;
    char field4;
    char field5;
    char field6;
    char field7;
};

struct datatype2
{
    public uint field8;
    public uint field9;
}

struct datatype3
{
    unsigned int field10;
    union
    {
        datatype1 field11;
        datatype2 field12;
    } field13;
    uint field14;
    unsigned char field15;
    uint field16;
}

What would the resulting structs look like in c#?  I have had a few ideas, some of which seem to work but result in a blue screen with a message of reference_by_pointer after a while, and I was thinking that maybe some thing about my struct definition is wrong, and somehow the data is not fitting in the struct correctly.  Here is what I currently have:
    [StructLayout( LayoutKind.Sequential )]
    public struct datatype1
    {
        public byte field1;
        public byte field2;
        public byte field3;
        public byte field4;
        public byte field5;
        public byte field6;
        public byte field7;
    }

    [StructLayout( LayoutKind.Sequential )]
    public struct datatype2
    {
        public uint field8; // Digital i/p event
        public uint field9;
    }

    public struct datatype3
    {
        public uint field10;

        [StructLayout( LayoutKind.Explicit )]
        public struct AnonymousStruct
        {
            [FieldOffset( 0 )]
            public datatype1 field11;

            [FieldOffset( 0 )]
            public datatype2 field12;
        }

        public AnonymousStruct field13;

        public uint field14;

        public byte[] field15;

        public uint field16;
    }

Am I doing this all wrong?
EDIT:  In response to a request for more info, here is an example usage, but not that I cannot provide the population of the fields because that is hidden in the API.
Also, it is possible it is a problem with the API, but that is more unlikely than me screwing up the Interop to it.
    ...inside thread....
    datatype3 dt = new datatype3();
    while( true )
    {
        api.get_next_value( ref dt );
        PrintData( dt );
        Thread.Sleep( 55 );
    }

    /// <summary>
    /// Prints the data from the event.  Used for debugging purposes.
    /// </summary>
    /// <param name="evp"></param>
    private void PrintData( datatype3 evp )
    {
        if( evp.field10 == 2 )
        {
            Console.WriteLine( "datatype2" );
            Console.WriteLine( "\tfield8val: " + evp.field13.field12.field8);
            Console.WriteLine( "\tfield9val: " + evp.field13.field12.field9 );
        }
        else if( evp.de_type == 1 )
        {
            Console.WriteLine( "datatype1" );
            Console.WriteLine( "\tfield1val:  " + evp.field13.field12.field1 );
            Console.WriteLine( "\tfield2val:  " + evp.field13.field12.field2 );
            Console.WriteLine( "\tfield3val:  " + evp.field13.field12.field3 );
            Console.WriteLine( "\tfield4val:  " + evp.field13.field12.field4 );
            Console.WriteLine( "\tfield5val:  " + evp.field13.field12.field5 );
            Console.WriteLine( "\tfield6val:  " + evp.field13.field12.field6 );
            Console.WriteLine( "\tfield7val:  " + evp.field13.field12.field7 );
        }
        else
        {
            return;
        }
    }

I apologize for not being able to provide absolute calls or true context, but I must honor NDA's even if it means reducing the quality of answers.
EDIT 2: Is it at all possible that the two different sized datatypes being unioned together is having any affect on this situation?  I know that datatype1 has size of 7 bytes and datatype2 has a size of 8 bytes.  Could this cause some sort of memory issue?

A: There is no problem with your C# union. However, field15 is wrong. It's char in the C code and byte[] in the C# code. You need to declare it as byte in the C# code.
For what it's worth, you are safe to omit LayoutKind.Sequential since that is the default for a struct.


text:
Q: Empty space under iOS keyboard In my iOS app, after presenting the keyboard a second time, there is a blank space under the keyboard.

The space hides after pressing .?123.
I removed keyboardWillShowNotification and keyboardWillHideNotification and the same thing happens. I resize the UITextView at viewWillTransitionToSize:withTransitionCoordinator:, but I removed code to resize and the same thing happens.
It doesn't happen with my iPhone 7 but it happens with my iPad 6th gen. That's very strange because it's just on my app in this specific Text View.
Does that happened to someone? I can't find anything in Google.
Here is the source code of the View Controller: https://github.com/ColdGrub1384/Pyto/blob/master/Pyto/View%20Controllers/EditorViewController.swift
I use a view containing an UITextView inside it for syntax highlighting, but that has nothing to do with the bug because I also tested with a standard UITextView.

A: @objc protocol KeyboardConstraintListener: class
{
func didOpenKeyboard()
func didCloseKeyboard()
}

class KeyboardConstraint: NSLayoutConstraint
{
@IBOutlet
weak var listener: KeyboardConstraintListener?

@IBInspectable
var skipAutoCalculateMarginToBottom: Bool = false

@IBInspectable
var keepMarginWhenOpen: Bool = false

private var originalConstant: CGFloat = 0.0

override func awakeFromNib()
{
    super.awakeFromNib()
    self.originalConstant = self.constant

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(keyboardWillShow),
                                           name: UIResponder.keyboardWillShowNotification,
                                           object: nil)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(keyboardWillHide),
                                           name: UIResponder.keyboardWillHideNotification,
                                           object: nil)
}

deinit
{
    NotificationCenter.default.removeObserver(self)
}

@objc func keyboardWillShow(notification: Notification)
{
    self.listener?.didOpenKeyboard()
    self.updateConstant(notification: notification, showing: true)
}

@objc func keyboardWillHide(notification: Notification)
{
    self.listener?.didCloseKeyboard()
    self.updateConstant(notification: notification, showing: false)
}

private func updateConstant(notification: Notification, showing: Bool)
{
    let duration: TimeInterval = (notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.2

    guard let endFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else
    {
        return
    }

    guard let firstView: UIView = self.getView(item: self.firstItem) else
    {
        return
    }

    guard let secondView: UIView = self.getView(item: self.secondItem) else
    {
        return
    }

    guard let superview: UIView = firstView.superview else
    {
        return
    }

    let keyboardHeight: CGFloat = (showing ? max(endFrame.size.height - self.modifier(view: secondView), 0.0) : 0.0)

    CATransaction.begin()
    CATransaction.setDisableActions(true)
    superview.layoutIfNeeded()
    CATransaction.commit()

    UIView.animate(
        withDuration: duration,
        delay: 0,
        options: [.curveLinear],
        animations:
        {
            self.constant = keyboardHeight + self.originalConstant
            superview.layoutIfNeeded()
    },
        completion: nil)
}

private func modifier(view: UIView) -> CGFloat
{
    guard let window: UIWindow = view.window else
    {
        return 0.0
    }

    guard let superview: UIView = view.superview else
    {
        return 0.0
    }

    guard !self.skipAutoCalculateMarginToBottom else
    {
        return 0.0
    }

    let origin: CGPoint = superview.convert(view.frame.origin, to: nil)
    let bottom = origin.y + view.bounds.size.height
    let expand = window.bounds.size.height - bottom
    return expand - (self.constant - self.originalConstant) - (self.keepMarginWhenOpen ? self.originalConstant : 0.0)
}

private func getView(item: AnyObject?) -> UIView?
{
    if let view = item as? UIView
    {
        return view
    }
    else if let view = (item as? UILayoutGuide)?.owningView
    {
        return view
    }
    return nil
}

}
Create a constraint such that textView.bottom = safeArea.bottom

A: iOS / iPadOS 13 fixes this bug.


text:
Q: I have to fing avg of a number of arrays of positive integers with 0 marking the end of each of the array I'm given a range of arrays of positive integers with 0 marking the end of each of the array.I have to find avg. of each array ,rounded to nearest integer, with answer separated by spaces.
Any help will be highly appreciated.....
n=int(input(' Please enter the number of arrays:- '))
ans=[]
for i in range(n):
    def avg_of_array(nums):
        for j in range(len(nums)):
            if nums[j]==0:
                avg=int(sum(nums)/(len(nums)-1))
                ans.append(avg)
            if nums[j]==0 and nums[j+1]<len(nums):
                avg=int(sum(nums)/(j-1))
                ans.append(avg)
    print('The answers:- {n1}'.format(n1=' '.join(map(lambda x:str(x),ans))))


text:
Q: Selenium iframe within iframe I have the following python code :
 iframe = driver.find_element_by_name("iframe_name")

 driver.switch_to_frame(iframe)

 elem = driver.find_element_by_xpath("/html/body/iframe")

It is able to find the first iframe element and then switch to it however once it is in it and I try to access the second iframe element (by xpath since it does not have a name or id) I keep getting a "no such element error".
Can someone please help. I am trying to access the interior iframe so that I can get the src attribute within it.

A: Possible solutions.

*

*Try using wait for an element by XPath ("/html/body/iframe"), as often times the driver will fail to wait till switching to the frame is completed.

*Make sure that your XPath ("/html/body/iframe") is working. Also try identifying element using the tag name if there only one IFrame in the IFrame.
Hope that helps.


text:
Q: How parameter is working in single line expression of arrow function in useState function  const tick = () => {
     setCount(prevCount => prevCount+1);

       // setCount(count+1);
    }

My question is from where prevCount variable is getting it's initial value?
How the expression supplied to setCount() is working?
I have created a react example to explain.
React js example, please refer tick function in interval.jsx component.
Update:
As per a comment by Dennis Vash on my question I am supplying callback function to setCount() then Why it does not work if I write it like this?
   const tick = () => {
           setCount(updateCount(count))

           // setCount(count+1);
        }

     const updateCount = (myCount) => {
        return myCount + 1;
    }

A: the Arrow function works like this,
For single parameter brackets optional,
prevCount => prevCount+1 -> function(prevCount){return prevCount+1}
(prevCount) => prevCount+1 -> function(prevCount){return prevCount+1}
And for multiple parameters You need to add braket,
(prevCount, a, b, c) => prevCount+1 -> function(prevCount, a, b, c){return prevCount+1}
And for empty parameter You need to add empty brackets,
() => prevCount+1 -> function(prevCount){return prevCount+1}
For more info read, MDN's doc

## UPDATE:
here in your updated question, updateCount(count) is getting called directly. So use something like this,
setCount(updateCount)

A: You are getting setCount function from useState hook. which is itself a React inbuilt function.
So setCount is a function that accepts a function as a call back function.
Your code
setCount(prevCount => prevCount+1);

Let's simplify it for you
setCount(function(prevCount) {
    return prevCount+1
})

So here you can see that setCount accepts a function which will be called back as the last step of execution of the setCount function, at that time setCount will pass a previous value of the state variable as an argument to the callback function.


text:
Q: Compare igraph cluster membership across multiple iterations This question builds on the example of this one.
The aforementioned example shared this code for storing communities lists after multiple iterations of a given clustering algorithm. For instance, for 100 iterations:
communities <- list()
for (i in 1:100){
  set.seed(3+i)
  communities [[i]] <- cluster_spinglass(graph_obj)
}

Using igraph, if I run multiple iterations of a clustering method that has some sort of randomness to it (e.g. spinglass), I will obtain slightly different results at each time. Consequently, at each run, I might end up with a different number of clusters, and a different set of nodes within each cluster. Is there a way to keep track of how often certain nodes end up in the same clusters, across multiple iterations? The rationale would be to find out if, for instance, in 100 iterations, a certain node A was placed 90 times in the same cluster with node B, and 10 times elsewhere.

A: There will be one number for each pair of nodes, so it seems
natural to keep track of this in a vcount x vcount matrix.
First, some sample data.
library(igraph)

set.seed(1234)
g = erdos.renyi.game(13, 0.2)

Initialize a matrix to all zeros and then add one to the (i,j)
element each time that nodes i and j are in the same community.
COMM = matrix(0, nrow=vcount(g), ncol=vcount(g))
for(i in 1:100){
    set.seed(3+i)
    CS = cluster_spinglass(g)
    for(m in 1:max(CS$membership)) {
        Group = which(CS$membership==m)
        COMM[Group, Group] = COMM[Group, Group] +1
    }
}
COMM
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
 [1,]  100    0    0   98    0    0    0    0    0     0   100     0   100
 [2,]    0  100    0    0   99    0   91   99    0     0     0    99     0
 [3,]    0    0  100    0    0  100    0    0  100   100     0     0     0
 [4,]   98    0    0  100    0    0    0    0    0     0    98     0    98
 [5,]    0   99    0    0  100    0   92  100    0     0     0   100     0
 [6,]    0    0  100    0    0  100    0    0  100   100     0     0     0
 [7,]    0   91    0    0   92    0  100   92    0     0     0    92     0
 [8,]    0   99    0    0  100    0   92  100    0     0     0   100     0
 [9,]    0    0  100    0    0  100    0    0  100   100     0     0     0
[10,]    0    0  100    0    0  100    0    0  100   100     0     0     0
[11,]  100    0    0   98    0    0    0    0    0     0   100     0   100
[12,]    0   99    0    0  100    0   92  100    0     0     0   100     0
[13,]  100    0    0   98    0    0    0    0    0     0   100     0   100

Now you can see that node 1 and 4 are in the same community 98 times out of 100,
but nodes 2 and 7 are only in the same community 91 times out of 100.
(Usually, there were 3 communities but sometimes there were 4. For example, when i=60,
we got 4 communities.)


text:
Q: How do Gold rewards in Smite work? I'm pretty new to smite and I don't quite get how the gold reward system works there. Sometimes I feel like I got gold although I didn't lasthit a creep. Also personally I don't find the interface clear when it comes to displaying how much gold you just earned.
So basically My questions are:

*

*Which actions will get you gold?

*How much gold do they give you?

I'm especially interested in the conquest (Classic 5v5 MOBA) mode.

A: Actions that get you gold:

*

*Being in the vicinity when a minion or jungle creep dies (I believe it's 50 feet). This method only gets you partial, unless you have Watcher's gift

*

*You will not get any gold if your defending objectives (towers, phoenix, titan) last hit the minion

*Last hitting a minion gets you an additional 50% bonus

*killing jungle creeps

*destroying objectives (towers, phoenixes, gold fury, Fire Giant). Everyone on the team receives gold regardless of where they are.

*getting a kill assist on a god (damaging, CCing, or "body blocking" counts as assist)

*First Blood (the first god kill of the game) is an additional 200 gold bonus

*getting a kill on a god. the formula for how much you earn per kill is below.

Base Amount = (150 + (Gold Earned by Victim / 100))
       Level Adjustment = ((enemy level - player level) * .1) This is capped at +/- .6. Total = (Base Amount + (Base Amount * Level
  Difference Adjustment)) * 1.1 ^ Opponents Kill Streak

In Conquest:

*

*All gods start with 1500 gold

*towers are 200 gold global, 250 for assist in bringing it down

*phoenixes are 150 global, 200 for assist bringing down

*small jungle fury gives 71 gold (if solo or with Bumba's mask)

*large(mid) jungle fury gives 90 gold (again, jungle so if solo or with the Mask)

*jungle buff camps give 91 gold

*gold fury is 300 global

*fire giant is 150 global

*last hit is a 50% bonus added to the "normal" proximity reward

*Archer minions give 18 gold on last hit if solo, 12 proximity.

*Melee minions give 25 gold on last hit if solo, 17 proximity.

*brute minions (big melee guys) give 29 gold if solo, 20 proximity.

When friendly gods are around you the gold reward splits evenly. Example, if you are in the duo lane, archer minions will give 6 gold, but if you or your partner god last hit while you have Watcher's, you will get 9.
The other modes merely scale on this base formula.
There is also options in the game to tweak reward text so it's more clear. The default pops up near your god with pretty small text. God kill rewards will also show up in the chat feed.


text:
Q: How do I refer to the "return" of a function in a method from another class in Python? Here is my code:
class MetricTensor:  #The Metric Tensor Class
    def __init__(self, g0, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13, g14, g15): #Metric components
        self.g0 = g0
        self.g1 = g1
        self.g2 = g2
        self.g3 = g3
        self.g4 = g4
        self.g5 = g5
        self.g6 = g6
        self.g7 = g7
        self.g8 = g8
        self.g9 = g9
        self.g10 = g10
        self.g11 = g11
        self.g12 = g12
        self.g13 = g13
        self.g14 = g14
        self.g15 = g15

    def LMetric(self):
        lmetric = [self.g0, self.g1, self.g2, self.g3, self.g4, self.g5, self.g6, self.g7, self.g8, self.g9, self.g10, self.g11, self.g12, self.g13, self.g14, self.g15]
        return list(lmetric)

    def Mmetric(self,lmetric):
        mmetric = np.matrix([lmetric[0],lmetric[1],lmetric[2],lmetric[3], [lmetric[4],lmetric[5],lmetric[6],lmetric[7]], [lmetric[8],lmetric[9],lmetric[10],lmetric[11]], [lmetric[12],lmetric[13],lmetric[14]],lmetric[15]])
        return mmetric

    def InvMmetric(self,mmetric):
         invmmetric =  self.np.linalg.inv(mmetric)
         return invmmetric
    def LInvMetric(self,invmmetric):
        linvmetric = list(invmmetric)
        return linvmetric

class ChristoffelSymbol(MetricTensor):
    def __init__(self,a, b, c):
        self.a = a
        self.b = b
        self.c = c
        Ca = None
        for k in numcoords:
            Ca += 1/2*(linvmetric)

Notice the last method of the MetricTensor class: LInvmetric, this function returns : linvmetric.
My question is:
How do I use this return (linvmetric) in a new class (ChristoffelSymbol), that is a subclass of the first (MetricTensor)?
More accurately, how do I only use one element in linvmetric (since it is a list, I want to use linvmetric[0], for example)?

A: Updated answer after some discussion:
You will also need to call the methods that you have defined in the MetricTensor class. The code below does this:
mt = MetricTensor("...args...")  # args here are all the metric components
lmetric = mt.LMetric()
mmetric = mt.Mmetric(lmetric)
invmmetric = mt.InvMmetric(mmetric)
linvmetric = mt.LInvMetric(invmetric)

Now linvmetric can be used in further code.

A: Just use self since it inherits from MetricTensor
self.LInvMetric() - will get you the full list
self.LInvMetric()[0]  - first elem and so on


text:
Q: SQL Exclude Row if Specific Value Exists Within Joined Field I am trying to write an SQL query that will allow me to exclude a record from TableA if it has at least one match against TableB.
I have written some code, as below, that almost gets me what I need -
SELECT a.ID,
  a.OPEN_DT,
  b.LINKCREATED,
  b.RULE__ID
FROM TableA a
LEFT JOIN TableB b
  ON a.ROW_WID = b.A_ROW_WID
WHERE EXTRACT(YEAR FROM a.OPEN_DT) >= '2013'
  AND NOT EXISTS (SELECT *
                  FROM TableB
                  WHERE A_ROW_WID = a.ROW_WID
                  AND EXTRACT(YEAR FROM b.CREATED) >= '2017')
;

Table A
ROW_WID   |   ID   |   OPEN_DT
---------------------------------
1         |    A   |  2013-01-01
2         |    B   |  2014-01-01
3         |    C   |  2017-01-01

Table B
RULE_ID   |   A_ROW_WID   |   LINKCREATED
---------------------------------
1         |    A          |   2014-01-01
2         |    A          |   2017-01-01
3         |    B          |   2017-01-01

The query above would return 1 row for ROW_WID = 1, 1 row for ROW_WID = 2 and nothing for ROW_WID = 3.
I would like my query to exclude ROW_WID=1 altogether because there is one row in TableB that has the year 2017.
I hope this question is clear, but let me know if not.
-EDIT-
Expected result would look like this -
   ID   |   OPEN_DT   |   LINKCREATED   |   RULE_ID
   C    |  2017-01-01 |   NULL          |   NULL

As ID 'C' from TableA has no link in TableB.
If there were an entry in A that had any links in B prior to 2017, they would be returned.  Just not any with a TableB entry >= 2017.

A: Your issue is that you aren't checking for the max created date in the NOT EXISTS:
SELECT a.ID,
  a.OPEN_DT,
  b.LINKCREATED,
  b.RULE__ID
FROM TableA a
LEFT JOIN TableB b
  ON a.ROW_WID = b.A_ROW_WID
WHERE EXTRACT(YEAR FROM a.OPEN_DT) >= '2013'
  AND NOT EXISTS (SELECT 'NE'
                  FROM TableB B2
                  WHERE A_ROW_WID = a.ROW_WID
                  AND B2.LINKCREATED= (SELECT MAX(BE.LINKCREATED) FROM TableB BE WHERE B2.A_ROW_WID=BE.A_ROW_WID)
                  AND EXTRACT(YEAR FROM b2.CREATED) >= '2017')

A: Try using not in:
SELECT a.ID,
  a.OPEN_DT,
  b.LINKCREATED,
  b.RULE__ID
FROM TableA a
LEFT JOIN TableB b
  ON a.ROW_WID = b.A_ROW_WID
WHERE EXTRACT(YEAR FROM a.OPEN_DT) >= '2013'
  AND b.rule_id not in (select rule_id from TableB where A_ROW_WID in (SELECT
                  A_ROW_WID
                  FROM TableB
                  WHERE EXTRACT(YEAR FROM b.CREATED) >= '2017')a)b