text:
Q: Uncertainty of a line between two coordinates with uncertainties in QGIS I am trying to plot the uncertainty of a line between two coordinates with uncertainties. I have created polygons around 2 coordinates to represent the uncertainty region around each point.  I then create random points in each polygon, and then join them using the points to paths function.  Looks something like this:

I want to plot a region that represents the probability of the lines, and also takes the uncertainty region of the original endpoints into account - should look like this;

The uncertainty region needs to be at the 95% confidence level.  I am new to QGIS, I thought maybe by creating a grid and populating cells within the grid I could somehow come up with a polygon that represents a probability density area?
I am using QGIS Desktop 3.0.1 with GRASS 7.4.0. I believe I will need large numbers of random points/lines to achieve what I want which may make processing any algorithms slow?

A: That was a fun problem! I solved it using QGIS 2.18 but I don't think the tools have drastically changed in 3.0.
1. Generate the lines
I won't give much details here since you already have the lines you need. I have written a script to generate these lines, but it works only up to QGIS 2.18. Needless to say, the more lines the better your estimation.
2. Create a grid
Go to Vector > Research Tools > Vector Grid (QGIS 2.18). In QGIS 3.0, it seems that you have to open the processing toolbox (Processing > Toolbox) then look for the grid tool.
For the grid extent, choose "Use layer/canvas extent" (3 dots on the right). Choose whatever cell size you want, but be prepared to face long computation times if your grid is too thin. Choose "Output grid as polygons" in "grid type".
3. Count lines by grid cell
This is a little tricky. You first have to cut your lines so that each line is split across the cells. To achieve that, use the intersection tool (Vector > Geoprocessing Tools > Intersection in both QGIS 2.18 and 3.0). Choose the line layer as "Input layer", and the grid as "Intersection layer".
To prepare the next step, we have to add a field to the layer we just obtained. Select this layer and open the field calculator; check the "create a new field option", set 'newid' as name, keep 'numeric' as type. In the "Expression" box, write $rownum, then click OK. You will get a new field with a unique id for each line segment.
Then, we'll use the mean coordinates tool (Vector > Analysis tools > Mean coordinates in QGIS 2.18, again in the toolbox for QGIS 3.0). Set the intersected layer (from the previous operation) in the "input layer" field, and 'newid' as "Unique ID field". This gives you a point layer, each point corresponding to a line segment.
Finally, use the "Count points in polygon tool" (in Vector > Analysis tools for both QGIS 2.18 and 3.0). Set the grid in the "Polygons" field and the newly created point layer in the "Points" field. This will create a new field in the grid with the number of line segments in each grid cell. You can divide this number by the total number of lines in the field calculator if you want, if you need an estimation of line probability.
4. Example results
Obtained with 2000 lines and a uniform point repartition inside the uncertainty regions (you might want to try a gaussian repartition too).

Same uncertainty parameters, with 5000 lines and a thinner grid (took several hours to run):

A: @ArMoraer I have been off this topic for a while, finally got to trial it.  I am having issues with my lines and mean coordinates from the intersected lines.
My lines have been created from random points then points to paths, I believe the issue is that all the lines created this way are treated as 1 object?  For example, when I do the intersections and enquire on one all intersected lines within a grid cell are highlighted as below.

I tried exploding the intersection layer, but unfortunately this explodes the lines to any intersection vertex not to the ends of lines at grid intersection as I intend. This has a similar result with paths layer prior to intersection with the grid.
I then thought the exploded lines would still be valid statistically for what I want to achieve, however when I try to obtain mean coordinates with the rownum as the unique field, I only get 1 mean coordinate for each grid cell, not each line segment.  See below. (red line show 1 exploded line)

Am I right in assuming that each line has to be unique in some way for this to work, and that is tied into my method of creating random points then points to paths?  Do you have any suggestions to work around this issue?


text:
Q: Using Mockito spy in one class to Call static method from another class Trying to use Mockito's spy function for my JUnit test. I originally had a Class:
public class App1 {
    public String method1() {
        sayHello();
    }

    public sayHello() {
        Systems.out.println("Hello");
    }
}

Everything in my test class was working correctly with mockito spy on above class:
@Test(expected = IOException.class)
public void testMethod1Failure(){
    App1 a1 = spy(App1);
    doThrow(IOException.class).when(a1).sayHello();

    a1.method1();
}

But after that i had to switch things around and take sayHello() method into another class to be used as static method:
public class App1 {
    public String method1() {
        App2.sayHello();
    }
}

public class App2 {
    public static void sayHello() {
        Systems.out.println("Hello");
    }
}

After this change, my original JUnit testcase is broken and i am unsure how i can use Mockito spy to start App1 that calls the external App2 static method... does anyone know how i can do it? Thanks in advance

A: Mockito does not support mocking static code. Here are some ways to handle it:

*

*Use PowerMockito or similar framework as suggested here: Mocking static methods with Mockito.

*Refactor your code converting static method back to an instance method. As you've found static methods are not easy to Unit test.

*If it's inexpensive to execute actual static method in question then just call it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Context switch between threads in a process
For Kernel-Level-Threads when one thread blocks for some I/O another thread is free to run, but in User-Level-Threads what happens if one thread is blocked?

Will that process remain blocked i.e. no other thread will execute or another thread will be scheduled to run. What happens exactly?

A: User-level threads are pieces of user code that execute in sequential fashion - one thread runs for a while then transfers the control to another thread and so on. If one of those threads make a syscall that blocks then the process as a whole blocks. User-level threading looks like a single threaded process to the kernel. No concurrent scheduling on multiple CPUs is possible.
The main advantage of kernel-level threads is that they run independently from one another and can be scheduled on different CPUs. If one blocks, others continue to execute.


text:
Q: Beautify whitespace in math environment with aligned with hline I'm kind of surprised I can't find this issue already addressed somewhere, it seems so basic:  I want to typeset basic algebra solutions where you write an equation and then under it you write what you do to both sides, and then you underline that as if it's adding two things, and below that you show the result.  For example, what I've been trying to write is the following,
\documentclass{article}
\usepackage{amsmath}
\begin{document}
    \begin{alignat*}
    x & -1 = & 3\\
     & +1  & +1\\ \cline{1-3}
    &x &= 4
    \end{alignat*}
\end{document}

and most of this looks lovely except that the white space between the "+1   +1" line and the horizontal line just looks ugly.  I can't use an underline because of all the alignment control.  I thought of using \toprule but that doesn't seem to work in a math environment.  Other ideas?

A: although i'm pretty sure this is addressed in another question, here is a suggestion.
(however, your use of alignat is missing one important thing -- the number of columns.)
all you need to do is, after the next-to-last line, just before the \cline, specify
an optional negative vertical space.  here i've used twice the height of a lowercase "x":
\documentclass{article}
\usepackage{amsmath}
\begin{document}
    \begin{alignat*}{2}
    x & -1 = & 3\\
     & +1  & +1\\[-2ex] \cline{1-3}
    x & \phantom{{}-1} = & 4
    \end{alignat*}
\end{document}

A: You probably want to use array, rather than alignat, in order to have finer control.
I propose two versions, on the left one, {+1} avoids space between the two symbols.
\documentclass{article}
\usepackage{amsmath,array,booktabs}
\begin{document}
\[
\begin{array}{
  @{}
  r % for x
  @{}
  >{{}}r % for -1 and +1
  @{}
  >{{}}c<{{}} % for the =
  @{}
  r % for the right hand side
  @{}
}
x &  -1  & = &  3\\
  & {+1} &   & +1\\
\midrule
x &    & = &  4
\end{array}
\qquad
\begin{array}{
  @{}
  r % for x
  @{}
  >{{}}r % for -1 and +1
  @{}
  >{{}}c<{{}} % for the =
  @{}
  r % for the right hand side
  @{}
}
x & -1 & = &  3\\
  & +1 &   & +1\\
\midrule
x &    & = &  4
\end{array}
\]
\end{document}


