text:
Q: How do I manually find and remove a virus?
Possible Duplicate:
Computer is infected by a virus or a malware, what do I do now?

I believe I have a virus and the virus scanning tools I tried so far haven't found any (I will continue to run them in the meantime). However, how do I manually find and remove a virus?
My first steps were to look at msconfig startup and services.  I found nothing suspicious (all but one app (Launchy, which is a incredibly convenient tool) were signed. All my services are signed as well.
Why I believe i have a 'virus' is that randomly I will get a privileged prompt to run install 1 and immediately after I hit "No" it will prompt again for install 2. When I boot up I use 3GB of RAM.  When I look at task manager and look at the memory size of the apps it adds up to 1.4GB of RAM. When I log out/in I am using the 1.3 or 1.4 GB of RAM as normal. I sometimes see my CPU usage being eaten by 'cmd'. I have no idea what process ran it.
How do I find and remove this virus manually? The symptoms above should give you some ideas of where to start when tracking and removing the virus.
Unless the virus hijacked a chrome update, I do not believe I hit "Yes" for a privileged prompt to get it onto my machine, but it doesn't make sense that it could run on startup if I have never done that.

A: Look for it in process list in Windows Task Manager (enable "show processes from all users" option).
If process in Task Manager isn't killable (for example, a pair of virus processes taking care of each other), find the corresponding file on disk and revoke access rights for it with CACLS, then try to kill the beast again :)
Also I suggest StRun software to check startup list for malware. MSConfig doesn't show BHOs (Browser Helper Objects) and other ways malware usually employs to get called on reboot.

A: High quality viruses cannot be found by the user and will not show in the process list, so unless you know how the virus was written, you have no chance to remove the more stealthy infections. See my post here, use the Windows System Sweeper or Kaspersky boot CD to scan and remove the infection.


text:
Q: How does one display a Wordpress website within 'Static Html: iFrame Tabs' in Facebook so that it adjusts to the page's content height? I have tried various solutions to get the iframe to adjust according to the website's content height, so that I can do away with vertical scrollbars, but cannot get a satisfactory solution.
Many solutions ask for a section of code to be added on the 'server side'. If that means I have to edit lines of code within my Wordpress files, where would I do this?
Here is a link to the iframe in question.

A: Rather than try to adjust the Facebook page to fit your WordPress install, you're better off changing your WordPress theme to deal with being shown in a Facebook iframe.
When displayed in the iframe, you should have a theme that is fixed-width to your canvas, and no sidebars. Just a content pane. You would then have your regular theme for when visitors arrive outside of a Facebook frame.
The Virtual Theme plugin looks like it could help with this. I've never used it personally.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is using deciles to find correlation a statistically valid approach? I have a sample of 1,449 data points that are not correlated (r-squared 0.006).
When analyzing the data, I discovered that by splitting the independent variable values into positive and negative groups, there seems to be a significant difference in the average of dependent variable for each group.
Splitting the points into 10 bins (deciles) using the independent variable values, there seems to be a stronger correlation between the decile number and the average dependent variable values (r-squared 0.27).
I don't know much about statistics so here are a few questions:

*

*Is this a valid statistical approach?

*Is there a method to find the best number of bins?

*What is the proper term for this approach so I can Google it?

*What are some introductory resources to learn about this approach?

*What are some other approaches I can use to find relationships in this data?

Here is the decile data for reference: https://gist.github.com/georgeu2000/81a907dc5e3b7952bc90
EDIT: Here is an image of the data:

Industry Momentum is the independent variable, Entry Point Quality is dependent

A: 0. The correlation (0.0775) is small but (statistically) significantly different from 0. That is, it looks like there really is correlation, it's just very small/weak (equivalently, there's a lot of noise around the relationship).
1. What averaging within bins does is reduce the variation in the data (the $\sigma/\sqrt{n}$ effect for standard error of a mean), which means that you artificially inflate the weak correlation.  Also see this (somewhat) related issue.
2. Sure, fewer bins means more data gets averaged, reducing noise, but the wider they are, the "fuzzier" the average becomes in each bin because the mean isn't quite constant - there's a trade-off. While one might derive a formula to optimize the correlation under an assumption of linearity and the distribution of the $x$'s, it wouldn't take full account of the somewhat exploitable effect of noise in the data. The easy way is to just try a whole variety of different bin boundaries until you get what you like. Don't forget to try varying the bin-widths and bin-origins. That strategy can occasionally prove surprisingly useful with densities, and that kind of occasional advantage can be carried over to functional relationships - perhaps enabling you to get exactly the result you hoped for.
3. Yes. Possibly start with this search, then perhaps try synonyms.
4. This is a good place to start; it's a very popular book aimed at non-statisticians.
5. (more seriously:) I'd suggest smoothing (such as via local polynomial regression/kernel smoothing, say) as one way to investigate relationships. It depends on what you want, exactly, but this can be a valid approach when you don't know the form of a relationship, as long as you avoid the data-dredging issue.

There's a popular quote, whose originator appears to be Ronald Coase:

"If you torture the data enough, nature will always confess."

A: I do not believe that binning is a scientific approach to the problem.   It is information losing and arbitrary.  Rank (ordinal; semiparametric) methods are far better and do not lose information.  Even if one were to settle on decile binning, the method is still arbitrary and non-reproducible by others, simply because of the large number of definitions that are used for quantiles in the case of ties in the data.  And as alluded to in the nice data torture comment above,  Howard Wainer has a nice paper showing how to find bins that can produce a positive association, and find bins that can produce a negative association, from the same dataset:
 @Article{wai06fin,
   author =          {Wainer, Howard},
   title =       {Finding what is not there through the unfortunate
    binning of results: {The} {Mendel} effect},
   journal =     {Chance},
   year =        2006,
   volume =      19,
   number =      1,
   pages =       {49-56},
   annote =      {can find bins that yield either positive or negative
    association;especially pertinent when effects are small;``With four
    parameters, I can fit an elephant; with five, I can make it wiggle its
    trunk.'' - John von Neumann}
 }

A: I found the localgauss package very useful for this.
https://cran.r-project.org/web/packages/localgauss/index.html
The package contains

Computational routines for estimating and visualizing local Gaussian
parameters. Local Gaussian parameters are useful for characterizing
and testing for non-linear dependence within bivariate data.

Example:
    library(localgauss)
    x=rnorm(n=1000)
    y=x^2 + rnorm(n=1000)
    lgobj = localgauss(x,y)
    plot(lgobj)

Result:

A: Splitting the data into deciles based on the observed X ("Entry Point Quality") appears to be a generalization of an old method first proposed by Wald and later by others for situations wherein both X and Y are subject to error.  (Wald split the data into two groups.  Nair & Shrivastava and Bartlett split it into three.)  It is described in section 5C of Understanding robust and Exploratory Data Analysis, edited by Hoaglin, Mosteller and Tukey (Wiley, 1983).  However, a lot of work on such "Measurement Error" or "Error in Variables Models" has been done since then.  The textbooks that I've looked at are Measurement Error:  Models, Methods and Applications by John Buonaccorsi (CRC Press, 2010) and Measurement Error Models by Wayne Fuller (Wiley, 1987).
Your situation may be somewhat different because your scatterplot leads me to suspect that both observations are random variables and I don't know whether they each contain measurement error.  What do the variables represent?

A: Perhaps you would benefit from an exploratory tool.  Splitting the data into deciles of the x coordinate appears to have been performed in that spirit.  With modifications described below, it's a perfectly fine approach.
Many bivariate exploratory methods have been invented.  A simple one proposed by John Tukey (EDA, Addison-Wesley 1977) is his "wandering schematic plot."  You slice the x-coordinate into bins, erect a vertical boxplot of the corresponding y data at the median of each bin, and connect the key parts of the boxplots (medians, hinges, etc.) into curves (optionally smoothing them).  These "wandering traces" provide a picture of the bivariate distribution of the data and allow immediate visual assessment of correlation, linearity of relationship, outliers, and marginal distributions, as well as robust estimation and goodness-of-fit evaluation of any nonlinear regression function.
To this idea Tukey added the thought, consistent with the boxplot idea, that a good way to probe the distribution of data is to start at the middle and work outwards, halving the amount of data as you go.  That is, the bins to use need not be cut at equally-spaced quantiles, but instead should reflect the quantiles at the points $2^{-k}$ and $1-2^{-k}$ for $k=1, 2, 3, \ldots$.
To display the varying bin populations we can make each boxplot's width proportional to the amount of data it represents.
The resulting wandering schematic plot would look something like this.  Data, as developed from the data summary, are shown as gray dots in the background.  Over this the wandering schematic plot has been drawn, with the five traces in color and the boxplots (including any outliers shown) in black and white.

The nature of the near-zero correlation becomes immediately clear: the data twist around.  Near their center, ranging from $x=-4$ to $x=4$, they have a strong positive correlation.  At extreme values, these data exhibit curvilinear relationships that tend on the whole to be negative.  The net correlation coefficient (which happens to be $-0.074$ for these data) is close to zero.  However, insisting on interpreting that as "nearly no correlation" or "significant but low correlation" would be the same error spoofed in the old joke about the statistician who was happy with her head in the oven and feet in the icebox because on average the temperature was comfortable.  Sometimes a single number just won't do to describe the situation.
Alternative exploratory tools with similar purposes include robust smooths of windowed quantiles of the data and fits of quantile regressions using a range of quantiles. With the ready availability of software to perform these calculations they have perhaps become easier to execute than a wandering schematic trace, but they do not enjoy the same simplicity of construction, ease of interpretation, and broad applicability.

The following R code produced the figure and can be applied to the original data with little or no change.  (Ignore the warnings produced by bplt (called by bxp): it complains when it has no outliers to draw.)
#
# Data
#
set.seed(17)
n <- 1449
x <- sort(rnorm(n, 0, 4))
s <- spline(quantile(x, seq(0,1,1/10)), c(0,.03,-.6,.5,-.1,.6,1.2,.7,1.4,.1,.6),
            xout=x, method="natural")
