General Topology: the inverse of a constant function

Question: We have always been taught that a function assigns to every element in the domain a single unique element in the range. If a rule of assignment assigns to one element in the domain more than one element in the range then it isn't a function.
Now in Munkres' Topology, on page 107, it says:
"If $f:X \rightarrow Y$ maps all of $X$ into the single point $y_0$ of $Y$, then $f$ is continuous."
But we cannot speak of the continuity of $f$ unless $f^{-1}$ is defined, because the topological definition of continuity (in Munkres and other textbooks) states that $f:X \rightarrow Y$ is continuous if for every open subset $V$ of $Y$, the set $f^{-1}(V)$ is open in $X$.
How then can the constant function above be continuous when $f^{-1}$ maps a single $y_0$ to ALL $x \in X$? How is it a function? Or is the elementary definition of "function" relaxed in topology?
Comment: The $f^{-1}$ in that definition is not the compositional inverse of $f$, but the function $f^{-1}:P(Y)\to P(X)$ defined by $f^{-1}(A)=\{x\in X:\ f(x)\in A\}$ for $A\subset Y$, where $P(X)$ denotes the set of subsets of $X$. The same symbol is used for two things, but usually one can tell which is which from the context (the nature of the argument between parentheses).
Comment: If $f:\{1,2,3\}\to \{1,2,\{1,2\}\}$ is defined by $f(1)=1$, $f(2)=2$, and $f(3)=\{1,2\}$, I don't know how to tell what is $f^{-1}(\{1,2\})$. :-p But well ... In those cases ask the writer.
Answer: $f^{-1}(U)=\{x\in X | f(x)\in U\}$, here we do not need that the function $f^{-1}$
there exist, we only use definition of the pre-image of set by $f,$ and off course
any constant function is continuous because given any pen set $U$ in $Y$
we have two possibilites, $y_0\in U$ in this case $f^{-1}(U)=X$ which is open
and if $y_0\notin U$ then $f^{-1}(U)=\emptyset$ which is open.
Answer: $f^{-1}$ denoting a function needs not to be defined.
$f^{-1}(V)$ denoting the preimage of $V$ w.r.t. $f$ needs to be defined (and is) for every set $V\subseteq Y$.
It is defined as: $$f^{-1}(V):=\{x\in X\mid f(x)\in V\}$$
If $f$ is constant then $f^{-1}(V)\in\{\varnothing, X\}\subseteq\tau_X$ for every $V\subseteq Y$ so $f$ is continuous.


Strcpy and strcat functions in C

Question: I'm using the C programming language in Visual Studio 2015, and I'm simply trying to prompt the user for three sentences of text that are then combined into one, three sentence paragraph. I just can't get my strcpy and strcat functions to work.
Thoughts??
Thank you so much in advance!
#include <string.h>
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MASTERSIZE 300

int main()
{

char *calcTotalMessage(char[100], char[100], char[100]);
#define MSIZE 100
#define MSIZEE 100
#define MSIZEEE 100

int read;
char message[MSIZE];
char m2[MSIZE];
char m3[MSIZE];
char* totalM;

printf("Enter a sentence:");

scanf_s("%s", &message);

printf("Enter another sentence:");
scanf_s("%s", &m2);

printf("Enter third sentence:");
scanf_s("%s", &m3);

totalM = calcTotalMessage(message, m2, m3);
printf(totalM);

return 0;
}

char *calcTotalMessage(char *m1, char *m2, char *m3)
{
void strcat(char, char);
void strcpy(char, char);
char *totalM = "";

strcpy(*totalM, *m1);
strcat(*totalM, *m2);
strcat(*totalM, *m3);

return totalM;

}

Comment: What goes wrong and how? Describe the problem.
Answer: char *totalM = "";

So totalM points at a string literal. Modifying literals is disallowed by the C standard. You won't necessarily get a compile time error, but your program has undefined behavior. It's unlikely to behave properly.
strcpy(*totalM, *m1);

Then you attempt to pass strcpy a char (the type of *totalM and *m1), and not a pointer. That character is converted to some nonsensical pointer value that you attempt to write at. That again results in undefined behavior. You compiler even tried to warn you, but instead of heeding those errors you added declarations for functions that don't exist (strcpy(char, char)).
I suggest you pass the output buffer into calcTotalMessage instead of returning it.
void calcTotalMessage(char const *m1, char const *m2, char const *m3, char *output) {
    output[0] = '\0';
    strcpy(output, m1);
    strcat(output, m2);
    strcat(output, m3);
}

To be called like this:
char totalM[MSIZE + MSIZEE + MSIZEEE] = {'\0'};
calcTotalMessage(message, m2, m3, totalM);

A point regarding style. You won't usually see function declarations anywhere but at file scope. So don't get too used to declaring functions inside another function scope.

Strcpy and strcat functions in C


Given a variable of double type, how to output it with 3 digits after the decimal point in C

Question: void avg(int sum, int count){

double result = sum/count;
printf("running average is %d/%d = %f\n",sum,count,result);

}

//Here function avg returns avg of sum and total no. of inputs, I need to display the output of the double result variable to 3 digits after the decimal
Answer: Just checked we can do by:
printf("%.3f",result);

Comment: But you'll always get `X.000` because you have done *integer division*. You need `double result = (double)sum / count;`


get `(UInt8.min + UInt8.max) * 3` to console

Question: With swift, when I input this code below, I could not get the sumInt number to console?
<code>    let minValue=UInt8.min
    let maxValue=UInt8.max
    let sumInt=(maxValue+minValue)*3
    println(sumInt)
</code>
after I change the code as below
<code>    let minValue=UInt8.min
    let maxValue=UInt8.max
    let sumInt:Int=(maxValue+minValue)*3
    println(sumInt)
</code>
I got an error

Could not find an overload for '*' that accepts the supplied arguments

how can I make it right?
Comment: This is like page 2 of the book, by the way.
Comment: What are you expecting the output to be? Your minValue will be 0 (minimum of unsigned int) and multiplying your maxValue by 3 will overflow (might crash, or maybe it will just wrap around, not sure). What are you trying to achieve? Try using smaller values. Also the compiler error might be because 3 is inferred to be Int type and can't multiply with UInt type (but not sure about that)
Comment: possible duplicate of [Swift: Errors when using different integer sizes](http://stackoverflow.com/questions/24048334/swift-errors-when-using-different-integer-sizes)
Answer: Its because the type you get from the sum is again a UInt8.. try
<code> let minValue=UInt8.min
    let maxValue=UInt8.max
    let sumInt:Int8=(maxValue+minValue)*3 //overflow
    println(sumInt)
</code>
Or
<code>let minValue=UInt8.min
let maxValue=UInt8.max
let sumInt:Int=(Int)(maxValue+minValue)*3
println(sumInt)
</code>
But notice that the number sumInt will now be valid because its no longer a UInt8 which goes up to only 255 and it overflows in the first code snippet.


Selenium IDE - always fail on any 500 error

Question: Is there an easy way to tell Selenium IDE that any action that results in a http 500 response means the test failed?
I have tests that are 75 page requests long.  Sometimes, I get a crash and burn somewhere in the middle, but the tests come back green.
Comment: Just be aware that these commands (from my answer) should be put in place each time a 500 error can potentially occur.. normally after a clickAndWait, this occurs.  But it can happen in many situations.
Answer: Taking a look at selenium-api.js, I saw that there is a parameter ignoreResponseCode in the signature of the doOpen method in selenium-api.js :
Selenium.prototype.doOpen = function(url, ignoreResponseCode) {

This parameter is used by the browserbot object :
if (!((self.xhrResponseCode >= 200 && self.xhrResponseCode <= 399) || self.xhrResponseCode == 0)) {
    // TODO: for IE status like: 12002, 12007, ... provide corresponding statusText messages also.
    LOG.error("XHR failed with message " + self.xhrStatusText);
    e = "XHR ERROR: URL = " + self.xhrOpenLocation + " Response_Code = " + self.xhrResponseCode + " Error_Message = " + self.xhrStatusText;
    self.abortXhr = false;
    self.isXhrSent = false;
    self.isXhrDone = false;
    self.xhrResponseCode = null;
    self.xhrStatusText = null;
    throw new SeleniumError(e);
}

I've tried calling the open function from selenium IDE with value = false and this results in an error (test failed).
My PHP test page was :
<?php
    header('HTTP/1.1 500 Simulated 500 error');
?>

And this results in :

For me, this solves the problem of checking HTTP response status.
Answer: Make a JavaScript file called "user-extensions.js" and add it to the Selenium-IDE under Options > Options.  If you are running Selenium RC, pass it into the parameter when starting up your server in the jar command.  There should be a user extensions javascript file attribute.

Then close and restart Selenium-IDE.  The User-Extensions file is cached when the IDE starts up.
Add this code to your Selenium user-extensions.js file to make a custom command called "AssertLocationPart".  As you know "assertLocation" and "storeLocation" are standard commands.  I tried to reduce the extra line of code to storeLocation just by getting the href in the custom function.  I wasn't able to get the doAssertValue command to work.  I'll have to post my own question for that.  That's why it's commented out.  For now, just use "this.doStore" instead.  And add an extra line to your script after your custom AssertLocationPart command.  Since we're not actually doing an assertion in the custom function/command, we should call it "storeLocationPart" (function would be named "doStoreLocationPart"), not "assertLocationPart" (function would be named "doAssertLocationPart"), and just pass in the first parameter.  But if you can get the doAssert* to work, please let me know.  I'll mess with it another day since I need to do this same thing for work.
Selenium.prototype.doAssertLocationPart = function(partName,assertTo) {

    var uri = selenium.browserbot.getCurrentWindow().document.location.href;
    //alert("URI = " + uri);

    var partValue = parseUri(uri,partName);
    //alert("Part '" + partName + "' = " + partValue);

    //this.doAssertValue(partValue,assertTo);
    this.doStore(partValue,"var_"+partName);
};

// Slightly modified function based on author's original:
// http://badassery.blogspot.com/2007/02/parseuri-split-urls-in-javascript.html
//
// parseUri JS v0.1, by Steven Levithan (http://badassery.blogspot.com)
// Splits any well-formed URI into the following parts (all are optional):
//
// - source (since the exec() method returns backreference 0 [i.e., the entire match] as key 0, we might as well use it)
// - protocol (scheme)
// - authority (includes both the domain and port)
//     - domain (part of the authority; can be an IP address)
//     - port (part of the authority)
// - path (includes both the directory path and filename)
//     - directoryPath (part of the path; supports directories with periods, and without a trailing backslash)
//     - fileName (part of the path)
// - query (does not include the leading question mark)
// - anchor (fragment)
//
function parseUri(sourceUri,partName){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};

    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
        if (uriPartNames[i] == partName) {
            return uri[uriPartNames[i]];  // line added by MacGyver
        }
    }

    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
        if (partName == "directoryPath") {
            return uri.directoryPath;  // line added by MacGyver
        }
    }

    return uri;
}