text:
Q: Showing the unique maximum of a function Suppose $f(x) = G^{-1}\left(\frac{1}{2}+\frac{1}{2}G(H(x)\right)+G^{-1}\left(\frac{1}{2}G(H(1-x)\right) $,
where $x\in[0,1]$ and $G,H$ are strictly increasing, strictly concave functions with $G(0)=H(0)=0$ and $G(1)=H(1)=1$.
If we assume first-order differentiability of $f(.)$, then I believe it is easy to show that the maximiser is some $x>0.5$. However, I am having some difficulties in showing that this is a unique maximiser.
I've drawn a few examples in Mathematica but I cannot seem to construct an example for falsification which supports my intuition that the maximiser is unique, but unfortunately, this lacks any proper rigor.
Any ideas would be most grateful, thanks!


text:
Q: Python transpose data set Looking for a python script to do this. The below only is only a sample and  values are for CPU consumption in seconds.
I have a CSV in the format:

col1    col2   col3    col4  Apr2018   May2018   June2018   July 2018
-----------------------------------------------------------------
Job1    ABD    dt.com  BU1   45087     67547      876465    987564
Job2    ACS    pl.com  BU2   94768     87658      987689    97678

Now I want to be able to get like this in a dataframe/ Table

col1    col2   col3    col4  Date      Value
---------------------------------------------
Job1    ABD    dt.com  BU1   Apr2018    45087
Job1    ABD    dt.com  BU1   May2018    67547
Job1    ABD    dt.com  BU1   June2018   876465
Job1    ABD    dt.com  BU1   July2018   987564

Job2    ACS    pl.com  BU2   Apr2018     94768
Job2    ACS    pl.com  BU2   May2018     87658
Job2    ACS    pl.com  BU2   June2018    987689
Job2    ACS    pl.com  BU2   July2018      97678

A:    import pandas as pd
   df=pd.read_csv("csv file")
   convert_df = pd.melt(df, id_vars=["col1","col2","col3,"col4"],
                  var_name="Date", value_name="Value")
   convert_df = convert_df.sort(["col1","col2","col3,"col4"])
   print(convert_df)

there is function melt in pandas dataframe.


text:
Q: Safe to delete/clear log file Just checking why my Jenkins builds have been failing and it seems that
the main jenkins.log file has swallowed all available space on my drive. Would it be safe to remove this file (would jenkins create another) then i could change logging settings.
Or is there information needed within this file on jobs/pipelines?
Sorry for noob question
Thanks

A: It is totally safe to delete jenkins.log file. Jenkins doesn't read any information from log file.
When you delete the file, jenkins will create a new file when writing the new logs.


text:
Q: Can Camunda be integrated with Apache Pulsar? I am looking into Camunda for using as an orchestration framework and was wondering if it can be integrated with our Pulsar topics ? I saw the support for Kafka and couldnt find anything on apache pulsar.

A: You can contact Camunda via a ticket in Github.
I don't see direct Apache Pulsar support.
If you run KoP (Kafka on Pulsar) module on Apache Pulsar it should work fine as most things work that way.
See https://github.com/riferrei/is-using-kop-a-good-idea
https://docs.streamnative.io/platform/v1.0.0/concepts/kop-concepts


text:
Q: where should I define functions that i use in __init__ I'm writing a class that makes use of some functions inside its __init__ function and I'm not sure about the best practice of where to define those functions. I usually like to define __init__ first but if I need to use the a function/method within the __init__ then it needs to be defined first. I dont want to define it outside the class as its useless outside the class but it seems messy to me to define methods before the __init__. What are the normal conventions for this?

A: The normal convention is indeed to put __init__ before other methods. The reason this works is that functions aren't evaluated until invoked. From the Python docs:

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.
The function definition does not execute the function body; this gets executed only when the function is called.

A: Just add the methods to your class like every other method
class Test(object):
    def __init__(self):
        self.hi()

    def hi(self):
        print "Hi!"

No problem at all.
While it is not mentioned in the Python Style Guide IIRC, it's convention to let __init__ be the first method in your class.

A: It's better to define __init__ function as first function, and you can call functions defined after __init__ inside it.
class A:
    def __init__(self):
        print self.x()

    def x(self):
        return 10

A: Why should it be 'messy' to define methods after the init ? Think about it that way :
When you define
class MyClass(object):

    def __init__(self):
        self.something = whatever
        self.do_something_else()

    def do_something_else(self):
        ...

__init__ is a method of your MyClass class, just like do_something is; it's just the first method of the class that will be called when you create an instance of MyClass. So, putting __init__ first is not only customary but also logical.
Your do_something_else method doesn't have to be defined first because you use it in __init__. From the point of view of MyClass, it's a method like another. When you create your myclass=MyClass() instance, do_something_else has already been defined...


text:
Q: parsing strings for specific elements - python I have a  pandas data-frame that contains a column of sentences with pattern:
row 1 of column : "ID is 123 or ID is 234 or ID is 345"
row 2 of column : "ID is 123 or ID is 567 or ID is 876"
row 3 of column : "ID is 567 or ID is 567 or ID is 298".
My aim is to extract the numbers in each row and save them in a list or numpy array.  Since there is a pattern (the number always comes after "ID is", I thought that regex might be the best way to go for it (but I am not sure how to use regex for multiple extractions in 1 string.
Any advice?

A: Standard module re can use '\d+'
re.findall('\d+', "ID is 123 or ID is 234 or ID is 345")

to get list [123,234,345].
To make sure you can also use 'ID is (\d+)'
re.findall('ID is (\d+)', "ID is 123 or ID is 234 or ID is 345")

In DataFrame you can use .str.findall() to do the same for all rows.
import pandas as pd

df = pd.DataFrame({
  'ID': [
    "ID is 123 or ID is 234 or ID is 345",
    "ID is 123 or ID is 567 or ID is 876",
    "ID is 567 or ID is 567 or ID is 298",
  ]
})

print('\n--- before ---\n')
print(df)

df['result'] = df['ID'].str.findall('ID is (\d+)')

print('\n--- after ---\n')
print(df)

Result:
--- before ---

                                    ID
0  ID is 123 or ID is 234 or ID is 345
1  ID is 123 or ID is 567 or ID is 876
2  ID is 567 or ID is 567 or ID is 298

--- after ---

                                    ID           result
0  ID is 123 or ID is 234 or ID is 345  [123, 234, 345]
1  ID is 123 or ID is 567 or ID is 876  [123, 567, 876]
2  ID is 567 or ID is 567 or ID is 298  [567, 567, 298]

If you need only column result as numpy array then you can get df['result'].values.
And if you need as nested list: df['result'].values.tolist().


text:
Q: If I was to take light and loop it between two iron cores, like a transformer with copper; what would happen? Precursor: I am not a physicist, and don't claim to be. I'm sorry if the question is easily answered.
Question: If I were to take light and loop it between two iron cores, similar to the way copper in a transformer is wound between two iron cores and a connecting core on top to give more or less voltage; would something happen? Like if I took 5 loops of light around one iron core, and then had 30 loops of light around another iron core; and connected them with a top piece of iron, would something happen? I ask because if I can take 480v and step it down to 120v through iron and a less wound piece of copper, then why can't I change the pressure and space of light with the same method of stepping up and down it's amount of energy? This is an honest question, and I'm sorry if I'm just uneducated and sound like a nut for some reasons I wouldn't understand. Thank you to anyone with the insight and the time to answer this question.

A: Nothing would happen. You would need a fiber optic cable, no light gets out, the iron core does nothing to the light, so your second fiber optic (with more or less loops) would not have any light in it or any connection with the other light.


text:
Q: Nuxt Axios Returns Error when moving between pages I am building a nuxt application which I am using axios with.
In my index.vue, I have the following code.
<template>
  <div>
    <Hero />
    <Homebooks :details="details" />
  </div>
</template>

<script>
export default {

  // USING ASYNC AWAIT
  // async asyncData ({
  //   $axios,
  //   error
  // }) {
  //   try {
  //     const details = await $axios.$get('http://127.0.0.1:8001/api/books')
  //     return {
  //       details
  //     }
  //   } catch (e) {
  //     error({
  //       statusCode: 503,
  //       mesage: 'Unable to fetch'
  //     })
  //   }
  // }
  // USING ...
  asyncData ({ $axios, error }) {
    return $axios.$get('http://127.0.0.1:8001/api/books').then((response) => {
      return {
        details: response
      }
    }).catch((e) => {
      error({
        statusCode: 503,
        message: 'Unable to fetch data'
      })
    })
  }
}
</script>

When I move away from the page to another page. And I come back to it either using the back button or following the link the menu
          <nuxt-link to="/" prefetch class="nav-link active">
            Home
          </nuxt-link>

It returns the error

Unable to fetch event
An error occurred while rendering the page. Check the developer tools console for details.

But when I refresh the page the whole data populate again from the response from the API without error.
I don't know what I am doing wrong here.

A: In config/cors.php use
'paths' => ['api/*']


text:
Q: Renaming external 3rd party library classes in my library I want to add add 3rd part library to my library (which will be used by other developers), so if I have for example this class SBJson do I prefix it with my two letter prefix to be EXSBJson also I saw somewhere somebody is using underscore EX_SBJson. What is the naming convention/style in this case?.

A: There is no general convention, but we have used the following approaches:

*

*Use the same prefix as the library (so if we develop XYFunctionality, we would name it XYSBJson). A lot of source projects use this approach (e.g. Dropbox)

*Talk to other devs, if possible. In most cases, it is enough to distribute the library separately from 3rd party libs (so we ship a .a binary file and a working source project of the 3rd party library so other devs can use it). This also allows other devs to upgrade the 3rd party library to get bugfixes as long as there aren't breaking API changes.

Btw. much of what SBJson does can also be done using NSJsonSerialization which comes with iOS 5+


text:
Q: Do intermediate subdomains need to exist? If I have the hosts example.com and leaf.intermediate.example.com in DNS records for example.com, but do not have any records for intermediate.example.com itself, does that cause a problem in some situations or is it bad style or etiquette for some reason? I have web servers set up like this and everything seems to work fine, but just wanted to check if there's something I'm missing.

A: TL;DR: yes intermediate subdomains need to exist, at least when queried for, per definition of the DNS; they may not exist in the zonefile though.
A possible confusion to eliminate first; Definition of "Empty Non-Terminal"
You may be confusing two things, as other answers seem also to do. Namely, what happens when querying for names versus how you configure your nameserver and the content of the zonefile.
The DNS is hierarchical. For any leaf node to exist, all components leading to it MUST exist, in the sense that if they are queried for, the responsible authoritative nameserver should reply for them without an error.
As explained in RFC 8020 (which is just a repeat of what was always the rule,
but just some DNS providers needed a reminder), if for any query, an authoritative nameserver reply NXDOMAIN (that is: this resource record does not exist), then it means that any label "below" this resource does not exist either.
In your example, if a query for intermediate.example.com returns NXDOMAIN, then any proper recursive nameserver will immediately reply NXDOMAIN for leaf.intermediate.example.com because this record can not exist if all labels in it do not exist as records.
This was already stated in the past in the RFC 4592 about wildcards (which are unrelated here):

The domain name space is a tree structure.  Nodes in the tree either
own at least one RRSet and/or have descendants that collectively own
at least one RRSet.  A node may exist with no RRSets only if it has
descendants that do; this node is an empty non-terminal.
A node with no descendants is a leaf node.  Empty leaf nodes do not
exist.

A practical example with .US domain names
Let us take a working example from a TLD with a lot of labels historically, that is .US. Picking any example online, let us use www.teh.k12.ca.us.
Of course if you query for this name, or even teh.k12.ca.us you can get back A records. Nothing conclusive here for our purpose (there is even a CNAME in the middle of it, but we do not care about that) :
$ dig www.teh.k12.ca.us A +short
CA02205882.schoolwires.net.
107.21.20.201
35.172.15.22
$ dig teh.k12.ca.us A +short
162.242.146.30
184.72.49.125
54.204.24.19
54.214.44.86

Let us query now for k12.ca.us (I am not querying the authoritative nameserver of it, but that does not change the result in fact):
$ dig k12.ca.us A

; <<>> DiG 9.11.5-P1-1ubuntu2.5-Ubuntu <<>> k12.ca.us A
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59101
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1480
;; QUESTION SECTION:
;k12.ca.us.         IN  A

;; AUTHORITY SECTION:
us.         3587    IN  SOA a.cctld.us. hostmaster.neustar.biz. 2024847624 900 900 604800 86400

;; Query time: 115 msec
;; SERVER: 127.0.0.10#53(127.0.0.10)
;; WHEN: mer. juil. 03 01:13:20 EST 2019
;; MSG SIZE  rcvd: 104

What do we learn from this answer?
First, it is a success because the status is NOERROR. If it had been anything else and specifically NXDOMAIN then teh.k12.ca.us, nor www.teh.k12.ca.us could exist.
Second, the ANSWER section is empty. There are no A records for k12.ca.us. This not an error, this type (A) does not exist for this record, but maybe other record types exist for this record or this record is an ENT, aka "Empty Non Terminal": it is empty, but it is not a leaf, there are things "below" it (see definition in RFC 7719), as we already know (but normally the resolution is top down, so we will reach this step before going one level below and not the opposite like we are doing here for demonstration purpose).
This is why in fact, as a shortcut, we say the status code is NODATA: this is not a real status code it just means NOERROR + empty ANSWER section, which means there is no data for this specific record type but there may be for others.
You can repeat the same experiment for the same result if you query with the next "up"  label, that is the name ca.us.
Queries' results vs zonefile content
Now from where the confusion can come? I believe it may come from some false idea that any dot in a DNS name means there is a delegation. This is false.
Said differently, your example.com zonefile can be like that, and it is totally valid and working:
example.com. IN SOA ....
example.com. IN NS ....
example.com. IN NS ....

leaf.intermediate.example.com IN A 192.0.2.37

With such a zonefile, querying this nameserver you will get exactly the behavior observed above: a query for intermediate.example.com will return NOERROR with an empty answer. You do not need to create it specifically in the zonefile (if you do not need it for other reasons), the authoritative nameserver will take care of synthesizing the "intermediate" replies, because it sees it needs this empty non-terminal (and any others "in-between" if there had been other labels) as it sees the leaf name leaf.intermediate.example.com.
Note that this is a widespread case in fact in some areas, but you might not see it because it targets more "infrastructure" records that people are not exposed to:

*

*in reverse zones like in-addr.arp or ip6.arpa, and specifically the last one. You will have records like 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.a.1.d.e.1.6.8.0.0.0.0.0.0.2.6.2.ip6.arpa. 1h IN PTR text-lb.eqiad.wikimedia.org. and there is obviously not a delegation at each dot, nor resource records attached at each label

*in SRV records, like _nicname._tcp.fr. 12h IN SRV 0 0 43 whois.nic.fr., a domain can have many _proto._tcp.example.com and _proto._udp.example.com SRV records because by design they must have this form, but at the same time _tcp.example.com and _udp.example.com will remain Empty Non-Terminals because never used as records

*you have in fact many other cases of specific construction of names based on "underscore labels" for various protocols such as DKIM. DKIM mandates you to have DNS records like whatever._domainkey.example.com,  but obviously _domainkey.example.com by itself will never be used, so it will remain an empty non-terminal. This is the same for TLSA records in DANE (ex: _25._tcp.somehost.example.com. TLSA 3 1 1 BASE64==), or URI records (ex: _ftp._tcp    IN URI 10 1 "ftp://ftp1.example.com/public")

Nameserver behavior and generation of intermediate replies
Why does the nameserver synthesize automatically such intermediate answers? The core resolution algorithm for the DNS, as detailed in RFC 1034 section 4.3.2 is the reason for that, let us take it and summarize in our case when querying the above authoritative nameserver for the name intermediate.example.com (this is the QNAME in protocol below):

*Search the available zones for the zone which is the nearest
ancestor to QNAME.  If such a zone is found, go to step 3,
otherwise step 4.

The nameserver finds zone example.com as nearest ancestor of QNAME, so we can go to step 3.
We have now this:

*Start matching down, label by label, in the zone. [..]

a. If the whole of QNAME is matched, we have found the
node. [..]
b. If a match would take us out of the authoritative data,
we have a referral.  This happens when we encounter a
node with NS RRs marking cuts along the bottom of a
zone. [..]
c. If at some label, a match is impossible (i.e., the
corresponding label does not exist), look to see if a
the "*" label exists. [..]

We can eliminate cases b and c, because our zonefile has no delegation (hence there will be never a referral to other nameservers, no case b), nor wildcards (so no case c).
We only have to deal here with case a.
We start matching down, label by label, in the zone.
So even if we had a long sub.sub.sub.sub.sub.sub.sub.sub.example.com name, at some point, we arrive at case a: we did not find a referral, nor a wildcard, but we ended up at the final name we wanted a result for.
Then we apply the rest of the content of case a:

If the data at the node is a CNAME

Not our case, we skip that.

Otherwise, copy all RRs which match QTYPE into the
answer section and go to step 6.

Whatever QTYPE we choose (A, AAAA,  NS, etc.) we have no RRs for intermediate.example.com as it does not appear in the zonefile. So the copy here is empty. Now we finish at step 6:

Using local data only, attempt to add other RRs which may be
useful to the additional section of the query.  Exit.

Not relevant for us here, hence we finish with success.
This exactly explains the behavior observed: such queries will return NOERROR but no data either.
Now, you may ask yourself: "but then if I use any name, like another.example.com then by the above algorithm I should get the same reply (no error)", but observations would instead report NXDOMAIN in that case.
Why?
Because the whole algorithm as explained, starts with this:

The following algorithm assumes that the RRs are organized in several
tree structures, one for each zone, and another for the cache

This means that the above zonefile is transformed into this tree:
+-----+
| com |  (just to show the delegation, does not exist in this nameserver)
+-----+
   |
   |
   |
+---------+
| example | SOA, NS records
+---------+
   |
   |
   |
+--------------+
| intermediate | no records
+--------------+
   |
   |
   |
+------+
| leaf | A record
+------+

So when following the algorithm, from the top, you can indeed find a path: com > example > intermediate (because the path com > example > intermediate > leaf exists)
But for another.example.com, after  com > example you do not find the another label in the tree, as children node of example. Hence we fall into part of choice c from above:

If the "*" label does not exist, check whether the name
we are looking for is the original QNAME in the query
or a name we have followed due to a CNAME.  If the name
is original, set an authoritative name error in the
response and exit.  Otherwise just exit.

Label * does not exist, and we did not follow a CNAME, hence we are in case: set an authoritative name error in the response and exit, aka NXDOMAIN.
Note that all the above did create confusion in the past. This is collected in some RFCs. See for example this unexpected place (the joy of DNS specifications being so impenetrable) defining wildcards: RFC 4592 "The Role of Wildcards in the Domain Name System" and notably its section 2.2 "Existence Rules", also cited in part at the beginning of my answer but here it is more complete:

Empty non-terminals [RFC2136, section 7.16] are domain names that own
no resource records but have subdomains that do.  In section 2.2.1,
"_tcp.host1.example." is an example of an empty non-terminal name.
Empty non-terminals are introduced by this text in section 3.1 of RFC
1034:
# The domain name space is a tree structure.  Each node and leaf on
# the tree corresponds to a resource set (which may be empty).  The
# domain system makes no distinctions between the uses of the
# interior nodes and leaves, and this memo uses the term "node" to
# refer to both.

The parenthesized "which may be empty" specifies that empty non-
terminals are explicitly recognized and that empty non-terminals
"exist".
Pedantically reading the above paragraph can lead to an
interpretation that all possible domains exist--up to the suggested
limit of 255 octets for a domain name [RFC1035].  For example,
www.example. may have an A RR, and as far as is practically
concerned, is a leaf of the domain tree.  But the definition can be
taken to mean that sub.www.example. also exists, albeit with no data.
By extension, all possible domains exist, from the root on down.
As RFC 1034 also defines "an authoritative name error indicating
that    the name does not exist" in section 4.3.1, so this apparently
is not    the intent of the original definition, justifying the need
for an    updated definition in the next section.

And then the definition in next section is the paragraph I quoted at the beginning.
Note that RFC 8020 (on NXDOMAIN really meaning NXDOMAIN, that is if you reply NXDOMAIN for intermediate.example.com,  then leaf.intermediate.example.com can not exist) was mandated in part because various DNS providers did not follow this interpretation and that created havoc, or they were just bugs, see for example this one fixed in 2013 in one opensource authoritative nameserver code: https://github.com/PowerDNS/pdns/issues/127
People needed then to put specific counter measures just for them: that is not aggressively caching NXDOMAIN because for those providers if you get NXDOMAIN at some node, it may still mean you get something else than NXDOMAIN at another node below it.
And this was making QNAME minimization (RFC 7816) impossible to obtain (see https://indico.dns-oarc.net/event/21/contributions/298/attachments/267/487/qname-min.pdf for longer details), while it was wanted to increase privacy. Existence of empty non-terminals in case of DNSSEC also created problems in the past, around handling of non-existence (see https://indico.dns-oarc.net/event/25/contributions/403/attachments/378/647/AFNIC_OARC_Dallas.pdf if interested, but you really need a good understanding of DNSSEC before).
The following two messages give an example of problems one provider had to be able to properly enforce this rule on Empty Non-Terminals, it gives some perspective of the issues and why we where there:

*

*https://mailarchive.ietf.org/arch/msg/dnsop/XIX16DCe2ln3ZnZai723v32ZIjE

*https://lists.dns-oarc.net/pipermail/dns-operations/2019-April/018640.html

A: If you are directly querying the authoritative DNS server, you will get answers without problems.
However, you will not get a valid answer if you are querying via another DNS server which does not have a valid cache. Querying for intermediate.example.com will result in NXDOMAIN error.

A: To directly answer the question, no you do not need to add records for intermediate names that you are not actually using, however that doesn't mean that those names do not exist.
As for whether these names exist or not, that is actually a whole separate question for which I hope to provide a brief and rather intuitive answer.
It all boils down to that DNS is a tree structure, where each label in a domain name is a tree node. Eg www.example.com. has the labels www, example, com and `` (root node), which are the tree nodes that form the path all the way to the root.
What maybe makes this fundamental nature of DNS non-obvious is that almost always when managing DNS data there is no tree to be seen and we don't generally work directly with the tree nodes themselves, instead we typically have a flattened list of what record data that should exist at different domain names (effectively tree paths, as per above).
What happens when this flattened list is used is that the DNS server software constructs the tree based on the existing records, and if there are gaps between the nodes that have records (eg there are records for foo.bar.example.com. and example.com. but not bar.example.com.) these are simply considered empty tree nodes. That is, these are domain names / nodes that do in fact exist, the tree is not broken, these nodes just don't have any data associated with them.
Consequently, if you query one of these empty nodes you will get a NODATA response (NOERROR status + SOA in authority section), saying that the requested record type did not exist at this node. If you instead query some name that actually doesn't exist you will get a NXDOMAIN response, saying that the requested domain name does not exist in the tree.
Now, if you want the nitty gritty details, do read Patrick Mevzek's very thorough answer.

A: It's possible that I misunderstand Khaled's answer, but the lack of intermediate records should in no wise be a problem with the resolution of the subzoned name.  Note that this dig output is not from, nor directed to, an authoritative DNS server for teaparty.net or any subzone thereof:
[me@nand ~]$ dig very.deep.host.with.no.immediate.parents.teaparty.net
[...]
;; ANSWER SECTION:
very.deep.host.with.no.immediate.parents.teaparty.net. 3600 IN A 198.51.100.200

Indeed, you should be able to do that dig yourself, and get that answer - teaparty.net is a real domain, under my control, and really does contain that A record.  You can verify that there are no records for any of those zones between very and teaparty.net, and that it has no impact on your resolution of the above hostname.


text:
Q: JQuery: OnClick not working A part of my table looks somewhat like this:

     DRAFT

     DRAFT

     DRAFT

To handle the on-click -events, i've written the following function:
$(document).ready(function () {
     Console.log("loading Tiers");
     LoadTiers();
     Console.log("Tiers have been loaded, loading Eventhandlers");
     SetTableEventHandlers();
}

function SetTableEventHandlers() {

    $(".deletelnk").click(function ()
    { _delete($(this)); });

    $(".infolnk").click(function ()
    { _getInfo($(this)); });
}

function _delete(lnkClicked)
{
   alert("delete clicked");
   ....
}

function _getInfo(lnkClicked)
{
   alert("Info clicked");
   ....
}

Yet only the delete seems to be working. I'm not getting any alert from _getInfo.
Can anyone see why?
Note: the tags with class="deletelnk" are declared on the html-page, class="infolnk" are dynamically added. Yet the setting of the event handlers occurs after they have been added dynamically.

A: event binding for dynamically added element can be done using .on, so
change
$(".infolnk").click(function ()
    { _getInfo($(this)); });

to
 $("table tr").on("click",".infolnk",function ()
    { _getInfo($(this)); });

A: You are missing closing a tags

DRAFT

A: You can use
$(".deletelnk").click(function (){
    _delete($(this));
});

$(".infolnk").click(function (){
    _getInfo($(this));
});

function _delete(lnkClicked){
    alert("delete clicked");
}

function _getInfo(lnkClicked){
    alert("Info clicked");
}


text:
Q: Redefine "[<-" in S3 class in R I have a S3 class that contains two matrices. I want to use [ and ] functions to replace the element in both matrices.
For example:
twoMat <- function(MatA,MatB)
{
  x <- list(MatA = MatA, MatB = MatB)
  class(x) <- "twoMat"
  x
}

Suppose A is my S3 class with matrices B and C as members.
I want to type this:
A = twoMat(B,C)
A[A$B<3] <- NA

And get this for the members:
B[A$B<3] <- NA
C[A$B<3] <- NA


text:
Q: How do i use the % placeholder to write something in python? I have been asked to use the % placeholder to write something in python. I don't know how to do it can you help.

A: The formatting you're looking to use is as follows:
Say you want to place two variables,
name = 'Randy'
age = 55

into a string. You would use the following syntax
"Howdy, %s. You are %s years old." % (name, age)

This will place your two variables within the string and return this:
"Howdy, Randy. You are 55 years old."

However, this formatting method has become outdated. Once strings require several parameters, it will quickly become less readable. Python now prefers that you use the following format:
"Howdy, {}. You are {} years old.".format(name, age)"

Which will also return
"Howdy, Randy. You are 55 years old."

There are also some neat tricks, like using dictionaries to store your variables and format the string from there, like such.
person = {'name': 'Randy', 'age':55}
"Howdy, {name}. You are {age} years old.".format(**person)

Which will return the same sentence as above, and is easily readable. It also tells the code user what variables are supposed to be placed where which helps in making sense of your code.
Hope this helped, good luck and happy coding!


text:
Q: How do I determine whether my pokemon scales with physical or special damage? How do I determine whether my pokemon scales with physical or special damage?
It seems like neither type, range/melee, roles, nor colour on moves indicates the scaling of each pokemon's attack.
I have done some testing individually, but I see no pattern nor information that the game provides in an accessible spot - am I missing something?

A: Update: This is now accessible in-game since the 1.2.1.3 patch!
Under the "Pokémon" menu, you can check under the Pokémon name in the left side:

You're right: the game doesn't provide this information in an accessible spot.
As far as I know, the only way to test this is by playing in Practice Mode, and comparing the damage inflicted to the clone with / without some equipped items.
People have already done the hard work for us, so I'll just quote Serebii here:

Pokémon
Attack Type

Venusaur
Special

Charizard
Physical

Blastoise
Special

Pikachu
Special

Alolan Ninetales
Special

Wigglytuff
Special

Machamp
Physical

Slowbro
Special

Gengar
Special

Mr. Mime
Special

Snorlax
Physical

Blissey
Special

Gardevoir
Special

Absol
Physical

Garchomp
Physical

Lucario
Physical

Mamoswine
Physical

Crustle
Physical

Greninja
Physical

Talonflame
Physical

Sylveon
Special

Zeraora
Physical

Cinderace
Physical

Greedent
Physical

Eldegoss
Special

Cramorant
Special

Note that the basic attack of each Pokémon might use a different attack type than listed.


text:
Q: Why does Terraform want to create the custom attribute again? I am try to use the Vsphere_custom_attribute resource. On the first run on an VSphere it runs fine but on the second run I get the error below.
Do you have any ideas how to solve this ?
or did i just use it wrong ?
I use this Version of Terraform and Vsphere provider.
Terraform v0.12.12

*

*provider.template v2.1.2

*provider.vsphere v1.13.0

These are the code parts where i create the custom attributes and where i use it.
resource "vsphere_custom_attribute" "hostname" {
  name                = "hypervisor.hostname"
  managed_object_type = "VirtualMachine"
}

resource "vsphere_virtual_machine" "vm" {
  ...
  custom_attributes = "${map(vsphere_custom_attribute.hostname.id, "${var.vsphere_name}${var.vsphere_dom}" )}"
  ...
}

Error :
Error: could not create custom attribute: ServerFaultCode: The name 'hypervisor.hostname' already exists.

  on main.tf line 32, in resource "vsphere_custom_attribute" "hostname":
  32: resource "vsphere_custom_attribute" "hostname" {

terraform plan:
I do not understand why Terraform want to create it the custom attribute as it already exists.
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # vsphere_custom_attribute.hostname will be created
  + resource "vsphere_custom_attribute" "hostname" {
      + id                  = (known after apply)
      + managed_object_type = "VirtualMachine"
      + name                = "hypervisor.hostname"
    }

A: This is because you're saying create the 'resource' instead of pulling the 'data' from vsphere. I had this confusion as well until understanding the 'vsphere_datastore' input required.
Try something like this (im using octopus deploy for variable replacement so ignore that im using invalid #{, should be ${ or just straight string for 0.12.x
...
data "vsphere_custom_attribute" "consul_backend_path" {
  name = "consul.backend.path"
}
...
resource "vsphere_virtual_machine" "windows_virtual_machine" {
...
custom_attributes = map(data.vsphere_custom_attribute.consul_backend_path.id, "custom_attribute_value")
...
}

Keep in mind, this requires the resource of the custom attribute to be in vcenter before this virtual_machine resource is created. Otherwise you will need to do a logic test to validate if the tag is required.


text:
Q: How to pass/inject "text" inside the URL in react-router v3? I want to pass a video ID to my URL.
Let's assume the user is on page where all the videos are listed:
Video1
Video2
Video3
Video4
and the current URL is "/videos"
Now, if the user clicks on any of the video, i want to push that selected video id to the URL.
new URL: "/videos?id=Video1"
I'm currently using react-router v3
<Route component={HomePage}>
 <IndexRoute component={AssetPage}/>
 <Route path='/assets' component={AssetPage}/>
 <Route path='/video' component={VideoPage}/>
 <Redirect from='*' to='/'/>
</Route>


text:
Q: How to set default value of WiX Msi install path in the ui to Program Files? I have created a WiX installer MSI. When i run the msi, the installation path is asked for in the UI. Currently it loads the drive containing most of the free space. How can I set it to be at program files folder all the time? I tried the below line but it didn't work.
 <Property Id="WIXUI_INSTALLDIR" Value="C:\\Program Files\" />

Below is the error I get for the above element.
 The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2343. The arguments are: , ,

How can I make the UI load C:\Program Files as the default location all the time? Any help would be much appreciated.

A: You want to make use of the already defined windows installer properties which are always defined by Windows Installer (caveat on some 64-bit only properties). In this case specifically the ProgramFilesFolder
Try using a directory definition like this:
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFilesFolder">
                <Directory Id="INSTALLDIR" Name="MyProductFolder" />
            </Directory>
        </Directory>
    </Fragment>
</Wix>

And then, following the same principal as this quick tutorial page about using WixUI_InstallDir
You'll want to do
<Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" />

Now when you show the UI page that lets you change the install location it should have the value C:\Program File\MyProductFolder
As a side-note, I would avoid making the install location just C:\Program Files because that may cause you to add a ton of extraneous files to this location where they should instead be contained in a product/program folder.
You should also never try to hardcode a path like "C:\Program Files\". In this specific case I can give you two quick examples why not to. There is no guarantee that the user is using the C:\ drive as their main drive or even uses a C:\ drive at all (one anecdote of this here). Another issue is (for 32-bit installs) on a 32-bit machine you'll want to install into the Program Files location but on a 64-bit machine you'll want to install into the "Program Files (x86)" location.


text:
Q: How can I filter emails from a specific email address on Office 365 API? I've users with thousands of emails but I need to fetch only unread emails from specific people. I have the following call but it is not working for me.
curl -i https://graph.microsoft.com/v1.0/me/messages$filter=From/EmailAddress/Address eq 'alerts-noreply@mail.windowsazure.com' H 'Content-Type: application/x-www-form-urlencoded' -H 'Authorization: Bearer token ....'

{
  "error": {
    "code": "BadRequest",
    "message": "Unsupported segment type. ODataQuery: users/020f1da4-031d-4....26513bb0/messages=From/EmailAddress/Address",
    "innerError": {
      "request-id": "2aaaaeb...42-ffc6d0e44f3d",
      "date": "2017-01-24T01:30:44"
    }
  }
}

How can I fetch emails from MS Office API "FROM" specific people without fetching all emails to our system?

A: You were missing the character ? after messages. To filter the messages from specify user with unread messages, you can use the request below:
GET:https://graph.microsoft.com/v1.0/me/messages?$filter=from/emailAddress/address+eq+'xx@xxxx.onmicrosoft.com'+and+isRead+eq+false

A: You can find an example of how to do this, and other examples of using common query parameters in Microsoft Graph in Microsoft Graph optional query parameters.


text:
Q: Heroku fails to install dependency - How do I fix it? I'm trying to push an app to Heroku (first time) and it continues to fail when attempting to install on of the dependencies in the requirements.txt file.
The dependency is for the etsy-python library ("pip install etsy" fails).
Locally, I was able to get this to work by downloading and building the source. How can I get past this issue with Heroku?
requirements.txt:
Flask==0.9
Jinja2==2.6
Werkzeug==0.8.3
etsy==0.3.1
geopy==0.94.2
httplib2==0.7.7
oauth2==1.5.211
python-etsy==0.1.2
python-twitter==0.8.4
requests==1.0.4
requests-oauth==0.4.1
simplejson==3.0.4

A: I was able to fix this by modifying the requirements.txt as follows:
Although the pypi package for Etsy is not working, the source is ok and builds without problems.
Flask==0.9
Jinja2==2.6
Werkzeug==0.8.3
-e git+https://github.com/mcfunley/etsy-python.git#egg=etsy-python
geopy==0.94.2
httplib2==0.7.7
oauth2==1.5.211
python-etsy==0.1.2
-e git+https://github.com/bear/python-twitter.git#egg=python-twitter
requests==1.0.4
requests-oauth==0.4.1
simplejson==3.0.4

A: I'm getting this error when I try to install etsy locally:
ValueError: Invalid IPv6 URL

I'd say that the official py-etsy is outdated and broken, the Github repo was last updated a year ago: https://github.com/mcfunley/etsy-python. This library is more recent (5 months ago): https://github.com/priestc/python-etsy.
It's not on pypi, but clone it locally and include it in your project.


text:
Q: Regular Expression from long string I have the following characters running on DataFrame:
1.83\n1\n71%\n4.25\nX\n18%\n4.30\n2\n11%\n+88

I'm trying regular expression to achieve this: 1.83\n4.25\n4.30
I've so far tried this code snippet in pandas:
import re

clean_dict = {'[nX%+]':'','\n1':''}

but this fails to remove the other unwanted characters.
I'm using regex101.com for testing
What's the best way to resolve this?

A: This produces the string you want:
Not sure if it will meet all your needs though. Your question is lacking some details.

import re
import pandas as pd

df = pd.DataFrame(['1.83\n1\n71%\n4.25\nX\n18%\n4.30\n2\n11%\n+88'], columns=['A'])

def match(x):
    matches = re.findall(r'(---\d\.\d+|\d\.\d+)', x.replace('\n', '---'))
    new_string = ''.join([x for x in matches])
    return new_string.replace('---', '\\n')

df['new_string'] = df["A"].apply(lambda x: match(x))
print(df)

#                                                A        new_string
# 0  1.83\n1\n71%\n4.25\nX\n18%\n4.30\n2\n11%\n+88  1.83\n4.25\n4.30

A: Have you considered not using regex?
text = '1.83\n1\n71%\n4.25\nX\n18%\n4.30\n2\n11%\n+88'
split = text.split('\n')
print('\n'.join([split[0], split[3], split[6]])

You may need to replace '\n'.join(...) with '\\n'.join(...) if you want to retain \n as two readable characters in the resulting string instead of them being one line break character.
Explanation:
First you split the entire text into segments separated by \n, where \n is then discarded. This gives you a list of segments.
You can access each segment by using the index via text[index], in this case split[0] to get the first segment in the list named split.
You then create a list with the segments you desire to use [split[0], split[3], split[6]]. The remaining segments are being unused.
You re-join the segments in this new list by using ''.join(list_of_segments), where you specify that you want to join them with the \n characters. Since \ is an escape character, you need to escape it as well, therefore you use \\n, which results in '\\n'.join(list_of_segments).

A: You can use
df['A'].str.replace(r'(?m)^(?!\d+\.\d+$).*\n*', '').str.strip()

See the regex demo. Details:

*

*(?m) - re.M inline option, makes ^ match start of a line position and $ match the end of a line position

*^ - start of a line

*(?!\d+\.\d+$) - no one or more digits, . and one or more digits till the end of the line

*.* - the whole line, zero or more chars other than line break chars, as many as possible

*\n* - zero or more line feed chars.

The .str.strip() is necessary to remove the trailing newline char if there was a match at the end of the string.
Pandas test:
>>> import pandas as pd
>>> df=pd.DataFrame({'A': ['1.83\n1\n71%\n4.25\nX\n18%\n4.30\n2\n11%\n+88']})
>>> df['A'].str.replace(r'(?m)^(?!\d+\.\d+$).*\n*', '').str.strip()
0    1.83\n4.25\n4.30
Name: A, dtype: object


text:
Q: How to add CircularProgressIndicator in flutter Here is my all code samples. How can I add a circular progress indicator when user press the signup button?
    class CreateAccountScreen extends StatefulWidget {
      @override
      _CreateAccountScreenState createState() => _CreateAccountScreenState();
    }

    class _CreateAccountScreenState extends State<CreateAccountScreen>
        with SingleTickerProviderStateMixin {

      Future<Profile> _profile;
      ProgressDialog _progressDialog;
      bool _isloading;

Here is the button click Function:
    _pressCreateAccountButton(){
        print("User pressed \"CREATE ACCOUNT\" button");
        print("Login: ${editControllerName.text}, E-mail: ${editControllerEmail.text}, "
            "password1: ${editControllerPassword1.text}, password2: ${editControllerPassword2.text}");
        // Navigator.pushNamedAndRemoveUntil(context, "/main", (r) => false);
        // Navigator.push(context, MaterialPageRoute(builder: (context) => BuisnessType()));
        // MaterialPageRoute(builder: (context) => BuisnessType());

        if(editControllerName.text == null || editControllerEmail.text == null || editControllerPassword1.text == null || editControllerPassword2.text == null || editControllerContact.text == null){
            Fluttertoast.showToast(
                msg: "Please input the necessary field",
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.BOTTOM,
                timeInSecForIosWeb: 1,
                backgroundColor: Colors.red,
                textColor: Colors.white,
                fontSize: 16.0);
        }else if(!editControllerEmail.text.contains("@") || !editControllerEmail.text.contains(".") || !editControllerEmail.text.contains("com")){

          Fluttertoast.showToast(
              msg: "Please input valid email address",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0);
        }else{

          _isloading = !_isloading;

            _profile = getProfileData(editControllerName.text.toString(), editControllerEmail.text, editControllerPassword2.text,editControllerContact.text, 3);
        }
      }

Here is the rest api call function:
Future<Profile> getProfileData(String name, String strEmail, String strPass,String strPhone, int type) async{
    await AllApiCall.userRegistration(name, strEmail, strPass, strPhone, type).then((value) {

      print(value.success.token);

      setState(() {
        _isloading = false;
      });

      Navigator.push(context, MaterialPageRoute(builder: (context) => BuisnessType()));
    });
  }

Rest is design of that page:
  final editControllerName = TextEditingController();
  final editControllerEmail = TextEditingController();
  final editControllerPassword1 = TextEditingController();
  final editControllerPassword2 = TextEditingController();
  final editControllerContact = TextEditingController();

  @override
  void initState() {
    super.initState();
    _isloading = false;
  }

  @override
  void dispose() {
    editControllerName.dispose();
    editControllerEmail.dispose();
    editControllerPassword1.dispose();
    editControllerPassword2.dispose();
    editControllerContact.dispose();
    super.dispose();
  }

I have added _isloading but its not working in my case. Is there any way to fix this issue?

A: You can use the loading_overlay package. You can find it here:
https://pub.dev/packages/loading_overlay
You will have to define a bool isLoading, and initially set it's value to false.Like this: bool isLoading = false;.Then import the loading_overlay package by writingimport 'package:loading_overlay/loading_overlay.dart'; at the top of your file.
Now, wrap all of your widgets with the LoadingOverlay widget like this:
LoadingOverlay(
progressIndicator: CircularProgressIndicator(),
isLoading: isLoading, // our previously defined variable
child: YourWidgets(),
)

Now when you need to start a loading process you can write:
setState(()=>isLoading=true);
And to stop it write:setState(()=>isLoading=false);
If you have any questions please let me know.


text:
Q: Pass all state values to child component I have a legacy application which passes a JSON to create a multi-page form. I'm trying to create a common multi-page form component in which we can just past a json to generate a form.
The application uses a buildFormState which sets the state in the parent component as:
constructor(props) {
  super(props);
  this.state = this.buildFormState();
}

 buildFormState() {
let state = SCREENS.reduce(function(o, s) {
    let _s = s.fields.reduce(function(_o, _f) {
        _o[_f.name] = _f.type == 'checkbox'  ? [] : '';
        return _o;
    }, {});
    return Object.assign(o, _s);
}, {});
state.current_screen = 0;
return state;
}

And this is my call to my MultiPageForm component:
<MultiStepForm SCREENS = {SCREENS} current_screen = {this.state.current_screen} state = {this.state} submitState={this.submitState.bind(this)} uploadPhoto={this.uploadPhoto.bind(this)} completeForm={this.completeForm.bind(this)} />

And my constructor in the MultiStepForm Component is:
constructor(props) {
super(props);
// this.state = this.props;
this.state = this.props.state;
this.SCREENS = this.props.SCREENS
}

But it doesn't pass the state properly as some things get passed while others don't. Is there a way I can pass everything properly without having to individually assign it in the child component?

A: You can pass all the state like this:
<MultiStepForm {...this.state} />

If you don't want to split it and instead send it as an object:
<MultiStepForm childState={this.state} />

The use of state string as a prop name should not be a problem, still, it is better to avoid it.


text:
Q: Am I incrementing my sliding window too far out? I am working on solving this question on LeetCode which finds the longest substring of a given string without repeating characters. My solution is working for some strings (such as 'pwwkew'), but not for others (such as 'ckilbkd'). Any suggestions?
public int LengthOfLongestSubstring(string s) {
    if (s.Length < 2) return s.Length;

    HashSet<char> existing = new HashSet<char>();
    Stack<string> vals = new Stack<string>();

    int start = 0;
    int end = 1;
    int result = 1;
    existing.Add(s[0]);

    while (end < s.Length && start < end)
    {
        if (!existing.Contains(s[end]))
        {
            if (end == (s.Length - 1))
            {
                result = s.Length - start;
                Console.WriteLine("here");
                break;
            }

            existing.Add(s[end]);
            end++;
        }
        else
        {
            var res = s.Substring(start, end - start);

            if (vals.Count == 0)
            {
                vals.Push(res);
                result = res.Length;
            }
            else if (res.Length > vals.Peek().Length)
            {
                vals.Pop();
                vals.Push(res);
                result = res.Length;
            }

            if (s[end] == s[end - 1])
            {
                start = end;
                end++;
            }
            else
                start++;
        }
    }

    return result;
}


text:
Q: Add password hash in pdo login I cannot manage to add a password hash in my sign up code. I am new to PDO and I tried different things but cannot manage to make a working registration with password hash!
Can someone help me? Here my code:
<?php
  include('header.php');
  // Check if logged in
if($user->is_loggedin()!="")
{
    $user->redirect('home.php');
}
$error='';
if(isset($_POST['btn-signup']))
{

// trim empty spaces on inserted data
   $uname = trim($_POST['name']);
   $umail = trim($_POST['email']);
   $upass = trim($_POST['password']);
   $repeat_password = trim($_POST['repeat_password']);

//  validate username
   if($uname=="") {
      $error.= "provide username !
";
   }
//  validate e-mail
   else if($umail=="") {
      $error.= "provide email id !
";
   }
   else if(!filter_var($umail, FILTER_VALIDATE_EMAIL)) {
      $error.= 'Please enter a valid email address !
';
   }
//  validate password
   else if($upass=="") {
      $error.= "provide password !
";
   }
   else if(strlen($upass) < 6){
      $error.= "Password must be atleast 6 characters
";
   }
      else if( $upass!=$repeat_password){
      $error.= "Password Does Not Match
";
   }
   else
   {

    // check if email is already taken
      try
      {
        //   prepare statement
         $stmt = $DB_con->prepare("SELECT email FROM users WHERE  email=:umail");
         $stmt->execute(array(':umail'=>$umail));
         $row=$stmt->fetch(PDO::FETCH_ASSOC);

         if($row['email']==$umail) {
            $error.= "sorry email id already taken !
";
         }
        //  if everything is validated save data
         else
         {
            if($user->register($uname,$umail,$upass))
            {

                $_SESSION['success']='You have been Registered  Successfully';
                $user->redirect('login.php');
            }
         }
     }
    //  set the error mode
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  }
}

And here the class "user"
<?php
class User
{
    private $db;

    function __construct($DB_con)
    {
      $this->db = $DB_con;
    }
//  get user by passed in data
    public function register($uname,$umail,$upass)
    {
       try
       {
         //   $new_password = password_hash($upass, PASSWORD_DEFAULT); // Creates a password hash;
         $new_password = $upass;

           //    prepared statement
           $stmt = $this->db->prepare("INSERT INTO users(name,email,password,user_type)
                                                       VALUES(:uname, :umail, :upass,'user')");
            // bind param with values
           $stmt->bindparam(":uname", $uname);
           $stmt->bindparam(":umail", $umail);
           $stmt->bindparam(":upass", $new_password);
           $stmt->execute();

           return $stmt;
       }
       //  set the error mode
       catch(PDOException $e)
       {
           echo $e->getMessage();
       }
    }

    public function login($umail,$upass)
    {
       try
       {
        //  prepare statement
          $stmt = $this->db->prepare("SELECT * FROM users WHERE email=:umail  LIMIT 1");
          $stmt->execute(array(':umail'=>$umail));
          $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
          if($stmt->rowCount() > 0)
          {
             if($upass==$userRow['password'])
             {
                $_SESSION['user_id'] = $userRow['id'];
                $_SESSION['name'] = $userRow['name'];
                   $_SESSION['role'] = $userRow['user_type'];
                return true;
             }
             else
             {
                return false;
             }
          }
       }
       //  set the error mode
       catch(PDOException $e)
       {
           echo $e->getMessage();
       }
   }

   public function is_loggedin()
   {
      if(isset($_SESSION['user_id']))
      {
         return true;
      }
   }

   public function redirect($url)
   {
       header("Location: $url");
   }

   public function logout()
   {
        session_destroy();
        unset($_SESSION['user_id']);
        return true;
   }
}
?>

In the commented line in the class script you can see a try I made, it hashed the password but then the pw wouldn't be saved in my sql database.
Sorry if the question is stupid but I am learning :)

A: I want to point out few things first:

*

*Do not use trim to users password. Unless if you want to restrict your users from entering spaces to their passwords.

*Use === when doing comparison. It is better because it checks datatype at the same time. For example if you have "2" and 2 and you use == operator it equals. It is good practice to check datatype because it prevents alot error from happening.
As what comes to problem that you wanted to get answer
You don't use password_hash function at any point. You only assign raw password to variable and assign this variable to bind_param function.
$new_password = $upass;

Should be instead
$new_password = password_hash($upass, PASSWORD_DEFAULT);

However i do not recommend using PASSWORD_DEFAULT as you could get more secure hash by using PASSWORD_ARGON2I. You can check more information about password_hash from PHP manual.
And to help you out even more: when you want to verify that user enters correct password at login you need to use password_verify(). It compares hash to password that user entered and if it is correct this function will return true.
Example:
$login_status = password_verify($_POST['password'], $user_password_from_database);
if($login_status === true) {//set session etc...}

You can read more about password_verify here


text:
Q: Password problem after creating a new user  I created a new user account and when I try to login to that account by switching accounts it said wrong password. I searched here and found my answer here - Create a new user in 12.04?
Now when I clicked enable this account and I don't know what happened from then.. now I'm with a problem that ubuntu don't recognising my password. It's saying there's no password set but when I'm clicking it it's asking for old password.

A: I would suggest taking NlightNFotis' advice: open a terminal and type
sudo passwd <user>


text:
Q: Haskell Type Errors with division I have the below simple program to find the average of a list. I know my error is related to the inference of types but I cannot correct it. Can I get a correction and a simple explanation for this?
average :: Float
average= uncurry (/) . sumlen

sumlen ::[Int]-> (Int,Int)
sumlen = foldl f (0,0)
         where f (s,n) x = (s+x,n+1)

The error is:
  • Couldn't match expected type 'Float'
                      with actual type '[Int] -> Int'
   • Probable cause: '(.)' is applied to too few arguments
          In the expression: uncurry (/) . sumlen
          In an equation for 'average': average = uncurry (/) . sumlen

A: Summary: Haskell is a strongly typed language.
You force the type of sumlen to be [Int] -> (Int,Int).
The type of (/) is Fractional a => a -> a -> a.
Let us typecheck your function. First we will try to infer its type:
average = (uncurry (/)) . sumlen
uncurry :: (a -> b -> c) -> (a,b) -> c
(/) :: Fractional d => d -> d -> d
(.) :: (f -> g) -> (e -> f) -> e -> g
sumlen :: [Int] -> (Int,Int)
So:
e = [Int]
f = (Int,Int) = (a,b) = (d,d)
g = d = Int
average :: Fractional Int => [Int] -> Int

Now you tell Haskell that average :: Float and Haskell tells you that a float is not a function. This is your error.
If you remove the annotation then you will be told that there is no instance Fractional Int. This is because you can't represent or reasonably approximate 1 / 2 as an Int.
How to fix this?
Step 0 is to not write down a type signature that is wrong (ie average :: Float)
One thing you could do is have a more general sumlen. Try Num a => [a] -> (a,a) instead. You could even have (Num a, Num b) => [a] -> (a,b). Then you can have the sensible type average :: Fractional a => [a] -> a
Another thing you could do is convert from integers:
average xs = fromIntegral s / fromIntegral l where
  (s,l) = sumlen xs


text:
Q: как задать клик динамическому классу? var product__cart = '';
var refresh = function() { for (key in goods) {
    if (parseFloat(goods[key].price) <= parseFloat(document.getElementById('price__filter__do').value) || parseFloat(document.getElementById('price__filter__from').value) >= parseFloat(goods[key].price)) {
        product__carts +=
        '
'
        +''
        +'
' +goods[key].name +'
'
        +'
 Код товару:' +goods[key].code +'
'
        +'
' +goods[key].price +' Грн' +'' +'
'
        +'
'
    }
    document.getElementById('catalog__goods').innerHTML = product__carts
}};

$('#catalog__goods').on('click', '.add__basck', function(event){

    console.log('d')
})

A: На самом деле все просто.
То что вы используете ".on()" - Это уже верно.
К динамическим элементам так и нужно обращаться. Используя метод ".on()"
Если не работает попробуйте указать "document" или .find() вместо "$('#catalog__goods')"
var product__cart = '';
var refresh = function() {

for (key in goods) {
    if (
        parseFloat(goods[key].price) <= parseFloat(document.getElementById('price__filter__do').value) ||
        parseFloat(document.getElementById('price__filter__from').value) >= parseFloat(goods[key].price)
    ){
        product__carts +=
        '
'
        +''
        +'
' +goods[key].name +'
'
        +'
 Код товару:' +goods[key].code +'
'
        +'
' +goods[key].price +' Грн' +'' +'
'
        +'
'
    }
    document.getElementById('catalog__goods').innerHTML = product__carts
}};

$(document).on('click', '#catalog__goods .add__basck', function(event){
    console.log('d')
})

Вы используете и js и jquery, все это можно написать на jQuery
А так же я не обнаружил у вас в коде класс "add__basck"


text:
Q: assert Json Validation Errors does not work I am not an expert and I could not find anything about my error. I hope someone can help me to understand my error.
I am trying to test the validation of the required attributes of a POST request in Laravel.
TEST
I am using the assertJsonValidationErrors method to validate the JSON errors from my controller.
/** @test */
public function name_email_password_required_in_creation()
{
    $response = $this->post('/users', [
        'contact' => '545678987'
    ]);
    $response->assertJsonValidationErrors(['name','password','email']);
}

Controller
$validator = Validator::make($request->all(),[
        'name' => 'required',
        'email' => 'required|unique:users,email',
        'password' => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json($validator->errors(), 400);
    }

Error:
1) Tests\Feature\UsersTest::name_email_password_required_in_creation
Failed to find a validation error in the response for key: 'name'
Response does not have JSON validation errors.
Failed asserting that an array has the key 'name'.
I applied inside the test a
dd($response->getContent()); to see what is happening and in the response is:
"{"name":["The name field is required."],"email":["The email field is required."],"password":["The password field is required."]}"
It seems to be a string but I don't know if it is causing the error, because the JSON contains the key fields errors.
I do know how to solve it. Thanks in advance.

A: Instead of this:
$response = $this->post('/users', [
    'contact' => '545678987'
]);

Use headers to accept json like this:
$response = $this->json('POST', '/users', ['contact' => '545678987'],
    ['Accept' => 'application/json']
);

Also for validation errors the response code is 422, so use:
if ($validator->fails()) {
    return response()->json($validator->errors(), 422);
}


text:
Q: Using Intersect to copy data between sheets I am writing an Excel macro (Excel 2016) to copy data between sheets.  Rather than use the typical Range command (for instance, Sheet2.Range("A1:A15").Value = Sheet1.Range("A1:A15").Value) I want to use Named Ranges for the Columns, in case I ever insert columns in either sheet in the future. I also want to use Intersect, in case I ever add/delete rows in the future.  I have been able to get this to work when I am copying data within the SAME worksheet, but it is giving me a "400 error" when I try to do it from one worksheet to another.  I am not sure what I am doing wrong.
First, here is a line of code that works when copying data within the same worksheet.
Intersect([P1B_CalcPercent1], Rows(FirstRow & ":" & LastRow)).Value = Intersect([P1B_CalcPercent2], Rows(FirstRow & ":" & LastRow)).Value

Here is my sub for trying to copy a range of cells from one sheet to another.  The line that begins with Intersect is giving me the 400 error.
Sub Copy_from_1A_Button()

Dim FirstRow As Integer, LastRow As Integer

Application.ScreenUpdating = False

ThisWorkbook.Sheets("Page 1B").Activate

Module7.UnprotectPage1BSheet

FirstRow = Range("B_first_row").Value
LastRow = Range("B_last_row").Value

If MsgBox("Are you sure you wish to do this? Data in the target cells will be overwritten.", vbYesNo) = vbYes Then

    Intersect([P1B_JobTitles], Rows(FirstRow & ":" & LastRow)).Value = Intersect([P1A_JobTitles], Rows(FirstRow & ":" & LastRow)).Value

End If

Module7.ProtectPage1BSheet
Application.ScreenUpdating = True

End Sub

Both 'P1A_JobTitles' and 'P1B_JobTitles' are named ranges that have a scope of Workbook, but they exist on different sheets.  (Side question: would it matter if the scope of each was just the sheet it was on?)
I tried putting "Application." in front of Intersect in both places, but I got the same error.
Any ideas why the Intersect method isn't working to copy from one sheet to another?

A: You're getting this error because ROWS returns a Range object that represents all the rows on the specified worksheet. Because you aren't specifying a worksheet, it's just using the active sheet. You need to qualify it with the name of the worksheet you want to use it on. To do this dynamically, you can use something like this:
Intersect(Range("SomeName"), Worksheets(Parent.Range("SomeName")).Rows("1:2")).Address

A: Try,
dim i as long, j as long, pa as string, pb as string, P1A_P1B as variant
dim p1a as worksheet, p1b as worksheet

P1A_P1B = array("P1__JobTitles", "P1__CalcPercent")
set p1a = ThisWorkbook.workSheets("Page 1A")
set p1b = ThisWorkbook.workSheets("Page 1B")
...

for i=lbound(P1A_P1B) to ubound(P1A_P1B)
    pa = replace(P1A_P1B(i), "__", "A_")
    pb = replace(P1A_P1B(i), "__", "B_")
    with Intersect(p1a.Range(pa), p1a.Range(FirstRow & ":" & LastRow))
        Intersect(p1b.Range(pb), p1b.Range(FirstRow & ":" & LastRow)).resize(.rows.count, .columns.count) = .Value
    end with
next i
...


text:
Q: Wrapping TD contents of datatable inside a span tag am using data table and loading data from db using Ajax.  the data is getting loaded properly.  but i want to enclose each context of TD inside a span tag like below
cell content

currently the output is coming as
cell content

how do i do this?  am using datatable and bootstrap.

A: add this and it worked
var id;
fnRender: function (oObj) {id = oObj.aData[0]
                       return '' + oObj.aData[0] + '';
    }


text:
Q: Dealing with multiple standards in single class library I'm currently working on a project which will support multiple file writing specifications (imagine if you had to support something like XML 1.0, XML 2.0, XML 3.0, etc) called ADIF. Currently there are two standards (version 1.0 and version 2.2.2), and they are both used commercially and both still heavily used.
Specification version 2.2.2 incorporates much of version 1.0 but there are some slight differences which rules out some inheritance and other OOP tools.
How would you organize your project to support older versions, yet continue to keep up with new standards.

*

*Namespaces (Standard.Version1, Standard.Version222, Standard.Version223 (next version?), etc.) in a single class library? Seems sloppy.

*Separate class library for each in the same solution (Version222.dll, Version223.dll, etc.)? Seems excessive.

*etc.

I do intend to implement some code which will convert from one version to another.
Basically, I'm looking for some advice on how to best organize this type of project.
http://www.adif.org/

A: You stated that there isn't a good inhertance hierarchy that you can implement?
If so I would recommend that you follow the namespace technique for your library, which can use any commonality possible inside the dll to reduce the work load for yourself.  Having two api's will make it significantly easier for you to test and also nicely deal with issues regarding the differences between versions.
i.e. your version 2.2.2 api would only accept objects of the 2.2.2 version to prevent issues in the library.

A:
Specification version 2.2.2 incorporates much of version 1.0 but there are some slight differences which rules out some inheritance and other OOP tools.

Object composition can be a much more powerful tool for OOP than inheritance, which is IMO overused.
What ways can you find to break the problem down into simpler subsystems?


text:
Q: UISegmentedControl image highlighting bug in iOS6 Currently I have a small segmented control with 3 separate segments.
What I want to do is, if selected, change the image of that specific segment to a different image.
So far I've managed to make it very similar to what I want, and a new image is displaying when selected, but a small part of the new image is covered by a blue highlight (shown below), and no matter what I try, I can't get rid of it:

For some reason the highlighting is overriding part of the image.
I'd like to know how to completely disable any highlighting/change of a segmented control when selected, or any other option which would achieve my question.
What I've tried so far:

*

*setting background image of UISegmentedControl

*UISegmentedControl custom background image
My code (just testing out one image for any selected button as you can see):
-(IBAction)languageChanged:(UISegmentedControl *)sender {
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] init];
    [segmentControl addTarget:self action:@selector(segmentedControlValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentControl];

    [sender setImage:[UIImage imageNamed:@"rsz_langue-francais-on.png"] forSegmentAtIndex:sender.selectedSegmentIndex];
}

A: I am not 100% sure if this will work, but the segment colour is determined by tintColor.
So you could simply set tintColor to [UIColor clearColor];
EDIT:
I have read that it is an issue with iOS6 and above. To fix the problem set the width for each individual section rather than the whole segmented control.
Here is some example (untested) code for a UISegmentedControl with a width of 180:
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 6.0) {
    [[UISegmentedControl appearance] setWidth:90 forSegmentAtIndex:0];
    [[UISegmentedControl appearance] setWidth:90 forSegmentAtIndex:1];
}
else{
    segmentedControl.frame = CGRectMake(0, 0, 180, 30);
}

EDIT 2:
I have only ever been able to change a segment control tint colour when the style is set to 'Bar' rather than 'Plain'. I really up this changes soon as the consistency of colour within my apps is compromised.
A temporary and dirty fix could be to check the momentary state to YES. This would make it only blue for a second and your custom images will still make it seem selected.

A: In the end, the only way I was able to fix (maybe avoid would be a better word) the problem was by changing the style of the uisegmentedcontrol from 'Plain' to 'Bar', which removed the blue highlighted spacing in between segments, like Patrick suggested above. I have heard this is a known iOS6 bug, and hopefully it is fixed soon.


text:
Q: C++:How to generate a list of non-repeated random number For instance, generating a list of non-repeated random number from 0 to 51.[0,51]
for(int i = 0;i<52;i++)
   {

    //print out 0,1,2,3,4,5,6,7,8,....,51.

   }

A: Create an array or vector and randomly shuffle.
vector<int> v;
for(int i = 0; i < 52; ++i)
    v.push_back(i);
std::random_shuffle(v.begin(), v.end()); //need #include <algorithm>

First random number will be v[0], you have 52 non repeating random numbers

A: It looks like you are trying to shuffle a deck of cards for homework ;)
Here's the code in Python to help you get started:
def shuffle(deck):
    for i in xrange(len(deck)):
        rand_index = random.randint(i, len(deck) - 1)
        temp = deck[i]
        deck[i] = deck[rand_index]
        deck[rand_index] = temp


text:
Q: Install ffmpeg with applescript I'm trying to create an applescript that installs ffmpeg.  I have two issues.

*

*I want to install Xcode, homebrew, ffmpeg, node, grant permissions, and ffmpeg-progressbar-cli one at a time. Not all at once but in that order.  ffmpeg is dependant on xcode so it needs to wait before xcode is done installing.

*The command for homebrew requires " which applescript makes me change to a ' before I can run it but in this case it doesn't work.

Here is the script I have so far.
tell application "Terminal"
    do script "xcode-select --install && ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" && brew install ffmpeg && brew install node && sudo chown -R $(whoami) /usr/local/bin /usr/local/etc && npm install --global ffmpeg-progressbar-cli"
    activate
end tell

I tried this and it doesn't seem to work as intended.
tell application "Terminal"
        do script "sudo chown -R $(whoami) /usr/local/bin /usr/local/etc && xcode-select --install"
        display dialog "Select OK once Xcode has installed" buttons {"OK"} default button 1
        do script "ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)""
        display dialog "Select OK once Homebrew has installed" buttons {"OK"} default button 1
        do script "brew install ffmpeg"
        display dialog "Select OK once ffmpeg has installed" buttons {"OK"} default button 1
        do script "brew install node"
        display dialog "Select OK once node has installed" buttons {"OK"} default button 1
        do script "npm install --global ffmpeg-progressbar-cli"
        display dialog "Select OK once ffmpeg-bar has installed" buttons {"OK"} default button 1
        activate
    end tell

For the second issue it needs to be
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
but applescript makes me change it to
ruby -e '$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)'
with single quote which doesn't work.
Help and suggestions apreciated!

A: Ok, try the following script, but see caveats below:
shellScriptHandler("xcode-select --install", false)
shellScriptHandler("sudo chown -R $(whoami) /usr/local/Cellar", true)
shellScriptHandler("ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\" <<< " & return, false)
shellScriptHandler("sudo chown -R $(whoami) /usr/local/var/homebrew /usr/local/share/zsh /usr/local/share/zsh/site-functions", true)
shellScriptHandler("/usr/local/Homebrew/bin/brew install ffmpeg", false)
shellScriptHandler("/usr/local/Homebrew/bin/brew install node", false)
shellScriptHandler("sudo chown -R $(whoami) /usr/local/bin /usr/local/etc", true)
shellScriptHandler("/usr/local/bin/npm install --global ffmpeg-progressbar-cli", false)

on shellScriptHandler(command, usesAdmin)
    log command
    (*
        The try block catches any errors and reports them; the user can choose
        to continue execution if it's a warning, or cancel execution outright.

        The 'eval' statement forces do shell script to read the standard
        interactive $PATH variable, so that it sees /user/local/, otherwise it
        can't find the files it needs.
    *)
    try
        do shell script "eval `/usr/libexec/path_helper -s`; " & command administrator privileges usesAdmin
    on error errstr
        display dialog errstr buttons {"Continue", "Cancel"} default button "Continue"
    end try
end shellScriptHandler

Caveats:

*

*If there is a previous install of homebrew, the first line may fail with a permissions error; on my system, it tried to copy something from the Xcode bundle to /usr/local/Homebrew/.git/..., but needed root privileges. I solved that problem by deleting the folder /usr/local/Homebrew entirely, but that might be a bit drastic for the general case. You'll have to see if the problem recurs.

*I added a couple of chown commands in lines 2 and 4. These popped up as errors when I ran the ruby script and brew install.... You may run across other such errors based on idiosyncrasies in different systems, but it shouldn't hurt to add more such commands to straighten out the permissions in /usr/local.

*This script should run with a minimum of user interaction, but it does need the occasional 'ok' or password entry. Those could be automated, but I'm not sure it's worth it.


text:
Q: I keep getting compiler error C2086 So I got this the C++ Primer Plus and in one of the excersices I needed to writte a programm to get the BMI of a person i needed to ask for the height in feet and inches and then make a convertion to just inches, then ask the person their weight in pounds and convert it to kilograms ans that was it
I appreciate the help in advance =)
Keep getting this error
Severity    Code    Description Project File    Line    Suppression State
Error   C2086   'double inches': redefinition   ConsoleApplication14
  #include "stdafx.h"
  #include <iostream>

  using namespace std;

  int main()
{

    const double inchesFactor = 12;

    const double metersFactor = 0.0254;

    const double massFactor = 2.2;

    double height;
    double weight;
    double BMI;
    double inches;
    double mass;
    double meters;

    cout << "Enter height " << flush;
    cin >> height;
    cout << "Enter weight " << flush;
    cin >> weight;

    double inches = (height * inchesFactor);
    double mass = weight / massFactor;
    double meters = inches / 0.5;
    double BMI = mass / meters;

    cout << "Your BMI is " << BMI << endl;

A: The code below runs, you need to delete the extra doubles. I removed the  #include "stdafx.h" beacuse i am not using VS, but you can put it back
#include <iostream>

  using namespace std;

  int main()
{

    const double inchesFactor = 12;

    const double metersFactor = 0.0254;

    const double massFactor = 2.2;

    double height;
    double weight;
    double BMI;
    double inches;
    double mass;
    double meters;

    cout << "Enter height " << flush;
    cin >> height;
    cout << "Enter weight " << flush;
    cin >> weight;

    inches = (height * inchesFactor);
    mass = weight / massFactor;
    meters = inches / 0.5;
    BMI = mass / meters;

    cout << "Your BMI is " << BMI << endl;

    return 0;
    }

A: Let's take a look at your code. Here you declare a bunch of variables of type double:
double height;
double weight;
double BMI;
double inches;
double mass;
double meters;

Then you ask the user to input height and weight:
cout << "Enter height " << flush;
cin >> height;
cout << "Enter weight " << flush;
cin >> weight;

And here you make bunch of calculations:
double inches = (height * inchesFactor);
double mass = weight / massFactor;
double meters = inches / 0.5;
double BMI = mass / meters;

When you write double inches = (height * inchesFactor); you're telling the compiler that "I want a new variable of type double with the name inches, and I want to set it to the value of (height * inchesFactor). But you can't make a new variable named inches because you have already declared a variable with that name earlier.
If you omit the type and just write inches = (height * inchesFactor); you are instead telling the compiler: "I want to set the variable inches, which I've declared elsewhere, to the value of (height * inchesFactor).
So to fix your code, replace the last block of code above to just:
inches = (height * inchesFactor);
mass = weight / massFactor;
meters = inches / 0.5;
BMI = mass / meters;

since you've already declared inches, mass, meters and BMI earlier.


text:
Q: JSON Object for jqGrid subgrid This is my 3rd question about JSON data for jqGrid's subgrid, till now I did not get a single comment. Please somebody help.
my 1st questionand the
2nd one
I am having trouble getting to know the json format to be used by a subgrid in jqGrid. In my 2nd question i asked about the format that I should be using for a particular scenario
for the given image

Is this the proper JSON String?
var myJSONObject = {
"list": [
    {
        "elementName": "TERM",
        "attribute": [
            {
                "name": "information",
                "firstValue": "Required fixes for AIX",
                "secondValue": "Required fixes for AIX"
            },
            {
                "name": "name",
                "firstValue": "PHCO_34",
                "secondValue": "PHCO_34"
            },
            {
                "name": "version",
                "firstValue": "1.0",
                "secondValue": "2.0"
            }
        ],
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": false
    },
    {
        "elementName": "Asian-Core.ASX-JPN-MAN",
        "attribute": [
            {
                "name": "information",
                "firstValue": "Man",
                "secondValue": "Man"
            },
            {
                "name": "name",
                "firstValue": "Asian-Core.ASX-JPN-MAN",
                "secondValue": "Asian-Core.ASX-JPN-MAN"
            },
            {
                "name": "version",
                "firstValue": "B.11.23",
                "secondValue": "B.11.23"
            }
        ],
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true
    }
]
};

If yes, my 1st question this is where i reached so far
$('#compareContent').empty();
    $('
')
    .html('

'+
            '

')
    .appendTo('#compareContent');

    var grid = jQuery("#list2");

    grid.jqGrid({
        datastr : myJSONObject,
        datatype: 'jsonstring',

        colNames:['Name','Result1', 'Result2'],
        colModel:[
            {name:'elementName',index:'elementName', width:90},
            {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100},
            {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100},
        ],
        pager : '#gridpager2',
        rowNum:10,
        scrollOffset:0,
        height: 'auto',

        autowidth:true,
        viewrecords: true,
        gridview: true,
        jsonReader: { repeatitems : false, root:"list" },
        subGrid: true,

        /*subGridModel: [{
            //subgrid columns names
            name: ['Name', 'Version', 'Information'],
            //subgrid columns widths
            width: [200, 100, 100],
            //subrig columns aligns
            align: ['left', 'left', 'left']

          }]*/

        // define the icons in subgrid
        subGridOptions: {
            "plusicon"  : "ui-icon-triangle-1-e",
            "minusicon" : "ui-icon-triangle-1-s",
            "openicon"  : "ui-icon-arrowreturn-1-e",
            //expand all rows on load
            "expandOnLoad" : true
        },
        subGridRowExpanded: function(subgrid_id, row_id) {
            var subgrid_table_id, pager_id;
            subgrid_table_id = subgrid_id+"_t";
            pager_id = "p_"+subgrid_table_id;
            $("#"+subgrid_id).html("

");
            jQuery("#"+subgrid_table_id).jqGrid({
                datastr : myJSONObject,
                datatype: 'jsonstring',
                colNames: ['Name','Value1','Value2'],
                colModel: [
                    {name:"name",index:"name",width:90},
                    {name:"firstValue",index:"firstValue",width:100},
                    {name:"secondValue",index:"secondValue",width:100},
                ],
                rowNum:20,
                pager: pager_id,
                sortname: 'name',
                sortorder: "asc",
                height: 'auto',
                autowidth:true,
                jsonReader: { repeatitems : false, root:"attribute" }
            });
            jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false})
        }
    });
    grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false});

Any type of suggestions/comments/solutions are welcome. Thanks
My output

A: You code has small errors in the declaration of the myJSONObject variable and the code which create the contain of the div#compareContent should be fixed to
$('#compareContent').empty();
$('
'+
  '

'+
        '

')
.appendTo('#compareContent');

Small other syntax errors are the trailing commas in the colModel: the comma before ']' should be removed.
Now to your main problem. You should change datastr : myJSONObject in the subgrid to something like
datastr : myJSONObject.list[0]

then the modified demo will show the data: see here.
One more problem which you has is the absent of ids in your data. You should modify the structure of the data to define the unique ids for very grid row and every subgrid row. You should take in the considerations that ids from the data will be used as id of
 elements and HTML don't permit to have id duplicates on one HTML page.
UPDATED: See here an example of modification of your JSON input and the jqGrid so that ids will be used.

A: a couple of suggestion that may/maynot workout
when using subgrid select the grid as
var mygrid = jQuery("#mygrid")[0];

replace
var grid = jQuery("#list2");

with
var grid = jQuery("#list2")[0];

Ref: http://www.trirand.com/blog/?page_id=393/help/2-questions-about-jqgrid-subgrid-and-jsonstring
also change your json to a valid json
{
    "list": [
        {
            "elementName": "TERM",
            "attribute": [
                {
                    "name": "information",
                    "firstValue": "RequiredfixesforAIX",
                    "secondValue": "RequiredfixesforAIX"
                },
                {
                    "name": "name",
                    "firstValue": "PHCO_34",
                    "secondValue": "PHCO_34"
                },
                {
                    "name": "version",
                    "firstValue": "1.0",
                    "secondValue": "2.0"
                }
            ],
            "isEqual": false,
            "isPrasentinXml1": true,
            "isPrasentinXml2": false
        }
    ]
}

verfified by www.jsonlint.com
you may find the following link useful
jqGrid with JSON data renders table as empty