#plot(s, type="l")
e <- rnorm(length(x), sd=1)
y <- s$y + e # ($ interferes with MathJax processing on SE)
#
# Calculations
#
q <- 2^(-(2:floor(log(n/10, 2))))
q <- c(rev(q), 1/2, 1-q)
n.bins <- length(q)+1
bins <- cut(x, quantile(x, probs = c(0,q,1)))
x.binmed <- by(x, bins, median)
x.bincount <- by(x, bins, length)
x.bincount.max <- max(x.bincount)
x.delta <- diff(range(x))
cor(x,y)
#
# Plot
#
par(mfrow=c(1,1))
b <- boxplot(y ~ bins, varwidth=TRUE, plot=FALSE)
plot(x,y, pch=19, col="#00000010",
     main="Wandering schematic plot", xlab="X", ylab="Y")
for (i in 1:n.bins) {
  invisible(bxp(list(stats=b$stats[,i, drop=FALSE],
                     n=b$n[i],
                     conf=b$conf[,i, drop=FALSE],
                     out=b$out[b$group==i],
                     group=1,
                     names=b$names[i]), add=TRUE,
                boxwex=2*x.delta*x.bincount[i]/x.bincount.max/n.bins,
                at=x.binmed[i]))
}

colors <- hsv(seq(2/6, 1, 1/6), 3/4, 5/6)
temp <- sapply(1:5, function(i) lines(spline(x.binmed, b$stats[i,],
                                             method="natural"), col=colors[i], lwd=2))


text:
Q: incorrect count of unique text in awk I am getting the wrong counts using the awk below.  The unique text in $5 before the - is supposed to be counted.
input
chr1    955543  955763  chr1:955543-955763  AGRN-6|gc=75    1   15
chr1    955543  955763  chr1:955543-955763  AGRN-6|gc=75    2   16
chr1    955543  955763  chr1:955543-955763  AGRN-6|gc=75    3   16
chr1    1267394 1268196 chr1:1267394-1268196    TAS1R3-46|gc=68.2   553 567
chr1    1267394 1268196 chr1:1267394-1268196    TAS1R3-46|gc=68.2   554 569
chr1    9781175 9781316 chr1:9781175-9781316    PIK3CD-276|gc=63.1  46  203
chr1    9781175 9781316 chr1:9781175-9781316    PIK3CD-276|gc=63.1  47  206
chr1    9781175 9781316 chr1:9781175-9781316    PIK3CD-276|gc=63.1  48  206
chr1    9781175 9781316 chr1:9781175-9781316    PIK3CD-276|gc=63.1  49  207

current output
1

desired output (AGRN,TAS1R3, PIK3CD) are unique and counted
3

awk
awk -F '[- ]' '!seen[$6]++ {n++} END {print n}' file

A: Try
awk -F '-| +' '!seen[$6]++ {n++} END {print n}' file

Your problem is that when ' ' (a space) is included as part of a regex to form FS (via -F) it loses its special default-value behavior, and only matches spaces individually as separators.
That is, the default behavior of recognizing runs of whitespace (any mix of spaces and tabs) as a single separator no longer applies.
Thus, [- ] won't do as the field separator, because it recognizes the empty strings between adjacent spaces as empty fields.
You can verify this by printing the field count - based on your intended parsing, you're expecting 9 fields:
$ awk -F '[- ]' '{ print NF }' file
17  # !! 8 extra fields - empty fields

$ awk -F '-| +' '{ print NF }' file
9   # OK, thanks to modified regex

You need alternation -| + to ensure that runs of spaces are treated as a single separator; if tabs should also be matched, use '-|[[:blank:]]+'

A: Including "-" in FS might be fine in some cases, but in general if the actual field separator is something else (e.g. whitespace, as seems to be the case here, or perhaps a tab), it would be far better to set FS according to the specification of the file format. In any case, it's easy to extract the subfield of interest. In the following, I'll assume the FS is whitespace.
awk '{split($5, a, "-"); if (!(count[a[1]]++)) n++ }
     END {print n}'

If you want the details:
awk '{split($5, a, "-"); count[a[1]]++}
     END { for(i in count) {print i, count[i]}}'

Output of the second incantation:
AGRN 3
PIK3CD 4
TAS1R3 2


text:
Q: Android custom spinner adapter binding I'm trying to create a generic spinner adapter that can bind to a list of objects from a database, having id and name properties, so that I can 1) get the id corresponding to the value selected in the spinner; and 2) set the selected item based on the object id, not the position, as ids won't match the positions in the spinner:
id name
-- -----
1  Alice
3  Bob

The following code for a custom adapter found here is a good start and is generic:
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SpinAdapter<T> extends ArrayAdapter<T> {
private Context context;
private List<T> values;

public SpinAdapter(Context context, int textViewResourceId, List<T> values) {
    super(context, textViewResourceId, values);
    this.context = context;
    this.values = values;
}

public int getCount() {
    return values.size();
}

public T getItem(int position) {
    return values.get(position);
}

public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView label = new TextView(context);
    label.setTextColor(Color.BLACK);
    label.setText(values.toArray(new Object[values.size()])[position]
            .toString());
    return label;
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    TextView label = new TextView(context);
    label.setTextColor(Color.BLACK);
    label.setText(values.toArray(new Object[values.size()])[position]
            .toString());

    return label;
}
}

In order to set the selected value, I need the adapter to return the position for an object given its id. I was thinking adding a method such as public int getPosition (long id) looping through all the items in the list and returning the index of the one having the correct id.
However, as a beginner, I'm not quite at ease with generic types, abstract types and interfaces. I tried replacing the generic <T> by an abstract class DatabaseItem such as:
public abstract class DatabaseItem  {
    public abstract long getId();
    public abstract String getName();
}

And making my object class extend DatabaseItem, but I don't think this works.
Any help would be appreciated.

A: Following bigdestroyers' comment, I used an interface:
public interface DatabaseItem  {
    public abstract long getId();
    public abstract String getName();
}

Then added the following method in the custom adapter:
public int getPosition(long id){
    int position = -1;
    for(T v : values) {
        if(((DatabaseItem)v).getId() == id) {
            position = values.indexOf(v);
        }
    }
    return position;
}

Not sure that's the best or the more elegant way to do, but it seems to do the trick.


text:
Q: play fullscreen video on button click I was browsing on squarespace's website and saw that they have a button in the bottom right that plays a fullscreen video after it's clicked. When I used bigvideo.js, the video was blurry, but the one Squarespace uses isn't blurry and it also has it's own player. Does someone know how I could achieve this? I'm mainly wondering about how to make my own player and play a video without linking to another html page.
EDIT: It seems they've put videos as the backgrounds. How could they do that?
LINK: http://www.squarespace.com/
Screenshot: http://postimg.org/image/ilptcpvcx/

A: HTML 5 player has full screen built in.
Alternatively you could look at flowplayer or sublime video.
As for the blurry video are you sure its not just your video quality?


text:
Q: Ext.Net how to get all TreeNode IN TreePanel AS List Ext.Net how to get all TreeNode IN TreePanel AS List
foreach(Node treenode in treepanel.Nodes) {
   string nodeID = treenode.NodeID;
}

A: You can do it Recursively:
    //Create a list
    List<Node> list = new List<Node>();

    //pass you tree root as a parameter
    GetAllNodes(YourTreePanel.root);

    protected void GetAllNodes(NodeCollection nodes) {

        foreach (Node item in nodes)
        {
            //if your node has children call the function again
            if (item.Children.Count > 0) GetAllNodes(item.Children);

            //finally add the node to the list
            list.Add(item);
        }
    }


text:
Q: Structure project by inheritance? The usual approach is to do what libraries do: group your (single file) classes by component where folder = namespace, right? That makes sense for code that is mostly meant to be used by other projects.
But wouldn't it be better to structure your actual application by inheritance? The major benefit would be that just by looking at the folder structure, you'd already know what inherits from what. In single inheritance languages like PHP, it's certainly possible.
After all, what is the benefit of structuring your actual, own application folders like libraries? So let's assume a simple MVC structure, something like this:
— classes
  |— controller
     |— IndexController.php
     |— PostsController.php
  |— extends
     |— MySqlDatabase.php
     |— HtmlTemplate.php
  |— Controller.php
  |— Database.php
  |— Template.php
— interfaces
  |— extends
     |— HttpControllers.php
  |— Controllers.php
— traits
  |— Cacheable.php

This would be combined with an autoloader that additionally looks for classes in an extends sub-folder inside any specified path, if it could't find one there already. The specified paths would be: /classes;/interfaces;/traits;/classes/controller. The last one is a special case, because I felt like grouping all controllers in an extra folder, so I had to explicitly add that one.
Creating those is also required, if you want to further inherit from the classes in there, because the autoloader wouldn't look for an extends/extends folder. A neat side-effect would also be that going crazy deep on inheritance is kinda discouraged.
What do you think? Which immediate flaws can you depict from this? I guess the additional file system access due to checking paths that may not exists is one.

A: Whenever someone thinks of a new and improved way of doing something, I am reminded of the relevant XKCD:

I urge anyone to really consider whether after they've created their standard, if they think the total number of actively used standards will in fact decrease. Because if it stays the same, you've not changed anything, and if it increases, you've added to the problem.
In other words, your new standard must out right replace at least TWO existing standards. Therefore, a good measure of the value of your standard if to find two existing standards which would be significantly improved.

Parts of your idea match up (for coincidental reasons) with how things are structured today.

*

*MVC controllers are generally put together and also tend to have shared inheritance, i.e. deriving from the same class

*It's not uncommon for specific implementation of a base class to be one namespace level up from where its implementations are. Especially for tests, I've commonly seen them share a base class fixture that is found closeby to the derived test classes.

