Q:

Twitter Bootstrap textboxes size limit

I'm using bootstrap text boxes as :

         Contact List
          <select class="form-control" id="list" name="list">
             <option value="">Please Select</option>
          </select>

        <input class="form-control" id="contact_id" maxlength="3" size="4" name="contact_id">
         <button type="button" class="btn btn-primary" id="load_contact">Load Contact</button>

I would like to align textbox and button at the right side of dropdownlist, but currently textbox is aligned through out the page.
Here is a screenshot :

A:

Bootstrap use a 12 columns based row...
You have (for large view : col-lg) 14 columns ( col-lg-4 + col-lg-10 )
So just modify this to have a sum of 12 ( 4 + 8 ) ( I changed to col-xs for see it a xtra small )

         Contact List
          <select class="form-control" id="list" name="list">
             <option value="">Please Select</option>
          </select>

        <input class="form-control" id="contact_id" maxlength="3" size="4" name="contact_id">
         <button type="button" class="btn btn-primary" id="load_contact">Load Contact</button>

Here is a fiddle


Q:

How can I listen for signals from Docker in .Net Core Executable?

I have a console application written in .Net Core. I will be running this in a Docker container.  I would like to gracefully stop the process when a docker stop command is given, rather than just letting the process get killed in the middle of doing something.  Is there a way that I can listen for this signal from within the console application?  Before containers, I would just have the console app listen for something to be typed in the console window.  If there is a way to have docker send a message through standard input, I could work with that, I just do not know enough about Docker, yet, to know what is possible.

A:

My solution is going to end up being to not use a console application, after all.  I learned that if I create a web project, I can tell when the container has requested a shutdown with the ApplicationStopping CancellationToken in the website's Startup.  So, rather than having the container start up a long running console application, it will just host a website that has no web content.  The website will just start up my long running process, and when the container sends a signal to the website that it is shutting down, my process can gracefully stop.
public void Configure(IApplicationBuilder app
                , IHostingEnvironment env
                , IApplicationLifetime applicationLifetime)
{
    applicationLifetime.ApplicationStarted.Register(ApplicationStarted);
    applicationLifetime.ApplicationStopping.Register(ApplicationStopping);
    applicationLifetime.ApplicationStopped.Register(ApplicationStopped);
}


Q:

sqlite select minimum and maximum from two tables

I have two tables
table1
c1t1    c2t1
1       saanu
3       abc

table2
c1t2    c2t2
2       val2
4       val4

I have to find out the values of c2t1 and c2t2 for the minimum and maximum value of c1t1 and c1t2 with one line command.
For the above example I have to find saanu and val4

A:

One approach:
select max(case c1 when min1 then c2 end) c2_first,
       max(case c1 when max1 then c2 end) c2_last
from (select c1t1 c1, c2t1 c2 from table1
       union all
       select c1t2 c1, c2t2 c2 from table2) u
cross join
(select min(min11, min12) min1, max(max11, max12) max1 from
 (select min(c1t1) min11, max(c1t1) max11 from table1) t1
 cross join
 (select min(c1t2) min12, max(c1t2) max12 from table2) t2) m

SQLFiddle here.


Q:

Where clause in LINQ query is not recognized in vb.net?

The entity field is not recognized in the following Where clause.  Is the VB wrong?
Dim projects = context.projects
               .OrderBy(Function(x) x.name)
               .Select(Function(x) {x.id, x.name})
               .Where(Function(x) x.id <> sourceid)

If I take the Where off, it works fine. Also, if I flip the Where and the OrderBy, Where is fine, but now OrderBy fails.

A:

Try this:
Dim projects = context.projects
                               .OrderBy(Function(x) x.name)
                               .Select(Function(x) New With {x.id, x.name})
                               .Where(Function(x) x.id <> sourceid)

The New With keyword should create an IEnumerable of anonymous type. You can then work with the id property in the Where clause without having to change the order of your operations.
There is nothing stopping you from doing the operations OrderBy, Select, Where in that order. The above code will certainly compile and run. However, logically you need to do the Where before Select, since the former is a filtering operation, while the latter is a projection.


Q:

trace_printf not working with floats

Using Eclipse IDE to program an STM32F0xx Discovery board.  Attempting to do some math buy taking the TIM2 clock counter and dividing it by 48000000 to arrive at a time period.
If I declare my working variable as uint32_t it gives me the truncated answer.  What I want is a decimal value and I would have thought that declaring it as a float would solve the issue, but when I do that nothing gets printed.
variable = (TIM2->CNT)/48000000;
trace_printf("%i",variable);

works with a uint32_t declared variable however changing the place holder to %f or even leaving as is for a float declaration produces nada.  Does it need to be cast as a float?
Its been so long since I've done any C coding and I'm certain I've had this same issue before when using CooCox but I can't remember what the solution was back then.

A:

TY @harmic!  http://www.ece.uvic.ca/~brent/ceng355/printf.html

Printing Floating Point Numbers Using trace_printf
To enable the trace_printf to print floating point numbers do the following in your project.

Under the projects menu item select properties option.
Expand out the C/C++ Build Section and select the settings option.
Now select the tab "Tool Settings". Under the section "Cross ARM C++ Linker" select Miscellaneous.
Click the checkbox that says "Use float with nano printf (-u_printf_float).
Now click apply and then OK.
Rebuild your project and floating point numbers should now print.

Please see picture below for configuration settings and sample code with results.

That's exactly what I needed.  I'll spread the word around in class about that link.


Q:

Is the name change proposal "Second-Language Acquisition" really appropriate?

Over on Area 51, one of the proposed names for this site was Second Language Acquisition. While the term does accurately describe the scope of the stack, the part that really bothers me is the "Second Language". Questions on this site are not only restricted to a second language. It's perfectly fine if you have any questions about learning a third or fourth language. For that reason, I suggest we change this name proposal to "New Language Acquisition" or something like that.

A:

Just like "dual citizenship" is usually used to refer to two or more—not "two and only two"—citizenships, I understand "second language" to mean "not the first", rather than "between the first and the third". So I don't think your concern is warranted.
Wikipedia defines a second language as

a language that is not the native language of the speaker, but that is used in the locale of that person. In contrast, a foreign language is a language that is learned in an area where that language is not generally spoken.

So one could make the argument that it's excluding foreign language learning, but not that it's excluding learning a third or fourth language. It's simply not what that term means.

That being said, the current title "Language Learning" seems very clear to me, and I don't see why it would need to be changed.

A:

For future readers: questions about native language acquisition, including re-acquisition, are also on-topic. So the name "Second Language Acquisition" would be a bad fit for the site.


Q:

Extract multiple indices from matrix

I want to access multiple indices of a matrix as shown below. So what I want is indices (1,3),(2,6),(3,7) to be set to one. However, as you can see the entire column is set to one. I can see what it is doing but is there a way to do what I want it to (in an elegant way - no loops).
a=zeros(3,10)
a(1:3,[3 6 7])=1

a =

 0     0     1     0     0     1     1     0     0     0
 0     0     1     0     0     1     1     0     0     0
 0     0     1     0     0     1     1     0     0     0

I realise that you can do something along the lines of
x_idx=1:3, y_idx=[3 6 7];
idx=x_idx*size(a,2)+y_idx;
a(idx)=1;

but just wondering if there was a better, or proper way of doing this in Matlab

A:

You can use sub2ind, which essentially is doing what you have mentioned in your post, but MATLAB has this built-in:
a = zeros(3,10);
a(sub2ind(size(a), 1:3, [3 6 7])) = 1

a =

     0     0     1     0     0     0     0     0     0     0
     0     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     0     1     0     0     0

Another way would be to create a logical sparse matrix, then use this to index into a:
a = zeros(3,10);
ind = logical(sparse(1:3, [3 6 7], true, size(a,1), size(a,2)));
a(ind) = 1

a =

     0     0     1     0     0     0     0     0     0     0
     0     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     0     1     0     0     0


Q:

How to diff two file lists and ignoring place in list

I have two lists of files which I want to diff.
The second list has more files in it, and because they are all in alphabetical order when I diff these two lists I get files (lines) that exists in both lists, but in a different place.
I want to diff these two lists, ignoring line place in the list.
This way I would get only the new or missing lines in the list.
Thank you.

A:

You can try this approach which involves "subtracting" the two lists as follows:
$ cat file1
a.txt
b.txt
c.txt

$ cat file2
a.txt
a1.txt
b.txt
b2.txt

1) print everything in file2 that is not in file1 i.e. file2 - file1
$ grep -vxFf file1 file2
a1.txt
b2.txt

2) print everything in file1 that is not in file2  i.e. file1 - file2
$ grep -vxFf file2 file1
c.txt

(You can then do what you want with these diffs e.g. write to file, sort etc)
grep options descriptions:
  -v, --invert-match        select non-matching lines
  -x, --line-regexp         force PATTERN to match only whole lines
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -f, --file=FILE           obtain PATTERN from FILE

A:

Do the following:
cat file1 file2 | sort | uniq -u
This will give you a list of lines which are unique (ie, not duplicated).
Explanation:
        1) cat file1 file2 will put all of the entries into one list
        2) sort will sort the combined list
        3) uniq -u will only output the entries which don't have duplicates

A:

The deft command to use here is the humble comm command:
To demonstrate, let's create two input files:
$ cat <<EOF >a
> a.txt
> b.txt
> c.txt
> EOF

$ cat <<EOF >b
> a.txt
> a1.txt
> b.txt
> b2.txt
> EOF

Now, using the comm command to get what the question wanted:
$ comm -2 a b
        a.txt
        b.txt
c.txt

This shows a columnar output with missing files (lines in a but not in b) in the first column and extra files (lines in b but not in a) in the second column.
What exactly does comm do?
Here's the output if the command is typed without any switches:
$ comm a b
                a.txt
        a1.txt
                b.txt
        b2.txt
c.txt

This shows three columns thus:

Lines in a but not in b
Lines in both a and b
Lines in b but not in a

What the numbered switches -123 do is it hides the specified column from the output.
So for example:

Specifying -13 results in common lines only
Specifying -12 results in lines only in b
Specifying -23 results in lines only in a
Specifying -2 results in the symmetric difference
Specifying -123 results in no output


Q:

Is it safe to indent with 2 spaces?

I know the general answer to "How should I indent my code" is generally "do as you wish but do it the same way as everyone on your team", but in the last time I've seen many projects and platforms relying on a 2-space indentation.
I just want to make sure I get the "best bang for my buck" when indenting and make sure it's future-proof. Changing the structure in a project later on is a pretty big problem considering compatibility, etc.
Most projects now rely on 2 Spaces, 4 Spaces or Tabs.

Projects and their indentation:

tabs