Then add this to your web.config file and make sure customErrors is turned off.  Since you have a 500 error, it will redirect the user to the default page.  Feel free to add a custom page for a 500 HTTP status code if you want to be specific in your Selenium scripts.
<customErrors mode="On" defaultRedirect="/ErrorHandler.aspx">
    <error statusCode="401" redirect="/AccessDenied.aspx" />
    <error statusCode="403" redirect="/AccessDenied.aspx" />
    <error statusCode="404" redirect="/PageNotFound.aspx" />
</customErrors>

This is what your commands will look like in the IDE:

Make sure you're on this page (or something similar) before running the script:
https://localhost/ErrorHandler.aspx?aspxerrorpath=/path/pathyouweretryingtoviewinwebapp.aspx

Log shows that it passed!

[info] Executing: |storeLocation | var_URI | |
[info] Executing: |echo | ${var_URI} | |
[info] echo: https://localhost/ErrorHandler.aspx?aspxerrorpath=//path/pathyouweretryingtoviewinwebapp.aspx
[info] Executing: |assertLocationPart | fileName | ErrorHandler.aspx |
[info] Executing: |assertExpression | ${var_fileName} | ErrorHandler.aspx |
Comment: you may have to still parse the URL anyway, even with that.. doesn't that get the entire "Location"/URL/href?
Comment: I just tested that and it stores the entire URL including query string parameters, so you'd have to parse it anyway... although I think they have a pattern parameter.  It would be interesting to learn how the pattern parameter works though.
Answer: Using the error handler from my previous answer:
Command: assertLocation
Target: regexp:^(https://localhost/ErrorHandler.aspx).*$

Or (per your comment) it's inverse if you don't have error handling turned on, use AssertNotLocation. This may require more work on the person writing the scripts.  You'd have to keep track of all pages.
More on pattern matching:
http://seleniumhq.org/docs/02_selenium_ide.html#matching-text-patterns
http://www.codediesel.com/testing/selenium-ide-pattern-matching/


Maximum size of a summary?

Question: Situation
I am making a website which purpose is to sum up (including all spoils) books, video games, series etc ... The goal is for people to catch up with the story if :

They didn't play the last game for instance and want to know what happened
They just forgot some details and want to be reminded

Question
As everything is based on these summaries, what is the maximum size that a user could bear to read ? It has to be complete but short enough for the user in order not to be discouraged. Is there any known study on the topic ?
Answer: This is a tricky question and the answers would definitely not give you a word count. The reason being that the user's reading habits and concentration thresholds are very erratic on the internet
If you want to find out more about this, this is a good article.
What could you do (other than keeping the word count low)?
I'd suggest breaking down the summary. Have it broken down into sections like:
Story Recap
Recaps don't have to summarize the previous game, movie or video. They need to focus on the most relevant or the most attention seeking moments.
What you need to know
This section could highlight only the parts that are carried over from the previous part to the sequel. Just the bare bone knowledge jotted down in points.
Story Synopsis
Summarize what the point of the previous story was and what was conveyed. This could be 1 to 2 paragraphs long depending upon the depth you want to go into and on how dense the story actually was.
Reviews and accolades
Let's face it, this immediately has a huge impact. Reflect the IMDb, RT, Metacritic scores for movies/TV shows with some top reviews for movies. IGN ratings for games and View count, Like count for videos and copies sold, bestseller rankings, etc for books.
Comment: Thanks for your answer. Breaking down the summary could be interesting, but I don't really get the differences between your different parts, don't they mean the same thing ?
Comment: Let me try to clarify. **Story Recap** is like a compilation of short clips (5-10 sec) of the most important scenes. **What you need to know** is like bullet points containing just the spoilers/what the user needs to know to move forward. **Story synopsis** is more detailed summary (1-2 paragraphs) of the movie/series/episode/game.

Hope this helps you distinguish between the 3
Comment: Hi thanks, I get it now. But what about "what you need to know" ? Isn't it just like story recap ?
Comment: Now that I think about it, yes. It's nearly the same thing. Sorry about that. I guess you don't need to put all these sections. Just pick the ones that are relevant and if something seems redundant, then leave it out
Comment: @Shashimee To me, I think _Story Recap_ would highlight / summarise what you would have got out of the first game if you had played it yourself, but is written "in isolation". _What you need to know_ lists the things that will help you in the next instalment. So: if the first game had a dramatic plot-twist, that was "important" to that game, but knowledge of the twist is not needed in the second game, it would go in the first category. A (seemingly) minor event from the first game, but that is needed (or at least helps) in playing the second game, might only be in the second category.
Answer: Rather than thinking about maximum length, focus on maximising engagement and readability by using appropriate headings, typography (line length, font size, line height, etc.), and producing high-quality content.
Headings
Headings for each series/game will likely vary. For example, if the series is heavily dependent on geography (think: Game of Thrones), you'd likely want a section highlighting plot points in each area.  However, there are two headings that will likely exist for all games/series: Summary and Characters.

Summary

An overview of the entire game / season
the major plot points

Characters

A list of the characters, and their major plot points in the season

As Shreyas suggested, I'd strongly recommend breaking the summary into chunks. However, chunking is just the first step. To ensure readability, you have to pay close attention to your typography.
Typography
You have to make it easy to read. Here's a great article on how people read, including recommendations for measure, font size, and line height. To summarize:
Measure (a.k.a. line length)

Aim for between 45 and 85 characters per line
65 seems to work very well

Font size

Both too big and too small create problems
Size of font will depend on the viewing device
On a desktop, use at least 16 px for body copy

Line height

The horizontal space between your lines
No perfect line height, but 150% of your font size is a good guideline

Content
In addition to the text descriptions, depending on the available resources, you might consider adding additional content.
Video summaries
Having video recaps of each game or season might be helpful. Some people prefer to watch videos than to read. With a transcription, users can search the video to search for specific information.
Visual timeline
Another thing to consider is adding a high level visual timeline of the series / show. This would require some graphic skill, but would provide a high level overview of the major plot points in the series at a glance. I'm envisioning a chart, with the x axis as time (start to finish). Each season could have a slightly different coloured background, and the major plot points (for each character, region, or whatever is appropriate for the game/series) are plotted along the Y axis. You'd have to think through this in more detail, but it would provide a quick synopsis of the plot without requiring a bunch of reading.
I think the most difficult part of your work will be to condense the material to provide a summary, but hopefully some of these ideas are helpful.
Answer: I think Shreyas answer covers everything here, and the article they posted was a good read.
I'd just like to add though, to take into account your users:
What kind of gamers are they?
If they are playing games where they usually read a lot of text, it's probably not going to be an issue. But if they are more, fast-paced action games, you'll need to take that into account, and break it up and make it more entertaining to read.
Also think about
You want to keep users on your site for as long as possible, and have them click through everything etc. get them navigating all the links. If it's a lot to read they might skip it entirely, considering they can just go and play the game instead - if that makes sense?
Answer: My researchurfing tells me people are willing to read up to 3000 words if the article contains quality in-depth content (links below).  Given that most summaries are much shorter than that, I don't think you have much to worry about as far as maximum length.
A few examples of <1000 word summaries I pulled from TV Tropes:

A 830-word summary
A 160-word summary
A 644-word summary

As far as UX goes, I second what others are saying about making your content easy to parse and navigate.
Ultimately you won't find the sweet spot for article length until you test your content on real users.  I recommend instrumenting your site and tuning based on real data once you have something working.
Research on optimal word length:
Snap Agency says:

As you can see, the ideal length of word count vs. average organic traffic is sitting pretty at 2,250-2,500 words.

Source: https://www.snapagency.com/blog/whatll-be-the-best-length-for-a-blog-article-in-2016-for-seo
Lean Labs quotes:

Medium reports the ideal length of a blog post is 7 minutes or 1,600 words.
The average American reads at about 300 words per minute.
SERPIQ reports that from an SEO perspective, the top 3 Google results are between 2,350 and 2,500 words.
Moz reports that posts between 1800 and 3000 words attract 15 times more links.
Neil Patel has found that posts of at least 1,500 words earn the best SEO, social sharing, and engagement results.

Source: https://www.lean-labs.com/blog/the-ideal-length-for-business-blog-posts-when-less-is-more

Maximum size of a summary?


R: print multiple types of plots on one page

Question: I am trying to plot multiple plots in one page. I know functions like gridExtra::grid.arrange that can plot graphs generated by ggplot2 package. The problem I am facing is that I have two plots (bar.plot and density.plot below) that are generated by ggplot2 package and one plot generated using limma::vennDiagram function. I have tried the below but it is not working:
output <- paste('summary.pdf')
pdf(output,width = 25,height = 20)
par(mfrow = c(3, 3))
plot(bar.plot)
plot(density.plot)
print(vennDiagram(dat.venn, circle.col = col,cex = c(3,3,3)))
invisible(dev.off())

dat.venn is a data of type VennCounts:
 I-H-10003-T1-D1 I-H-10003-T2-D1 I-H-10003-T3-D1 Counts
               0               0               0      0
               0               0               1     41
               0               1               0     81
               0               1               1     66
               1               0               0     10
               1               0               1      2
               1               1               0      4
               1               1               1     56
attr(,"class")
[1] "VennCounts"

I am unable to find a venn diagram package that is compatible with the grid.arrange function. I don't think that VennCounts cant be printed out with grid.arrange function and ggplot2 plots can be printed out with par function.
UPDATE:
I tried using pushViewport but it is still printing the venn diagram on the next page:
pdf(output,width = 25,height = 20)

# Create layout : nrow = 2, ncol = 2
pushViewport(viewport(layout = grid.layout(2, 2)))

# A helper function to define a region on the layout
define_region <- function(row, col){
  viewport(layout.pos.row = row, layout.pos.col = col)
}

# Arrange the plots
print(bar.plot, vp = define_region(1, 1:2))
print(density.plot, vp = define_region(2, 1))
print(vennDiagram(dat.venn, circle.col = col,cex = c(3,3,3)), vp = define_region(2, 2))
dev.off()

Any help would be much appreciated!
Comment: https://cran.r-project.org/web/packages/gridBase/vignettes/gridBase.pdf
Comment: I don't see where you use functions from the gridBase package there.
Comment: Having needed to combine a mixture of plot types (grid-based and otherwise such as Excel, plotrix, etc.) I have saved them all as. .png files, used the read.PNG function of the grid package to load them, and then converted them with the rasterGrob function.  Once all the plots are comparable in format, grid.arrange() does the trick.
Comment: @Roland See my update
Comment: The link that you gave me is a manual for gridBase. I saw there were some suggestions using `pushViewport` and I used it.
Comment: The suggestions are more specific than that.
Comment: @lawyeR Thank you very much! This worked!! Can you move your comment to an answer so I can accept it? Cheers!
Answer: First, save each of the files as .png files, such as save(yourfile, file = "yourname.png").
Second, use the read.PNG function of the grid package to load them, such as yours.png <- readPNG("yourfile.PNG")
After that, convert them with the rasterGrob function as in g1 <- rasterGrob(yours.png, interpolate=TRUE).
Once all the plots are comparable in format, grid.arrange() does the trick.  It might look like this:
grid.arrange(g1, g2, g3, nrow=1)  # one row
dev.copy(png,'threeplots.png')   # to save the array of plots
dev.off()                         # to close the device

Answer: The gridGraphics package, like gridBase, makes the mixing of grid, ggplot, lattice and base graphics fairly straightforward. The grid.echo() function converts a base graphic into a grid graphic. (The advantage of using gridGraphics is that base graphics become amenable to editing and modification via grid; see gridGraphics.pdf.)
In the following, I draw two ggplots and a venn diagram (taken for the vennDiagram help page in the limma package), and I position the three plots within viewports, making sure the venn diagram plot is subjected to the grid.echo treatment.
UPDATE to ggplot2 2.0.0  (Default stat for geom_bar is stat = "count")
  library(ggplot2)
  library(gridGraphics)
  library(grid)
  library(limma)  # From bioC software repository

  grid.newpage()

  # Position 1st ggplot
  pushViewport(viewport(y = 1, height = 1/3, just = "top"))
  gg1 <- ggplot(mtcars, aes(x = mpg)) + geom_density()
  print(gg1, newpage = FALSE)
  upViewport()

  # Position 2nd ggplot
  pushViewport(viewport(y = .5, height = 1/3, just = "centre"))
  gg2 <- ggplot(mtcars, aes(x = factor(carb, levels = 1:8))) +
          geom_bar() + scale_x_discrete(drop = FALSE)
  print(gg2, newpage = FALSE)
  upViewport()

  # Function to draw venn diagram - the venn diagram is taken from ?vennDiagram
  plotfun <- function() {
   Y <- matrix(rnorm(100*6),100,6)
   Y[1:10,3:4] <- Y[1:10,3:4]+3
   Y[1:20,5:6] <- Y[1:20,5:6]+3
   design <- cbind(1,c(0,0,1,1,0,0),c(0,0,0,0,1,1))
   fit <- eBayes(lmFit(Y,design))
   results <- decideTests(fit)
   a <- vennCounts(results)
   print(a)
   mfrow.old <- par()$mfrow
   par(mfrow=c(1,2))
   vennDiagram(a)
   vennDiagram(results,
       include=c("up", "down"),
       counts.col=c("red", "blue"),
       circle.col = c("red", "blue", "green3"))
  }

  # Position the venn diagram
  pushViewport(viewport(y = 0, height = 1/3, just = "bottom"))
  grid.echo(plotfun, newpage = FALSE)
  upViewport(0)


Find the duplicate integer number using List

Question: I do a function that find duplicate integers and store and utput number of them as they were arrays.
I Create list called "Hit" for excluding operation for repetitive number. If I once have find all dupclicates for number I do not need do it again.
But "Hit" List does not work. It gives me out of range error.
For ex: I have array int[] in_number = {1, 2, 2, 4, 5, 6, 6};
Without "Hit"
It would give me. I already do it. It works.
0
1 2
1 2
3
4
5 6
5 6

Output
With "Hit" I try to do (it does not work)
0
1 2
3
4
5 6

But I wanna (best way)
1 2
5 6

Here is code:
namespace arrow
{
    class Program
    {
        static void Main(string[] args)
        {
        int Min = 0;
        int Max = 10;
        int[] in_number = new int[100];
        Random randNum = new Random();
        for (int i = 0; i < in_number.Length; i++)
        {
            in_number[i] = randNum.Next(Min, Max);
        }
        duplicate_number_List (in_number);
        }

        static void dupnumlist (int[] in_number) // Find duplicate numbers
                {
                    List<List<int>> duplicate_pair = new List<List<int>>();
                    List<int> Hit = new List<int>();
                    for (int i = 1; i < in_number.Length; i++)
                    {
                        List<int> SubList = new List<int>();
                        foreach (int number in Hit)
                            {
                                if (number == in_number[i]) // Will match once
                                {
                                    i++; // go to next iteration; passing unnecessary
                                }
                            }

                        for (int j = 0; j < in_number.Length; j++)
                        {
                            if (in_number[j]==in_number[i])
                            {
                                SubList.Add(j);
                                Hit.Add(in_number[i]);
                            }
                        }
                        duplicate_pair.Add(SubList);
                    }

                    foreach (var sublist in duplicate_pair)
                    {
                        foreach (var value in sublist)
                        {
                        Console.Write(value);
                        Console.Write(' ');
                        }
                        Console.WriteLine();
                    }
                    foreach (var value in Hit)
                    {
                        Console.Write(value);
                        Console.Write(' ');
                    }
                    Console.WriteLine();
                }
    }
}

I don`t wanna use built-in functions
Comment: Do you need the duplicate pairs, or just any duplicates? What rule makes numbers pair up? In your example of {1, 2, 2, 4, 5, 6, 6}, 1 and 5 are not duplicate, why are they in your expected output?
Comment: OK. I need to find duplicate, not pair. I do not wanna output first number but I do.
Comment: Try this http://stackoverflow.com/questions/14363424/how-to-find-list-has-duplicate-values-in-liststring
Answer: It sounds like you're looking for something like this:
int[] in_number = {1, 2, 2, 4, 5, 6, 6};
var duplicates =
    from a in in_number.Select((value, index) => new { value, index })
    group a by a.value into g
    where g.Count() > 1
    select g.First();

The first line selects each number in the integer list as well as its index as pairs. The second line groups pairs with the same value together. The third line filters out any groups with only one member. And finally, the last line returns the first pair in each group, which will contain the value as well as the lowest index.
You can then loop through the duplicates and write them out like this:
foreach (var dup in duplicates)
{
    Console.WriteLine("{0} {1}", dup.index, dup.value);
}

Update
If you can assume that the input array is already sorted, here is a solution using only a dictionary:
var previousValue = in_number[0];
var duplicates = new Dictionary<int, int>();
for(int i = 1; i < in_number.Length; i++) // Note: starting at 1 instead of 0
{
    if (previousValue == in_number[i] && !duplicates.ContainsKey(i))
    {
        duplicates.Add(previousValue, i - 1);
    }
    previousValue = in_number[i];
}

If the input array may not be sorted, then it's a bit more difficult, but you can still do it with a pair of Dictionaries:
var first = new Dictionary<int, int>();      // Stores the first instance of each value and its index
var duplicates = new Dictionary<int, int>(); // Stores any subsequent instances with the previous index
for(int i = 0; i < in_number.Length; i++)
{
    if (!first.ContainsKey(in_number[i]))
    {
        first.Add(in_number[i], i);
    }
    else if (!duplicates.ContainsKey(in_number[i]))
    {
        duplicates.Add(in_number[i], first[in_number[i]]);
    }
}

Comment: Nice thanks. But I do not wanna use in-bult functions or LINQ now.
Comment: @user3103832 Is there a reason for that? is this homework? Also, can we assume that the list is already sorted?
Comment: I do it for me. Of course this is not best alg but all I wanna is find some simple solution.
Comment: @user3103832 What about using built-in data structures, e.g. `Dictionary` or `HashSet`? Is that allowed?
Comment: Good idea. I already thinked about this. It is next my step after **List**. Another step is array of List. But I learning. I need to practice with Dictionary and HashSet.
Answer: Why not use a HashTable class? Store the values on Key and Value property on HashTable, then if it's equal to a previous entry, do not store it at all.
Refer to this, I promise this will be the easiest way.
Comment: HashTables are basically untyped dictionaries. Using an untyped data structure when a perfectly good strongly typed one will work equally well is bad practice and is likely to end up causing more problems if overused. This is just practice for OP now, but we should not be handing out bad advice.


Triggers on change date

Question: I'm trying to create some triggers in my db.
Now I need to create a trigger that "fire" a procedure when the date have changed. It's a Db for the management of a Bank.
I need some procedure that start at a programmed date. For example, if I want to set an operation of accredit for the 24/05/2014, this procedure starts only when the current date is equal to the specified value.
I have read that there are some "scheduler" that can help me, but I don't know how to use them! (I'm using phpPgAdmin) There's something that I can do without setting some scheduled procedure? Only using a trigger?
this is my (wrong) trigger
CREATE TRIGGER programmata
    AFTER INSERT ON transazione
    FOR EACH ROW
    EXECUTE PROCEDURE trans_programmata();

and this is the (wrong) procedure "trans_programmata()"
DECLARE
   p bit := 0;
BEGIN
   IF(new.programmata = p)THEN
     PERFORM * FROM aggiorna_conto();
   ELSE
      IF new.data >= current_date THEN
          PERFORM * FROM aggiorna_conto();
      END IF;
  END IF;
  RETURN NULL;
END;

Here is the table "transazione"
CREATE TABLE transazione (
    id integer NOT NULL,
    data date NOT NULL,
    tipo bit(1) NOT NULL,
    ammontare numeric(11,2) NOT NULL,
    programmata bit(1) NOT NULL,
    descrizione character varying(50) NOT NULL,
    fk_conto integer NOT NULL,
    fk_utente character(16) NOT NULL,
    fk_categoria character varying(20) NOT NULL
);

obviously, this way the trigger only "fires" when the inserted value of "data" is equal to the current date.
Comment: Please define *exactly* when the trigger is supposed to fire.
Comment: Sorry, I don't understand your clarification!

As I wrote in the post, I specified :

"I need some procedure that start at a programmed date(a date in the future). For example, if I want to set an operation of accredit for the 24/05/2014(when the current date of today is 19/05/2014), this procedure starts only when the current date is equal to the specified value(in this case 24/05/2014, for example)."

Hope this can help!
Comment: the value 'date' in the table 'transazione' was created for this purpose.

So when the current_date is equal to the 'date' of the specified transaction, the trigger fire
Comment: Instead of "AFTER INSERT" I need something like "WHEN the value 'date' of all my row in table 'transazione' is equal to current_date FIRE the procedure 'trans_programmata' "

It's like the db has to check this table after the change of day
Answer: Triggers (or event triggers in pg 9.3+) only fire on defined data events. What you are talking about is a scheduled (time-based) event. There is nothing built into Postgres for that.
I generally use cron jobs to schedule jobs like this.
There is also pgAgent, which used to be packaged with pgAdmin. (From pgAdmin v1.9 onwards, pgAgent is shipped as a separate application.)

Triggers on change date


Reading neighbouring pixels during object draw call

Question: I need something to be cleared up for me, and I hope this is the right place to ask my question:
I intend to attempt stochastic transparency, where I will draw glass panes and smoke particles onto the g-buffer for deferred shading.
For every 2x2 cell of pixels, I will allow up to 3 of the 4 pixels to be used for glass or smoke. The last pixel is always the opaque background. But say we have this situation:

Camera
(Near clip plane)
Smoke particle
Glass pane
Solid wall
(Far clip plane)

The smoke particle is in front of the glass pane, and would occupy all 3 pixels. This I do not want, and therefore I will need to check whether neighbouring pixels in that 2x2 cell already have 'smoke' or 'glass' written to them, rather than just the simple Z-check.
I therefore wish to sample neighbouring pixels from the same g-buffer that I'm currently writing to, but this seems not possible, am I right? And why do the depth & stencil buffers seem to be exceptions to this, or does this have something to do with only reading the exact pixel you are about to write to?
I hope the way I formulated the question(s) make sense, and is sufficiently detailed.
Answer: In general you can't safely read from neighboring pixels in the render target you're currently writing to. You can sample from them, but there's no guarantees about how other pixels are scheduled on the GPU, so it's a race condition—you might get the neighboring pixel value either before or after modification, and it might change frame to frame due to unpredictable scheduling differences.
You can read from the same pixel you're about to write to, but only if your geometry is set up to ensure that nothing is overlapping in screen space (e.g. a full-screen pass). If other triangles in the same render pass are overlapping the same area on screen, then you have a race condition again, similar to the neighboring-pixels case. (You can use fragment_shader_interlock or equivalent functionality to address this case, but it is not universally supported across all GPU vendors, and it can also be slow.)
The depth and stencil buffers, as well as fixed-function blending (additive, alpha, etc) can get around this because they have special-purpose hardware that sorts the fragments in submission order in order to apply those simple fixed operations.
I believe the way stochastic transparency usually works is to randomize the set of pixels output and use spatial/temporal filtering to clean up the noise afterward. So you wouldn't have such fine-grained control like "within each 2x2 block, there will be N pixels of this, and M pixels of that". It would be more probablistic, like "on average, X% of the pixels will be this, and Y% of the pixels will be that", with the exact outputs being randomly chosen each frame.
Comment: Thank you for your answer. I guess I do not need any more than the details you have provided.
And regarding using noise for the stochastic transparency: Yes that is correct, however I have not managed to create a filter that can tidy up the image sufficiently, so I hoped I might get around that by coming up with something like the 2x2 block thing that could work.
(I will now move on to plan B: using some kind of spatial hashing function for the noise so that the sample distribution becomes more favorable for the filtering process.)


Writing code for destructor in side derived class in case of multiple inheritance with polymorphism increasing size of Derived class. Why?

Question: #include <iostream>
struct Base1
{
public:
    virtual void show()=0;
};
struct Base2
{
public:
    virtual void Display()=0;
};
class Derived:virtual public Base1,virtual public Base2
{
public:
    virtual void show(){}
    virtual void Display(){}

};
void main()
{
    using namespace std;
    cout<<sizeof(Derived);
}

output is showing 12
but when i insert destructor of Dervied class i.e. following code
#include <iostream>
struct Base1
{
public:
    virtual void show()=0;
};
struct Base2
{
public:
    virtual void Display()=0;
};
class Derived:virtual public Base1,virtual public Base2
{
public:
    virtual void show(){}
    virtual void Display(){}
        ~Derived(){}

};
void main()
{
    using namespace std;
    cout<<sizeof(Derived);
}

then it is showing 20 as output. why?
Comment: Not critical, but what compiler is that reproduced on?
Comment: @sharptooth : - whenever i am running the program it is showing same result..
Comment: i am working on visual vc++ 9.0
Answer: 1) Your base classes do not have virtual destructor.
2) main return int, not void
What you ask is implementation defined. Using g++ 4.3.0, I got the same size in both cases (8 bytes should be good result on a 32-bits PC).
EDIT
Under implementation defined, I meant it depends on how the virtual inheritance is implemented. Usually, the derived class contains pointers to base classes, but that't not necessary the case.
In the case of g++, to be able to get the address of every sub-object (pointer to a base class), the size of Derived should be 12 bytes (on a 32-bit machine), but because all classes are empty (i.e. without member variables), the compiler is free to optimize the size of empty base classes, and to reduce the size to 8 bytes (not 4 bytes, because it needs to be able to provide different address of both base classes).
Comment: If it is implementation defined, it should be documented somewhere in the gcc manual. Can you pull it out?
Comment: i have added virtual ~Base1() and virtual ~Base2() in respective class.but result is same i.e when ~Dervied() not present then 12 when i inserted then it showing 20.i am working on visual vc++ 9.0
Comment: @Chubsdad Having problems finding it in the gcc manual, but the edit explains how the inheritance is implemented in g++. The implementation should be similar for vc9, no?
Comment: @VJo:- Can u explain in terms of VC++ compiler.taking both the cases individually.
Comment: @Suri No, because I know very little about windows and VC++ compiler.
Comment: @VJo:i think you r talking about structure padding concept.but i think this concept is different from structure padding.but probably implementation of virtual concept is the reason.but how it is implemented is the question.
Comment: @Suri No. Structure padding is different. It would happen for example in this case struct A{ int a : 7; int b : 13;}; Now take a look at your example. I see no member variables.
Answer: Well, looking at the generated code, the first example has this memory layout:
| Derived::vtable |  Base1::vtable  |  Base2::vtable  |

The second has this layout:
| Derived::vtable |   00 00 00 00   |  Base1::vtable  |   00 00 00 00   |
|  Base2::vtable  |

What are the zeros I don't know. They are not padding, since padding is left uninitialized with CCCCCCCC. Maybe they are used as counters or flags when deleting the virtual subobjects and when you add the destructor these fields are added to the class. I failed in making them different from 00000000.
Anyway, you can add this to your question: Why when I make the destructor virtual then the layout becomes
| Derived::vtable |   00 00 00 00   |  Base1::vtable  |   00 00 00 00   |
|  Base2::vtable  |     padding     |

(24 bytes)?


How do I use a variable for the name of a table in a DBI query?

Question: How do I using a variable for the name of a table in a DBI query? I know how to use placeholders as part of the where clause, but how do I do this for the table name?
I would like to do something like this:
 my $table_name='table1';
 my $query = $dbh_cgi->prepare("select * from ?");
 $query->execute($table_name);

So far, I end up getting a MySQL syntax error because DBI adds quotes around the name, table1.
Answer: One of the limitations of placeholders is that they can't be used for table names.  Instead of using a placeholder, you can use a variable.  To make sure the variable's contents are safe, use quote_identifier(), for example:
my $table_name='table1'; #-- Or get this from somewhere else
my $safe_table_name =  $dbh_cgi->quote_identifier($table_name);
my $query = $dbh_cgi->prepare("select * from $safe_table_name");
$query->execute();


Why do I get an unexpected result with a ternary condition?

Question: Can anyone explain to me this result please:
(trad = {foo: "Foo", bar:"Bar"}).has_key? :foo ? trad[:foo] : :foo
=> false

I expected it to return:
=> "Foo"

Answer: (trad = {foo: "Foo", bar:"Bar"}).has_key? :foo ? trad[:foo] : :foo

is like:
(trad = {foo: "Foo", bar:"Bar"}).has_key? (:foo ? trad[:foo] : :foo)

:foo ? trad[:foo] : :foo is evaluated to "Foo" because :foo is treated as truth value.
(trad = {foo: "Foo", bar:"Bar"}).has_key? "Foo" yields false because there's no "Foo" key.

Use following (override precedence by surrounding parentheses) to get the expected result:
>> ((trad = {foo: "Foo", bar:"Bar"}).has_key? :foo) ? trad[:foo] : :foo
=> "Foo"

Hash#fetch(key, default) seems more appropriate:
>> {foo: "Foo", bar:"Bar"}.fetch(:foo, :foo)
=> "Foo"
>> {foo: "Foo", bar:"Bar"}.fetch(:baz, :baz)
=> :baz

Comment: Nice call on `Hash#fetch`.
Comment: Very clear. Thanks. (Hash#fetch is way better, thanks for that)
Answer: For want of parenthesis the app was lost...
(trad = {foo: "Foo", bar:"Bar"}).has_key? :foo  ? trad[:foo] : :foo  # => false
(trad = {foo: "Foo", bar:"Bar"}).has_key?(:foo) ? trad[:foo] : :foo  # => "Foo"

I'd be careful writing code like this:
(trad = {foo: "Foo", bar:"Bar"})

It's not idiomatic, so use:
trad = {foo: "Foo", bar:"Bar"}
trad.has_key?...

The reason is, in times of panic, like at 2:45 AM when your coding partner gets a call about a system outage because he's on call, and dives into the code, that assignment could be hard to find.
In a code review I'd suggest something like this over the other:
trad = {foo: "Foo", bar:"Bar"}
trad.has_key?(:foo) ? trad[:foo]
                    : :foo        # => "Foo"

Note: This only works on Ruby 1.9+.
That all said, I'd highly recommend using fetch as recommended by @falsetru.


Not sure if fstab or driver messed up my pc

Question: total newbie here. My old XP box died last week; bought a used HP 6000 Pro with integrated VGA.  Decided to go single boot Ubuntu, had a cd made for me.  All was going well. Partitioned the disk as follows:
sda1: 32G primary swap
sda2: 32G primary / ext4
sda3: Extended
sda5: 8G logical /tmp
sda6: 28G logical /var
sda7: 100G logical /usr
sda8: 200G logical /home
sda4: 100G primary /dos

Installed standard from cd, then
sudo apt upgrade all

Then installed Synaptic, added multiverse and restricted repos, Cinnamon, gcc, g++, blender...
And there I hit a snag: blender refused to run withou a gpu. Now, I intended to buy a Radeon and a wide screen with FreeSynch, but I don't have the money yet (unemployed), so I figured why not move the videocard from the XP box.
I tried the card first, see if it would auto-detect. The card is 4.5" format; my new box is 3.5" format, so I had to bend some metal to get the card to plug in. The bios did detect it, and I changed IRQ5 from Intel VGA to Nvidia. Ubuntu was booting until user screen, then froze. So I figured it needed a driver. My old box is Dell Dimension 9200. I believe the videocard is Nvidia GT230 or GT250. Either way, the right package for the driver seemed to be 430.108, so I installed it, and all its dependencies.
When Synaptic finished I got a message that I had to fix something with resume.  I had that problem before and managed it by fixing the UUID of my swap partition, sda1;  but this time the number was correct.  I checked fstab and panicked to see the order of my partitions changed, with comments sayin they were different during installation.  I worked hard at restoring the original order of the partitions.  Maybe it's not relevant?  All the tutorials say fields are separated by a space or tab;  nobody clarifies whether multiple spaces or tabs are acceptable.  Are they?
At the end of the day, I don't think I changed anything important, but when I try to boot with the video card I get a black screen regardless if I'm booting from disk or CD.
Without the videocard I can boot from install cd;  but trying to boot from disk I see very fast text messages on the screen, the last of which I think mentions sda1, and then a black screen with a flashing cursor top left.
With the videocard in place, CTRL-ALT-F4 doesn't work for me. Tried it on two consecutive boots. The first boot I hit the 3 keys as the Ubuntu logo came on, and it showed a bit of VGA tex, then went black. Second time I booted it never got to the logo. After a millisecond flash of text it went black and the 3 keys do nothing. Now, without the videocard, the only diff the 3 keys make is going from logo directly to flashing cursor, instead of having to wait a few seconds. I noticed the heatsink on the gpu has a bit of play. I'm willing to give up on using blender. Just want it to work again
Comment: The Ubuntu version is 20.04 or something close to that;  totally up to date.  As for /var and /tmp being separate partitions it's the result of reading too many recommendations and being a perfectionist without really knowing anything, I guess.
Comment: The delimiter in *fstab* is *whitespace* which means a space, tab or any combination of the two (allowing those of us who need vertical columns to space out so we see the *order* that makes us happy). I still don't know if you're talking about server, desktop or other, and it's best if you've precise with details, 20.04 or something?  could mean a 20.04.1 *alpha*, a RC, or other *daily* which is different to a *finished* or *released* product  (these alternate images are unlikely, but it's best if we're given the specific details of your system)
Comment: 20.04 LTS, desktop was and is my intention.
Comment: I'm currently booted from the cd.  If I do a blkid,, I don't see a /dev/sda1 at all there.  I see 2, 4, 5, 6, 7 and 8, all ext4 (besides /dev/sr0 cd rom), but no swap partition.
Comment: Found my fstab, first device I have:  (can't use carriage return here):  UUID=74f4ae6a-0f0f-4e32-890e-3df252ddbc38  none  swap sw  0  0
Comment: Not sure If I'm supposed to comment or answer.  Never seen this paradigm in a bbs.
Comment: When it boots and then freezes, can you should be able to get a text only console by pressing CTRL+ALT+F4. From there, (with the graphics card plugged in) you should be able to sign in and then run `sudo apt update` and then `sudo ubuntu-drivers autoinstall` just to make sure you have the correct drivers installed. Also, you can run commands to check your disk from there as well so you don't need the CD (that is, if you can sign into the console).
Comment: With the videocard in place, CTRL-ALT-F4 doesn't work for me. Tried it on two consecutive boots.  The first boot I hit the 3 keys as the Ubuntu logo came on, and it showed a bit of VGA tex, then went black.  Second time I booted it never got to the logo. After a millisecond flash of text it went black and the 3 keys do nothing.  Now, without the videocard, the only diff the 3 keys make is going from logo directly to flashing cursor, instead of having to wait a few seconds.  I noticed the heatsink on the gpu has a bit of play.  I'm willing to give up on using blender. Just want it to work again
Comment: Welcome to Ask Ubuntu. This is a question answer site. The comments are our channel for asking for clarification. Please [edit your question](https://askubuntu.com/posts/1258356/edit) and add all the new information **inside the question**.
Comment: @DanW58 You may need to boot nomodeset to boot with the card until you get the drivers installed. [See here for instructions.](https://askubuntu.com/a/38834/167115)
Comment: Also, did you transpose the numbers? The nvidia website says you need version 340.108 but your question states 430.108.
Comment: Yes, I was writing from memory.  I was getting ready to reinstall, but I'll try your nomodeset suggestion first.
Comment: @user68186, ok, I'm used to people across the www hating when an original post is changed, as it may invalidate many replies to it;  but here the idea is to have just two posts: 1 question and 1 answer at the end of the process?  I'm not sure what to do now with the comment-dialogue.
Comment: @DanW58 Also, if you switch to CTRL+ALT+F4, you can switch back to the regular session using CTRL+ALT+F1 and CTRL+ALT+F2. Additionally, you can get a verbose output during boot by removing "quite spash" from the same line in grub that you use to insert nomodeset. Removing "quiet splash" will disable the splash screen and you should see log messages during boot and if the boot process hangs up somewhere, you will see a message telling you what it is getting stuck on.
Comment: @DanW58 Another thing is that you have to wait until after it boots up to use CTRL+ALT+F4. If you do that during the boot process, it can automatically switch you back to your regular screen after it boots so wait until after the splash screen or wait until after it gets stuck to use CTRL+ALT+F4.
Answer: Sorry guys, I just couldn't take it anymore;  I'm reinstalling.
Sad, after a full week working on this install, but I was on the verge. This graphics card goes to the trash where it belongs. I can see that upgrading hardware in linux is Hell, so blender will have to wait until I can build a better PC and fresh install a distro on it.
Comment: Thanks, good to know abou swap partitions an Lubuntu and Xubuntu.  The "reason" I put 32 gigs is I planned to upgrade memory to 16G,  which may never happen... Lubuntu and Xubuntu, I'll try them.  Thanks!
Comment: I'm set in lubuntu right now and I love it right out of the box.  Haven't even tried any themes, but I love the no-nonsense organization of the icons and menu. Using gdm3 for now;  set to try sddm after next reboot.  Thanks for the tip;  I would have missed out on a lot of goodness.  UPDATE: just tried sddm;  doesn't do it for me;  going back.
Comment: One more thing, you really don't need a 32GB swap partition. For 4GB of RAM you only need a 4GB swap partition if you plan on using hibernation. If you don't plan on hibernating, you really don't even need a swap partition as Ubuntu will use a swap file on newer versions automatically without a swap partition.
Comment: Also, on an older PC, Lubuntu, Xubuntu, or Ubuntustudio all run with less resources than the standard Ubuntu desktop and so they might run better. You can even install one or more of these desktops as a software package through synaptic or apt. Then, you can switch desktop environments on your login screen and keep your regular desktop in case you don't like it.
Comment: Also, Ubuntustudio and Ubuntustudio desktop is based on XFCE , the same as Xubuntu, except it has some bundled packages for music, graphic arts, photography, etc. The desktop is set up different but it functions the same and is lightweight like Xubuntu.


Unable to install winehq-staging, Ubuntu 16.04 64bit

Question: I have been running wine on Ubuntu 16.04, installed via sudo apt-get install wine, but I would like to switch to wine-staging.  I am attempting to follow the instructions at https://wiki.winehq.org/Ubuntu
I first uninstalled wine and made sure all packages were up to date:
sudo apt-get remove wine wine-mono wine-gecko winetricks
sudo apt-get autoremove
sudo apt-get update
sudo apt-get upgrade

I then rebooted and ran the following series of commands:
sudo dpkg --add-architecture i386
wget -nc https://dl.winehq.org/wine-builds/Release.key
sudo apt-key add Release.key
sudo apt-add-repository https://dl.winehq.org/wine-builds/ubuntu/
sudo apt-get update

However, the command to install winehq-staging fails with unmet dependency on wine-staging:
sudo apt-get install --install-recommends winehq-staging

The following packages have unmet dependencies:
 winehq-staging : Depends: wine-staging (= 2.13.0~xenial)
E: Unable to correct problems, you have held broken packages.

Installing wine-staging fails with unmet dependency on wine-staging-i386:
sudo apt-get install wine-staging

The following packages have unmet dependencies:
 wine-staging : Depends: wine-staging-i386 (= 2.13.0~xenial)
E: Unable to correct problems, you have held broken packages.

Installing wine-staging-i386 fails with various unmet dependencies on -i386 packages.  Showing a few of them (the list is much longer):
sudo apt-get install wine-staging-i386

The following packages have unmet dependencies:
 wine-staging-i386:i386 : Depends: libasound2:i386 (>= 1.0.16) but it is not installable
                          Depends: libglib2.0-0:i386 (>= 2.12.0) but it is not installable
                          Depends: libgphoto2-6:i386 (>= 2.5.9) but it is not installable
                          Depends: libgphoto2-port12:i386 (>= 2.5.9) but it is not installable

(snip)
                          Recommends: libxslt1.1:i386 (>= 1.1.25) but it is not installable
                          Recommends: libxxf86vm1:i386 but it is not installable
E: Unable to correct problems, you have held broken packages.

If I try to install the first one, it is not available:
sudo apt-get install libasound2:i386

Package libasound2:i386 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  libasound2-data

E: Package 'libasound2:i386' has no installation candidate

However, package libasound2-data is already installed and the latest version.
I'm not sure what to try next.
Answer: this is an addition to the answer of Elber CM
before execution of "$ sudo apt-get install --install-recommends winehq-staging" I needed to install the following libraries:
$ sudo apt-get install libasound2-plugins:i386
$ sudo apt-get install wine-staging-i386
$ sudo apt-get install wine-staging

and finally
$ sudo apt-get install --install-recommends winehq-staging

voila, now it works.
Comment: Thank you very much. That is a great advice - I tried to solve it for hours, pulling my hairs off, until I found your answer. It is interesting, why the `aptitude` did not see this solution - the only advice it gave me included uninstalling 90% of all packages on my system.
Answer: I managed to install wine for Ubuntu 18.04 with next steps:
# basic steps
sudo dpkg --add-architecture i386
wget -nc https://dl.winehq.org/wine-builds/winehq.key
sudo apt-key add winehq.key
sudo apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ bionic main'

# fix of the broken dependency
sudo add-apt-repository ppa:cybermax-dexter/sdl2-backport

# install winehq
sudo apt install --install-recommends winehq-staging

Found the solution here.
Comment: Perfect, thank you.  That one backport PPA was the only thing I needed to make the official instructions work.
Answer: English is not my native language so please be patient.
Apparently the solution is a little more complex, following tutorial on:
https://codereviewvideos.com/blog/wine-1-9-11-on-ubuntu-16-04/
It's necesary to install first some libraries:
sudo apt-get install gcc-multilib libasound2-dev:i386 libgsm1-dev:i386 libjpeg8-dev:i386 liblcms2-dev:i386 libldap2-dev:i386 libmpg123-dev:i386 libopenal-dev:i386 libv4l-dev:i386 libx11-dev:i386 libxinerama-dev:i386 libxml2-dev:i386 zlib1g-dev:i386

Then make a update again:
sudo apt-get update

Again some missing libraries:
sudo apt-get install libcapi20-dev:i386 libcups2:i386 libdbus-1-3:i386 libfontconfig:i386 libfreetype6:i386 libglu1-mesa:i386 libgphoto2-6:i386 libncurses5:i386 libosmesa6:i386 libsane:i386 libxcomposite1:i386 libxcursor1:i386 libxi6:i386 libxrandr2:i386 libxslt1.1:i386 ocl-icd-libopencl1:i386 libgd3:i386

Finally make the installation required:
Stable branch
sudo apt-get install --install-recommends winehq-stable

Development branch
sudo apt-get install --install-recommends winehq-devel

Staging branch
sudo apt-get install --install-recommends winehq-staging

PSDT: Some of the librares could be included, that depends of other programs that could use them and Ubuntu version.
Answer: Solved the problem by checking all checkboxes in "Software and Updates".  After that, I was able to successfully install all dependencies and wine staging via:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install --install-recommends winehq-staging

Comment: Enabling `universe` package in the "Ubuntu Software" tap of the "Software & Updates" tool did the trick for me.
Answer: I would like to also concur that
sudo add-apt-repository ppa:cybermax-dexter/sdl2-backport

fixed my broken dependency issue.
might have installed those libraries previously mentioned for nothing.


Permit only Admin users to mount Windows partition

Question: I have Ubuntu installed along with Win-7. In the Ubuntu File manager under Devices there is an entry with my computer name. Clicking that selection mounts the Windows partition.
What I'd like to accomplish:
I would like the Admin level users to be able to use the menu as described above. However, I would like to not permit Standard Users to mount the partition or even have the mount point visible on the File manager menu.
I've tried various methods described on this forum and on other internet searches that involve modifying fstab, but none gave me the results I'm looking for. What is the correct method for doing this?
Answer: Check your <code>/etc/fstab</code> file, the mounting permissions are in there, it sounds like a user like has been added for those filesystems you wish to be root mountable only.
The manual page has more info
https://linux.die.net/man/8/mount
Comment: Thanks for the reply, but the drive partition is not being loaded in fstab. The partition is being displayed by the File Manager from a link in /dev/disks/by-label.
Comment: The partition is being displayed by the File Manager is from a link in /dev/disks/by-label. , which points to /sda1.
The link appears to be loaded automatically when Ubuntu starts up. Changing permissions on either the link or sda1 had no effect on visibility.
Also, more info this is Ubuntu 14.04.
So, the question still remains, how would I hide this partition as described above in the original question?


How to call oracle stored procedure in spring using entity manager?

Question: create or replace PROCEDURE TEST
(
Role IN VARCHAR2,
     OUTPUT
 OUT SYS_REFCURSOR
)
AS
BEGIN
 OPEN OUTPUT FOR
Select PC.PRODUCT_NAME,P.PARTNER_NAME
............
.............
  WHERE PC.ROLE_NAME='POS_LEAD';
END TEST;

Calling above procedure In Spring using below code
StoredProcedureQuery findByYearProcedure = entityManager.createStoredProcedureQuery("TEST");

StoredProcedureQuery storedProcedure = findByYearProcedure
            .registerStoredProcedureParameter("Role", String.class, ParameterMode.IN)
            .registerStoredProcedureParameter("SYS_REFCURSOR", Object.class,ParameterMode.REF_CURSOR);
            .setParameter("Role", "admin");

System.out.println(storedProcedure.getResultList());

But I am getting an error.

ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'TEST'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

can any one help?
Answer: I tried to duplicate your issue but I cannot, though I'm using Postgres instead of Oracle.  Just to be sure, can you do this instead:
StoredProcedureQuery storedProcedure = findByYearProcedure
            .registerStoredProcedureParameter(1, String.class, ParameterMode.IN)
            .registerStoredProcedureParameter(2, Object.class,ParameterMode.REF_CURSOR);
            .setParameter("Role", "admin");

Thanks
Comment: Also perhaps it needs to be a void.class instead of Object.class as seen in https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/stored-procedure-with-ref-cursor.html


Dilemma: dropdown design with active link and active sub elements

Question: I have an element that could look a bit like the one below (it's not a select box). My challenge is that Sport (in this example) is just as important as the subsections (e.g Football, Basketball) within Sport.
Sport   ▼
This means that I have two options:

I make the whole element one interaction, which then calls for a link to "All Sports" in the bottom of the toggle layer. This feels clumsy somehow.
I make the interaction for Sport a seperate interaction and use the arrow to toggle. This is what I want to do, but I am afraid people will interpret the element as one interaction and thus expect Sport to toggle rather than to initiate a full pageload to the "Sport" section.

Any suggestions on this?
Comment: Can the list be collapsed? If not, then you can replace the dropdown arrow with some other visual elements because the arrow usually indicates a toggle.

Instead of using "All Sports" within the sub view (I think that's what you're describing), you can make the top level "All Sports" to begin with. In addition, you can eliminate the indentations so that "All Sports" is on the same level but contains the rest of the sub sections.
Answer: The element is perceived as a whole control due to label and triangle proximity and dropdown pattern familiarity. In your second option you divide the control on two parts, implementing rules which are hidden to users. So this way could lead to user's confusion because it breaks familiar pattern.

First option is better. At least, interaction rules are obvious at first sight. Then, on mouse over, user discovers element's content. You also could handle click event for the Sport label, which leads to All sports page. Such solution is used quite often in menu.

Although there are two links to the same page (Sport and All sports), the interaction is non-confusing for a user.
An example of such solution you could see here, at SE user menu:

UPDATE on @André comment
You mentioned panel (ribbon, toolbar) extender control, which is not fits this question. As @Larson said, he used dropdown element with subitems. To demonstrate the difference with  real-world examples, take a look at the picture, please.

The last picture with border setup dropdown button is close to @Lars' second option. With a little differences:

On mouse over the button clearly displays two parts: the button itself and dropdown button (triangle).
Inside dropdown panel there is the same border style as on the button's face, i.e. close to @Lars' first option.
In Word users have several ways to perform the same action, but on site this menu could be single mean for an action, so it should be totally clear.
Comment: I disagree with this pattern being unfamiliar. It is used frequently in ribbons or toolbars. Usually, the segmentation becomes appearent there when the mouse moves over the button. If you're aiming for touch, this is obviously a problem of course, but it is not unfamiliar.
Comment: @André I've updated the answer, please, take a look.
Comment: What tool do you use for your nice markups?
Comment: Hej @JOG! I use [Xara Designer](http://www.xara.com/us/).


ubuntu 13.04 64bit on pentium 4, 2 GHz with 2 GB RAM

Question: please advice can i run ubuntu 13.04 64bit  on Pentium 4 cpu of  2 Ghz clock, 2GB RAM with nvidia 210 GPU with 1 GB ram.
Answer: You have not provided enough information on your processor to determine whether it is of 64 or 32-bit. If you are already running Windows, try this link here
If your pentium cpu is indeed a 64-bit cpu, you can safely go on to installing a 64-bit flavour of Ubuntu; otherwise, stay with the 32-bit version.


Children could not be evaluated

Question: I am trying to make the following query work:
var query = from c in context.ChargeMultipliers where c.Description.Replace(" ", string.Empty).ToUpper() == description.ToUpper().Replace(" ", string.Empty)select c;

In the above I am trying to trim the sql field "Description" into a string with no spaces, all uppercase and a comparison description string also trimmed and converted to upper. However, I receive "Children could not be evaluated"as the result of the query.
Any ideas on why this happens?
Comment: Please post the exception stack trace.
Comment: Probably Linq to Entities could not translate c.Description.Replace(" ", string.Empty).ToUpper() in valid SQL, you simply try to use Linq to objects on Linq to Entities.
Answer: When debugging your query, following SQL statement is generated:
SELECT
    [Extent1].[ID] AS [ID],
    [Extent1].[Description] AS [Description],
    FROM [dbo].[ChargeMultipliers] AS [Extent1]
    WHERE (UPPER(REPLACE([Extent1].[Description], N' ', @p__linq__0))) = (UPPER(REPLACE(@p__linq__1, N' ', @p__linq__2)))

As you can see, the comparison is also trimmed in the SQL statement and string.Empty woud be passed as a parameter which is maybe not the empty character in the understanding of the database.
I would prefer to do this before building the query:
        string descriptionTrim = description.Replace(" ", string.Empty).ToUpper();

        var query = from c in context.ChargeMultipliers
                    where c.Description.Replace(" ", "").ToUpper() == descriptionTrim
                    select c;

The generated SQL query looks quite simpler now and you can easily find out what really will be compared in the WHERE clause:
SELECT
    [Extent1].[ID] AS [ID],
    [Extent1].[Description] AS [Description],
    FROM [dbo].[ChargeMultipliers] AS [Extent1]
    WHERE (UPPER(REPLACE([Extent1].[Description], N' ', N''))) = @p__linq__0

Comment: That's true. Also replacing `string.Empty` with `""` will eliminate one of the parameters. But all that doesn't answer the OP question.
Comment: I just improved my answer. Replacing string.Empty with "" might help because the c# string.Empty must not necessarily match with the database's 'empty'.
Comment: The point is that improved or not, you are answering a different question, not the one asked by the OP, which is what is causing *"Children could not be evaluated" exception*.
Comment: You're right. I was more attracted by the query than the error message, which I've never seen outside the debugging mode by the way.

Children could not be evaluated


Unable to display the widget parameter when initializing

Question: class reusableCard extends StatelessWidget {
  reusableCard({required this.colour, this.cardChild});
  final Color colour;
  final Widget? cardChild;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: colour,
        borderRadius: BorderRadius.circular(20),
      ),
      margin: EdgeInsets.all(20),
    );
  }
}

i am calling a class named reuseabelCard with two parameter among which one is a of Widget datatype.
when calling i am passing a column containing icon and text ,but the the widget is not getting displayed at all.
Expanded(
  child: reusableCard(
    colour: ActiveColourCard,
    cardChild: Column(
      children: [
        Icon(FontAwesomeIcons.mars),
        SizedBox(
          height: 10.0,
        ),
        Text(
          'Male',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ],
    ),
  ),
),

I am expecting for the icon and text to be displayed.
Answer: you forgot to add cardChild on reusableCard build() method
    return Container(
      decoration: BoxDecoration(
        color: colour,
        borderRadius: BorderRadius.circular(20),
      ),
      margin: EdgeInsets.all(20),
      // add this line
      child: cardChild ?? null,
    );

also, by dart convention, you should name classes with PascalCase (ReusableCard instead of reusableCard)
Comment: Thanks for responding ,it was helpful.
Answer: You are not calling the cardChild in reusableCard widget.
class reusableCard extends StatelessWidget {
  reusableCard({required this.colour, this.cardChild});
  final Color colour;
  final Widget? cardChild;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: colour,
        borderRadius: BorderRadius.circular(20),
      ),
      margin: EdgeInsets.all(20),
      child: cardChild,
    );
  }
}


When clicked on button the image is not changing for the first time. Button image is to be changed when clicked for the first time

Question: <code>if( [[favbutton imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"wishlwhite.png"]])
{
    [favbutton setImage:[UIImage imageNamed:@"wishlistwhite.png"] forState:UIControlStateNormal];

    // other statements
}
else
{
    [favbutton setImage:[UIImage imageNamed:@"wishlwhite.png"] forState:UIControlStateNormal];

    // other statements
}
</code>
Comment: check condition this way - `if ([favbutton.currentImage isEqual:[UIImage imageNamed:@"wishlwhite.png"]])`
Answer: You really shouldn't be checking the image in the button to determine state. Declare a separate property to test, e.g.
<code>@property (nonatomic, assign) BOOL isWishList; // or something

-(IBAction) toggleButton: (id) sender {

    if (self.isWishList) {
        [favbutton setImage:[UIImage imageNamed:@"wishlistwhite.png"] forState:UIControlStateNormal];
        // other statements
    } else {
        [favbutton setImage:[UIImage imageNamed:@"wishlwhite.png"] forState:UIControlStateNormal];
        // other statements
    }
    self.isWishList = !self.isWishList
}
</code>


Transpose the Json Using JQ : Filtering the inner List when using Map for the parent

Question: Hi I am trying to transpose the json from one format to another using the JQ.
My source JSON and JQ query is available at: https://jqplay.org/s/vt_4IbskaS
Issues with my query:

I am not able to filter the Inner Array of Assets. (rendition == dog)
I am not able to limit / remove the unwanted fields from the inner Array of Assets , i want only ID, Rendition and FileName..

My JQ Query::
<code>{CompletedInstances,status , "AppMap": (.serviceResponse |  map( { (.appId): .assets } ) | add ) }
</code>
Expected response:
<code>{
  "AppMap": {
    "testFile1234": {
      "assets": [
        {
          "filename": "testFile1234.scc",
          "rendition": "Dog",
          "assetId": 6565223
        },
        {
          "filename": "testFile1234-BG.wav",
          "rendition": "Dog",
          "assetId": 8234169
        },
        {
          "filename": "testFile1234-DK.wav",
          "rendition": "Dog",
          "assetId": 8234171
        }
      ]
    },
    "testFile4444": {
      "assets": [
        {
          "filename": "testFile1234.scc",
          "rendition": "Dog",
          "assetId": 8842169
        }
      ]
    }
  },
  "CompletedInstances": 0,
  "status": "Completed"
}
</code>
Comment: Where are you *trying* to do either filter? I don't see any attempt at it in your code.
Comment: Also, please ensure that the question itself includes your input and actual output, not just desired output. Otherwise, it'll stop being helpful to others if the jqplay link ever breaks.
Answer: This gets the expected output:
<code>{"AppMap": (.serviceResponse
            | map({ (.appId): ({"assets": (.assets | (map(select(.rendition=="Dog"))
                               | map({filename, rendition, assetId}) ))})}) | add),
 CompletedInstances, status}
</code>
Comment: The output from your filter is missing the "assets" key that is expected.  Also, I think you'll find that using the `pipe` as the first rather than last element of a line is easier on the eye and can serve as a helpful guide to program logic.
Comment: @peak, thanks for noticing that. Although I have updated my answer, I feel there can be a better solution.


CI Static D/C/M Routes and URI params

Question: I have a bit of a tricky one, and I'm not even sure if CI is designed to work this way.
I have a subdomain, lets call it test.warren.com
test.warren.com points to a CI index.php, which is separate from the main index.php that is loaded when accessing warren.com.
The test.warren.com's index.php has static routes defined, as per the CI comments
<code>/*
 * --------------------------------------------------------------------
 * DEFAULT CONTROLLER
 * --------------------------------------------------------------------
 *
 * Normally you will set your default controller in the routes.php file.
 * You can, however, force a custom routing by hard-coding a
 * specific controller class/function here.  For most applications, you
 * WILL NOT set your routing here, but it's an option for those
 * special instances where you might want to override the standard
 * routing in a specific front controller that shares a common CI installation.
 *
 * IMPORTANT:  If you set the routing here, NO OTHER controller will be
 * callable. In essence, this preference limits your application to ONE
 * specific controller.  Leave the function name blank if you need
 * to call functions dynamically via the URI.
 *
 * Un-comment the $routing array below to use this feature
 *
 */
    // The directory name, relative to the "controllers" folder.  Leave blank
    // if your controller is not in a sub-folder within the "controllers" folder
    $routing['directory']   = 'subdir';

    // The controller class file name.  Example:  Mycontroller
    $routing['controller']  = 'testcontroller';

    // The controller function you wish to be called.
    $routing['function']    = 'testmethod';
</code>
Now this all works dandy - I have my one-method website. Nothing else is accessible; only that method. If I go to test.warren.com - I get whatever is executed by testmethod().
Now, the part I can't do - is pass in URI params
EG: test.warren.com/param1/param2/param3  --- 404
As far as I can debug the reason this doesn't work is because when the router class is initialized, it tries to check if 'param1' is a controller class or a directory; which is in-line with what a standard CI configuration would expect. And then 404s out.
I think I can work around it by editing the main core/CodeIgniter.php that is loaded at the bottom of index.php; but I'm very hesitant as this CI installation has multiple site installations.
CI is v2.0.3
Does anyone know if this is possible?
Comment: are you trying to directly pass the parameter right after your domain name as you mentioned in your example test.warren.com/param1/param2/param3?
Answer: If you are using your "default route" in this way, you will need to setup a secondary route to pass the paramaters.
i.e.
<code>$route['(:any)/(:any)/(:any)'] = 'controller/action/$1/$2/$3';
</code>
This "should" work, as to match it, you would have to pass three parameters and if you don't pass three, it will revert to the default controller or 404 (if only one or two are passed.)
Hope that helps?

CI Static D/C/M Routes and URI params


How do you transform a `FixedSqlAction` into a `StreamingDBIO` in Slick?

Question: I'm creating an akka-stream using Alpakka and the Slick module but I'm stuck in a type mismatch problem.
One branch is about getting the total number of invoices in their table:
  def getTotal(implicit session: SlickSession) = {
    import session.profile.api._
    val query = TableQuery[Tables.Invoice].length.result
    Slick.source(query)
  }

But the end line doesn't compile because Alpakka is expecting a StreamingDBIO but I'm providing a FixedSqlAction[Int,slick.dbio.NoStream,slick.dbio.Effect.Read].
How can I move from the non-streaming result to the streaming one?
Answer: Taking the length of a table results in a single value, not a stream.  So the simplest way to get a Source to feed a stream is
def getTotal(implicit session: SlickSession): Source[Int, NotUsed] =
  Source.lazyFuture { () =>
    // Don't actually run the query until the stream has materialized and
    //  demand has reached the source
    val query = TableQuery[Tables.Invoice].length.result
    session.db.run(query)
  }

Alpakka's Slick connector is more oriented towards streaming (including managing pagination etc.) results of queries that have a lot of results.  For a single result, converting the Future of the result that vanilla Slick gives you into a stream is sufficient.
If you want to start executing the query as soon as you call getTotal (note that this whether or not the downstream ever runs or demands data from the source), you can have
def getTotal(implicit session: SlickSession): Source[Int, NotUsed] = {
  val query = TableQuery[Tables.Invoice].length.result
  Source.future(session.db.run(query))
}

Answer: Would sth like this work for you?
def getTotal() = {
  // Doc Expressions (Scalar values)
  // https://scala-slick.org/doc/3.2.0/queries.html
  val query = TableQuery[Tables.Invoice].length.result

  val res = Await.result(session.db.run(query), 60.seconds)
  println(s"Result: $res")
  res
}


Can't uninstall old kernel

Question: I can't install a new kernel because by boot partition is full. However I also can't remove an old kernel:
sudo apt-get purge -f  linux-image-3.2.0-29-generic-pae
[.. reading package lists etc, standard stuff, not relevant & was too lazy to translate it]
The following packages have unmet dependencies:
 linux-image-generic-pae : depends on: linux-image-3.2.0-41-generic-pae but shall not be installed
E: unmet dependencies. try »apt-get -f install« without giving a package name (or give a solution).

Any idea how I can fix this? Thanks :-)
(Note: apt-get -f install also fails: not enough free space!)
Comment: I never tried that, but the man page mentions a parameter named `-m` aka `--ignore-missing`. So you could try `sudo apt-get purge -m linux-image-3.2.0-29-generic-pae`. The error message looks like you already tried to update, and that partly started but then broke due to lack of free space, so apt now sees some "inconsistent state". Having it ignore that might enable you to remove that package. However, make sure you have at least one working linux-image left, or your system might break completely (3.2.0-32 could still be there I guess).
Comment: Thank you guys. `purge -m` didn't help, same problem. But the linked solution (manually removing one of the kernels and then removig it with apt-get too) helped. I could then install linux-image-3.2.0-41-generic-pae, after (!) that a normal apt-get upgrade was possible and removing older kernels too.
Answer: Are you running Linux 3.2.0-29-generic-pae? Try uname -r. To clean out OLD kernels, try:
Kver=$( uname -r)
( dpkg -l linux-image\*; dpkg -l linux-doc\*;dpkg -l linux-headers\*) | egrep -v "$Kver"

to get a list of obsolete packages you can apt-get purge.
You will be a sad bunny if you manage to delete your current kernel. Do you have a Live CD or install disk handy?
Comment: No, I wouldn't have deleted the current kernel ;-) I fixed it manually like mentioned in the linked duplicate. Your 2 lines, will they only list old kernels or also remove them?

Can't uninstall old kernel


less css and node js troubles

Question: When I try to install less css compiler under my Ubuntu 13.10 box I get following message and lescss don't working. In what way I can fix the problem? I execute:
sudo npm install -g less

After this I get e list with OK messages:
npm http 304 https://registry.npmjs.org/cryptiles
npm http 304 https://registry.npmjs.org/ctype/0.5.2
npm http 304 https://registry.npmjs.org/combined-stream
npm http GET https://registry.npmjs.org/delayed-stream/0.0.5
npm http 304 https://registry.npmjs.org/sntp
npm http 304 https://registry.npmjs.org/boom
npm http 304 https://registry.npmjs.org/delayed-stream/0.0.5

And list finished with following:
 /usr/local/bin/lessc -> /usr/local/lib/node_modules/less/bin/lessc
    firstname.lastname@example.com /usr/local/lib/node_modules/less
    ├── firstname.lastname@example.com
    ├── email@example.com
    ├── email@example.com (email@example.com)
    ├── email@example.com (firstname.lastname@example.com)
    └── email@example.com (email@example.com, firstname.lastname@example.com, email@example.com, firstname.lastname@example.com, email@example.com, email@example.com, email@example.com, email@example.com, email@example.com, email@example.com, firstname.lastname@example.com)

After this when I tried the following commands:
echo "@foo: 25px; #foobar{font-size: @foo};" > style.less
sudo lessc ./style.less ./style.css

I get the following error:
/usr/bin/env: node: No such file or directory

After I executed
ln -s /usr/bin/node /usr/local/bin/nodejs

and created symlinks there is no errors but lessc compiler don't working properly.
I have created file to test. It content is:
cat style.less
@color: #4D926F;

#header {
  color: @color;
}
h2 {
  color: @color;
}`

and after trying
lessc styles.less > styles.css

There is created file - styles.css but the file is empty.
I also try commands that I tryed before - see top on the post.
lessc styles.less styles.css

But it not working. There is no file as a result.
When I tried
sudo npm install -g less

In the last line I receive following error.
npm http 200 https://registry.npmjs.org/delayed-stream/-/delayed-stream-0.0.5.tgz
/usr/bin/lessc -> /usr/lib/node_modules/less/bin/lessc
npm ERR! Refusing to delete: /usr/bin/lessc not in /usr/lib/node_modules/less
File exists: /usr/bin/lessc
Move it away, and try again.

npm ERR! System Linux 3.11.0-19-generic
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "-g" "less"
npm ERR! cwd /home/georgi
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! path /usr/bin/lessc
npm ERR! code EEXIST
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/georgi/npm-debug.log
npm ERR! not ok code 0

Comment: Those exact commands worked for me pasted into my node server. Running ubuntu 12.04 with node installed. Can you run node from where you are (is it in your PATH)?
Comment: The question is edited.
Comment: When you type `env node --version` does it tell you your node version or does it tell you *"No such file or directory"*? And, what is the output of `which env`? What distro of Linux are you using?
Comment: where is your lessc version ? `lessc -v`
Comment: lessc -v don't output nothing.
Comment: normally, lessc print this on your console : `lessc 1.4.1 (LESS Compiler) [JavaScript]` and if you try just `lessc` to get the 'man page'
Comment: So I have general issue with installation ..  What I can do?
Comment: try `sudo npm cache clean` and `npm cache clean` and restart less install
Comment: try sudo npm cache clean and npm cache clean - this don't change nothing. Never mind I'm using koala now:  http://koala-app.com/
Answer: The > command operator is incorrect in your command. The correct command is :
lessc [sourcefile] [destfile]

For your example, your command is :
lessc styles.less styles.css

Comment: I alto tried lessc styles.less styles.css but there is no file as result.
Comment: Try `lessc styles.less styles.css --verbose`
Comment: lessc styles.less styles.css --verbose dont generate error but don't output nothing.

less css and node js troubles


The regression analysis below relates US annual energy consumption in trillions of BTUs to

Question: The regression analysis below relates US annual energy consumption in trillions of BTUs to the independent variable "US Gross Domestic Product (GDP) in trillions of dollars."

Which of the following is the lowest level at which the independent variable is significant?

A 0.94
B
0.10
C
0.05
D
0.01
please help
Comment: Please don't post homework questions here without at least explaining your current thoughts. Do you know what statistical significance is and how it relates to P-values (there's a hint)?
Comment: because of p-value is 0.0000
I think The lowest level at which the independent variable is significant is 0.01
Answer: Your comment is correct, adel, but you should make sure you're getting the p-value from the correct place (as there are basically 3 p-values listed, all of which have value of 0.0000).
The question is also oddly phrased - what this test is really doing is saying whether the coefficient for the independent variable in the regression formula is statistically significantly different from 0. The question gets at the spirit of this, but isn't really the right phrasing.
Regardless, from output like this you look at the chart at the bottom. If you want to know if the coefficient of the independent variable is different from zero, look at the independent variable line - in this case, the very bottom one labeled "GDP ($trillions)". This line tells you (from left to right) the following:
a) In the regression formula, the coefficient of this variable is 3,786. That effectively means that for every increase of $1 trillion in GDP, energy consumption goes up by 3,786 trillion BTUs
b) The std. error of this coefficient is 220
c) The test statistics is 17.19
d) The p-value (i.e. the probability of the coefficient actually equaling zero) is 0.0000
Given that, if you've chosen a significance level of pretty much anything, you would conclude that the coefficient is not equal to zero and therefore, in the language of the question, that the independent variable is significant.
If, by contrast, that last p-value was .027, then the independent variable would be significant at a .05 level, but not at a .01 level.
Always remember to pick your significance level first, though! Not after you calculate the p-values.


Why is the value being stored in the register 0x605040c, rather than 12?

Question: I'm reviewing for a test, and I cant figure out why the answer for this is  0x605040c rather than 12, or for the one after, why it's 0123000 rather than 123.
Thanks for the help, the code is below. I've run it in QtSPIM and i still cant figure it out!
data
var1:  .byte 12
var2:  .byte 4,5,6
var3:  .word 1,2,3,4,5,6,7,8,9
  .globl main
.text
main:
la $t1, var1
la $t2, var2
la $t3, var3
lb $a1,1($t2) #$a1= 0x5
lw $a1, 0($t1) #$a1= 0x605040c
lui $a1,0x123 #$a1= 0x01230000
lw $a1, 0($t3) #$a1= 0x1
sll $a1,$a1,3 #$a1= 0x8

Answer: the answer to your questions can generally be answered by reading a reference document about each MIPS instruction that you use.
I will assume that your MIPS machine is little-endian.
First, let's look at your memory:
Address:      0     1  2  3   4  5  6  7   8  9  10 11  12 13 14 15 ... 36 37 38 39
Value (hex):  0C    04 05 06  01 00 00 00  02 00 00 00  03 00 00 00 ... 09 00 00 00
Label:        ^var1 ^var2     ^var3

Now we'll analyze the tricky parts of your code:
lw $a1, 0($t1)

^ This means load the 32-bit (4-byte) word starting at address t1, in little endian. With t1 = var1, the 4 bytes are 0C 04 05 06. The interpretation as a 32-bit integer is 0605040C.
lui $a1,0x123 #$a1= 0x01230000

^ This means load the immediate 16-bit constant into the upper 16 bits, and make the bottom 16 bits all zero. (Refer to the reference, skip down to LUI.)


How to omit empty/null field's before submitting form with Formik

Question: I'm using formik to handle form state and pass it on to a function that will send a patch request to the API, but when the form is sent all the fields(including empty and or null) fields so the API treats it as an input and overwrites the previous data.
my formik initialValues:
<code>                enableReinitialize
                initialValues={{
                    firstname: userdata?.firstname ?? "",
                    lastname: userdata?.lastname ?? "",
                    age: userdata?.age ?? "",
                    phone: userdata?.phone ?? "",
                    secondary_phone: userdata?.secondary_phone ?? "",
                    image: null,
                    sex: userdata?.sex ?? "",
                    height: userdata?.height ?? "",
                    wereda: userdata?.wereda ?? "",
                    kebele: userdata?.kebele ?? "",
                    address: userdata?.address ?? "",
                }}
</code>
in the example above most of the fields will not be null since I am setting the initial data from the server but making this the only guard and putting hope on the user to not clear the input before sending is a big risk, also I cannot send the image URL as a field value to the server since it needs an image file and I don't like the idea of converting the URL to a js File object, so how can I omit all the fields that are "" or null before passing it over to the function that will take care of the API request?? thanks in advance.
Answer: Never mind, I googled it and found some code, modified it to look like this:
<code>     Object.keys(values).forEach(key => {
            if (values[key] === '' || values[key] === null) {
                     delete values[key];
              }
            });
</code>
It iterates trough the object and deletes any that has a value of either "" or null


Area vs Volume Paradox

Question:
Possible Duplicate:
How can a structure have infinite length and infinite surface area, but have finite volume?

Hi,
I have this question that I quite cant explain why.
So the area under the curve $$y=\frac{1}{x}$$ from 1 to infinity equals
$$\lim_{r->\infty } \ln(r) |_1^r = \infty $$
And the volume of the solid by rotation the equation about the x-axis from 1 to infinity is
$$\int_{1}^{\infty} \pi\left (\frac{1}{x} \right )^2 dx$$
which evaluates to the area being $$\pi$$
So, whats the explanation for the area being infinite but the volume being finite?
Comment: http://en.wikipedia.org/wiki/Gabriel's_Horn
Answer: This is called Gabriel's horn." There isn't much to "explain": it just is, as a consequence of how things work. In short, it's a paradox (a result that is counter to expectations or intuition), not a contradiction.
You can accomplish a similar situation if you imagine starting with a cylinder of, say, radius $r$ and height $h$. The volume is $\pi r^2h$, the surface area is $2\pi rh$. If try to make the cylinder taller and thinner so as to keep the volume constant, you will necessarily increase the height a lot faster than you are decreasing the radius, because the decrease in the radius will be quadratic while the increase in the height will be linear (if you decrease the radius by a factor of $\frac{1}{4}$th, the volume decreases by a factor of $\frac{1}{16}$, so you would need to increase the height by a factor of $16$ to keep up); however, that will result in a net increase in the surface area (if you decrease the radius by $\frac{1}{4}$ and increase the height by a factor of $16$, then the surface area increases by a factor of $4$). If you keep making the cylinder taller and thinner and keeping the volume constant, then the surface area will necessarily grow without bound. So you have a "continuous deformation" of the cylinder that keeps the volume constant, but the surface area grows without bound.
With Gabriel's Horn you have a similar situation (with your figure lying on its side); intuitively, you are reducing the radius sufficiently faster than the "length" so that the total volume decreases, but not so fast that the total surface length also decreases. Intuitively, the "inside" is getting small fast enough that it does not amount to much, but just "fast enough" that the outside does not decrease fast enough.
It's just like the fact that you can add an infinite number of positive numbers,
$$\frac{1}{1^2} + \frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{4^2}+\cdots+\frac{1}{n^2} + \cdots$$
and yet get a finite total, but if you change it just a bit you can get something infinite:
$$\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{n} +\cdots$$
which diverges.

Area vs Volume Paradox


How to check if xml files dumped from database are up to date?

Question: I have a mysql database and the application which connects to it, dumps required tables into xml, imports some info from them and then works on this info.
However I have no idea how to check if these xml files need updating while application starts.
I thought about checking if number of entries has changed but if someone modifies existing entry it won't be updated. Overwriting all files each time and importing them again takes too much time.
Unfortunately I cannot modify database to create a field which stores a "last modification" information.
Have you got any idea?
Answer: Create a modify/insert trigger. I you can do it.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
The purpose of this trigger is to update another table when your table is altered.
Answer: How can you not modify the database?  If that particular table is off limits to you, then make a new table (in that database or another), which holds updated information referencing the table you're trying to possibly re-query.
I often have these defacto columns in a table:

InsertedDate
InsertedBy
UpdatedDate
UpdatedBy
Active

You can use a compbination of InsertedDate and UpdatedDate to check whether you need to pull the XML out or not.
Another (albeit ugly) option is to keep a separate "tracking" table that contains a copy of the XML values, and you can then compare the two if they are the same or different.  If different, get latest and use it and then update your tracking table with it.
Comment: Like I said I cannot modify a database because some stupid guy who was working before me developed our CRM software that way, that it crashes each time the database structure is altered... but thanks for your reply.


How much bandwith does a competitve CS:GO match require?

Question: I have recently started playing CS:GO and I use limited usage internet connection. I want to know bandwidth usage a competitive CS:GO match has.
Details,
-Official server competitive match.
-Nothing extra downloaded as I play on default maps and stuff.
-Ping lies between 64 - 200
-match lasts 30-40 minutes
-I play for 1 to 3 hours straight
Can someone help?
Answer: if you are on 64 tick , its around 25KB/s (both up+down).
if you are on 128 tick , its around 70KB/s (both up+down).

64 tick -> 1 hour play -> 87 MB
128 tick -> 1 hour play -> 246 MB

you can use application like

windows resource monitor
du meter
NetLimiter

There are a lot software out there that you can track what resource you are using.
Comment: It also depends on the amount of voice chat going on in-game, so it's hard to say. But these figures should give a base estimate.
Comment: you are right, this also will add data but you can disable this feature and not use it to save data.
Comment: This is cool. so its about 25-50kbps youd say? That frightens me a little bit. my internet struggles to hit 100 sometimes, and if anyone else dares to look at the chrome logo it dips way below 30...