*Base(r) classes tend to be more broad-sweeping, (more) derived classes tend to be more specific. Top-level directories tend to be named/structured after the broad architecture, while deep subfolders tend to be niche and specific.

*Contracts are commonly kept in a little bag of their own, much like you have done with your interfaces and traits (but not base classes) here. While contracts are more commonly interfaces than base classes, it's not unheard of for some base classes to be part of a publically exposable set of contracts.

But there's also a whole lot of conceptual conflict going on here.

*

*Developers don't always know the entire inheritance tree. For example, your controllers may all inherit from a premade Controller class from your framework, but do you know what Controller inherits from, and how deep that rabbit hole goes? Because if you don't then how will you be able to define your top level directory (= the "basest" class, if you will)

*Are you including TPL base classes into the folder structure? If I inherit from a TPL's BaseThing class, should I use a /BaseThing folder level?

*

*If yes, then your codebase is structured based on external libraries, which is going to bite you when your dependencies change.

*If no, since you claim that the file structure would help with revealing the inheritance structure, then you don't really know what MyDerivedThing derives from, do you?

*You seem to think about a project as being a single file tree. The predominant majority of professional software projects have multiple projects/layers, which immediately breaks your single-tree structure. In other words, your system would need to enforce a single-project approach in order for your system to make any sense.

*I am struggling to see how you would be able to sanely implement inverted dependencies, though this may just be because it's tied in to the broader "no multiple projects" problem with your approach.

*All static classes would have to live in the top level directory with no possible subdivision, since static classes can't inherit.

*While there are differences between them, on a polymorphic level, base classes and interfaces are very closely tied together and used in the same way, but your system very specifically ostracizes the interfaces to their own folder whereas the base classes belong to their own folder. This forces a two-pronged approach for what is essentially much of the same thing.

*Although I suspect you've already realized this, interfaces would become rogue agents as their implementations can be anywhere, without any way to group them in the same inheritance directory.

*You would lose the ability to define your contracts in a separate assembly to ensure that it can be shared (e.g. if part of your codebase is a public package)

*You would force the developer of a base class to also have to be the one developing the inherited classes, or at least have access to and work in the same source code. While this is commonly the case for developers to work on the full stack of their project, it would preclude things such as third-party libraries which provide a base class for you to extend.

*I'm no PHP dev but what I surmise from how traits work, much of what I said about interfaces applies to traits as well.

*If during a change, a base class is now made to derived from another (more baser) class, you would have to move your entire ancestry down one level. While that may not be very hard to do in a file explorer, it's at the very least going to cause a massive commit.

*I've worked in teams where most developers only had read access to the contracts, so that they could only implement the existing contracts and not modify them. This was done because the implementation developers were not intimately aware of the framework in which their implementation would run, and that framework needed to rely on its contracts being honored and not altered willy nilly. This becomes increasingly hard to do when your base classes are peppered across the project file tree instead of kept separate.

The major benefit would be that just by looking at the folder structure, you'd already know what inherits from what.

Proper naming and a basic understanding of the (contextual) problem domain already tend to have you covered there. There are hardly any, if any cases whereby at the same time:

*

*The base class and derived class names are not thematically linked

*The naming is considered good

After all, what is the benefit of structuring your actual, own application folders like libraries?

Created software remains successful for as long as it is usable. Successful software tends to grow and people try to find new applications for the software, which means that there is a general push towards increasing the size of the codebase, or reusing it across platforms.
In both scenarios, you would've pre-emptively painted yourself in a corner if you had been using a single-project approach where part of the contracts (i.e. the base classes) is peppered in with the implementations. It makes it harder to separate the resuable business logic from the application-specific view logic.
Even in your own example, you already stumbled on this:

The last one is a special case, because I felt like grouping all controllers in an extra folder, so I had to explicitly add that one.

You're already needing to make exceptions for common cases just because "you felt like it". That is indicative of your proposed standard either needing to be commonly circumvented, or that the proposed standard very quickly starts feeling too constrained, which highly negates its value as a broadly used standard.

A neat side-effect would also be that going crazy deep on inheritance is kinda discouraged.

Quite the contrary. In any enterprise grade application, the depth of inheritance tends to be incredibly shallow compared to the breadth of the codebase (i.e. how many non-inheriting classes there are that are genetically unrelated to one another).
All of these non-inheriting classes would live in the same folder, which would become a maintenance nightmare. People would really want to subdivide them further, into logical groups that make sense to the humans working with the code (like you've already done yourself by making a special group for controllers).
But since your proposed system demands that the file tree and inheritance tree are the same, this wrongly incentivizes developers who want to subdivide your non-inheriting classes to invent "fake base classes" just so they can get away with sorting things neatly into folders. In other words, you're going to end up with more inheritance than you did before.
Much like your single-project attitude, the idea that you think that having a wide-but-not-deep file structure (i.e. shallow inheritance leads to a wide, not deep, folder structure) makes me suspect that you are currently working in relatively small and lightweight codebases where it's easy enough to keep the whole codebase in view.
Because you're working in a lighter codebase, any flaws of your approach don't weigh very heavy. You're able to mentally cope with the drawbacks, and some of the benefits make sense from your perspective.
But this is a biased view. Most projects are not like yours.
I can tell you now, hand on heart, that I would quit my current project if I had to see our 3700+ base classes in both the same project and directory folder (I just did a search through our codebase for non-inheriting classes across the solution). And keep in mind that this is not a spaghetti codebase, but an above-averagely clean architecture with a company which very much prioritizes a clean, loosely coupled and long term sustainable approach, instead of banging things out and cutting corners for short deadlines to please their client.


text:
Q: Passing an int variable to another activity makes the app crash,using putExtras I am trying to pass a specific int variable through to another class but it crashes the program. Please have a look:
First activity
public void highQuiz(View view){

    Intent j= new Intent(this,HighScoreTable.class);

    j.putExtra("new_variable_name",(int)lowerInt);

    startActivityForResult(j, 0);   }

Second activity
    TextView hs1 = (TextView)findViewById(R.id.textView1);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        int lowerInt= extras.getInt("new_variable_name");
        hs1.setText(""+lowerInt);
    }

Log
04-29 18:36:21.243: E/AndroidRuntime(2104): FATAL EXCEPTION: main

04-29 18:36:21.243: E/AndroidRuntime(2104): Process: oxley.It, PID: 2104

04-29 18:36:21.243: E/AndroidRuntime(2104): java.lang.RuntimeException: Unable to start activity ComponentInfo{oxley.It/oxley.It.HighScoreTable}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.ActivityThread.access$800(ActivityThread.java:144)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.os.Handler.dispatchMessage(Handler.java:102)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.os.Looper.loop(Looper.java:135)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.ActivityThread.main(ActivityThread.java:5221)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at java.lang.reflect.Method.invoke(Native Method)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at java.lang.reflect.Method.invoke(Method.java:372)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

04-29 18:36:21.243: E/AndroidRuntime(2104): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

04-29 18:36:21.243: E/AndroidRuntime(2104):     at oxley.It.HighScoreTable.onCreate(HighScoreTable.java:25)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.Activity.performCreate(Activity.java:5933)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)

04-29 18:36:21.243: E/AndroidRuntime(2104):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)

04-29 18:36:21.243: E/AndroidRuntime(2104):     ... 10 more

A: From stack track looks like textview is null
    TextView hs1 = (TextView)findViewById(R.id.textView1);

Make sure you have defined the textview and its not null after you do findViewById.

A: While starting the activity you are keeping that integer value in intent. and while reading in second activity you are getting it from Bundle which is inside the intent so you are not getting.
so read that integer value from intent.
TextView hs1 = (TextView)findViewById(R.id.textView1);
Intent i=getIntent();
i.getIntExtra("new_variable_name",0);
hs1.setText(""+lowerInt);

A: try
         if(getIntent().hasExtra("new_variable_name"))
                  getIntent().getIntExtra("new_variable_name");

A: In your First Activity
change
j.putExtra("new_variable_name",(int)lowerInt);

to
j.putExtra("new_variable_name",lowerInt);

No need to Parse value to integer.
and then in you Second Activity
Change
Bundle extras = getIntent().getExtras();
    if (extras != null) {
        int lowerInt= extras.getInt("new_variable_name");
        hs1.setText(""+lowerInt);
    }
to
     Bundle extras = getIntent().getIntExtra();
if (extras != null) {
    int lowerInt= extras.getIntExtra("new_variable_name");
    hs1.setText(String.valueOf(lowerInt));
}


text:
Q: How do I find out when badges were awarded to me? I got quite a nice collection of badges in the mean time, so I pretty much lost the overview when which badge was awarded to me. I tried hovering over the badges on the badges-page of my profile, but that didn't reveal when the badge was awarded to me.
Ho do I know when I received a badge?

A: Also with this answer, you can see in activity tab-> badges subtab in your profile.

A: Click on a badge on your profile

You'll see the date there:

Note that the badges were not awarded all at once.

A: Click on the badge. The page will tell you when you got it (or the multiple times when you did).


text:
Q: readv() failed on PROPFIND request while reading php://input (PHP 7, nginx) After upgrading my Server to PHP 7 I get several errors while running ownCloud in its current version 8.1.1.
I tried to figure out what the problem is and I came down to Sapi.php of Sabre lib.
I wrote a very small test script to isolate the error. While running the following code using a PROPFIND request, I see errors in the log and I don't get any output out of php://input.
<?php
    fopen("php://input", 'r+');
    echo "Done";
?>

Request using cURL:
curl -i -X PROPFIND https://cloud.example.com/readv-demo.php  -d 'Demo'

Error in nginx error log:
*285599 readv() failed (104: Connection reset by peer) while reading upstream, client: 5.35.252.37, server: cloud.example.com, request: "PROPFIND /readv-demo.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "cloud.example.com"