WordPress
jQuery
CakePHP
Git
Linux Kernel (doesn't seem to be consistent)

4 spaces

Django
Symfony
Stackoverflow
Zend Framework
Yahoo
MacVim
Memcached

2 spaces

Google
HTML5 Boilerplate
Ruby on Rails
Drupal
Node.js
Github
Blueprint-Css
Jekyll
Chosen
backbone.js
Modernizr
Scriptaculous
Clojure
Facebook (I think)

The question is where is the "community" going? 2 Spaces or 4 Spaces?
My guess is 2 Spaces, since it manifests itself in the big companies and all the standards-pushing projects are using it.
What do you think of the current and future situation? Is it wise to adapt 2 Spaces indentation?

A:

We indent with TABS at our organization for one simple reason.
Tab's can be converted to spaces, but spaces cannot be converted to tabs (reliably).
Once you get the hang of it most editors let you set the TAB-WIDTH, so you can see the code as indented as you would like. 2, 4, 6 spaces!


Q:

Can I force pandas to return a view when I query a dataframe?

Given this dataframe
df = pd.DataFrame({'x': range(10,51,10),
                   'y': [False]*5})
print(df)
--------
    x      y
0  10  False
1  20  False
2  30  False
3  40  False
4  50  False

Is there a way to query that dataframe on x and force pandas to return a view that I can modify sometime in the future?
view = df.loc[df.x <= 20]
print(view._is_view) # returns False
# ... life goes by for a while
view.y = True # does not modify original df

I know I could do this
df.loc[df.x <=20, 'y'] = True

but in my case, the query and the assignment need to be separated by time and code space. My current workaround is to grab the indexes from the query, and just modify the original dataframe instead of messing with the view.
Note I have omitted this for simplicity, but in my actual app, I need to assign each row of the view one by one, separated by time. The view would be slick if I could get it to work.

A:

The pandas documentation currently provides very little guidance in that respect. I could not find a documented list of situations in which a view is guaranteed to be returned, e.g. there are no guarantees that .loc returns a view, as your example demonstrates.
From my understanding, two of the conditions that make it more likely for a view to be returned when using .loc are:

The slice accessed by .loc has only a single dtype (for an answer in a similar context, see the accepted answer by juanpa.arrivillaga here: In Pandas, does .iloc method give a copy or view?)
The selection is a basic slice [i:j] of the underlying numpy array (this is my understanding of the accepted answer by unutbu here: pandas dataframe view vs copy, how do I tell?)

In your specific case that would mean changing df.loc[df.x <= 20] to df.loc[0:1,'y'], as follows:
df = pd.DataFrame({'x': range(10,51,10),
                   'y': [False]*5})
view = df.loc[0:1,'y']
print(view._is_view)  # returns True
view[:] = True
print(df)

which results in:
    x      y
 0  10   True
 1  20   True
 2  30  False
 3  40  False
 4  50  False

Whether this is applicable to your use case depends on whether the selection in x is continuous, as it is in your simplified example.


Q:

Kotlin - Is there a way to pass property values to another object with properties of the same name?

Is there a way to pass property values to another object with properties of the same name to avoid having "repeated" code?
For example, avoid having where CepReceiptsInfo is different class than value but they share some properties name and type :
   val cepReceiptsInfo = CepRecepitsInfo()
    cepReceiptsInfo.operationTimestamp = value.operationTimestamp
    cepReceiptsInfo.sentDate = value.sentDate
    cepReceiptsInfo.sentTime = value.sentTime
    cepReceiptsInfo.concept = value.concept
    cepReceiptsInfo.referenceNumber = value.referenceNumber
    cepReceiptsInfo.amount = value.amount
    cepReceiptsInfo.trackingKey = value.trackingKey
    cepReceiptsInfo.bankTarget = value.bankTarget
    cepReceiptsInfo.bankSource = value.bankSource
    cepReceiptsInfo.sourceClienteName = value.sourceClienteName
    cepReceiptsInfo.beneficiaryName = value.beneficiaryName
    cepReceiptsInfo.accountNumberTarget = value.accountNumberTarget
    cepReceiptsInfo.term = value.term
    cepReceiptsInfo.authorizationNumber = value.authorizationNumber
    cepReceiptsInfo.linkCep = value.linkCep
    cepReceiptsInfo.status = value.status
    cepReceiptsInfo.bankSourceRefund = value.bankSourceRefund
    cepReceiptsInfo.causeRefund = value.causeRefund
    cepReceiptsInfo.accountTargetRefund = value.accountTargetRefund
    cepReceiptsInfo.currency = value.currency
    cepReceiptsInfo.accountNumberSource = value.accountNumberSource
    cepReceiptsInfo.accountTypeSource = value.accountTypeSource
    cepReceiptsInfo.accountTypeTarget = value.accountTypeTarget
    cepReceiptsInfo.indicatorRefund = value.indicatorRefund
    cepReceiptsInfo.amountIntRefund = value.amountIntRefund
    cepReceiptsInfo.operationRefundTimestamp = value.operationRefundTimestamp
    cepReceiptsInfo.dateMovement = value.dateMovement
    cepReceiptsInfo.timeMovement = value.timeMovement
    cepReceiptsInfo.dateRefund = value.dateRefund
    cepReceiptsInfo.timeRefund = value.timeRefund

to something like f.e.:
val cepReceiptsInfo = CepReceintsInfo()
cepReceiptsInfo.assignFrom(value)

both Classes are data classes.

A:

I don't know of a way without reflection.
fun Any.assignFrom(other: Any) {
    val thisProperties = this::class.memberProperties
        .filterIsInstance<KMutableProperty<*>>()
        .map { it.name to it }
        .toMap()
    for (property in other::class.memberProperties){
        thisProperties[property.name]?.setter?.call(this, property.getter.call(other))
    }
}


Q:

Sorted values and values higher then 1 pandas

How do i print only values from an pandas groupby that have more then 2 values
value1,value2,value3
hi,1,2
he,1,2
ho,1,2
hi,1,2
ho,1,2
hi,1,2

If an csv file has the values above and the csv file name is abo.csv
import pandas as pd
df = pd.read_csv('abo.csv')
test = df.groupby('value1').value2.count()
print(.....)

How can i make the print funktion print:
hi 3
ho 2

and skip he because it is only 1 time in the csv. I also want to print the highest value first (most common).

A:

I think using pandas.DataFrame.groupby() is an over-kill in this specific use case. Try pandas.Series.value_counts() like this.
>>> values_counts = df.value1.value_counts()
>>> print(values_counts[values_counts >= 2])
hi    3
ho    2


Q:

Java 'do while' loop not working

I have this code:
import java.util.*;

public class Vormpjes {

    public static void main(String[] args){
        String vorm;
        String nogmaals;
        double diameter;
        double basis;
        double hoogte;

        Scanner keyboard = new Scanner(System.in);

        do {
            System.out.println("Kies uit de 'cirkel', 'driehoek' of 'vierhoek':");
            vorm = keyboard.nextLine();

            if (vorm.equals("cirkel")){
                System.out.println("Geef een diameter op (in cm)");
                diameter = keyboard.nextDouble();

                cirkel C1 = new cirkel();
                C1.setDiam(diameter);
                System.out.println("De diameter = " + C1.getDiam() + " cm");
                System.out.println("De straal = " + C1.getRadius() + " cm");
                System.out.println("De oppervlakte van de cirkel = " + C1.berekenOpp() + " cm2");
                System.out.println("");
            }

            if (vorm.equals("driehoek")){
                System.out.println("Geef de basis van de driehoek (in cm)");
                basis = keyboard.nextDouble();

                driehoek D1 = new driehoek();
                D1.setBasis(basis);
                System.out.println("Geef de hoogte van de driehoek (in cm)");
                hoogte = keyboard.nextDouble();
                D1.setHoogte(hoogte);
                System.out.println("De oppervlakte = " + D1.berekenOppDriehoek() + " cm2");
                System.out.println("");
            }

            System.out.println("Typ 'J' in als u het programma nogmaals wilt uitvoeren, druk anders op een andere wilekeurige toets.");
            nogmaals = keyboard.nextLine();
        }
        while (nogmaals.equalsIgnoreCase("J"));
    }
}

And the class 'cirkel' (that's how you spell circle in Dutch haha)
public class cirkel extends Vormpjes{

    public double diam;
    public double r;

    //constructor
    public cirkel(){

    }

    public double getDiam(){
        return this.diam;
    }

    public void setDiam(double diam){
        this.diam = diam;
    }

    public double getRadius(){
        r = 0.5 * getDiam();
        return this.r;
    }

    public double berekenOpp(){
        return Math.PI * r * r;
    }

    public double berekenOmtrek(){
        return 2 * Math.PI * r;
    }

}

When the program asks the user if he wants to run the program again or not, I'm unable to type anything after while condition.
Why is it not working? I don't get errors or anything...

A:

Each time you call nextDouble() the user will enter a double and press enter. This will put a double and a newline in the buffer. The double is consumed by nextDouble(), but the newline character lingers around until you call nextLine().
In your case this becomes a problem, because when you ask the user for a J (or something else) the "old" newline character is consumed before the user manages to enter anything.
In other words, simply change
diameter = keyboard.nextDouble();

to
diameter = keyboard.nextDouble();
keyboard.nextLine();

to consume the newline character that was entered after the double.


Q:

An uncountable subset in $\Bbb{R}^n$ in which each $n$ elemented subset is a base

Using Zorn's Lemma I can show that there is an uncountable subset in $\Bbb{R}^n$ such that any $n$-elemented subset is independent. Can you construct such a set ??

A:

$$\{\,(1,t,\ldots,t^{n-1})\mid t\in\mathbb R\,\}$$


Q:

why is absolute element width limited by inline-block parent

I have the following setup:

div {
    position: relative;
    display: inline-block;
}

div div {
    position: absolute;
    top: 100%;
    background: green;
}

a {
   width: 25px;
   float: left;
}

    some

      1
      2

My question is why the div that contains a elements collapses on parent div width? I'd expect a elements to stay in one line but they wrapped. Is it expected behavior? How can I work around it?

A:

I'd expect a elements to stay in one line but they wrapped. Is it expected behavior?

Yes. they're floated left, but the parent is absolute positioned so constrained from the document floats. Has no width set so the inner elements align to the available space (0) even being left-floated.
a elements are inline elements by default.
First of all you'll have to remove float from your anchors, set them rather to be inline-block. Still they're vertically positioned, to fix that set white-space: nowrap; to the parent.

div{
    display: inline-block;
    position: relative;
}

div div {
    position: absolute;
    top: 100%;
    background: green;
    white-space: nowrap; /* needed! for inner inline elements */
}

a {
   width: 25px;
   display:inline-block; /* needed just for the 25px width! (otherw. remove) */
}

    some

      1
      2


Q:

tshark extract fields with their string representation

I have a tshark's pcap file with data that I want to analyze. I would like to analyze it and export to CSV or xls file. In the tshark documentation I can see that I can either use -z option with proper arguments or -T together with -E and -e. I'm using python 3.6 on Debian machine. Currently, my command looks like this:
command="tshark -q -o tcp.relative_sequence_numbers:false -o tcp.analyze_sequence_numbers:false " \
              "-o tcp.track_bytes_in_flight:false -Q -l -z diameter,avp,272,Session-Id,Origin-Host," \
              "Origin-Realm,Destination-Realm,Auth-Application-Id,Service-Context-Id,CC-Request-Type,CC-Request-Number," \
              "Subscription-Id,CC-Session-Failover,Destination-Host,User-Name,Origin-State-Id," \
              "Multiple-Services-Credit-Control,Requested-Service-Unit,Used-Service-Unit,SN-Total-Used-Service-Unit," \
              "SN-Remaining-Service-Unit,Service-Identifier,Rating-Group,User-Equipment-Info,Service-Information," \
              "Route-Record,Credit-Control-Failure-Handling -r {}".format(args.input_file)

Later I'm processing it with pandas dataframe like so:
# loops adding TCP and/or UDP ports to scan traffic from
    if args.tcp:
        for port in args.tcp:
            command += " -d tcp.port=={},diameter".format(port)

    if args.udp:
        for port in args.udp:
            command += " -d udp.port=={},diameter".format(port)

    # calling subprocess with output redirection to task variable
    task = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

    # a loop adding new data dictionaries to data_list
    for line in task.stdout:
        line = re.sub(r"'", "", line.decode("utf-8")) # firstly, decode byte string and get rid of '
        # secondly, split string every whitespace or = and obtain dictionary-like list of keys, values
        line = re.split(r"\s|=", line)

        # convert obtained list to ordered dictionary to preserve column order
        # transform list to dictionary so that each i item is dictionary key and i+1 item is it's value
        dict = OrderedDict(line[i:i+2] for i in range(0, len(line)-2, 2))
        data_list.append(dict)

    # remove last 4 dictionaries (last 4 lines of task.stdout)
    data_list = data_list[:-4]
    df = pd.DataFrame(data_list).fillna("-") # create data frame from list of dicts and fill each NaN with "-"
    df.to_excel("{}.xls".format(args.output_file), index=False)
    print("Please remember that 'frame' column may not correspond to row index!")

When I open output file I can see that it works ok, except the fact that in e.g. CC-Request-Number I have numeric values instead of string representation, that is e.g. in Wireshark I have data like this:

and in the output excel file in the CC-Request-Number column I can see 3 in the row corresponding to this packet, instead of TERMINATION-REQUEST.
My question is: how can I translate this number to its string representation, while using -z option, or (as I can guess from what I've seen on the web) how can I get fields mentioned above with their values using -T and -e command? I listed all available fields with tshark -G but there are too many of them and I can't think of any reasonable way to find the ones that I want.

A:

Thanks to John Zwick's suggestion, this answer and Python documentation on The ElementTree XML API I implemented code presented below (I downloaded dictionary.xml and chargecontrol.xml from official Wireshark Github repository):
chargecontrol_tree = ET.parse("chargecontrol.xml")
dictionary_tree = ET.parse("dictionary.xml")
chargecontrol_root = chargecontrol_tree.getroot()
dictionary_root = dictionary_tree.getroot()

# list that will contain data dictionaries
data_list = []

# base command
command = "tshark -q -o tcp.relative_sequence_numbers:false -o tcp.analyze_sequence_numbers:false " \
          "-o tcp.track_bytes_in_flight:false -Q -l -z diameter,avp,272,Session-Id,Origin-Host," \
          "Origin-Realm,Destination-Realm,Auth-Application-Id,Service-Context-Id,CC-Request-Type,CC-Request-Number," \
          "Subscription-Id-Data,Subscription-Id-Type,CC-Session-Failover,Destination-Host,User-Name,Origin-State-Id," \
          "Requested-Service-Unit,Used-Service-Unit,SN-Total-Used-Service-Unit," \
          "SN-Remaining-Service-Unit,Service-Identifier,Rating-Group,User-Equipment-Info,Service-Information," \
          "Route-Record,Credit-Control-Failure-Handling -r {}".format(args.input_file)

# loops adding tcp and/or udp ports to scan traffic from
if args.tcp:
    for port in args.tcp:
        command += " -d tcp.port=={},diameter".format(port)

if args.udp:
    for port in args.udp:
        command += " -d udp.port=={},diameter".format(port)

# calling subprocess with output redirection to task variable
task = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

# a loop adding new data dictionaries to data_list
for line in task.stdout:
    line = re.sub(r"'", "", line.decode("utf-8")) # firstly, decode byte string and get rid of '
    # secondly, split string every whitespace or = and obtain dictionary-like list of keys, values
    line = re.split(r"\s|=", line)

    # convert obtained list to ordered dictionary to preserve column order
    # transform list to dictionary so that each i item is dictionary key and i+1 item is it's value
    dict = OrderedDict(line[i:i+2] for i in range(0, len(line)-2, 2))
    data_list.append(dict)

# remove last 4 dictionaries (last 4 lines of task.stdout)
data_list = data_list[:-4]
df = pd.DataFrame(data_list).fillna("-") # create data frame from list of dicts and fill each NaN with "-"

# values taken from official wireshark repository
# https://github.com/boundary/wireshark/blob/master/diameter/dictionary.xml
# https://github.com/wireshark/wireshark/blob/2832f4e97d77324b4e46aac40dae0ce898ae559d/diameter/chargecontrol.xml
df["Auth-Application-Id"] = df["Auth-Application-Id"].map({node.attrib["code"]:node.attrib["name"] for node in
      dictionary_root.findall(".//*[@name='Auth-Application-Id']/enum")})

# list of columns that values of have to be substituted
for col in ["CC-Request-Type", "CC-Session-Failover", "Credit-Control-Failure-Handling", "Subscription-Id-Type"]:
    df[col] = df[col].map({node.attrib["code"]: node.attrib["name"] for node in
          chargecontrol_root.findall((".//*[@name='{}']/enum").format(col))})

df.to_excel("{}.xls".format(args.output_file), index=False)
print("Please remember that 'frame' column may not correspond to row index!")


Q:

"Bootstrap could not be loaded" when deploying to Windows CE 7

I am trying to debug a c# application on a Motorola WT41N0 which runs Windows Compact Embedded 7 from Visual Studio 2008. When I press F5 to run the program, once visual studio tries to deploy to the device I get the following error: "The bootstrap could not be loaded."
I have previously run the program successfully on a Motorola WT4090 which runs Windows CE 5.
Does anyone know how I can fix this problem?

A:

Have you installed the Motorola driver for the new device?  I had the same issue until I installed 41x0c70BenPS010007.exe, which is their devices platform SDK.  This will install a new device in Visual Studio.
In the Visual Studio menu go to Tools->Options->Devices Tools->Devices and you should now have a WT41N0c70PSDK ARM7 Device.  If you don't have that then I don't think you can get the boot strap to load.
I did not have to set it as the default VS device or anything it just needs to be there and VS will figure out the rest.
Follow up for Question
From this link: https://support.symbol.com/support/supportcentral/supportcentral.do?id=m1
Click login,  it is on the right hand side (You have to have an account or create an account to download it)
On the next screen after login set the filter for: Product Line:Mobile Computers, Product:WT41N0, Document Type:Software Downloads, then hit “GO”.  The first result should be the “OS Updated Image and the PSDK.”  Follow the link to download it and then finally click “Request Download” near the bottom of the page.  They want a serial number of a device to continue.
You will want to read this before you go any further also.
https://docs.symbol.com/ReleaseNotes/PSDK_for_WT41N0_Readme_1_0_0.htm#Components


Q:

Is there something more efficient than joining tables in MySQL?

I have a table with entity-attribute-value structure. As an example, as entities I can have different countries. I can have the following attributes: "located in", "has border with", "capital".
Then I want to find all those countries which are "located in Asia" and "has border with Russia". The straightforward way to do that is to join the table with itself using entities are the column for joining and then to use where.
However, if I have 20 rows where Russia in in the entity-column, than in the joint table I will have 20*20=400 rows with Russia as the entity. And it is so for every country. So, the joint table going to be huge.
Will it be not more efficient to use the original table to extract all countries which are located in Asia, then to extract all countries which have border with Russia and then to use those elements which are in both sets of countries?

A:

You shouldn't end up having a huge number of records so this should work
SELECT  a.entity,
    a.located_in,
    a.border
FROM    my_table a
WHERE   a.border in (SELECT b.entity FROM my_table b WHERE b.entity = 'RUSSIA' )
AND     a.located_in = 'ASIA'


Q:

Trying to check if information written in a text file is equal to a variable within shell script

I'm still a newbie to Linux scripting. My goal is to determine if the information written in a .txt file is equal to a variable within the script. This is the code that I have written so far:
#!/bin/sh

a=-5

if [$(cat < top.txt) -eq $a ]; then
    echo "YES!"
else
    echo "NNOOO!"
fi

Please let me know what I should be doing. To reiterate, I want top.txt to equal -5. I currently have -5 written in the text but can't seem to get it to work.

A:

Use More Quotes™:
[ "$(cat top.txt)" = "$a" ]

However, beware that this doesn't handle the case where top.txt ends with a newline - $() will chop that right off. So you might be better served with this:
[ "$(cat top.txt; printf x)" = "$a"x ]

Another issue is that you can't check files containing the NUL character this way; variables can not contain NUL characters.
At this point I'd be tempted to ask what you are trying to achieve.


Q:

Write program which only accepts certain letters in java (exception handling)

I'm trying to create a program in Java that writes a line of characters, but only certain characters which in this case is "a" or "b". How would I do this?
Right now it writes "ababbbabbaab", but if it writes "oohmtkgfgk" for example, it needs to throw an exception.
public class Writer {
    public void writer() {
        try {
            FileWriter writer = new FileWriter("FSA.txt", true);
            writer.write("ababbbabbaab");
            writer.close();
        } catch (IOException e) {
            System.out.println("Error");
        }
    }
}

A:

Use regex ^[ab]*$ to validate the string instead of splitting and iterating. Saves lines of code. This regex validates whether the text contains only characters inside [], in your case a&b.
public static void main(String[] args) {

     try {
            FileWriter writer = new FileWriter("FSA.txt", true);
            String str = "ababbbabbaabc";
            validate(str);
            writer.write(str);
            writer.close();
        } catch (IOException e) {
            System.out.println("Error");
        }
}

private static void validate(String string) throws IOException {
    if(!string.matches("^[ab]*$"))
      throw new IOException();
}


Q:

Exchange 2010 Database Dismounted, Corrupted

Had a serious power surge combined with an outage.
When all came back online, I had several I.T. issues. The big one was our Exchange database dismounted. Using Exchange 2010 SP3, RU4.
I ran the eseutil /mh command and found it was a dirty shutdown.
Then I ran eseutil /p to repair the database.
Database repair completed successfully.
I then ran a chkdisk /R on the server itself (but not within eseutil - should I?).
Database still would not mount, so I moved all the logs to another folder. Then the database mounted.
Next, the Transport Service would not stay started. To fix this I renamed the SenderReputation folder, restarted the Transport Service, and it worked.
Now - many issues. In my e-mail I lost all my inbox items,  another user is getting sending errors "Event ID 10030" MSExchangeIS Mailbox Store "mismatch was detected between a view of the folder and the actual contents." Still other users are having odd issues here and there.
My diagnosis is that my database shell is corrupt and I need to create a new one. What do you guys think?
If you think this is what I need to do, I'd appreciate any reliable links on how this is best done.
Thanks everyone!

A:

Check if your .edb files are not locked by your local antivirus (btw that can also be the cause of the corruption)
I found also move the file to a different hardrive in case the corruption is hardware related.
You look here: http://forums.msexchange.org/m_1800600673/mpage_1/key_/tm.htm#1800600673


Q:

Oracle - complexer case statement in where-clause

In Oracle I need to set the where-clause of MYDATE depended on the month of the current year.
If month is equal or greater than April, then restrict MYDATE to the current year (01.01.YEAR - 31.12.YEAR)
ELSE restrict MYDATE to every date older then the current time.
I'd need a pure SQL solution, not PL/SQL if possible. I tried to adapt what I found in the net and at stackoverflow.com, but the syntax is wrong:
SELECT text, mydate
FROM mytable
WHERE
CASE
    WHEN to_number(TO_CHAR(sysdate, 'MM')) >= 4 -- if month of current year >= april
        THEN mydate >=TRUNC(LAST_DAY(SYSDATE), 'YYYY') --beginning of current year
        AND mydate  < TRUNC(LAST_DAY(SYSDATE)+1, 'YYYY') -- end of current year
    ELSE -- if month of current year < april
        mydate < sysdate;

Could anyone help me out here?
Thank you very much in advance.

A:

You don't need a CASE. Just AND / OR in the WHERE will do.
SELECT text, mydate
FROM mytable
WHERE
   (     to_number(TO_CHAR(sysdate, 'MM')) >= 4 -- if month of current year >= april
     AND mydate >=TRUNC(LAST_DAY(SYSDATE), 'YYYY') --beginning of current year
     AND mydate < TRUNC(LAST_DAY(SYSDATE)+1, 'YYYY') -- end of current year
   ) OR (
         to_number(TO_CHAR(sysdate, 'MM')) < 4
    AND  mydate < sysdate)
   );


Q:

How to remove words from one word to another word in string

Let's say the string is "i don't want to see these words."
How can I remove the words between "don't" and "words", so that the string will be "i don't words"
Assume I don't know the words between "don't" and "words".
Thanks.

A:

I'd probably do something like this. Find the index of the start word, then the end word, then pull anything not between them.
string sentence = "i don't want to see these words";
string startWord = "don't";
string endWord = "words";

int startIndex = sentence.IndexOf(startWord) + startWord.Length;
int endIndex = sentence.IndexOf(endWord);

return sentence.Remove(startIndex) + " " + sentence.Substring(endIndex);

This approach, of course, has some caveats, like that you'll want to decide whether to use IndexOf or LastIndexOf, because those could mean different things. But you should be able to work out which you'd like relatively easily. It's also case-sensitive, so be aware of that. Not to mention, "don't" obviously won't match with "do not" or even "dont," so make sure you're handling whatever cases you need to in order to make it actually work. Also, this isn't strictly whole words, so include terminators if you need.
I also assume there to be a space between them, but that may or may not be the case. You could probably figure out pretty easily what it should actually be.


Q:

Not able to checkout code from git

I am trying to fetch source code from a repository but when I run command to fetch the source code I get an error which says "error pathspec did not match any files known to git".
Following is the sequence of command that i run to fetch source code.
$ git remote add origin git@....
$ git fetch
$ git checkout test

A:

Git tries to resolve git checkout test like this:

If there is a local branch named "test", then checkout that
If there is a remote branch named "test", for example origin/test, then create a local branch from it and checkout (equivalent to git checkout -b test origin/test
If there is a file or directory named "test", then checkout that, which will undo uncommitted (but unstaged) changes to that file/directory

If none of the above match, then Git gives the error:

error: pathspec 'test' did not match any file(s) known to git.

I'm not sure what you were trying to do here. If you wanted to checkout the "test" branch, it seems it doesn't exist. Check what branches you have with git branch -a. If you wanted to checkout a file/dir, it doesn't exist. Check what files you have with git ls-files.


Q:

SSL SMTP mail on Windows Apache and PHP via Wordpress not working

I cannot seem to send an SMTP email (tried multiple plugins as I know the PHP Mail() is severely limited) via my wordpress UNLESS I send using a NON-SSL SMTP connection like GoDaddy supports. I have tried using Google Apps AND Amazon's AWS SES email service, and it always fails with a message similar to "could not connect to SMTP". I have tried the same SMTP configurations on third party email apps (as well as one that I built myself) and they work, so I do not believe it to be a simple case of using the incorrect SMTP info.
My WAMP setup was NOT a prebuilt kit, but instead combined & configured from the individual components.
I believe there may be a configuration setting that needs to be changed when using a Windows based Apache/PHP setup from scratch in order to send SMTP mail. Again, I would suspect it was simply due to a wordpress plugin problem, but after trying at least 4-5 different plugins, I am starting to believe it to be within the configuration settings.
System current is running:
Windows 2008 R2
Apache 2.4.6 (x64 using VC11)
PHP 5.5.3 (ThreadSafe - x64 using VC11)
Wordpress 3.8.3

I am willing to find and paste in any settings or info that may be helpful in deciphering this problem.
Thanks in advance for any help or suggestions!

A:

It seems that as almost every smtp email plugin in WP used PHPMailer....and since those plugins worked when sending unencrpyted SMTP transactions for emails, the problem was that in the PHP.ini file, the OpenSSL module was commented out. So I removed the comment, saved the PHP.ini, and restarted the Apache service for good measure and it worked.
I mistakenly though all OpenSSL support was enabled, but it turns out I only had the Apache OpenSSL module enabled...and using cURL in PHP must not rely on OpenSSL...as that was communicating with HTTPS sites.
For reference, the PHP.INI module was listed as: extension=php_openssl.dll


Q:

incorrect synatax near '>'

select (round(
   (isnull(sum(OD1.AfterDiscount),0)
    + isnull((select sum(td.freight) from K_FS_GenerateDcno TD where TD.Name =32),0)
    - isnull((select sum(recamount) from   K_FS_AmountReceived AR where  AR.Name=32),0)
   )>500000,0))
from  K_FS_OrderDetails OD
left outer join K_FS_OrderDetails1 OD1 on OD1.ID=OD.sno
left outer  join K_FS_DistributorDetails DD on DD.sno = OD.customername
where OD.confirmation='True' and OD.customername=32

I am getting an error at > 500000 condition...
please help me

A:

Try this instead:
        Select    a.*
        From (
             select round(
             (
                 isnull(sum(OD1.AfterDiscount),0)+
                  isnull((select sum(td.freight) from K_FS_GenerateDcno TD where TD.Name =32),0)  -
                  isnull((select sum(recamount) from   K_FS_AmountReceived AR where AR.Name=32),0)
            ),0)   as RoundedAmount
            from  K_FS_OrderDetails OD
            left outer join K_FS_OrderDetails1 OD1 on OD1.ID=OD.sno
            left outer  join K_FS_DistributorDetails DD on DD.sno = OD.customername
            where OD.confirmation='True' and OD.customername=32
        )   as a
        Where RoundedAmount > 500000

This will evaluate RoundedAmount after the calculations..


Q:

Setting up a double integral over a rectangle

I want to compute $\int \int _{R}6x^2y \, dx \, dy$ where $R$ is the rectangle $ [1,2] \times [3,4]$. My difficulty comes from the fact that I don't understand what the rectangle means. I graphed the area such that $1 \le x \le 3$ and $2 \le y \le 4$ and computed the integral $\int_1^3 \int_2^4 6x^2y \,dx \,dy$ but the answer is wrong and bigger.

A:

$$\int_{x=1}^2 \int_{y=3}^4 6x^2y \,dx \,dy = \int_{x=1}^2 21x^2 dx = 7[2^3 - 1^3] = 49.$$


Q:

Problema con collapse en bootstrap

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>

Uno

Dos

Uno

Dos

Logro hacer que al pasar el mouse se active pero me muestra los dos juntos
/---------------------------------/
estoy tratando de hacer un submenu usando collapse. Es algo asi:
Uno

Dos

Uno

Dos

El problema es que si doy click en el uno, abre normalmente, pero si doy click en el dos se cierra el uno y no abre el dos al menos que haga click otra vez. Se entiende? Espero me ayuden. Gracias

A:

Ahora si ahi queda la solucion a tu problema

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>

  Toggle first element
  <button class="btn btn-primary btn-collapse" type="button" data-toggle="collapse" data-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.


Q:

Allow flagging of upvoted comments

Currently, Stack Exchange doesn't allow flagging of comments you've upvoted.
For most flag reasons (for example, spam), you shouldn't upvote them in the first place, but it's reasonable for an upvoted comment to be obsolete, which is one of the flag reasons.
I'd rather not use the "Flag question" option, because that may get the wrong comment deleted.

A:

This was fixed network-wide a few weeks ago.  You can now flag comments you've upvoted, so you should be able to flag my comment above as obsolete now :-)
The Meta Stack Exchange question Allow flagging a comment after upvoting it appears to now be marked status-completed, so I'll do the same here.


Q:

Jersey client gives me different result than other client.

I am working on a Geometry Dash API for Java. I am using WireShark to find out how should some requests look like and then try to do some requests using this, then I write a some java code doing the request and parsing the response. But there's a request, that works inside the restlet client:
So I am getting:
1:TheRealC05:2:42854106:13:77:17:52:10:17:11:12:3:1051:46:1467:4:23:8:0:18:1:19:0:50:0:20::21:129:22:51:23:30:24:32:25:1:26:18:28:1:43:14:48:1:30:0:16:7450834:31:0:44::45::49:0:29:1

But doesn't work with Jersey client:
final Form form = new Form();
form.param("secret", getSecret());
form.param("gameVersion", "21");
form.param("binaryVersion", "34");
form.param("targetAccountID", "7450834");
final String text = this.httpClient.target(getDatabase()
        .path("/getGJUserInfo20.php")).request()
        .buildPost(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE))
        .invoke(String.class);

Here I am getting -1.
So what is the difference between those two requests?

A:

The problem is, that I was extending path to the database, so the method got wrong database url.


Q:

"Raw" string in Haskell for Regular Expression

I appear to be having trouble creating a regular expression in Haskell, what I'm trying to do is convert this string (which matches a URL in a piece of text)
\b(((\S+)?)(@|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b

Into a regular expression, the trouble is I keep getting this error in ghci
Prelude Text.RegExp> let a = fromString "\b(((\S+)?)(@|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b"

<interactive>:1:27:
    lexical error in string/character literal at character 'S'

I'm guessing it's failing because Haskell doesn't understand \S as an escape code. Are there any ways to get around this?
In Scala you can surround a string with 3 double quotes, I was wondering if you could achieve something similar in Haskell?
Any help would be appreciated.

A:

Every backslash in your string has to be written as a double backslash inside the double quotes.  So
"\\b(((\\S+)?)(@|mailto\\:|(news|(ht|f)tp(s?))\\://)\\S+)\\b"

A more general remark: you'd be better off writing a proper parser rather than using regular expressions.  Regular expressions rarely do exactly the right thing.

A:

Haskell doesn't support raw strings out of the box, however, in GHC it's very easy to implement them using quasiquotation:
r :: QuasiQuoter
r = QuasiQuoter {
    quoteExp  = return . LitE . StringL
    ...
}

Usage:
ghci> :set -XQuasiQuotes
ghci> let s = [r|\b(((\S+)?)(@|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b|]
ghci> s
"\\b(((\\S+)?)(@|mailto\\:|(news|(ht|f)tp(s?))\\://)\\S+)\\b"

I've released a slightly more expanded and documented version of this code as the raw-strings-qq library on Hackage.


Q:

Java: Distingushing between end of one message and end of the stream

I'm writing a small program writing to the command line, using SSH, and therefore usually getting output after some input.
So now I'm reading that output like this:
    new Thread() {
        public void run() {
            int character;
            try {
                while ((character = output.read()) != -1) {
                    string += character;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();

So far, I'm controlling the end of the stream. However, I would like to be able to estimate the end of one message (which doesn't have to be just one line) by which I mean the remote output to the sent input, respectively.
Is there a possibility to do this?
For instance, when I login via SSH, I send the command "ssh user@server", and now that reading thread should only read the "user@server's password:" message and then free the object's lock so that the writing stream can go on. But I don't know how to do that...

A:

There is no such thing as a message in TCP. It is a byte-stream. If you want messages, you have to define and implement them yourself. In some simple cases, a line is a message. As you've said that isn't the case here, it is up to you to define.


Q:

iphone 3g jailbreak: from 4.2.1 to 4.3.x. Is it possible?

Is it possible to jailbreak to 4.3.x a jailbreaked iphone 3g 4.2.1 (with a foreign locked sim)?

A:

No. 4.2.1 was the last version of iOS supported by the 3G.


Q:

Order by rating, then by time created

I've made a simple service where you can post rows and other people can rate them.
I want it to be ordered by rating, as it is now, and then ordered by time created. This would result in ratings above 0 at the top. First of these will be the latest.
My SQL ends like this:
ORDER BY d.rating DESC,
d.created DESC

...But it does not give me the wanted result. What am I missing?

A:

You would use:
ORDER BY d.rating, d.created DESC


Q:

Android: How to keep App Locale work independently from System Locale?

I have an issues related to display language. I am able to change the language inside the application ("en" for English and "ja" for Japanese) independently from OS system.
However, the problem is that when the application is in "ja" if users change the System language manually (not "en" or "ja") than my application auto-change the language to default ("en"). I want to make locale of my application stand alone, whatever language users change manually, the language of application still remain the same as when they log out.
EDIT
There are some useful links but they still cannot solve my problem. For example:
Change language programatically in Android
Could you give my any suggestion to do it?
Thank you in advance!

A:

Try this one:
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;

public void setLocale(String lang) {
    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, AndroidLocalize.class);
    startActivity(refresh);
    finish();
}

ADDED:
@Override
public void onConfigurationChanged(Configuration newConfig) {
    newConfig.setLocale(yourLocale);
    super.onConfigurationChanged(newConfig);
}

ADDED(2):
You have to set android:configChanges="layoutDirection|locale" in order to trigger onConfigurationChanged() when you change Locale.
I cannot fully understand why this happens, maybe there are some RTL languages...


Q:

linking error for libs in VC++

In my project exist two sub project.
main project is shopGUI
other ones are 'connection' and 'log'
I build at first a log.lib file from log project
then add it to connection project and build connection.lib
then I try use connection in main project(shopGUI) but I have linking error.
error said that in
connection.lib(Client.obj) : error LNK2019: unresolved external symbol "public: void __thiscall log::print....."
thanks herzl

A:

Libraries don't link in dependent libraries.
You'll need to link your ShopGui with both sub project libraries.


Q:

SQL Query with Aggregate function on Left Join of One-to-Many Relationship

I have a one-to-many relationship where each user has many tasks, which are rated by difficulty. I want to query for a list showing each user once along with their most difficult task.
users table: user_id, username
tasks table: user_id, task_id, taskname, difficulty
I've tried a query like
SELECT u.user_id, u.username, t.task_id, t.taskname, MAX(t.difficulty)
FROM users u
LEFT JOIN tasks t ON u.user_id = t.user_id
GROUP BY u.user_id

However, I get the not in GROUP BY clause error when running this.

A:

Assuming one user doesn't have two tasks with the same max difficulty, you can do something like this.  Although, this isn't very performant.  It will work fine on a small dataset, but should be redesigned if your dataset is very large at all.  Hopefully it will get you pointed in the right direction.
declare @users table (user_id int, username varchar(10))
declare @tasks table (task_id int, user_id int, taskname varchar(24), difficulty int)

insert into @users values
(1, 'John'),
(2, 'Sally'),
(3, 'Sam')

insert into @tasks values
(1, 1, 'prepare grocery list', 1),
(2, 1, 'do shopping', 2),
(3, 1, 'cook food', 3),
(4, 2, 'do shopping', 2),
(5, 2, 'prepare grocery list', 1),
(6, 3, 'cook food', 3)

select u.user_id, u.username, t.task_id, t.taskname, t.difficulty
from   @users u
       left join @tasks t on u.user_id = t.user_id
where  t.difficulty = (
         select max(x.difficulty)
         from   @tasks x
         where  t.user_id = x.user_id
       )

This will be more performant:
select u.user_id, u.username, t.task_id, t.taskname, t.difficulty
from   @users u
       left join @tasks t on u.user_id = t.user_id
       inner join (
         select x.user_id, max(x.difficulty) as max_difficulty
         from   @tasks x
         group by x.user_id
       ) as y on t.user_id = y.user_id and t.difficulty = y.max_difficulty

Both of these queries return the following dataset:
user_id     username   task_id     taskname                 difficulty
----------- ---------- ----------- ------------------------ -----------
1           John       3           cook food                3
2           Sally      4           do shopping              2
3           Sam        6           cook food                3

If a user has two max tasks with the same difficulty, then the query will include two rows for that user.
Although, showing the query plan for this SQL says the 2nd query costs almost double what the 1st query costs.  Having max() in the where clause seems to take be more efficient than placing the max() in the from clause.  I would try it both ways on your real data, and see what the query plan/cost is for you.


Q:

Tchau é usado fora do Brasil?

Tenho trabalhado com colegas italianos que utilizam o Ciao. Fiquei curioso e procurei a origem dessa palavra em Português.
Vi aqui que ela teve origem no Brasil por conta da imigração italiana e sua grafia aportuguesada “tchau” surgiu em 1925 no dicionário Houaiss. Pesquisei um pouco e vi alguns comentários que em algumas regiões de Portugal é usado também.
"Tchau" é realmente é usado em Portugal ou é uma palavra do Português do Brasil?

A:

Sim, tchau é muito comum em Portugal. Já a vi escrita tchau, txau, chau, xau e até mesmo ciao, à italiana. Como é uma palavra muito mais falada do que escrita, e muito informal, imagino que na hora de escrever, cada um escreve como lhe dá na telha. Tchau e chau são as formas dicionarizadas, quer no Dicionário da Academia das Ciências de Lisboa (2001), quer no Priberam e Infopédia.


Q:

jdbcTemplate.update freezes

I'm using a Spring JdbcTemplate without a "transactionManager" since I have mostly select to do.
When I try to call select queries from JUnit, it works, but when I try to call an "update", it freezes the test (no connection timeout, nothing, just waiting).
I've seen examples of jdbcTemplates insert/update without any transactionManager, but could it be the problem here ?
  public void insert(String param1, String param2) {

    String sql = "UPDATE MYTABLE SET name = :param1 where first_name = :param2";

    NamedParameterJdbcTemplate npJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
    SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("param1", param1).addValue("param2", param2);

    npJdbcTemplate.update(sql, namedParameters);
  }

A:

The problem here was I had passed the same update query on the same line in a SQL client (Oracle SQL developer) but it had not been committed in this client.
My JUnit had been stalled for 12 hours and right after I commit the query in SQL developer, the update occurred in the JUnit.
It had nothing to do with transaction management in the app or autocommit status of the datasource.


Q:

C++ vector not inserting

I have the following
std::vector<Cube> well = vector<Cube>();
createCube(well, x, y, z, id);

Later I try to insert a Cube into the vector like this,
void Viewer::createCube(std::vector<Cube> vec, int x, int y, int z, int id) {
    float rgb[] = {0.0f, 0.0f, 1.0f};
    vec.push_back(Cube(QMatrix4x4(), -1));
    int loc = vec.size() - 1;
    std::cout << "loc:" << loc << std::endl;
    vec.at(vec.size() - 1).matrix.translate(x,y,z);
}

I get output loc = 0.
Why is it not the new Cube to my Vector?

A:

You are passing the vector by value to the createCube function; that means that your vector is copied and then the element is added to the new vector and not to the original one. You can fix it by changing your method signature to:
void Viewer::createCube(std::vector<Cube>& vec, int x, int y, int z, int id)


Q:

Why does TSA security vary so much for different airports?

I would assume TSA (Transportation Security Administration) security to be especially tight no matter the airport, but it seems that the different airports I have been to have often very different policies.
For example, I went to OAK (Oakland International), but security was very very lax. For example, shoes stayed on the entire time, electronics did not need to be taken out of the backpacks, belts and wallets did not need to come out. No full body scanners were in place, only metal detectors and the usual bag screening.
However, IAD (Washington Dulles) and SFO (San Franciso International) were much more stringent, requiring full body scanners, shoes and metal objects going in containers, etc.
Is there a reason that these security protocols vary so widely in different airports?
To note, I flew domestic on each flight. This "data" was composed out of 3 trips leaving from OAK, then flying back.  Security protocols remained the same flying

A:

There are 67,000 people in the TSA, and an increasing number of airports that opt for privatized security companies to do the job instead, so some variance will be inevitable.  In your particular case, it sounds like either you've been going through the TSA Precheck line at OAK, or they're confused/lazy/running a quiet trial and applying the Precheck rules to all passengers:

TSA Precheck allows passengers who have been pre-approved to keep on
  their shoes and belt, not remove their jackets, keep their laptops
  inside their cases, and not have to remove select liquids and gels
  from their bags.

Full-body scanners are not mandatory and are in fact being removed now from all airports because (shh) they didn't work.

A:

In a word, money.  And to some extent, people.
Everything costs. Some airports have had scares in the past and will allocate more money to TSA procedures.  Some changes, like the Global Entry Pass, have improved some things and will cost additional money.
Let's say the TSA has decided some new fancy scanner is the latest and greatest bomb detector.  Can every airport afford to buy it? Even if the city or government pays for it (I'm not sure who does), people have to be trained to use it. And some of that technology is pretty modern - no longer are we checking people's bags for water bottles, it's now determining whether power packs for charging cellphones might or might not be potentially explosive batteries.  When SSD harddrives became mainstream, iyt required more training as staff had been told to look for moving parts in laptops' harddrives, and now there aren't any.
There's also limits in staff numbers - they all cost. So at certain times at certain airports you're far more likely to be selected for gunpowder residue screening. Why? The guy's job is to check a person, and when that's done, look up and pick the next person. At peak times, 50 people may have walked past him in that time. He can't check them all.  However at quieter times, or in a smaller airport, the traffic of passengers is lower and he can check a greater percentage.
Same applies with drug/fruit-sniffing dogs. They get tired, require training, and can only be on the floor for a given period of time and check a limited number of bags.
So in a few words perhaps: money, time, and people.


Q:

How can I perform this cumulative sum in MATLAB?

I want to calculate a cumulative sum of the values in column 2 of dat.txt below for each string of ones in column 1. The desired output is shown as dat2.txt:
dat.txt  dat2.txt
1 20     1 20  20   % 20 + 0
1 22     1 22  42   % 20 + 22
1 20     1 20  62   % 42 + 20
0 11     0 11  11
0 12     0 12  12
1 99     1 99  99   % 99 + 0
1 20     1 20  119  % 20 + 99
1 50     1 50  169  % 50 + 119

Here's my initial attempt:
fid=fopen('dat.txt');
A  =textscan(fid,'%f%f');
in =cell2mat(A);
fclose(fid);

i = find(in(2:end,1) == 1 & in(1:end-1,1)==1)+1;
out = in;
cumulative =in;
cumulative(i,2)=cumulative (i-1,2)+ cumulative(i,2);

fid = fopen('dat2.txt','wt');
format short g;
fprintf(fid,'%g\t%g\t%g\n',[out cumulative(:)]');
fclose(fid);

A:

Not completely vectorized solution (it loops through the segments of sequential 1s), but should be faster. It's doing only 2 loops for your data. Uses MATLAB's CUMSUM function.
istart = find(diff([0; d(:,1)])==1); %# start indices of sequential 1s
iend = find(diff([d(:,1); 0])==-1); %# end indices of sequential 1s

dcum = d(:,2);
for ind = 1:numel(istart)
    dcum(istart(ind):iend(ind)) = cumsum(dcum(istart(ind):iend(ind)));
end

dlmwrite('dat2.txt',[d dcum],'\t') %# write the tab-delimited file

A:

Here's a completely vectorized (albeit somewhat confusing-looking) solution that uses the functions CUMSUM and DIFF along with logical indexing to produce the results you want:
>> data = [1 20;...  %# Initial data
           1 22;...
           1 20;...
           0 11;...
           0 12;...
           1 99;...
           1 20;...
           1 50];
>> data(:,3) = cumsum(data(:,2));       %# Add a third column containing the
                                        %#   cumulative sum of column 2
>> index = (diff([0; data(:,1)]) > 0);  %# Find a logical index showing where
                                        %#   continuous groups of ones start
>> offset = cumsum(index.*(data(:,3)-data(:,2)));  %# An adjustment required to
                                                   %#   zero the cumulative sum
                                                   %#   at the start of a group
                                                   %#   of ones
>> data(:,3) = data(:,3)-offset;        %# Apply the offset adjustment
>> index = (data(:,1) == 0);            %# Find a logical index showing where
                                        %#   the first column is zero
>> data(index,3) = data(index,2)        %# For each zero in column 1 set the
                                        %#   value in column 3 to be equal to
data =                                  %#   the value in column 2

     1    20    20
     1    22    42
     1    20    62
     0    11    11
     0    12    12
     1    99    99
     1    20   119
     1    50   169


Q:

OpenCV finding corners of contours

I am completely new to OpenCV. For practice I decided to do a "Sudoku Solver". So far I was able to do this :
public Mat processImage(final Mat originalImage, final CvCameraViewFrame frame) {
    image = originalImage.clone();
    image = frame.gray();

    /*
      We load the image in grayscale mode. We don't want to bother with the colour information,
      so just skip it. Next, we create a blank image of the same size. This image will hold
      the actual outer box of puzzle.
     */
    Mat outerBox = new Mat(image.size(), CV_8UC1);

    /*
      Blur the image a little. This smooths out the noise a bit and makes extracting the grid
      lines easier.
     */
    GaussianBlur(image, image, new Size(11, 11), 0);

    /*
      With the noise smoothed out, we can now threshold the image. The image can have varying
      illumination levels, so a good choice for a thresholding algorithm would be an adaptive
      threshold. It calculates a threshold level several small windows in the image.
      This threshold level is calculated using the mean level in the window. So it keeps things
      illumination independent.

      It calculates a mean over a 5x5 window and subtracts 2 from the mean.
      This is the threshold level for every pixel.
     */
    adaptiveThreshold(image, outerBox, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 2);

    /*
      Since we're interested in the borders, and they are black, we invert the image outerBox.
      Then, the borders of the puzzles are white (along with other noise).
     */
    bitwise_not(outerBox, outerBox);

    /*
      This thresholding operation can disconnect certain connected parts (like lines).
      So dilating the image once will fill up any small "cracks" that might have crept in.
     */
    Mat kernel = new Mat(3,3, outerBox.type()) {
        {
            put(0,0,0);
            put(0,1,1);
            put(0,2,0);

            put(1,0,1);
            put(1,1,1);
            put(1,2,1);

            put(2,0,0);
            put(2,1,1);
            put(2,2,0);
        }
    };
    dilate(outerBox, outerBox, kernel);

    final List<MatOfPoint> contours = new ArrayList<>();
    findContours(outerBox, contours, new Mat(outerBox.size(), outerBox.type()), CV_SHAPE_RECT, CHAIN_APPROX_SIMPLE);

    final Integer biggestPolygonIndex = getBiggestPolygonIndex(contours);

    if (biggestPolygonIndex != null) {
        setGreenFrame(contours, biggestPolygonIndex, originalImage);
        return originalImage;
    }

     return outerBox;
}

It ends up looking like this

So everything inside green area would be my puzzle. My question is how to extract it and do some digit recognition on it.
So in my mind first logical step would be to cut this area. But I have no idea how can I get it. So how can I get the corners of green contours ?
Any help/hint is welcome.

A:

After some tries I was able to solve it
    final List<MatOfPoint> contours = new ArrayList<>();
    findContours(outerBox, contours, new Mat(outerBox.size(), outerBox.type()), CV_SHAPE_RECT, CHAIN_APPROX_SIMPLE);

    final Integer biggestPolygonIndex = getBiggestPolygonIndex(contours);
    if (biggestPolygonIndex != null) {
        final MatOfPoint biggest = contours.get(biggestPolygonIndex);
        List<Point> corners = getCornersFromPoints(biggest.toList());
        System.out.println("corner size " + corners.size());
        for (Point corner : corners) {
            drawMarker(originalImage, corner, new Scalar(0,191,255), 0, 20, 3);
        }

        setGreenFrame(contours, biggestPolygonIndex, originalImage);
    }

private List<Point> getCornersFromPoints(final List<Point> points) {
    double minX = 0;
    double minY = 0;
    double maxX = 0;
    double maxY = 0;

    for (Point point : points) {
        double x = point.x;
        double y = point.y;

        if (minX == 0 || x < minX) {
            minX = x;
        }
        if (minY == 0 || y < minY) {
            minY = y;
        }
        if (maxX == 0 || x > maxX) {
            maxX = x;
        }
        if (maxY == 0 || y > maxY) {
            maxY = y;
        }
    }

    List<Point> corners = new ArrayList<>(4);
    corners.add(new Point(minX, minY));
    corners.add(new Point(minX, maxY));
    corners.add(new Point(maxX, minY));
    corners.add(new Point(maxX, maxY));

    return corners;
}

private Integer getBiggestPolygonIndex(final List<MatOfPoint> contours) {
    double maxVal = 0;
    Integer maxValIdx = null;
    for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
        double contourArea = contourArea(contours.get(contourIdx));
        if (maxVal < contourArea) {
            maxVal = contourArea;
            maxValIdx = contourIdx;
        }
    }

    return maxValIdx;
}

private void setGreenFrame(final List<MatOfPoint> contours,
                           final int biggestPolygonIndex,
                           Mat originalImage) {
    drawContours(originalImage, contours, biggestPolygonIndex, new Scalar(124,252,0), 3);
}


Q:

Is there a NOT (window).scroll function in jQuery?

I'm trying to set up a function that stops working when the user scrolls, is there an oposite to the function below?
 $(window).scroll(function() {
     //while user is not scrolling do this
 });

Here's the function I want to stop working when the user scrolls as I have multiple instances of this using data rows, the problem I'm having is when one tooltip starts loading and the user scrolls over several more by accident or chance, the page jumps to the last one to load.
This function is in an on page load:
var targets = $( '[rel~=tooltip]' ),
        target  = false,
        tooltip = false,
        title   = false;
targets.bind( 'mouseenter', function()
{
    target  = $( this );
    tip     = target.attr( 'title' );
    tooltip = $( '

' );

    if( !tip || tip == '' )
        return false;

    target.removeAttr( 'title' );
    tooltip.css( 'opacity', 0 )
           .html( tip )
           .appendTo( 'body' );

    var init_tooltip = function()
    {
        if( $( window ).width() < tooltip.outerWidth() * 1.5 )
            tooltip.css( 'max-width', $( window ).width() / 2 );
        else
            tooltip.css( 'max-width', 500 );

        var pos_left = target.offset().left + ( target.outerWidth() / 2 ) - ( tooltip.outerWidth() / 2 ),
            pos_top  = target.offset().top - tooltip.outerHeight() - 20;

        if( pos_left < 0 )
        {
            pos_left = target.offset().left + target.outerWidth() / 2 - 20;
            tooltip.addClass( 'left' );
        }
        else
            tooltip.removeClass( 'left' );

        if( pos_left + tooltip.outerWidth() > $( window ).width() )
        {
            pos_left = target.offset().left - tooltip.outerWidth() + target.outerWidth() / 2 + 20;
            tooltip.addClass( 'right' );
        }
        else
            tooltip.removeClass( 'right' );

        if( pos_top < 0 )
        {
            var pos_top  = target.offset().top + target.outerHeight();
            tooltip.addClass( 'top' );
        }
        else
            tooltip.removeClass( 'top' );

        tooltip.css( { left: pos_left, top: pos_top } )
               .animate( {opacity: 1 }, 50 );
    };

    init_tooltip();
    $( window ).resize( init_tooltip );

    var remove_tooltip = function()
    {
        tooltip.animate( { opacity: 0 }, 50, function()
        {
            $( this ).remove();
        });

        target.attr( 'title', tip );
    };

    target.bind( 'mouseleave', remove_tooltip );
    tooltip.bind( 'click', remove_tooltip );
});

$('.propAvailable').hover(function(){

    if ($(this).attr("title") == "") {
        $(this).siblings("a.TypesOfProperties").click();
    }
});

A:

targets.on( 'mouseenter', doStuff);

function doStuff() {
    target  = $( this );
    tip     = target.attr( 'title' );
    tooltip = $( '

' );
    ......etc
}

var timer;

$(window).on('scroll', function() {
    clearTimeout(timer);
    targets.off( 'mouseenter', doStuff);
    timer = setTimeout(function() {
        targets.on( 'mouseenter', doStuff);
    },300);
});


Q:

Determining best angle of rotation to fit a rectangle inside a rectangle

I have two rectangles, inner shown in red and outer shown in blue. I'm trying to find the smallest angle to fit the inner box into the outer box, so that the red inner rect is rotated to the orientation of the green rect:

At first I made the center line of the inner box colinear to the outer box's diagonal:
$inner_\theta=atan2(outer_w,outer_l)$
But, this proved incorrect because the inner rect needs to be slightly off from colinear to fit correctly if the outer rect is not square.
I've noticed for an outer rect with a 1.5:1 aspect ratio, it appears that subtracting $atan2(inner_w/2,inner_l)$ lines things up correctly as in the above image, but I'm not sure a) if this is correct or b) why, and this also doesn't hold for other aspect ratios.
What is a correct solution to find $inner_\theta$?

A:

If $(l,b),(L,B)$ are length and breadth dimensions of small and big rectangles respectively , then resolving components along $(x,y)$ axes
$$ l \cos \theta + b \sin \theta = L $$
$$ l\sin \theta + b \cos \theta = B $$
Using the first equation the rotation of inner strip can be solved
$$\theta_{best-fit}= \cos^{-1}\frac{L}{\sqrt{l^2+b^2}}+ \tan^{-1}\frac{b}{l}$$
EDIT1:
The second equation could as well be used to yield same result as the two equations are coupled.
Restrictions $ l> L,\, b<B $ should be followed.


Q:

Equivalence of definitions of $H^1_0(\Omega)$

I would like to prove that the following definitions of $H^1_0(\Omega)$ are equivalent. In what follows $\Omega$ is supposed to be a bounded domain with smooth boundary.
$$1) \qquad H^1_0(\Omega) = \overline{C_0^{\infty}}^{\|\cdot\|_{H^1}}$$
$$2) \qquad H_0^1(\Omega) = \{u \in H^1(\Omega)\ :\ u_{|_{\partial \Omega}} = 0 \}$$
In the second definition $u_{|_{\partial \Omega}} = 0$ means that $Tu = 0$, where $T$ is the trace operator.
Can anyone help me?

A:

Let
$$ A = \overline{C_0^{\infty}}^{\|\cdot\|_{H^1}}$$
and
$$B = \{u \in H^1(\Omega)\ :\ u_{|_{\partial \Omega}} = 0 \}.$$
We also know $H^1(\Omega) = \overline{C^\infty}^{\|\cdot\|_{H^1}}$. Then, $A \subset B$ is apparent, since $\varphi|_{\partial\Omega} = 0$ for all $\varphi \in C_0^\infty(\Omega)$ and since the trace operator is continuous.
For $B \subset A$ let $v \in B$ be given. Then, there is a $\varphi \in C^\infty(\Omega)$ with $\|v - \varphi\|_{H^1} \le \varepsilon$. Finally, you can take a smooth cut-off function $\psi \in C_0^\infty(\Omega)$, such that $\| v - \varphi\,\psi\|_{H^1} \le 2 \, \varepsilon$.


Q:

How can I add buttons to Jquery UI dialog?

I'm using Jquery UI dialog box and I want to add a button. Can I use .html() as the function in the dialog?
$(".selector").dialog({
    buttons: [{
      text: "Ok",
      click: function () {
        $(this).dialog("close");
    },
    {
        text: "View Details",
        click: function () {
            $(this).html('Some HTML');
        }
    }]
});

A:

Use the option method to change the dialog's buttons on the fly. First use it with one argument to get the old buttons, modify that array, then use it with two arguments to change the buttons.
$( ".selector" ).dialog({
    buttons: [
        {
            text: "Ok",

            click: function() {
                $( this ).dialog( "close" );
            }
        },
        {
            text: "View Details",
            click:function(){
                var buttons = $(this).dialog("option", "buttons");
                buttons.push({
                    text: "New button",
                    click: function() {
                        alert("New button clicked");
                    }
                });
                $( this ).dialog("option", "buttons", buttons);
            }
        }
    ]
});


Q:

Express and Jade: getting a variable into JavaScript

I have the following issue: on the server side I am creating a graph. I would like to display this graph using the Sigma.js library. For reference, the generated data looks for example like this:
{ nodes:
    [ { id: '423ed89a-491d-416b-9c19-13fcb6db45bc',
        label: 'Nevens Jens',
        x: 0.5935997352935374,
        y: 0.36792555125430226,
        size: 5,
        color: '#fff' } ],
  edges: [] }

In my Express app, I use the following code to render a Jade-page:
app.get('/network', function (req, res) {
    //Function calls to generate graph
    function someCallback(data) {
        res.render('graph', {graphData: data});
    }
}

Next, in my Jade file, I would like to assign this data to a variable so I can use it in a JavaScript file:
script(src='/javascripts/vendor/sigma.min.js')
script.
    var graphData = '#{graphData}'
script(src='/javascripts/graph.js')

My JavaScript file looks like this:
$(document).ready(function () {

    console.log(graphData.nodes);
    console.log(graphData.edges);
    var s = new sigma({
        graph: graphData,
        renderer: {
            container: document.getElementById('graph-container'),
            type: 'canvas'
    }});
    s.refresh();

});

The problem is, when I look at the console in the browser, it shows undefined twice.
Is this a correct way of transferring data to a JavaScript file? Am I doing anything else wrong?

A:

You're outputting the data object as a String so you're probably seeing something like
var data = '[Object object]' in you outputted html.
Doing something like this in your jade template should fix this issue:
script.
  var graphData = !{graphData}

Let me know that this helps!
Edit:  Update with Adrian's comments


Q:

What workaround to pass an instance variable to the super constructor?

Ok, so this is not allowed:
public class ServiceError extends RuntimeException {

    private final UUID uuid = UUID.randomUUID();

    public ServiceError(...) {
        super("{" + uuid.toString() + "} " + ...); // error on reference to uuid
    }

But how can I do what I want? There is no Exception.setMessage, so I can't change the message after the super constructor has been completed, I need to pass the UUID in the constructor.

A:

I would do this:
public class ServiceError extends RuntimeException {

    private final UUID uuid;

    public ServiceError() {
        this(UUID.randomUUID());
    }

    private ServiceError(UUID uuid) {
        super("{" + uuid.toString() + "} " + ...);
        this.uuid = uuid;
    }
}

Basically this is just a matter of changing where the UUID.randomUUID() call is made, and using a constructor parameter both to construct the superconstructor argument and to save the value to the field afterwards.

A:

It sounds like you might want to override getMessage() in your class to return the message that makes sense for your exception class.
As an example, here is what ActivationException.getMessage() looks like in my JDK:
public String getMessage() {
    if (detail == null)
        return super.getMessage();
    else
        return super.getMessage() +
            "; nested exception is: \n\t" +
            detail.toString();
}


Q:

Tensorflow 2.0 and image processing

I'm just converting some code to tensorflow v2, but i'm facing an issue.
I used to use some tf.contrib.image functions in tensorflow v1 (dense_image_warp and rotate). I don't know how to replace them in v2.
Those functions are not part of the tf.image module.
The tf_upgrade_v2 script can't convert those methods.
Does someone know how to replace them to be v2 compatible ?
Thank you

A:

Many of the image processing functions that were historically housed in tf.contrib have been migrated to other locations in TensorFlow 2.0. dense_image_warp and rotate are now part of the tfa.image module in TensorFlow Addons.


Q:

setTimeout inside iframe load event doesn't seem to wait x seconds as expected

I want to trigger doSomething() only after a few seconds after an iframe is loaded but instead it triggers doSomething immediately why ?
    <html>
    <iframe id="myIframe"  src="myFrame.html" width=100% height=600></iframe>
    <script>
    iframe = document.getElementById("myIframe");

    function doSomething() {
      alert("it should have wait 5000 milliseconds, instead it triggers immediately");
    }

    if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
      var oldonreadystatechange = iframe.onreadystatechange;
      iframe.onreadystatechange = function(){
        if (iframe.readyState == "complete"){
          if (oldonreadystatechange != null) {
            oldonreadystatechange();
            setTimeout(doSomething(),5000);
          }
        }
      };
    } else {
      var oldonload = iframe.onload;
      iframe.onload = function(){
        if (oldonload != null) {
          oldonload();
        }
        setTimeout(doSomething(),5000);
      };
    }

    </script>
    </html>

A:

If you want to also pass parameters, one very simple way is to create a new anonymous function for setTimeout like this:
setTimeout(function(){ doSomething(123, anotherParam) }, 5000);

That's because in JavaScript if you pass function to another function as a parameter like this someFunction(anotherFunction()); you are passing the result of the execution of that function to someFunction.
What you want to do is give the reference of that function to setTimeout so that setTimeout decides when to run it.
Do this:
setTimeout(doSomething, 5000);


Q:

Can I remove the 3.13 kernel series from Kubuntu 14.04 LTS?

Some time ago, I installed the 4.4 kernel series in the form of the HWE option for Kubuntu 14.04 LTS.  I did this mainly because the 4.4 series kernel is a little faster than the 3.13 series.  Now, however, I'm still getting updates to both kernel versions, and occasionally, if they don't arrive on the same day, my reboot after the kernel upgrade will start the machine in the 3.13 series kernel.
Is it safe to uninstall the 3.13 kernel series package(s) from Kubuntu 14.04, in order to keep only the 4.4 series?  Is there something special I need to do to prevent this causing problems?

A:

Yes, you can remove the kernel packages (image and headers) with the 3.13 version. It is quite safe.
Meta packages linux-image-generic and linux-headers-generic will also be removed.
You already have other meta packages (linux-generic-lts-xenial, etc) to update the 4.4 kernels.


Q:

The origin of Tolkien's use of the term "hobbit"

In a footnote on page 29 of The Lay of Aotrou & Itroun Verlyn Flieger notes

the word korigans appears in the 1891 compendium of folklore known as The Denham Tracts (Vol. II, p. 79) where it is in the same word-list as the first recorded use of the word hobbits, another term which Tolkien put to good use in his own work.

However, in the Letters, Tolkien says

the etymology [of hobbit]: 'Invented by J.R.R. Tolkien'

(this in letter 316, to the editor of the Oxford English Dictionary)
And in letter 25 says

I have no waking recollection [...] of any Hobbit bogey in print by 1904

and that

hobbit-names [are] from Obvious Sources proper to their kind

Is this an issue of the origin of the term versus the origin of the creature, or is something else at play here? How did the term 'hobbit' originate, and how did the idea of the 'halfling' originate, especially with respect to Tolkien?

A:

There are two questions here: the origin of the idea of the ‘halfling’, and the origin of the word ‘hobbit’. The former seems to be adequately explained by European folklore, which describes dwarfs, elves, fairies, goblins, brownies, kobolds, leprechauns, and other kinds of small magical people. So I will concentrate on the latter.
Tolkien described the origin of the word in a letter to W. H. Auden:

All I remember about the start of The Hobbit is sitting correcting School Certificate papers in the everlasting weariness of that annual task forced on impecunious academics with children. On a blank leaf I scrawled: ‘In a hole in the ground there lived a hobbit.’ I did not and do not know why. I did nothing about it, for a long time, and for some years I got no further than the production of Thror’s Map. But it became The Hobbit in the early 1930s
J. R. R. Tolkien (1955). Letter to W. H. Auden. Number 163 in Humphrey Carpenter, ed. (1981). The Letters of J. R. R. Tolkien. London: George Allen & Unwin.

His biographer Humphrey Carpenter quoted another version of the story but (following his usual slipshod practice) without reference:

It was on a summer’s day, and he was sitting by the window in the study at Northmoor Road [in Oxford], laboriously marking School Certificate exam papers. Years later he recalled: ‘One of the candidates had mercifully left one of the pages with no writing on it (which is the best thing that can possibly happen to an examiner) and I wrote on it: “In a hole in the ground there lived a hobbit”. Names always generate a story in my mind. Eventually I thought I’d better find out what hobbits were like. But that’s only the beginning.’
Humphrey Carpenter (1977). Tolkien: A Biography, p. 172. Boston: Houghton Mifflin.

This must have been fairly soon after Tolkien took up his post as Professor of Anglo-Saxon at Pembroke College, Oxford, in 1925.
How are we to reconcile Tolkien’s version of events with the appearance of the word in the list of supernatural beings in the tracts of folklorist Michael Denham?

[…] pigmies, chittifaces, nixies, Jinny-burnt-tails, dudmen, hell-hounds, dopple-gangers, boggleboes, bogies, redmen, portunes, grants, hobbits, hobgoblins, brown-men, cowies, dunnies, wirrikows, alholdes, mannikins, follets, korreds, lubberkins, cluricauns, kobolds, leprechauns, kors, mares, korreds, puckles, korigans, sylvans, succubuses, black-men, shadows, banshees, lian-hanshees, clabbernappers, Gabriel-hounds, mawkins, doubles, corpse lights or candles, scrats, mahounds, trows, gnomes, sprites, fates, fiends, sybils, nick-nevins, whitewomen, fairies, thrummy-caps […]
James Hardy, ed. (1895). The Denham Tracts: A Collection of Folklore by Michael Aislabie Denham, volume II, p. 79. London: David Nutt.

There seem to be two possibilities: either Tolkien had in fact read the word in Denham (or some other source yet undiscovered) but had forgotten that he had done so; or the two occurrences of the word are independent inventions. The problem with the first of these possibilities is that Denham’s tracts are obscure:

Denham was an amateur folklorist who published many books and pamphlets, including twenty Minor Tracts on Folklore (1849–c. 1854). The majority of these Tracts were collected in an edition prepared for the Folklore Society in the 1890s, and the word hobbit appears in the second volume (1895) of this edition.
Peter Gilliver, Jeremy Marshall & Edmund Weiner (2006). The Ring of Words: Tolkien and the Oxford English Dictionary, p. 146. Oxford University Press.

In the absence of any evidence that Tolkien read Denham’s work, Gilliver et al. have to resort to speculation about how he might have done so:

The 1895 version would have been readily available in university libraries accessible to Tolkien (there is a copy in Oxford), and he was interested in folklore. Alternatively, he could have seen a list copied out by one of his friends or colleagues.
Gilliver et al., p. 148.

There is the tantalizing possibility of another source for the word. A letter to the Observer soon after the publication of The Hobbit in 1937, asked about the origins of the name:

Sir,—Dr. Julian Huxley, in one of his recent lectures, referred to the “little furry men” seen in Africa by natives and, although dimly in moonlight, by at least one scientist.
What I should like to know is whether these creatures provided the inspiration for Professor Tolkien’s attractive hobbit, the newest visitor to so many of our nurseries this Christmas. Naturally, I always read my children’s book before giving them to them, and I noticed that all the characters in the hobbit were nearly all drawn from real animal life or from real mythology. Few of them appeared to be invented.
On mentioning the hairy-footed hobbit, rather like a rabbit, to one of my contemporaries, I was amazed to see her shudder. She said she remembered an old fairy tale called “The Hobbit” in a collection read about 1904. This creature, she said, was definitely frightening, unlike Professor Tolkien’s. Would the Professor be persuaded to tell us some more about the name and inception of the intriguing hero of his book? It would save so many research students so very much trouble in the generations to come. And, by the way, is the hobbit's stealing of the dragon's cup based on the cup-stealing episode in Beowulf? I hope so, since one of the book's charms appears to be its Spenserian harmonising of the brilliant threads of so many branches of epic, mythology, and Victorian fairy literature. Yours, etc. ‘Habit’
‘Habit’ (16 January 1938). Letter to The Observer.

Tolkien replied, denying any knowledge of the “old fairy tale”:

I was born in Africa, and have read several books on African exploration. I have, since about 1896, read even more books of fairy-tales of the genuine kind. Both the facts produced by the Habit would appear, therefore, to be significant.
But are they? I have no waking recollection of furry pigmies (in book or moonlight); nor of any Hobbit bogey in print by 1904. I suspect that the two hobbits are accidental homophones, and am content* that they are not (it would seem) synonyms.
* Not quite. I should like, if possible, to learn more about the fairy-tale collection, c. 1904.
J. R. R. Tolkien (1938). Letter to The Observer. Number 25 in Carpenter (1981).

The “old fairy tale” has not turned up in 80 years of searching, and so it seems that ‘Habit’s friend was mistaken in her recollection, perhaps at the distance of 34 years having confused ‘The Hobbit’ with a similar-sounding title. An example of a tale that could fit the bill is ‘The Bar-gaist, or Boggart’ which was printed in John Roby’s Traditions of Lancashire (1829).
So I think it is more likely that Denham’s and Tolkien’s ‘hobbit’ are independent inventions. There is a word ‘hob’ (an abbreviation of ‘Robin’) from which they could both derive:

hob, n.1 2.a. = Robin Goodfellow or Puck; a hobgoblin, sprite, elf.
Oxford English Dictionary

This gave rise to the compounds ‘hobgoblin’ (an imp or sprite; a terrifying apparition), ‘hobhouchin’ (an owl), and ‘hob-thrush’ (a goblin), so it could also have assisted with the coining of ‘hobbit’.


Q:

Why does my program ask for a symbol 2 times instead of one(ignores first symbol)?

This is simple Hangman game:
public static void main(String[] args) {
    String[] words = {"writer", "that", "program"};
    int wordNumber = (int) (Math.random() * words.length);

    System.out.print("Enter a letter in word ");
    for (int i = 0; i < words[wordNumber].length(); i++)
        System.out.print('*');
    System.out.print(" > ");

    Scanner input = new Scanner(System.in);
    char letter;
    do {
        letter = input.nextLine().charAt(0);
        boolean asterisksInWord = false;
        String[] discoveredElements = new String[words[wordNumber].length()];
        int countOfTries = 0;
        int arrayCount = 0;
        int asteriskCount = 0;
        System.out.print("Enter a letter in word ");
        do {
            asterisksInWord = false;
            boolean contain;
            if (asteriskCount != 1) {
                asteriskCount = 0;
                for (char item : words[wordNumber].toCharArray()) {
                    contain = Arrays.asList(discoveredElements).contains(String.valueOf(item));
                    if (contain) {
                        System.out.print(item);
                    } else if (item == letter) {
                        System.out.print(item);
                        discoveredElements[arrayCount] = String.valueOf(item);
                        arrayCount++;
                    } else {
                        System.out.print('*');
                        asterisksInWord = true;
                        asteriskCount++;
                    }
                }
            }
            if (asterisksInWord) {
                System.out.print(" > ");
                letter = input.nextLine().charAt(0);
                if (asteriskCount != 1)
                    System.out.print("Enter a letter in word ");
            } else
                System.out.println("The word is " + words[wordNumber] +
                    " You missed " + (countOfTries + 2 - words[wordNumber].length()) + " time(s)");
            countOfTries++;
        } while (asterisksInWord);
        System.out.print("Do you want to guess another word? Enter y or n >");
    } while (input.nextLine().charAt(0) == 'y');
}

The log of it's run is
Enter a letter in word **** > t
Enter a letter in word t**t > h
Enter a letter in word th*t > a
The word is that You missed 0 time(s)
Do you want to guess another word? Enter y or n >y
y
Enter a letter in word **** >

My question is why does it ignores first symbol 'y' when asking "Do you want to guess another word?".
I'tried to create some test programs with same do-while conditions but they don't ask for character 2 times like that program.

A:

The program asks for your input two times, because you have programmed it like that. After printing - "Do you want to guess another word? Enter y or n >" - you do input.nextLine() inside the while condition as well as as the first statement after do , so it asks for input twice.
Maybe you can move the question Enter the letter in the word to the inner do loop instead of doing that in the if condition if (asterisksInWord) { .
Also, according to your current logic, it does not ignore your first symbol, that is the real one that decides whether to exit the loop or not, the next input is actually your first guess.


Q:

How is using WSL bash in vscode through the remote WSL extension different from using it by selecting as default shell while in windows?

Before I knew about the remote WSL extension for vscode, I had been using bash in it by selecting it as the default shell from the terminal option. What is the advantage of using remote WSL if all I wanted was to just use bash as the default terminal?

A:

Hi Rohan and welcome to SO!
I'll have a shot at answering this, though someone more knowledgeable might have better insight.
When you load VSCode in windows, it accesses your various PC resources as windows resources. For example your files will be from the windows folder structure. Even if you use WSL bash as your terminal, VSCode is still acting on a windows basis.
If you use the remote WSL extension, it leverages VSCodes separation of UI and Backend by remotely starting a VSCode backend in the WSL layer, and connecting the windows UI to that backend ('remotely' although on the same PC). Due to running the backend in a linux environment, the files are loaded as linux files and handled via the WSL system, rather than normal windows access.
With regard to the question 'What is the advantage?' I would suggest the advantage is that now instead of having a split between VSCode in windows and command line in WSL, you now have both acting in harmony through WSL. It should provide some benefits (especially when WSL2 hits properly and performance increases) around things not messing in a windows manner on files you are trying to use in a linux way, and just make things feel a bit more connected.
However if you're using WSL bash just as a command line replacement and not using it for it's linux goodness (though I don't know if this would be the case), there may be less of an advantage.
It's a stepping stone to switching to devcontainers, which are really neat.
This page might help more, but that's my understanding! https://code.visualstudio.com/docs/remote/wsl


Q:

Pressure-temperature dependence of a pure substance

Saturation temperature is defined as the temperature at which a pure substance say water, changes phase, at a fixed pressure. So water boils at 100⁰C , if the external pressure is kept constant at 101.3 kPa(1atm). At 12.35 kPa  water boils at 50°C, which indicates that there is a pressure-temperature dependence at saturation points, but is this p-t dependence driven by pressure only? i.e can we keep the pressure fixed at 1atm and still boil water at a temperature other than 100°C, by increasing the heat supply and hence increasing temperature.
Also, is this pressure-temperature dependence a consequence of the gibbs-phase rule.

A:

I guess you cannot increase the fluid temperature while keep the pressure constant when it is boiling. The temperature is fixed once the pressure is fixed determined by the fluid vapor pressure curve. Practically, it is more feasible, as you said, to adjust pressure. For example in a high pressure cook, the weight is used to adjust pressure and thus the cooking (boiling) temperature is increased.