The server worked like a charm using PHP 5.6 and I tried to run PHP 7 without modifications. Everything on server-side is fine but this error.
I also tried suggestions to get around readv() errors and modified several settings like:
max_input_time = ...
max_execution_time = ...
default_socket_timeout = ...
request_terminate_timeout = ...


text:
Q: User unable to remember google console login details I created a google cloud instance for a client and handed over the details to them but now, they don't know the google console email address. They know the IP because the app deployed there is still running. It may be time to pay soon and not knowing the console detail means they will not be able to pay.
Is there a way to get the details from the IP address of the console instance?

A: Without being able to login to the Google Cloud Console, you will have problems.
Note: I am listing contact Google Support as a last example because you do not have paid Google Support. Google Support only offers billing question support for free. Since you cannot sign into the Google Cloud Console, you cannot sign up to pay for support. However, losing your login might qualify as billing support since you need to pay for your services to keep them running.
Techniques:

*

*If you have access to a computer that has logged into the Google Cloud Console, try. A list of Google Accounts will be displayed to choose from. No guarantee, but usually people do not delete old accounts from Google Accounts. Try each one to access the Google Console. If you / they have forgotten the password, go thru the lost password process.

*When you sign up for Google Cloud, emails are sent to the account email address. Have everyone do a search for Google Cloud. My welcome email came from CloudPlatform-noreply@google.com.

*If you have created a Service Account, the json file will have the Project ID. This is globally unique and Google could lookup the account holder and send that person an email. Contact Google Support in this case.

*If you have a system that you setup the gcloud tools on for this project, run the command gcloud auth list. This will display the authenticated accounts. Usually one of them is a Google Accounts account that can login to the Google Console.

*Google Support can map the public IP address to an account. Contact Google Support in this case.


text:
Q: Load/Append multiple contents together with $('#id').html(contents) failing to load Load content is failing with jQuery $('#id').html() when I try to load below contents in Chrome/Edge. Same is working in IE11
Working on IE11 to Chrome/Edge migration
Issue - Style and div contents were loading with .html() but when it encounters JavaScript block, it fails to load. Unable to find respective functions further
Contents structure is
    var contents = "

";

$('#id').html(contents);


text:
Q: Colocar uma string corrida dentro da clausula IN do sql como se fosse um array Olá, necessito colocar dentro de uma cláusula IN do SQL um item que é string e precisa ser tratado como se fosse um array de string, utilizo o Oracle apex.
Tenho um item de página por exemplo :P10_CODIGO_PROJETO que contem o valor 'PJ8674,PJ8804,PJ8480'
Exemplo que eu tenho
SELECT * FROM PROJETOS WHERE CODIGO_PROJETO IN ('PJ8674,PJ8804,PJ8480')

porém o select acima me retorna no_data_found pois ele acha que o código do projeto é corrido mas o eq eu precisaria era que fosse como um IN mesmo
SELECT * FROM PROJETOS WHERE CODIGO_PROJETO IN ('PJ8674','PJ8804','PJ8480')

por acaso existe alguma função em PL/ SQL que possa me auxiliar neste problema?
objetivo

A: Da pra fazer utilizando a função INSTR e alterando um pouco sua condição de pesquisa.
Exemplo:
SELECT *
  FROM PROJETOS
 WHERE INSTR(',' ||'PJ8674,PJ8804,PJ8480' || ',',  ',' || CODIGO_PROJETO || ',') > 0

Veja este exemplo rodando aqui.
Essa condição representa o seguinte:
Procure por: ,PJ8674,
Dentro desse texto: ,PJ8674,PJ8804,PJ8480,.
Alguns contras:

*

*Não funciona caso o tamanho do parâmetro ultrapasse 4000 bytes.

*Não irá funcionar corretamente se os valores da coluna não forem uma chave.

*Se torna lento quando há muitos códigos dentro do mesmo parâmetro.


text:
Q: создане проекта selenide-testng-allure Здравстрвуйте, кто-то может помочь с pom-файлом под проект selenide-testng-allure? Т.к. я нашел на гите, но после прохождения теста пишет что репорт сломан..

A: Пробуй, у меня эта помка работает отлично!! Если что пиши
<properties>
    <java.version>1.8</java.version>
    <aspectj.version>1.8.10</aspectj.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.21.0</version>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>${project.basedir}/testng.xml</suiteXmlFile>
                </suiteXmlFiles>
                <testFailureIgnore>true</testFailureIgnore>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
    </dependency>

    <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-testng</artifactId>
        <version>2.6.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.25</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<reporting>
    <excludeDefaults>true</excludeDefaults>
    <plugins>
        <plugin>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-maven</artifactId>
            <configuration>
                <reportVersion>2.6.0</reportVersion>
            </configuration>
            <version>2.9</version>
        </plugin>
    </plugins>
</reporting>


text:
Q: How to do reusable function in react I am new in react stuff. My code structure look like this:
App - Calls - CallsChart - chart1
                         - chart2
                         - ...
    - Home  - HomeCharts - chart3
                         - chart4 ...
    - filter bar
    - type bar
    - navigation bar

So every dashboard (Calls, Home...) has bars and charts inside. But when user click on chart to generate new filter, I need this value to propagate from chart1 - CallsChart - Calls - App - filter bar. I am passing these parameters in props. For example:
//get filter
clickFilter(filter){
    this.props.chartFilter(filter);
}

But I need to define these basic function on every level of the way up (and down). How can I make these functions reusable? Define them only once and use them in every dashboard? I have found out that react doesn't have inheritance but it uses composition. I can't make this because I am just passing a parameter to parent.

A: As Dupocas said, you can wrap all your components in a top level component who manages your state. But also, if that is not your preference for your application, you can use React Redux to manage the application state as a single state changed only by actions. You can learn more at Using React Redux.

A: Inheritance in react is acomplished by hierarchy, if you need to propagate state to other components a elegant solution would be to wrap your components on a stateful parent component. In this way you fetch all the data you need and then distributes to it's children via props.


text:
Q: CFBundleLocalizations info.plist - How to put multiple languages I cannot find the answer for this question anywhere. I'm new to Xcode. I have developed two multilanguage iPhone apps and cannot upload them to iTunes Connect because I'm getting the famous error "the value for the info.plist key cfbundlelocalizations is not of the required type for that key". Everybody says that it's because I need to put there an array of values, but I don't know how to do it. If I need for example, English and French, what should I to put there? Something like this (0=en, 1=fr)?

A: The plist editor in Xcode seems to insist that it should be a string... if you want an array, try opening the plist file in a text editor, and adding this after a value:
    <key>CFBundleLocalizations</key>
    <array>
        <string>English</string>
        <string>French</string>
    </array>

so your plist would look like this:
...
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleLocalizations</key>
    <array>
        <string>English</string>
        <string>French</string>
    </array>
...

A: I was able to add German with English like so:
Changed:
<key>CFBundleDevelopmentRegion</key>
<string>en</string>

To:
<key>CFBundleLocalizations</key>
<array>
  <string>en</string>
  <string>de</string>
</array>


text:
Q: How is $U=\{x\in X | d(p,x)>r\} $ open? I know that $U=\{x\in X | d(p,x)<r, p\in X\}$ is open but in one of my exercises I am asked to show that $U$ is open if $U=\{d(p,x)>r\}$. I am not sure if I follow since this contradicts the definition of an open set.

A: The set $ U $ is indeed open - it's just not an open ball. The definition of an open set is that for every point $ x \in U $ there exists an open ball of finite size $ a $ centered at $ x $ such that for every point $ y $ in the ball, $ y \in U $. Let's say $ x $ is distance $ s > r $ from $ p $. You can use the triangle inequality (which is a property of distance metrics) to show that all points in a ball of radius $ a = \frac{s - r}{2} $ around $ x $ are in $ U $.
Proof: Let's say $ d \left ( p, x \right ) = s $ and $ d \left ( x, y \right ) < \frac{s - r}{2} $. The triangle inequality says:
\begin{align}
d \left ( p, y \right ) + d \left ( y, x \right ) & \geq  d \left ( p, x \right ) \\
d \left ( p, y \right ) + d \left ( y, x \right ) & \geq s \\
d \left ( p, y \right ) & \geq s - \frac{s - r}{2} = \frac{s + r}{2} > r
\end{align}
$ U $ is, as you correctly pointed out in the comments, not an open ball itself. This Wikipedia article explains how an open set is defined in terms of open balls.

A: Let $X$ be some metric space with a metric $d$.
Definition: An open BALL, $B_r{x}$ (or some similar notation) is the set of $\{y \in X| d(y,x) < r\}$. This is nothing more or less than a set of points.
Definition: An open SET is a set, $S$ so that for every point, $x \in S$ there exists some value $r > 0$ so the $B_r(x) \subset S$.  These sets can be ... all sorts of "shapes and sizes".  Being open is a property.
So for example:  $(-\infty, 1)$ is an open set.   The point $0.9999999$ is has an open ball completely inside but $(0,1)$. If $r = .00000001$ then $\{y|d(0.9999999,y) < 0.00000001\} = (0.9999998,0.99999991) \subset (-\infty, 1)$.
That's one point that has an open ball.  Because that point was so very, very close to "the edge" we had to find an open ball with a very, very small radius to fit in in $(-\infty, 1)$.  But that doesn't have an effect on the radius of $S$ itself.
But we can't show $(-\infty, 1)$ is open, just by showing one point.  We have to prove it for all $x\in (-\infty, 1)$.
For $x \in (-\infty, 1) $ we know $x < 1$ let $r = 1 -x$.  Then $B_r(x) = \{y| d(x,y) < 1- x\}$ so $y< x + (1-x) = 1$.  So $y \in (-\infty, 1)$ so $B_r(x) \subset S$.
As this is true for any $x \in (-\infty, 1)$ we know $(-\infty, 1)$ is open.
Now an example of a set that is NOT open is $(0, 1]$.  Let $r > 0$ then $B_r(1)$ contains $y$ that are larger than $1$.  This will be true no matter how small we make $r$.  So $B_r(1) \not \subset (0, 1]$.  So $(0,1]$ is not open.
So what about $U= \{x\in X|d(x,p) > r\}$ is that open or not.
Hint:
Let $x \in U$. Then $d(p,x) >r$ Let $s < \frac 12*(d(p,x) - r)$.  Is $B_s(x) \subset U$?
Hint for that question:  Let $z \in B_s(x)$.  Is $z \in U$?  What is $d(p,z)$?  Is $d(p,z)> r$
Hint for THAT question: What is $d(p,x)$?  What is $d(x, z)$ what is $d(p,x) + d(p,z)$?


text:
Q: JavaScript get first name and last name from string as array I have a string that has the following format: FirstName LastName
How can I change this into an array with the first element firstName and second lastName?
I did this, but no luck, it won't produce the right result:
var data = [myString.split('')[1], myString.split('')[2]]

How can I produce ["firstName", "lastName"] for any string with that format?

A: In order to parse HTML, use the best HTML parser out there, the DOM itself!

// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');

// set the innerHTML to your string
parser.innerHTML = "FirstName LastName";

// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;

// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");

// voila!
console.log(data);

EDIT
As @RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:

var parser = new DOMParser();
var doc = parser.parseFromString("FirstName LastName", "text/html");

console.log(doc.body.textContent.split(" "));

However, both methods work perfectly fine; it all comes down to preference.

A: Just match everything between  and .

var matches = "FirstName LastName".match(/(.*)<\/strong>/);
console.log(matches[1].split(' '));

A: The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.

let str = 'FirstName LastName';

let [,first, last] = str.split(/<[/\w\s-]+>|\s/g);

console.log(first, last);

/<[/\w\s-]+>|\s/g

Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.
Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""].

A: this is my approach of doing your problem. Hope it helps!
var str = "FirstName LastName";
var result = str.slice(0, -9).substr(8).split(" ");

Edit: it will only work for this specific example.

A: Another way to do this in case you had something other than an html

var string = "FirstName LastName";
string = string.slice(0, -9); // remove last 9 chars
string = string.substr(8); // remove first 8 chars
string = string.split(" "); // split into an array at space

console.log(string);


text:
Q: Prevent focus to call blur functionality I am validating an email address and creating an alert message if the validation fails. When user clicks "Ok" on the alert message, focus should be returned to email address text box.
I am facing a problem with focus functionality which is calling blur and blur functionality in turn again calls focus. It is running in infinite loop. Pls refer example below -
BlurAndFocusIssue
input.onblur = function() {
  samp.innerHTML="Called blur";
  if (!input.value.includes('@')) {
    input.classList.add('invalid');
    alert('Please enter a correct email.');
    document.getElementById("input").focus();
  }
};

input.onfocus = function() {
  samp.innerHTML="Called focus";
  if (this.classList.contains('invalid')) {
    this.classList.remove('invalid');
    error.innerHTML = "";
  }
};

Once focus is inside email address, i need to allow the user to enter the email address and get it validated on onBlur functionality..

A: Use setTimeout() to control Onblur
JSFiddle
input.onblur = function() {
  samp.innerHTML="Called blur";
  var validating = false; //<-- IMPORTANT
  if (!input.value.includes('@')) {
    input.classList.add('invalid');
     if(validating == false) {
              validating = true
              alert('Please enter a correct email.');
              setTimeout(function(){
              input.focus();
              validating = false;
            }, 1);
     }
  }
};

input.onfocus = function() {
  samp.innerHTML="Called focus";
  if (this.classList.contains('invalid')) {
    this.classList.remove('invalid');
    error.innerHTML = "";
  }
};


text:
Q: Updating a JFrame with the component from another method I am trying to add JPanel p4 to the JFrame but it doesn't seemed to work.
import java.awt.*;
import javax.swing.*;

public class Class4 {

    public static final long serialVersionUID = 1L;

    public JFrame f = new JFrame("Love Test");

    public void mainMethod(int event){

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500,200);
        f.setLayout(new GridBagLayout());

        if(event == 0){

            GridBagConstraints gbc = new GridBagConstraints();

            JPanel p = new JPanel();
            p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
            p.setBounds(150, 0, 500, 75);
            p.setPreferredSize(new Dimension(350,75));
            JTextField boy = new JTextField();
            boy.setMaximumSize(new Dimension(200,40));
            JTextField girl = new JTextField();
            girl.setMaximumSize(new Dimension(200,40));
            p.add(boy);
            p.add(girl);
            gbc.insets = new Insets(-90,310,0,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p,gbc);

            JPanel p3 = new JPanel(new BorderLayout());
            p3.setBounds(0, 0, 150, 75);
            p.setPreferredSize(new Dimension(150,75));
            Class5 c5o = new Class5();
            c5o.setPreferredSize(new Dimension(150,75));
            p3.add(c5o);
            gbc.insets = new Insets(0,0,90,330);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p3,gbc);

            JPanel p2 = new JPanel(new FlowLayout());
            Class7 c7o = new Class7();
            p2.add(c7o);
            p2.setPreferredSize(new Dimension(300,40));
            gbc.insets = new Insets(0,0,-20,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p2,gbc);

            f.setVisible(true);

        }

        if(event == 5){

            addLove();

        }

    }
    public void addLove(){

        GridBagConstraints gbc = new GridBagConstraints();
        JPanel p4 = new JPanel();
        p4.setBounds(0,120,500,55);
        Class2 c2o = new Class2();
        Dimension d2 = new Dimension(500,55);
        c2o.setPreferredSize(d2);
        p4.setPreferredSize(d2);
        p4.add(c2o);
        gbc.insets = new Insets(0,0,-130,0);
        gbc.gridx = 0;
        gbc.gridy = 0;
        f.add(p4,gbc);

        f.invalidate();
        f.validate();
        f.repaint();

        JOptionPane.showMessageDialog(null, "Test");
    }

}

However, if I twisted the code to what is shown below, JPanel p4 will be added to the JFrame.
import java.awt.*;
import javax.swing.*;

public class Class4 {

    public static final long serialVersionUID = 1L;

    public JFrame f = new JFrame("Love Test");

    public void mainMethod(int event){

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500,200);
        f.setLayout(new GridBagLayout());

        if(event == 0){

            GridBagConstraints gbc = new GridBagConstraints();

            JPanel p = new JPanel();
            p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
            p.setBounds(150, 0, 500, 75);
            p.setPreferredSize(new Dimension(350,75));
            JTextField boy = new JTextField();
            boy.setMaximumSize(new Dimension(200,40));
            JTextField girl = new JTextField();
            girl.setMaximumSize(new Dimension(200,40));
            p.add(boy);
            p.add(girl);
            gbc.insets = new Insets(-90,310,0,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p,gbc);

            JPanel p3 = new JPanel(new BorderLayout());
            p3.setBounds(0, 0, 150, 75);
            p.setPreferredSize(new Dimension(150,75));
            Class5 c5o = new Class5();
            c5o.setPreferredSize(new Dimension(150,75));
            p3.add(c5o);
            gbc.insets = new Insets(0,0,90,330);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p3,gbc);

            JPanel p2 = new JPanel(new FlowLayout());
            Class7 c7o = new Class7();
            p2.add(c7o);
            p2.setPreferredSize(new Dimension(300,40));
            gbc.insets = new Insets(0,0,-20,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p2,gbc);

            f.setVisible(true);

            JPanel p4 = new JPanel();
            p4.setBounds(0,120,500,55);
            Class2 c2o = new Class2();
            Dimension d2 = new Dimension(500,55);
            c2o.setPreferredSize(d2);
            p4.setPreferredSize(d2);
            p4.add(c2o);
            gbc.insets = new Insets(0,0,-130,0);
            gbc.gridx = 0;
            gbc.gridy = 0;
            f.add(p4,gbc);

            f.invalidate();
            f.validate();
            f.repaint();
        }

        if(event == 5){

            addLove();

        }

    }
    public void addLove(){

        JOptionPane.showMessageDialog(null, "Test");
    }

}

But the JPanel will shown immediately once I run the code. I only want the JPanel to show up after an event(pressing the button). All help will be greatly appreciated. Thanks.


text:
Q: gethostbyaddr too slow I use the following code, results are correct, but gethostbyaddr takes around 30 seconds.
function IPAddrToName(IPAddr: string): string;
var
  SockAddrIn: TSockAddrIn;
  HostEnt: PHostEnt;
  WSAData: TWSAData;
begin
  WSAStartup($101, WSAData);
  SockAddrIn.sin_addr.s_addr := inet_addr(PChar(IPAddr));
  HostEnt := gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
  if HostEnt <> nil then
    Result := StrPas(Hostent^.h_name)
  else
    Result := '';
end;

A: That's unlikely to be an issue with your code (unless WSAStartup is particularly slow).
The first thing I would do is to output the time (preferably to the millisecond, with GetTickCount, I think) in between each of those lines in your code, to find out exactly where the time is being spent.
The gethostbyaddr may well have to go out to a remote DNS machine to resolve the IP address into a hostname.
If your network is set up badly, or the DNS server containing that address is in the remote regions of the Tibetan mountains for example, resolution will take some time.
From your command line, enter:
nslookup x.x.x.x

(where x.x.x.x is the IP address you're interested in) and see how long that takes.
Based on your comment between the ruler lines below:

I am working on LAN with just 3 machines. Also that network is not connected to the internet. It takes 16 secs (+/- some millisecs) for only the line:
HostEnt := gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);

while:
GetHostByName(PChar(HostName));

is instantaneous. Below is the output of Ping (instant output) and nslookup:
c:\> ping 192.168.1.22
Reply from 192.168.1.22: bytes=32 time<1ms TTL=128 Packets:
    Sent = 4, Received = 4, Lost = 0 (0% loss)

c:\> nslookup 192.168.1.22
DNS request timed out.

I think your problem is with that timeout. It appears your network is set up okay for DNS name resolution but not IP reverse resolution.
When you just type nslookup, it should show you your DNS server that it's trying to use and this will probably give you a clue.
c:\pax> nslookup
Default Server:  pax01.neveryoumind.com
Address:  9.190.230.75

It may be that resolving names to IP addresses doesn't go out through DNS but is instead handled with local information.
That's about as much help as I can give you with the current information. Since this now seems very much a SuperUser question now rather than StackOverflow, I'll nudge it over to there.

A: Windows attempts different ways to perform host name resolution depending on the way your hosts and LAN are configured. See http://technet.microsoft.com/en-us/library/bb727005.aspx.
You should not test that code in a LAN which is not correctly configured, either using a DNS server (or at least a WINS one) or correct hosts files. Otherwise you could not get the result you'd expect in a properly configured LAN.


text:
Q: Limitar quantidade de caracteres html css Fiz este input com html + css e está tudo ok, só não cosigo limitar o número de caracteres para 10, tentei o maxlength="10" mas não responde. Alguém pode me ajudar?

<div class="searchBox">
    <input class="searchInput" type="number"  name="localizar" id="localizar" placeholder="numero do cliente">
    <button class="searchButton" href="#">
        <i class="material-icons">
            search
        </i>
    </button>
 </div>

A: A propriedade maxlength não funciona se o tipo do input for "number". Para esse problema, uma solução simples é mudar o tipo para text.

<input class="searchInput" type="text" name="localizar" id="localizar" placeholder="numero do cliente" maxlength="10"/>

Mas se você precisa que o tipo seja número para melhor uso nos celulares, você pode utilizar o tipo "tel" que irá exibir um teclado numérico e o maxlength funcionará do mesmo jeito.

<input class="searchInput" type="tel" name="localizar" id="localizar" placeholder="numero do cliente" maxlength="10"/>

Se por algum motivo você precisar utilizar o tipo "number", a solução será com JavaScript, onde você deverá definir o evento oninput no HTML para executar uma função quando o usuário inserir algo na caixa de texto. Veja o código abaixo:

function maxLen(input) {
  if (input.value.length > 10) {
    input.value = input.value.slice(0, 10);
  }
}
<input class="searchInput" type="number" name="localizar" id="localizar" placeholder="numero do cliente" oninput="maxLen(this)">


text:
Q: How to reposition my jQuery popup? I've got a popup working with jQuery but it is rendering at the same place as the DIV. I'd like the popup to render in the middle of the page. Is it possible? If yes, then how?
My CSS:
.newpopup {
    display:none;
    border: 1px solid black;
    background-color: #eee;
}

HTML:

<button>popup</button>

JavaScript:
function popup() {
    alert('test');
    var popup = $('.newpopup');
    popup.draggable();
    popup.resizable();
    popup.html('
Where is pancakes house?
');
    popup.show('fast');
}
$(document).ready(function(){
  $('button').click(function(){
     popup();
  });
})

A: Set your popup css position : absolute and use top & left properties to set your popup position.
  .newpopup {
    display:none;
    border: 1px solid black;
    background-color: #eee;
    position:absolute;
    top:50%;
    left:50%;
}

EDIT
I created a fiddle , Jsfiddle it works perfectly here, check it out.

A: You need to get the width and height of the screen, and the box you've created
var screen_width = $(document).width();
var screen_height = $(document).height();
var box_width = popup.width();
var box_height = popup.height();

You then need to set position:absolute; on .newpopup. As well as it's top and left positions
var top = (screen_height - box_height) / 2; // you might like to subtract a little to position it slightly higher than half way
var left = (screen_width - box_width) / 2;
popup.css({ 'position': 'absolute', 'top':top, 'left':left });

The code can be condensed, but it's easier to understand split up.
Edit:
You can add the pop-up box to the start of the page by using $(body).prepend(popup);, which will mean it does not get affected by any other element


text:
Q: If T and S are topologically conjugate homeomorphisms, T on X is minimal iff S on Y is minimal. (Definitions inside) Let $X$ and $Y$ be compact metric spaces, $T:X \to X$ and $S: Y \to Y$ homeomorphisms. We say $T$ and $S$ are topologically conjugate if there exists a homeomorphism $\phi: X \to Y$ such that $S(\phi(x))= \phi(T(x))$ for all $x \in X$.
We say a homeomorphism $T$ is minimal if for every $x \in X$, the set $\{T^k x: x\in \mathbb{Z}\}$ is dense in $X$.
The claim is that T is minimal iff S is minimal.
I have tried to show this but to no avail, as I get stuck trying to compare a ball around x with a ball around $\phi(x)$ which unless its an isometry I can not do anything interesting with to get my result. Thanks in advance!

A: It suffices to assume that $T$ is minimal and prove that $S$ is minimal, since the converse follows by the same argument, swapping $(T,S,\phi) \to (S, T, \phi^{-1})$. In metric spaces, we can use sequences.
Take $y \in Y$. We want to prove that $\{ S^ky \mid y \in Y \}$ is dense in $Y$. Let $y_0 \in Y$. Then $\phi^{-1}(y_0) \in X$, and since $T$ is minimal, there is a sequence $(k_n)_{n \geq 0}$ such that $T^{k_n}(\phi^{-1}(y)) \to \phi^{-1}(y_0)$. By continuity of $\phi$, and noting that $\phi \circ T \circ \phi^{-1} = S$ implies $\phi \circ T^{k_n} \circ \phi^{-1} = S^{k_n}$, we obtain $S^{k_n}(y) \to y_0$. Done.

A: It suffices to prove that if $T$ is minimal, then $S$ is minimal. Suppose $\{T^k(x) \mid k\in\mathbb{Z}\}$ is a dense subset of $X$ for each $x\in X$. Fix $y\in Y$. To show that $\{S^k(y) \mid k\in\mathbb{Z}\}$ is dense in $Y$, we let $U$ be a nonempty subset of $Y$. Then $\phi^{-1}(U)$ is a nonempty open subset of $X$, so by the density of $\{T^k(\phi^{-1}(y)) \mid k\in\mathbb{Z}\}$, there exists $k\in\mathbb{Z}$ such that $T^k(\phi^{-1}(y))\in\phi^{-1}(U)$. Therefore $$S^k(y)=S^k(\phi(\phi^{-1}(y)))=\phi(T^k(\phi^{-1}(y)))\in U,$$
as desired.
This shows that not only do we not need $\phi$ to be an isometry, but we don't even require $X$ and $Y$ to be compact or metrizable.

A: The fact you need, which is true for homeomorphisms even when they are not isometries, is this:

*

*for any homeomorphism $\phi : X \to Y$, a subset $A \subset X$ is dense if and only if the image subset $\phi(A) \subset Y$ is dense.

As the other answers show, if $y = \phi(x)$ you can apply this fact using $A = \{T^k(x) \,|\, k \in \mathbb{Z}\}$ and
$$\phi(A) = \{\phi(T^k(x)) \,|\, k \in \mathbb{Z}\} = \{S^k(\phi(x)) \, | \, k \in \mathbb{Z}\} = \{T^k(y) \,|\, k \in \mathbb{Z}\}
$$
You don't need that the homeomorphism is an isometry to prove this fact. You can use the open sets definition of continuity, as the other answers show.
Or, you can use the $\epsilon,\delta$ definition, in the following manner.
Suppose we know that $A \subset X$ is dense. Let's prove that $\phi(A) \subset Y$ is dense. Consider $y \in Y$ and $\epsilon>0$ and the open ball $B(y,\epsilon) \subset Y$. We must find a point of $\phi(A)$ contained in the ball $B(y,\epsilon)$. Let $x = \phi^{-1}(y)$. By continuity of $\phi$, there exists $\delta>0$ such that $\phi(B(x,\delta)) \subset B(y,\epsilon)$. Since $A \subset X$ is dense, there exists $a \in A$ such that $a \in B(x,\delta)$. It follows that $\phi(a) \in \phi(B(x,\delta)) \subset B(y,\epsilon)$, and clearly $\phi(a) \in \phi(A)$.


text:
Q: Can anyone list what are the different types of automation testing could be used to test web application in mobile devices I have done automation for web application using protractor. Now, I need to test the same in mobile device. Could anyone suggest me which tool can be used to test? I have gone through Appium. apart from it, is there any testing tools that could be used to test the protractor script in mobile device?

A: I think You can use Jasmine and karma for testing your application.
http://gonehybrid.com/how-to-write-automated-tests-for-your-ionic-app-part-1/
https://www.joshmorony.com/how-to-unit-test-an-ionic-2-application/


text:
Q: Can I access a variable a different stages of the request pipeline in Ruby on Rails 3 Is there a way of storing a query in a request level cache or is there a best practice I should be following to achieve the same results that I would get using .NET?
I'm a .NET developer who is working on RoR 3 application. I'm new to RoR
I noticed in the logs that the same model queries were happening in multiple places in a single web request. Once in a controller and again via a Helper on a Partial View.
In .NET I could query the DB and store the result in a memory location, this data would be available to any controller, helper, concern or view throughout the life of the request. The memory is released automatically at the end of request pipeline, thus providing much better performance without tight coupling or having to pass models all around and the approach has loose coupling.
RUBY Model
class Location < ActiveRecord::Base
  attr_accessible :latitude, :location, :longitude, :expires_at, :state, :postcode, :city, :country, :source

  def self.sydney
    where(city: 'SYDNEY', state: 'NSW').first unless where(city: 'SYDNEY', state: 'NSW').blank?
  end
end

.NET Model and Call to get DB or Cached data
public class LocationData
{
    public string City { get; set; }

    public string State { get; set; }

    public double Longitude { get; set; }

    public double Latitude { get; set; }
}

public static LocationData GetSydneyData()
{
    # Request Level Dictionary/HashTable

    var requestScopedHashTable = System.Web.HttpContext.Current.Items;

    # 2nd or greater time this method is called in a specific incoming request
    if (requestScopedHashTable.Contains("SydneyData"))
    {
        # Use cached version of the data
        return requestScopedHashTable["SydneyData"] as LocationData;
    }

    # 1st time this method is called in a specific incoming request
    # Query Database, store in request scope object, return the data
    requestScopedHashTable.Add("SydneyData", LocationMode.GetSuburb("Sydney"));

    # Use cached version of the data
    return requestScopedHashTable["SydneyData"] as LocationData;
}

A: First off, this conditional is redundant:
unless where(city: 'SYDNEY', state: 'NSW').blank?

If it's not blank, you'll just execute the same query again to get the result.
The DB adapter used by Rails might be smart enough to cache the query and the result, but it's still not very efficient.
(Also, in this case it's more idiomatic to use any? rather than blank?, as it just checks if the SQL count is greater than 0)
The solution you're looking for is memoization:
class Location < ActiveRecord::Base

  def self.sydney
    @sydney ||= where(city: 'SYDNEY', state: 'NSW').first
  end
end

The snippet above is the typical way to do it, but since ||= relies on the left-operand being truthy, if where().first returns nil the query will still be executed with each invocation.
The question is: what kind of result do you expect? Does Sydney always exist? If it doesn't, and you realistically expect nil, this could be a better approach:
class Location < ActiveRecord::Base

  def self.sydney
    if @_executed
      @sydney
    else
      @_executed = true
      @sydney = where(city: 'SYDNEY', state: 'NSW').first
    end
  end
end

(remember that undefined @ivars evaluate to nil, which is falsy)
If, on the other hand, you expect Sydney to be always present and unmutable (as if it were a static constant that just happens to live in the DB), the best solution is to store it in a CONSTANT and load it only once, on application startup:
class Location < ActiveRecord::Base

  SYDNEY = Proc.new do
    Location.where(city: 'SYDNEY', state: 'NSW').first
  end.call

  def self.sydney
    SYDNEY
  end
end


text:
Q: CasperJS array.push Making Variables Null I have a custom data type that I am populating, I have verified that data populates correctly but when I try to push it to an array the result is both the array and the custom data type variable are null.  Here is an example of what I am doing:
var values = [];
var temp = {};

temp['one'] = rows[i].cells[1].innerText.trim();
temp['two'] = rows[i].cells[2].innerText.trim();
temp['three'] = rows[i].cells[3].innerText.trim();
temp['four'] = rows[i].cells[4].innerText.trim();

values.push(temp);

When I output temp before values.push(temp); all expected values are present. When outputting either values or temp after values.push(temp); both are null.
Very confused, any help is appreciated.

A: Declare array and object like this..
var values = [];
var temp = {};

Example:

var values = [];
var temp = {};

temp['one'] = 'one';
temp['two'] = 'two';
temp['three'] = 'three';
temp['four'] = 'four';

values.push(temp);
console.log(values);

A: This was a dumb mistake on my part, nothing to do with the .push but want to answer for anyone else having the problem.
var values = [];

Was declared outside of any function, I thought I could do this and it would be global but that was a newbie mistake.


text:
Q: How to load a module from a separate `include` directory? My project's tsconfig.json contains this ...
"include": [
    "src/**/*",
    "generated**/*"
]

There are two files src/main.ts and generated/data.json
I would like to import data from 'data.json'; within src/main.ts. I can only make it work if generated/data.json is moved to src.
I am using webpack and ts-loader to output a bundle.
I have tried both using rootDirs and path mapping in tsconfig so that src/main.ts can import data fromdata.json;`, but to no avail.

A: If your import statements contain no relative specifiers (i.e., is just something like import data from "messages.json"), you will ONLY look in node_modules if your "moduleResolution" is "Node" (which is the most common).
I think a good solution for you might be to use the path mapping feature of the compiler (described here: https://www.typescriptlang.org/docs/handbook/module-resolution.html). You can then import your data using import data from 'generated/messages.json' if you set up the path mapping for generated to point wherever you want. That way you can avoid using the relative specifiers if that is what you want to avoid.
If that doesn't give you what you want, I'd recommend parsing through here https://www.typescriptlang.org/docs/handbook/module-resolution.html as that will give you basically all your options (unless you want to use a more complicated build system like webpack).


text:
Q: Java code to convert decimal to hexadecimal with Bitwise operators I have this code to convert decimal to hexadecimal, but I need it to work for numbers greater than 255.
        int v = 13;
        String hexV = "";
        for (int i=0; i<2; i++) {
            int rem = v & 15;
            v = (byte)(v >> 4);
            hexV = "0123456789ABCDEF".charAt(rem) + hexV;
        }
        System.out.println("V: " + hexV);

This code works great for numbers up until 255 but I need it to work for a much larger range. Given this code, how can I change it to work for larger numbers? Specifically the range (-524288 - 524287). I don't want to use toHexString or methods similar, I'm just trying to work with the code that I'm given.
I've tried changing the loop from i<2 to i<3 up to i<6 to accommodate for the extra places in the hexadecimal conversion but the result is never accurate. Usually the last two digits are correct and the rest of it isn't.

A: Run the loop until v becomes 0 and remove the cast to byte.
String hexV = "";
while (v > 0) {
    int rem = v & 15;
    v >>= 4;
    hexV = "0123456789ABCDEF".charAt(rem) + hexV;
}


text:
Q: Populating an NSPopUpButtonCell with string values I am trying to populate a NSPopUpButtonCell with a list of strings.  In -(init), I populate an NSArray with the values I want in the PopUp Button.  How do I connect this to the NSArrayController I added in IB?  Does my app delegate need an IBOutlet NSArrayController to connect to or is there a way to bind it?
Also, when I bind the NSArrayController to the NSPopUpButtonCell, do which Content do I bind it to?  Content or Content Values?
jorj

A: Bind the array controller's Content Array to your controller's array of strings. Bind both the pop-up button cell's Content and Content Values to your array controller's arrangedObjects.
Presumably, you also want to know which of these strings is selected. To do that, bind the pop-up button cell's Selected Object (which will be one of the objects in Content) to a property of your controller (the one that owns the original array).


text:
Q: MySQL search users, order friends above others
*

*I have a feature to search for users on my website,

*I also have a feature for friends on my site.

*I have a query to search for the correct users on my site, and

*I have a query that determines the users that a user is friends with, they both work as they should,

so what i need assistance with is combining the two, to order friends before other users.
Search query:
SELECT userID, fname, lname,
FROM names
WHERE (
    fname LIKE '".$term."%'
    OR lname LIKE '".$term."%'
    OR CONCAT(fname, ' ', lname) LIKE '".$term."%'
      )
AND userID!=$session
ORDER BY fname ASC, lname ASC
LIMIT 10

Friends query:
SELECT CASE WHEN userID=$session
            THEN userID2
            ELSE userID
            END AS friendID
FROM friends
WHERE (
       userID=$session
       OR userID2=$session
       )
AND state='1'

so, a statement that would compare the two should be something like, IF names.userID=friends.friendID
Now I found a users suggestion for a similar issue on stackoverflow that seems like it would be a simple way of doing this, however I'm not entirely sure how to add it with my particular friends query, as it's more of a complex query.
SELECT
    posting.id,
    IF(a.friend_id = b.criteria, 1, 0) AS is_friend
...
ORDER BY is_friend DESC, posting.id DESC

A: Use an outer join (left join) to join the user list returned by your first query with the friend list that your second query produces. Now you'll be able to sort on the fact whether the second row set has a match: if it does, the corresponding row should go first.
This is an example of how you could implement the above:
SELECT
  n.userID,
  n.fname,
  n.lname
FROM names n
LEFT JOIN (
  SELECT CASE WHEN userID=$session
              THEN userID2
              ELSE userID
              END AS friendID
  FROM friends
  WHERE (
         userID=$session
         OR userID2=$session
         )
  AND state='1'
) f
ON n.userID = f.friendID
WHERE (
    n.fname LIKE '".$term."%'
    OR n.lname LIKE '".$term."%'
    OR CONCAT(n.fname, ' ', n.lname) LIKE '".$term."%'
      )
AND n.userID!=$session
ORDER BY (f.friendID IS NULL), n.fname ASC, n.lname ASC
LIMIT 10

The first sorting criterion, (f.friendID IS NULL), evaluates to false if there's a matching f row, i.e. if the user is a friend, and to true otherwise. Consequently, since false sorts before true, the friends will be sorted before non-friends.


text: Q: Instance Segmentation and Object Detection on C++ on custom dataset? I am aware that I can perform object detection, and instance segmentation on YOLO networks in C++, but only on the coco dataset. Is there a way I can run the YOLO network in C++ but trained on a custom dataset?


text:
Q: make subdomain on IIS point to specific folder on other server i have a domain that i have full access to the IIS, and it hosts the main website.
i want to make a subdomain retrive files from another server (Media Temple grid hosting), in an specific path.
for example:
mysubdomain.domain.com (my IIS server)
get files from www.otherdomainandserver.com/sites/comunidade (Media Temple hosting)
i was able to set the IP address on the A Record, but i can't point to the correct folder that has the files, the specific path.
any thoughts on that?
thank you very much.

A: *

*Under your main domain's (domain.com) website right click and add new "Virtual Directory".

*On Add Virtual Directory dialog give whatever name (mysubdomain) you want to give in "alias" field. In physical path field give network folder's path and click ok.

*Right click on Virtual directory created in step 2 and select "Convert to Application"

*Make sure that app pool identity under which your subdomain app is running has at least read access to network folder.

Remember you can not map your subdomain application's physical path to virtual path from some other application's virtual path i.e.(www.otherdomainandserver.com/sites/comunidade). It has to be physical path e.g. \\myotherserver\myfoldertomap

A: I have found another way and that is less technical but let me share with you hope that will solve your problem.
Domain which you want to park to another server subfolder need to change the dns with another server DNS and addon that domain to the server where you want to point...while doing the addon process your cpanel would ask where you would like to point the directory and save this...BINGO the work is done you domain is pointed to another server directory.


text:
Q: Apache Rewrite: Redirect all pages except a few to the home page I am using Apache 2.2.3 for several domains and, for one of those domains, I am trying to redirect all pages with the exception of a few (say, page1 and page2) to the root www.domain2.com.  I want all other sites to be unaffected.
(The following should resolve to www.domain2.com/page1)
www.domain2.com/page1
(The following should resolve to www.domain2.com)
www.domain2.com/page3
The following is what I am trying and it is not working.  Essentially, for all requests to www.domain2.com I want all pages (save page1 and page2) to resolve to the root (www.domain2.com). I am having trouble with the negation (all pages except):
RewriteCond %{http_host} ^.*domain2\.com [nc]
RewriteRule ^.*domain2.com!(|/|/page1|/page2)$ http://www.domain2.com [r=301,nc,L]

A: This would redirect everything requested at domain2 (except page1 and otherpage) to the equivalent page at domain1

RewriteCond %{HTTP_HOST} ^.*.domain2.com [NC]
RewriteCond %{REQUEST_URI} !^/page1.html
RewriteCond %{REQUEST_URI} !^/otherpage.html
RewriteRule ^/(.*)$ http://www.domain1.com/$1 [R=301,L]

Example: www.domain2.com/index.html -> www.domain1.com/index.html
Duplicate the rewriteconds inside (or use regex like !^/(page1|otherpage)\.html as you need.


text:
Q: Is it possible to change the 'colormap' scale in Matlab? I have 2 matrices. Matrix A contains values between 0 and 1 and matrix B contains values between 0 and 90. I would like to display an image with a different color for the numbers in each matrix.
When I use the colormap function with:
figure; colormap(jet); imshow(A);

The image displayed has several levels of gray, when I am supposed to have several colors (because I am using jet).
When I use the colormap function with:
figure; colormap(jet); imshow(B);

The image displayed is completely white, probably because my values are higher than 64 (which is the max of jet).
How can I solve these two problems? I read a lot of tutorials in several forums but I can't find the answer...
Thank you very much for answering my problem!

A: Just normalize the matrix by its max value if the values are more than 1. So for your B matrix try:
imshow(B/max(B(:)))

A: You can specify the colormap scaling and the number of actual colors within the colormap like so:
figure; imshow( A, [0 1], 'Colormap', jet(100) );
figure; imshow( B, [0 100], 'Colormap', jet(100) );

The jet(100) indicates 100 unique colors within the colormap to be used.

A: You are using the wrong function for the task in hand.
imshow expects an N by M by 3 array input, of the RGB channels of an image. When you use a 2D matrix the function assumes it's a grayscale image (it's like replicating it to 3 identical matrices to create these three channels - if all the channels in RGB have the same values you get grayscale colors). You can use this function together with a colormap to get a colored matrix, but there are much more convenient alternatives.
One simple function for getting a colored representation of a matrix is imagesc or (image if you want to scale the values by yourself). This function takes the values in your matrix, and assign them a color from the colormap you choose:
A = rand(10);
figure; colormap(jet); imagesc(A);

Another option is pcolor, which works a little different but give a similar result. pcolor attach the values to the vertices of the cells (in oppose to the center, as imagesc does), and interpolate the color in each cell from its' vertices. The resulted colored matrix is always smaller in one row and one column because it takes n+1 points (values in the original matrix) to define n gaps (the cells in the colored matrix). Here is an example:
A = rand(10);
figure; colormap(jet); pcolor(A);
shading flat


text:
Q: Selecting and retrieving data from a class with a combo box My current set up has a class with only 2 variables currently (string type and int amount).
I override the ToString to print both of those things together. In my form I instantiate different instances of this class and populate the combo box just fine, it prints my override.
My question is how do I determine which instance is being selected? I can use selecteditem to retrieve my tostring override fine, but what if i want to alter the amount variable of a specific instance if its selected?
SelectedItem.Instance.VariableName
I imagine it would be something like this, I'm just not familiar with that syntax.

A: You can add the object to the combobox and then use Display member to determine which property is shown.
https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember(v=vs.110).aspx

A: Well, that depends on how you populate the data into your ComboBox. For instance, if you use data binding, you can do something like the following:
    Dictionary<string, YourClass> dict = new Dictionary<string, YourClass>();
    for (int x = 0; x <= 5; x++)
    {
        YourClass instance = new YourClass("Test", x);
        dict.Add(instance.ToString(), instance);
    }

    ComboBox1.DataSource = new BindingSource(dict, null);
    ComboBox1.DisplayMember = "key";
    ComboBox1.ValueMember = "value";

So you can easily interact with the interact with each instance based on the selected item of your ComboBox:
    Console.WriteLine(((YourClass)ComboBox1.SelectedValue).amount.ToString());

Hope that helps :)

A: Create a List<> of your instances and set that as the DataSource() of your ComboBox.  Then you can retrieve the selected item, update it somehow, then reset the DataSource causing the ComboBox to display the new values:
    private List<Thing> things = new List<Thing>();

    private void Form1_Load(object sender, EventArgs e)
    {
        Thing thing1 = new Thing();
        thing1.Item = "Bob";
        thing1.Value = 411;

        Thing thing2 = new Thing();
        thing2.Item = "Joe";
        thing2.Value = -1;

        things.Add(thing1);
        things.Add(thing2);

        comboBox1.DataSource = things;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (comboBox1.SelectedIndex != -1)
        {
            Thing thing = (Thing)comboBox1.SelectedItem;
            // now do something with "thing":
            thing.Value = thing.Value + 1;

            // reset the ComboBox to update the entries:
            comboBox1.DataSource = null;
            comboBox1.DataSource = things;
            comboBox1.SelectedItem = thing;
        }
    }

With Class Thing:
public class Thing
{
    public string Item = "";
    public int Value = 0;

    public override string ToString()
    {
        return Item + ": " + Value.ToString();
    }
}


text:
Q: link doesn't work in the my slider When I added links to the following slides, the only link that I am able to link to is the last slide no matter what I put. Is there any way I can use this slide code and also have the link works properly the same time?
html

<input type="radio" name="radio-btn" id="img-1" checked />

        ‹
        ›

<input type="radio" name="radio-btn" id="img-2" />

        ‹
        ›

<input type="radio" name="radio-btn" id="img-3" />

        ‹
        ›

<input type="radio" name="radio-btn" id="img-4" />

        ‹
        ›

css
.slides {
    padding: 0;
    width: 980px;
    height: 241px;
    display: block;
    margin: 0 auto;
    position: relative;
}

.slides * {
    user-select: none;
    -ms-user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
}

.slides input { display: none; }

.slide-container { display: block; }

.slide {
    top: 0;
    opacity: 0;
    width: 980px;
    height: 241px;
    display: block;
    position: absolute;
    transition: all .7s ease-in-out;
}

.slide img {
    width: 100%;
    height: 100%;
}

.nav label {
    width: 40px;
    height: 100%;
    display: none;
    position: absolute;
    opacity: 0.5;
    z-index: 9;
    cursor: pointer;
    transition: opacity .2s;
    color: #FFF;
    font-size: 50pt;
    text-align: center;
    line-height: 225px;
    font-family: "Varela Round", sans-serif;
    background-color: rgba(255, 255, 255, .3);
    text-shadow: 0px 0px 15px rgb(119, 119, 119);
}

.slide:hover + .nav label { opacity: 0.5; }

.nav label:hover { opacity: 1; }

.nav .next { right: 0; }

input:checked + .slide-container  .slide {
    opacity: 1;
    transition: opacity 1s slide;
}

input:checked + .slide-container .nav label { display: block; }

.nav-dots {
    width: 100%;
    bottom: 9px;
    height: 11px;
    display: block;
    position: absolute;
    text-align: center;
}

.nav-dots .nav-dot {
    top: 0px;
    width: 10px;
    height: 10px;
    margin: 0 4px;
    position: relative;
    border-radius: 100%;
    display: inline-block;
    background-color: rgba(0, 0, 0, 0.6);
}

.nav-dots .nav-dot:hover {
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.8);
}

js
setInterval(function(){
$(".next:visible").click();}, 5000);

Here is my codepen
Thanks.

A: There was a css issue regarding z-index. I have given a z-index value of 10 to the active slide corresponding to checked radio button.
input:checked + .slide-container  .slide {
   opacity: 1;
   z-index: 10;
   transition: opacity 1s slide;
}
input:checked + .slide-container .nav label {
   display: block;
   z-index: 10;
}

But you won't be able to access those sites in codepen, except codepen itself, in the same tab. Instead just open in new tab and see.
Refer this fiddle where you won't be able to open any of the 4 sites, unless you don't open them in new tab.


text:
Q: Can we write case statement without having else statement I have this query:
select case when id=1 then 'A'
when id=2 then 'B'
end
from test

It is giving me o/p as

Id
  A
  B
  NULL
  NULL
  NULL

I don't want to have NULL values in my output, I only want to compare in A and B, is it possible in case statement.

A: You can use a WHERE clause to restrict the output.
SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B'
END
FROM test
WHERE id IN (1,2)

Or if you wanted to showcase some other value instead of null use an else part inside the CASE statement.
SELECT CASE WHEN id=1 THEN 'A'
WHEN id=2 THEN 'B' ELSE 'Invalid'
END
FROM test

A: A case expression can only manipulate the value of an expression, not remove rows from the result. If you want to omit the nulls from the result, you'll have to add a where clause:
SELECT CASE WHEN id = 1 THEN 'A'
            WHEN id = 2 THEN 'B'
       END
FROM   test
WHERE  id IN (1, 2) -- HERE

A: Here you go:
select case when id=1 then 'A'
when id=2 then 'B'
end
from test
where id is not null

Or this:
select case when id=1 then 'A'
when id=2 then 'B'
end
from test
where id <> null