qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
221,568 | Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | 2008/10/21 | [
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] | According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:
>
> The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.
>
>
>
So in your case, I'd try
`Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);`
to get a handle to the physical monospaced font of the current platform your code is running on.
**Edit**: It seems that SWT doesn't know anything about logical fonts ([Bug 48055](https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055) on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font... | For people who have the same problem, you can download any font ttf file, put it in the resource folder (in my case /font/*\**\*.ttf) and add this methode to your application. It's work 100 %.
```
public Font loadDigitalFont(int policeSize) {
URL fontFile = YouClassName.class
.getResource("/fonts/DS-DIGI.TTF");
boolean isLoaded = Display.getCurrent().loadFont(fontFile.getPath());
if (isLoaded) {
FontData[] fd = Display.getCurrent().getFontList(null, true);
FontData fontdata = null;
for (int i = 0; i < fd.length; i++) {
if (fd[i].getName().equals("DS-Digital")) {
fontdata = fd[i];
break;
}}
if (fontdata != null) {
fontdata.setHeight(policeSize);
fontdata.setStyle(SWT.BOLD);return new Font(getDisplay(), fontdata));}
}return null; }
``` |
221,568 | Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | 2008/10/21 | [
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] | To the best of my knowledge, the AWT API does not expose underlying Font information. If you can get to it, I would expect it to be implementation dependent. Certainly, comparing the font mapping files in a couple of JRE lib directories, I can see that they are not defined in a consistent way.
You could load your own fonts, but that seems a little wasteful given you know the platform comes with what you need.
This is a hack that loads a JRE font:
```
private static Font loadMonospacedFont(Display display) {
String jreHome = System.getProperty("java.home");
File file = new File(jreHome, "/lib/fonts/LucidaTypewriterRegular.ttf");
if (!file.exists()) {
throw new IllegalStateException(file.toString());
}
if (!display.loadFont(file.toString())) {
throw new IllegalStateException(file.toString());
}
final Font font = new Font(display, "Lucida Sans Typewriter", 10,
SWT.NORMAL);
display.addListener(SWT.Dispose, new Listener() {
public void handleEvent(Event event) {
font.dispose();
}
});
return font;
}
```
It works on IBM/Win32/JRE1.4, Sun/Win32/JRE1.6, Sun/Linux/JRE1.6, but is a pretty fragile approach. Depending on your needs for I18N, it could be trouble there too (I haven't checked).
Another hack would be to test the fonts available on the platform:
```
public class Monotest {
private static boolean isMonospace(GC gc) {
final String wide = "wgh8";
final String narrow = "1l;.";
assert wide.length() == narrow.length();
return gc.textExtent(wide).x == gc.textExtent(narrow).x;
}
private static void testFont(Display display, Font font) {
Image image = new Image(display, 100, 100);
try {
GC gc = new GC(image);
try {
gc.setFont(font);
System.out.println(isMonospace(gc) + "\t"
+ font.getFontData()[0].getName());
} finally {
gc.dispose();
}
} finally {
image.dispose();
}
}
private static void walkFonts(Display display) {
final boolean scalable = true;
for (FontData fontData : display.getFontList(null, scalable)) {
Font font = new Font(display, fontData);
try {
testFont(display, font);
} finally {
font.dispose();
}
}
}
public static void main(String[] args) {
Display display = new Display();
try {
walkFonts(display);
} finally {
display.dispose();
}
}
}
```
This probably isn't a good approach as it may leave you exposed to locale issues. Besides, you don't know if the first monospaced font you come across isn't some windings icon set.
The best approach may just be to take your best guess based on a font/locale mapping whitelist and make sure that the users can easily reconfigure the UI to suit themselves via [FontDialog](http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/FontDialog.html). | If you want just a Monospaced font use "Courier" => `new Font(display, "Courier", 10, SWT.NORMAL)` |
221,568 | Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | 2008/10/21 | [
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] | I spent a while bashing my head against this one until I realised that obviously eclipse must have access to a monospace font for use in its text fields, console etc. A little digging turned up:
```
Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);
```
Which works if all you're interested in is getting hold of some monospace font.
**Edit:** Or based on @ctron's comment:
```
Font font = JFaceResources.getTextFont();
```
**Edit:** Caveat (based on @Lii's comment): this will get you the configured Text Font, which can be overriden by the user and may not be a monospace font. However, it will be consistent with, e.g., the font used in the editor and console which is *probably* what you want. | To the best of my knowledge, the AWT API does not expose underlying Font information. If you can get to it, I would expect it to be implementation dependent. Certainly, comparing the font mapping files in a couple of JRE lib directories, I can see that they are not defined in a consistent way.
You could load your own fonts, but that seems a little wasteful given you know the platform comes with what you need.
This is a hack that loads a JRE font:
```
private static Font loadMonospacedFont(Display display) {
String jreHome = System.getProperty("java.home");
File file = new File(jreHome, "/lib/fonts/LucidaTypewriterRegular.ttf");
if (!file.exists()) {
throw new IllegalStateException(file.toString());
}
if (!display.loadFont(file.toString())) {
throw new IllegalStateException(file.toString());
}
final Font font = new Font(display, "Lucida Sans Typewriter", 10,
SWT.NORMAL);
display.addListener(SWT.Dispose, new Listener() {
public void handleEvent(Event event) {
font.dispose();
}
});
return font;
}
```
It works on IBM/Win32/JRE1.4, Sun/Win32/JRE1.6, Sun/Linux/JRE1.6, but is a pretty fragile approach. Depending on your needs for I18N, it could be trouble there too (I haven't checked).
Another hack would be to test the fonts available on the platform:
```
public class Monotest {
private static boolean isMonospace(GC gc) {
final String wide = "wgh8";
final String narrow = "1l;.";
assert wide.length() == narrow.length();
return gc.textExtent(wide).x == gc.textExtent(narrow).x;
}
private static void testFont(Display display, Font font) {
Image image = new Image(display, 100, 100);
try {
GC gc = new GC(image);
try {
gc.setFont(font);
System.out.println(isMonospace(gc) + "\t"
+ font.getFontData()[0].getName());
} finally {
gc.dispose();
}
} finally {
image.dispose();
}
}
private static void walkFonts(Display display) {
final boolean scalable = true;
for (FontData fontData : display.getFontList(null, scalable)) {
Font font = new Font(display, fontData);
try {
testFont(display, font);
} finally {
font.dispose();
}
}
}
public static void main(String[] args) {
Display display = new Display();
try {
walkFonts(display);
} finally {
display.dispose();
}
}
}
```
This probably isn't a good approach as it may leave you exposed to locale issues. Besides, you don't know if the first monospaced font you come across isn't some windings icon set.
The best approach may just be to take your best guess based on a font/locale mapping whitelist and make sure that the users can easily reconfigure the UI to suit themselves via [FontDialog](http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/FontDialog.html). |
221,568 | Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | 2008/10/21 | [
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] | I spent a while bashing my head against this one until I realised that obviously eclipse must have access to a monospace font for use in its text fields, console etc. A little digging turned up:
```
Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);
```
Which works if all you're interested in is getting hold of some monospace font.
**Edit:** Or based on @ctron's comment:
```
Font font = JFaceResources.getTextFont();
```
**Edit:** Caveat (based on @Lii's comment): this will get you the configured Text Font, which can be overriden by the user and may not be a monospace font. However, it will be consistent with, e.g., the font used in the editor and console which is *probably* what you want. | If you want just a Monospaced font use "Courier" => `new Font(display, "Courier", 10, SWT.NORMAL)` |
221,568 | Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | 2008/10/21 | [
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] | For people who have the same problem, you can download any font ttf file, put it in the resource folder (in my case /font/*\**\*.ttf) and add this methode to your application. It's work 100 %.
```
public Font loadDigitalFont(int policeSize) {
URL fontFile = YouClassName.class
.getResource("/fonts/DS-DIGI.TTF");
boolean isLoaded = Display.getCurrent().loadFont(fontFile.getPath());
if (isLoaded) {
FontData[] fd = Display.getCurrent().getFontList(null, true);
FontData fontdata = null;
for (int i = 0; i < fd.length; i++) {
if (fd[i].getName().equals("DS-Digital")) {
fontdata = fd[i];
break;
}}
if (fontdata != null) {
fontdata.setHeight(policeSize);
fontdata.setStyle(SWT.BOLD);return new Font(getDisplay(), fontdata));}
}return null; }
``` | If you want just a Monospaced font use "Courier" => `new Font(display, "Courier", 10, SWT.NORMAL)` |
221,568 | Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | 2008/10/21 | [
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] | I spent a while bashing my head against this one until I realised that obviously eclipse must have access to a monospace font for use in its text fields, console etc. A little digging turned up:
```
Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);
```
Which works if all you're interested in is getting hold of some monospace font.
**Edit:** Or based on @ctron's comment:
```
Font font = JFaceResources.getTextFont();
```
**Edit:** Caveat (based on @Lii's comment): this will get you the configured Text Font, which can be overriden by the user and may not be a monospace font. However, it will be consistent with, e.g., the font used in the editor and console which is *probably* what you want. | For people who have the same problem, you can download any font ttf file, put it in the resource folder (in my case /font/*\**\*.ttf) and add this methode to your application. It's work 100 %.
```
public Font loadDigitalFont(int policeSize) {
URL fontFile = YouClassName.class
.getResource("/fonts/DS-DIGI.TTF");
boolean isLoaded = Display.getCurrent().loadFont(fontFile.getPath());
if (isLoaded) {
FontData[] fd = Display.getCurrent().getFontList(null, true);
FontData fontdata = null;
for (int i = 0; i < fd.length; i++) {
if (fd[i].getName().equals("DS-Digital")) {
fontdata = fd[i];
break;
}}
if (fontdata != null) {
fontdata.setHeight(policeSize);
fontdata.setStyle(SWT.BOLD);return new Font(getDisplay(), fontdata));}
}return null; }
``` |
46,599,446 | I'm seeking some help on how I can click the "Play Activity button" in our Global Productivity Hub in our office using excel VBA. I'm creating an attendance log in tool with lunch and break trackers. Once the employee click Log In with tool that I created, the GPH site will launch and will logged them in, the same thing with Log Out. However, I'm having difficulty in controlling the break and lunch button of GPH site using the tool that I created. I cannot find the correct elements to integrate to my vba code. I hope someone can help me with this. Please see below the HTML code of that particular button and the image.
```html
<tr class="top-five">
<td title="Play Activity" class="glyphicon glyphicon-play-circle play-activity" data-toggle="tooltip" data-team-id="e9575e8b-4682-734c-b28d-b1ee5532a8ce" data-activity-id="e0728017-a4fa-ef4b-91a6-262e5418a134" data-team-name="Technology Team"> </td>
<td>
<span title="Break Activities" class="act-ellipsis" data-toggle="tooltip">
<span class="ellip ellip-line"> Break Activities </span>
</span>
Break
</td>
<td title="Favorite" class="glyphicon glyphicon-star" data-toggle="tooltip" data-activity-id="e0728017-a4fa-ef4b-91a6-262e5418a134"></td>
</tr>
```
 | 2017/10/06 | [
"https://Stackoverflow.com/questions/46599446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8730433/"
] | You could use a rank analytic function here, e.g.
```
SELECT salary
FROM
(
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) dr
FROM c
) t
WHERE dr = 2;
```
This would return the second highest salary by dense rank, including all ties for second. | Explanation why your subquery can't work:
1. At first, records are read from the table in an arbitrary order. This is when they get their `rownum`.
2. Then aggregation takes place; all records for one `salary` are condensed to a single row. The `rownum` of the single rows you had before are no longer available.
3. Then the aggregated rows are filtered by `HAVING`, and this cannot work, as you are trying to access `rownum`. Moreover, conditions on `rownum = 2` always fail, because you are dismissing the first row, so it is "not read" and `rownum` 1 is still available, you dismiss the second, because you haven't even read `rownum` 1 yet, and so on. Criteria on `rownum` is always `rownum <= some_number` (except for 1 where you can have `rownum = 1`).
4. The last thing that happens is the sorting; the `ORDER BY` clause belongs at the end of the query hence. (It can only be followed by `FETCH FIRST n ROWS` as of Oracle 12c.)
Here is how to make it work with `rownum`:
```
select salary
from
(
select salary
from
(
select distinct salary
from c
order by salary desc
)
where rownum <= 2
order by salary
)
where rownum = 1;
```
This works, because Oracle is violating the SQL standard here. According to the standard, data from subqueries is considered unordered, but Oracle guarantees the order when working with `rownum`.
Here is how to do it with aggregation:
```
select max(salary) from c where salary < (select max(salary) from c);
```
Since Oracle 10 you can also use analytic functions as shown in Tim's answer. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | The lineup of Canon crop (EF-S) lenses is not nearly as broad as the full-frame (EF) lenses.
* In the focal length of interest, some EF options give better image quality than the respective EF-S options.
* Additionally, some EF lenses offer features that are not available for EF-S lenses, such as weather sealing and stronger construction.
* (Not specific to the lenses you listed but) specialty lenses are only available in EF format, like fisheye and tilt-shift.
so yes, there are reasons to get full-frame lenses for a crop camera. For the specific lenses in question, @Joanne C's reasoning makes sense but today I personally think it is less important than it seemed to be in the past, as you have greater chances of upgrading your rebel to a higher crop body (7D class) than to a FF class. By the time you finally upgrade to FF class, you can sell your crop lenses for a good value. | Short form:
In general it is wise then, and only then, when you seriously consider moving to a full frame body later.
If you don't then it is just a case-by-case decistion, as yours obviously is. You are thinking of a number of specific lens for now.
Then, when the choice is just beween an EF lens and an EF-S consider the following:
* There is noting wrong with using an EF lens on a crop body. Nor is there anything wrong with a lens park made of both kinds.
* A crop body would use the best parts of the projected image only. Important when you take reviews into account. You can then ignore their less than optimal quality in the edges, that some of them may show.
* EF-S lenses of the same optical quality when used on crop bodies can be significantly cheaper than the EF lense that you compare it with. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | The lineup of Canon crop (EF-S) lenses is not nearly as broad as the full-frame (EF) lenses.
* In the focal length of interest, some EF options give better image quality than the respective EF-S options.
* Additionally, some EF lenses offer features that are not available for EF-S lenses, such as weather sealing and stronger construction.
* (Not specific to the lenses you listed but) specialty lenses are only available in EF format, like fisheye and tilt-shift.
so yes, there are reasons to get full-frame lenses for a crop camera. For the specific lenses in question, @Joanne C's reasoning makes sense but today I personally think it is less important than it seemed to be in the past, as you have greater chances of upgrading your rebel to a higher crop body (7D class) than to a FF class. By the time you finally upgrade to FF class, you can sell your crop lenses for a good value. | As usual: it depends
* In terms of image quality, it's definitely wise as only the best part of the lens will be used (the center) by your camera. Lenses are usually sharper near the center and you will notice less vignetting.
* the downside is, EF lenses are usually more expensive than equivalent EF-S lenses.
* on the other hand, the EF-S 10-22 is a great lens, but there simply is no equivalent EF lens made by Canon. The 16-35 is simply a different focal range and the difference is very noticeable.
* your EF-S lenses will be useless when you upgrade to full frame
* note that you should ignore the famous "crop factor" in this regard. The focal length and field of view is the same for EF and EF-S lenses *on the same camera*.
* however, when reading a lens review that was made *on a FF camera*, note that the overall experience of that lens on a crop camera may be different (for example, I love the 70-200 on full frame, but rarely use it on my 7D as it gets "quite long" on that camera).
Simply said: When comparing an EF and an EF-S lens *of the same focal length*, the EF version will most probably have better image quality and cost more, but produce the same framing. Besides that, you need to evaluate other factors - for your lens choice - *not related to the EF/EFS mount type*, like focal length range, aperture, IS, build quality, size, weight, price and so on... |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | The lineup of Canon crop (EF-S) lenses is not nearly as broad as the full-frame (EF) lenses.
* In the focal length of interest, some EF options give better image quality than the respective EF-S options.
* Additionally, some EF lenses offer features that are not available for EF-S lenses, such as weather sealing and stronger construction.
* (Not specific to the lenses you listed but) specialty lenses are only available in EF format, like fisheye and tilt-shift.
so yes, there are reasons to get full-frame lenses for a crop camera. For the specific lenses in question, @Joanne C's reasoning makes sense but today I personally think it is less important than it seemed to be in the past, as you have greater chances of upgrading your rebel to a higher crop body (7D class) than to a FF class. By the time you finally upgrade to FF class, you can sell your crop lenses for a good value. | If you never plan on moving to a full frame body, then sticking with crop lenses are liable to be a smart path to take, because the lenses will be as sharp, be less expensive, smaller, and lighter. Most EF-S lenses have much more modern designs than their full-frame counterparts and the smaller sensor size means that the correction requirements for full-frame, which is why L lenses get so big and heavy and expensive, are often loosened. You get a better, simpler lens for less money.
I.e., consider the EF-S 17-55/2.8 instead of the EF 16-35 f/2.8L II.
If you plan on imminently moving to a full frame body, then sticking with full-frame lenses is probably wisest with the single exception of the ultrawide lens. With ultrawide, you cannot find any lens that's going to fulfill that role on both crop and sensor, due to the nature of how the sensor format affects the field of view of any lens. In this case, go ahead and get a crop ultrawide. They typically hold value well for resale, and will cost roughly half what a full-frame ultrawide will (e.g., $600 vs. $1000-$1500).
I.e., consider the EF-S 10-22 (or Tokina 11-16/2.8), and then sell it when you move to full frame to help fund an EF 16-35/2.8L II or EF 17-40 f/4L.
Lenses like the EF 17-40/4L and 16-35/2.8L can be used as walkaround zooms on crop bodies, but keeping them for full frame use doesn't mean you'll have a walkaround zoom on both crop and full frame. It means you'll have a walkaround on crop and an ultrawide zoom on full frame, and you'll probably still have to supplement with 24-70 or 24-105L when you get that 6D you're lusting after. And the 24-x L lenses aren't *quite* wide enough on a crop body for walkaround usage.
When you format switch from crop to full frame, *every* EF lens you have will get 1.6x shorter. Do the crop math backwards to see if that lens is going to be a good fit for you on full frame as well. I happily used a 24-105 f/4L IS USM on my XT and 50D for years, but only understood what it was really designed to be when I got a 5DMkII. And now I want an EF-S 15-85 IS USM for my 50D, so I'll have "the same lens" on crop. And a 70-200 is going to look on a full frame the way a 44-125 would look on your crop body. Maybe you'd wish you spent on a 100-400L instead. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | I bought a Canon 24-70mm f/2.8 L lens for my Canon 450D crop sensor body before I had purchased the full-frame Canon 5DMKII. By going this route, I had time to learn my lens on a crop body well before I could afford the full frame of the 5D. I even borrowed and used 70-200mm f/2.8 L lenses on the 450D body, which gave an additional crop factor for "perceived" zoom with little else to complain about.
Positives
* Owning a great lens at a lower price-point to buying a full-frame body
* Shooting great images without waiting around
Negatives
* Only knowing that I wasn't getting the "best" out of my lens in terms of the crop factor preventing me from achieving a "true" 24mm.
Note
* This topic does come up a lot, but the implication is that the intention exists to move to full frame. Plenty of photographers are happy with crop models, but these questions are usually handled in a "should I get the lens before the full frame body" sense. If so, go for it!
The difference between your kit lens and the 24-70 will astound you (with clarity). It will also delight you (when you realize how much sharper your shots are). And then it will depress you (when you remember how much these lens cost). | Short form:
In general it is wise then, and only then, when you seriously consider moving to a full frame body later.
If you don't then it is just a case-by-case decistion, as yours obviously is. You are thinking of a number of specific lens for now.
Then, when the choice is just beween an EF lens and an EF-S consider the following:
* There is noting wrong with using an EF lens on a crop body. Nor is there anything wrong with a lens park made of both kinds.
* A crop body would use the best parts of the projected image only. Important when you take reviews into account. You can then ignore their less than optimal quality in the edges, that some of them may show.
* EF-S lenses of the same optical quality when used on crop bodies can be significantly cheaper than the EF lense that you compare it with. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | If you have the money, go with the full frame option. The basic reasoning that I would have for that is simple: lenses will stay with you longer than the camera body. That's the nutshell answer.
Longer answer is that today you have a 550D and you're learning. Stay with that camera while you're doing that, until you feel that the photography you want to do is being impeded. Then you're going to look for something else. You might stay cropped sensor, you might not, but if you've shelled out thousands for lenses that are crop, then that may make the decision for you and that isn't ideal. Or you'll need to sell your lenses and you'll lose money in replacing. Also not ideal.
Net effect, if there is ever a real possibility that you'll buy a full frame Canon, new or used, then stick with the full-sized lenses. If this isn't a real possibility, then go crop. Just seriously consider all that first. | Short form:
In general it is wise then, and only then, when you seriously consider moving to a full frame body later.
If you don't then it is just a case-by-case decistion, as yours obviously is. You are thinking of a number of specific lens for now.
Then, when the choice is just beween an EF lens and an EF-S consider the following:
* There is noting wrong with using an EF lens on a crop body. Nor is there anything wrong with a lens park made of both kinds.
* A crop body would use the best parts of the projected image only. Important when you take reviews into account. You can then ignore their less than optimal quality in the edges, that some of them may show.
* EF-S lenses of the same optical quality when used on crop bodies can be significantly cheaper than the EF lense that you compare it with. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | I bought a Canon 24-70mm f/2.8 L lens for my Canon 450D crop sensor body before I had purchased the full-frame Canon 5DMKII. By going this route, I had time to learn my lens on a crop body well before I could afford the full frame of the 5D. I even borrowed and used 70-200mm f/2.8 L lenses on the 450D body, which gave an additional crop factor for "perceived" zoom with little else to complain about.
Positives
* Owning a great lens at a lower price-point to buying a full-frame body
* Shooting great images without waiting around
Negatives
* Only knowing that I wasn't getting the "best" out of my lens in terms of the crop factor preventing me from achieving a "true" 24mm.
Note
* This topic does come up a lot, but the implication is that the intention exists to move to full frame. Plenty of photographers are happy with crop models, but these questions are usually handled in a "should I get the lens before the full frame body" sense. If so, go for it!
The difference between your kit lens and the 24-70 will astound you (with clarity). It will also delight you (when you realize how much sharper your shots are). And then it will depress you (when you remember how much these lens cost). | If you never plan on moving to a full frame body, then sticking with crop lenses are liable to be a smart path to take, because the lenses will be as sharp, be less expensive, smaller, and lighter. Most EF-S lenses have much more modern designs than their full-frame counterparts and the smaller sensor size means that the correction requirements for full-frame, which is why L lenses get so big and heavy and expensive, are often loosened. You get a better, simpler lens for less money.
I.e., consider the EF-S 17-55/2.8 instead of the EF 16-35 f/2.8L II.
If you plan on imminently moving to a full frame body, then sticking with full-frame lenses is probably wisest with the single exception of the ultrawide lens. With ultrawide, you cannot find any lens that's going to fulfill that role on both crop and sensor, due to the nature of how the sensor format affects the field of view of any lens. In this case, go ahead and get a crop ultrawide. They typically hold value well for resale, and will cost roughly half what a full-frame ultrawide will (e.g., $600 vs. $1000-$1500).
I.e., consider the EF-S 10-22 (or Tokina 11-16/2.8), and then sell it when you move to full frame to help fund an EF 16-35/2.8L II or EF 17-40 f/4L.
Lenses like the EF 17-40/4L and 16-35/2.8L can be used as walkaround zooms on crop bodies, but keeping them for full frame use doesn't mean you'll have a walkaround zoom on both crop and full frame. It means you'll have a walkaround on crop and an ultrawide zoom on full frame, and you'll probably still have to supplement with 24-70 or 24-105L when you get that 6D you're lusting after. And the 24-x L lenses aren't *quite* wide enough on a crop body for walkaround usage.
When you format switch from crop to full frame, *every* EF lens you have will get 1.6x shorter. Do the crop math backwards to see if that lens is going to be a good fit for you on full frame as well. I happily used a 24-105 f/4L IS USM on my XT and 50D for years, but only understood what it was really designed to be when I got a 5DMkII. And now I want an EF-S 15-85 IS USM for my 50D, so I'll have "the same lens" on crop. And a 70-200 is going to look on a full frame the way a 44-125 would look on your crop body. Maybe you'd wish you spent on a 100-400L instead. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | I am going to keep it simple.
1. Many people do it. In fact, I have seen most people using APS-C camera with a mix of EF-S and EF lenses, and less people use **only** EF-S lenses.
2. Expensive lenses offers **excellent** image quality with the trade-off of being expensive, inflexible (usually a narrow zoom range, may cause more frequent lens changes) and heavy.
Do you want to spend more money, carry more weight, narrow your zoom range, **just to get better pixels**? This is entirely up to you, but **honestly** and generally, such lens is not a **must** by people not getting paid doing photography. | There are a few factors to consider here. Firstly the EF L range lenses are considerably better build quality than typical EF-S lenses and the optical quality tends to be much higher too. On a crop sensor the 70-200 f4 L is outstanding. You do however have to remember when choosing EF lenses to apply the crop factor to get the effective focal length. That said lenses tend to last a lifetime if you look after them so getting EF will not limit you to crop sensors in the future. I started off with a crop body but now use full frame as well so my early descision to only buy EF lenses has paid off.
The two major drawbacks of EF lenses are cost and weight. EF lenses have to project a larger image at the sensor so tend to contain bigger heavier elements. The 24-70 f2.8 L forinstance is quite heavy and has the tendency to feel unbalanced on lighter entry level bodies. They also tend to be quite a bit more expensive roughly 40-50% more than EF-S of the same focal range and maximum aperture.
If you look at lenses as an investment then cost is less of a factor and in my opinion the better image quality makes up for the extra weight. However this is a personal opinion and you may come to different conclusions after trying out some lenses. This is the most important thing to do, go to a shop and try some of these lenses for weight and quality then also factor this into your descision. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | If you never plan on moving to a full frame body, then sticking with crop lenses are liable to be a smart path to take, because the lenses will be as sharp, be less expensive, smaller, and lighter. Most EF-S lenses have much more modern designs than their full-frame counterparts and the smaller sensor size means that the correction requirements for full-frame, which is why L lenses get so big and heavy and expensive, are often loosened. You get a better, simpler lens for less money.
I.e., consider the EF-S 17-55/2.8 instead of the EF 16-35 f/2.8L II.
If you plan on imminently moving to a full frame body, then sticking with full-frame lenses is probably wisest with the single exception of the ultrawide lens. With ultrawide, you cannot find any lens that's going to fulfill that role on both crop and sensor, due to the nature of how the sensor format affects the field of view of any lens. In this case, go ahead and get a crop ultrawide. They typically hold value well for resale, and will cost roughly half what a full-frame ultrawide will (e.g., $600 vs. $1000-$1500).
I.e., consider the EF-S 10-22 (or Tokina 11-16/2.8), and then sell it when you move to full frame to help fund an EF 16-35/2.8L II or EF 17-40 f/4L.
Lenses like the EF 17-40/4L and 16-35/2.8L can be used as walkaround zooms on crop bodies, but keeping them for full frame use doesn't mean you'll have a walkaround zoom on both crop and full frame. It means you'll have a walkaround on crop and an ultrawide zoom on full frame, and you'll probably still have to supplement with 24-70 or 24-105L when you get that 6D you're lusting after. And the 24-x L lenses aren't *quite* wide enough on a crop body for walkaround usage.
When you format switch from crop to full frame, *every* EF lens you have will get 1.6x shorter. Do the crop math backwards to see if that lens is going to be a good fit for you on full frame as well. I happily used a 24-105 f/4L IS USM on my XT and 50D for years, but only understood what it was really designed to be when I got a 5DMkII. And now I want an EF-S 15-85 IS USM for my 50D, so I'll have "the same lens" on crop. And a 70-200 is going to look on a full frame the way a 44-125 would look on your crop body. Maybe you'd wish you spent on a 100-400L instead. | Short form:
In general it is wise then, and only then, when you seriously consider moving to a full frame body later.
If you don't then it is just a case-by-case decistion, as yours obviously is. You are thinking of a number of specific lens for now.
Then, when the choice is just beween an EF lens and an EF-S consider the following:
* There is noting wrong with using an EF lens on a crop body. Nor is there anything wrong with a lens park made of both kinds.
* A crop body would use the best parts of the projected image only. Important when you take reviews into account. You can then ignore their less than optimal quality in the edges, that some of them may show.
* EF-S lenses of the same optical quality when used on crop bodies can be significantly cheaper than the EF lense that you compare it with. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | The lineup of Canon crop (EF-S) lenses is not nearly as broad as the full-frame (EF) lenses.
* In the focal length of interest, some EF options give better image quality than the respective EF-S options.
* Additionally, some EF lenses offer features that are not available for EF-S lenses, such as weather sealing and stronger construction.
* (Not specific to the lenses you listed but) specialty lenses are only available in EF format, like fisheye and tilt-shift.
so yes, there are reasons to get full-frame lenses for a crop camera. For the specific lenses in question, @Joanne C's reasoning makes sense but today I personally think it is less important than it seemed to be in the past, as you have greater chances of upgrading your rebel to a higher crop body (7D class) than to a FF class. By the time you finally upgrade to FF class, you can sell your crop lenses for a good value. | I am going to keep it simple.
1. Many people do it. In fact, I have seen most people using APS-C camera with a mix of EF-S and EF lenses, and less people use **only** EF-S lenses.
2. Expensive lenses offers **excellent** image quality with the trade-off of being expensive, inflexible (usually a narrow zoom range, may cause more frequent lens changes) and heavy.
Do you want to spend more money, carry more weight, narrow your zoom range, **just to get better pixels**? This is entirely up to you, but **honestly** and generally, such lens is not a **must** by people not getting paid doing photography. |
17,028 | I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality? | 2011/11/08 | [
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] | There are a few factors to consider here. Firstly the EF L range lenses are considerably better build quality than typical EF-S lenses and the optical quality tends to be much higher too. On a crop sensor the 70-200 f4 L is outstanding. You do however have to remember when choosing EF lenses to apply the crop factor to get the effective focal length. That said lenses tend to last a lifetime if you look after them so getting EF will not limit you to crop sensors in the future. I started off with a crop body but now use full frame as well so my early descision to only buy EF lenses has paid off.
The two major drawbacks of EF lenses are cost and weight. EF lenses have to project a larger image at the sensor so tend to contain bigger heavier elements. The 24-70 f2.8 L forinstance is quite heavy and has the tendency to feel unbalanced on lighter entry level bodies. They also tend to be quite a bit more expensive roughly 40-50% more than EF-S of the same focal range and maximum aperture.
If you look at lenses as an investment then cost is less of a factor and in my opinion the better image quality makes up for the extra weight. However this is a personal opinion and you may come to different conclusions after trying out some lenses. This is the most important thing to do, go to a shop and try some of these lenses for weight and quality then also factor this into your descision. | Short form:
In general it is wise then, and only then, when you seriously consider moving to a full frame body later.
If you don't then it is just a case-by-case decistion, as yours obviously is. You are thinking of a number of specific lens for now.
Then, when the choice is just beween an EF lens and an EF-S consider the following:
* There is noting wrong with using an EF lens on a crop body. Nor is there anything wrong with a lens park made of both kinds.
* A crop body would use the best parts of the projected image only. Important when you take reviews into account. You can then ignore their less than optimal quality in the edges, that some of them may show.
* EF-S lenses of the same optical quality when used on crop bodies can be significantly cheaper than the EF lense that you compare it with. |
21,069,530 | I'm trying to somehow determine based on my interface what type came in and then do some validation on that type. Validation differes based on type that comes in.
```
public static bool RequestIsValid(IPaymentRequest preAuthorizeRequest)
{
switch (preAuthorizeRequest)
{
case
}
}
```
but either I can't do that with an interface or I'm not doing something that will make this work.
If I can't do that on an interface which looks like the probably because I think switch needs a concrete type, then how would I do this? Just regular if statements that check typeof?
Is that the only way? | 2014/01/12 | [
"https://Stackoverflow.com/questions/21069530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93468/"
] | `.myClass/DomElement > .myotherclassinsidethatelement` selects only the direct children of the parent class.
So:
```
<div class='myClass'>
<div class='someOther'>
<div class='myotherclassinsidethatelement'></div>
</div>
</div>
```
In this case, the `>` version won't select it.
See here: <http://jsfiddle.net/RRv7u/1/> | **UPDATE**
The previous answer I gave was incorrect. I was under the impression that inheritance and nesting were the same thing, but they are not. If anyone else had this impression, here is a resource explaining what nesting is:
<http://www.htmldog.com/guides/css/intermediate/grouping/>
Here is another explaining what specificity is:
<http://www.htmldog.com/guides/css/intermediate/specificity/>
And here is a final link explaining specificity and inheritance:
<http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/>
**Previous answer:**
>
> The angle bracket in CSS denotes inheritance. So when you say
>
>
>
> ```
> .class1 > .class2 { styles }
>
> ```
>
> You're saying that the styles you're about to apply for class2 are
> only going to be applied when class2 is a child of class1.
>
>
> |
5,515 | I know that mining pool shares have no value on their own, but it should be possible to find an average value based on the pool's average payout per share. [This site](https://en.bitcoin.it/wiki/Mining_pool_reward_FAQ#What_will_be_my_expected_payout_per_share.3F) describes the expected payout per share as `([block reward] - [pool operator's cut]) / [difficulty]`.
It seems to me that a share's "value" would necessarily be related to the difficulty as set by the pool--a pool with shares that are harder to find will have its users find fewer shares, making each share "worth" more. However, the equation above clearly doesn't work with the pool's difficulty, as most pools set difficulty to 1 and a share isn't worth ~48 BTC. How can I reconcile these issues to calculate the expected payout per share of a pool without knowing how many total shares are found?
**Edit:**
Ah, I think I've figured it out. The difficulty in the equation can be the network difficulty, because that's what makes it more or less likely that a given successful hash (earning a share) in a pool solves the block and earns the block reward. Thus, the network difficulty indirectly limits the value of a share. Is this correct?
**Edit Again:**
And now I'm back to being confused. If Pool A sets a higher difficulty than Pool B, Pool A's shares are worth more than Pool B's (assuming the same number of miners at a set hash rate) because they're rarer so each share will earn more at payout. How is this taken into account in the equation? | 2012/11/27 | [
"https://bitcoin.stackexchange.com/questions/5515",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/2029/"
] | If the global network difficulty is D and the difficulty of shares in the pool is d, then the probability that a share will lead to a valid block is d/D. The reward in this case is B, so the average reward per share is B\*(d/D). If the operator's average fee is f (so for example f=0.01 means 1% fee), the average reward miners get per share submitted is (1-f) \* B \* (d/D). | **Variable difficulty mining:**
If you are mining at a pool with a higher difficulty, then each share (proof-of-work) is worth more on average. Proving that you worked very hard is worth more than proving that you worked a little bit. Some pools now use variable difficulty, which means the difficulty can change over time. One share at difficulty X has the same average expected return as X shares of difficulty 1. It may be easiest to think of everything in terms of difficulty 1 shares.
**Average value of a share (proof-of-work):**
Basically each (difficulty 1) share's value is the block reward divided by the network difficulty. That's the average income of a block multiplied by the chance that the share creates a block (one divided by network difficulty). But keep in mind that transaction fees are part of the block reward. That's the bitcoin value of each share. If the pool uses merged mining the share would also have a value for each merged coin. That should also be included.
**Example:**
As I write this the new coins minted per block is about to drop from 50 to 25 BTC in just a few hours. Looking at <http://blockchain.info/charts/transaction-fees> the total transaction fees are roughly 25 BTC per day. With roughly 144 blocks per day, that is 0.17 BTC per block, making the total inccome for a block approximately 25.17 BTC.
With a difficulty of 3438908.96015914 that gives us an average value per share of 25.17/3438908.96015914 = 0.0000073191818369147015 BTC.
Assuming a pool that also gives you namecoins through merged mining, a share would have an additional value of approx. 50/1119016.08618347 = 0.000044682110129918345 NMC. With namecoins currently trading at 225 NMC to 1 BTC that puts the total value of a share at 0.000007517768993047672 BTC.
0.000007517768993047672 BTC per share, as opposed to
0.000007269747553550557 BTC which you get with the simplified formula (minted coins divided by difficulty). This **3.4% difference** can be worth noting as many would have you believe that the simpler formula shows you the full value of a share.
**Disclaimer:** I run a pool that pays out transaction fees and namecoins. |
81,413 | I was wondering if tension on both ends of a rope is still the same, even if there is objects with different weights on both sides of the rope. | 2013/10/20 | [
"https://physics.stackexchange.com/questions/81413",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/29959/"
] | I'm assuming there is a pulley involved which allows the tension from both objects to be in the same direction (i.e towards the source of gravity).

Taking this to be the case, yes, the tension in the rope is constant. However, the entire system will accelerate, with the heavier mass moving downwards. | They can be different at certain circumstances. For example, in a pulley problem if we assume that the pulley and the rope is massless then the tension is same.[](https://i.stack.imgur.com/g3g5g.jpg)
But if we consider them to have considerable mass then we can see that T1 is not equal to T2.
Hope it was helpful..... |
3,380,033 | I'm using xmlwriter to create an xml document. The xml document looks like this:
```
<?xml version="1.0" encoding="utf-8" ?>
<ExceptionsList />
```
How can i prevent the /> and appropriately end the root node?
Because of this, i can't append anything to the root node.
My code for creating the xml file looks like this:
```
string formatDate = DateTime.Now.ToString("d-MMM-yyyy");
XmlTextWriter xmlWriter = new XmlTextWriter(xmlfileName, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 3;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("ExceptionsList"); // ExceptionsList (Root) Element
xmlWriter.WriteEndElement(); // End of ExceptionsList (Root) Element
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
```
And I append to the root node like this:
```
XDocument xml = XDocument.Load(xmlFileName);
XElement root = xml.Root;
root.Add(new XElement("Exception",
new XElement("Exception Type", exceptionType),
new XElement("Exception Message", exceptionMessage),
new XElement("InnerException", innerException),
new XElement("Comment", comment)));
xml.Save(xmlFileName);
```
This gives me a stackoverflow at runtime error too.
Any help would be appreciated.
Thanks in advance! | 2010/07/31 | [
"https://Stackoverflow.com/questions/3380033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405046/"
] | Your code is right, and you don't need to change how your `ExceptionsList` element is closed.
```
xmlWriter.WriteStartElement("ExceptionsList"); // ExceptionsList (Root) Element
xmlWriter.WriteStartElement("Exception"); // An Exception element
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement(); // End of ExceptionsList (Root) Element
```
In your second snippet, you need to remove those white spaces from element name, as XML specification forbid that and add your elements into your `XDocument` instance, like this:
```
XDocument xml = new XDocument();
xml.Add(new XElement("Exception",
new XElement("ExceptionType", "Exception"),
new XElement("ExceptionMessage",
new XElement("InnerException", "innerException")),
new XComment("some comment")));
xml.Save("sample2.xml");
``` | I believe the problem is here:
```
new XElement("Exception Type", exceptionType),
new XElement("Exception Message", exceptionMessage),
```
Neither `Exception Type` nor `Exception Mesage` is a valid name for an xml element. Then of course, if you use *this* (doomed) method to log the error... stack overflow. |
17,578,280 | When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?
```
x = 1;
y = 2;
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
x = 3;
y = 4;
```
In here, I want to use the x and y values that were set at the time I set the src of the image (i.e. 1 and 2). In the code above, by the time the onload function would finish, x and y could be 3 and 4.
Is there a way I can pass values into the onload function, or will it automatically use 1, and 2?
Thanks | 2013/07/10 | [
"https://Stackoverflow.com/questions/17578280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497454/"
] | Make a private scope closure that will store x & y values:
```
imageObj.onload = (function(x,y){
return function() {
context.drawImage(imageObj, x, y);
};
})(x,y);
``` | Make a small function that handles it. Local variables will hold the correct scope.
```
function loadImage( src, x, y) {
var imageObj = new Image();
imageObj.src = src;
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
}
var x = 1,
y = 2;
loadImage("foo.png", x, y);
x = 3;
y = 4;
``` |
17,578,280 | When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?
```
x = 1;
y = 2;
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
x = 3;
y = 4;
```
In here, I want to use the x and y values that were set at the time I set the src of the image (i.e. 1 and 2). In the code above, by the time the onload function would finish, x and y could be 3 and 4.
Is there a way I can pass values into the onload function, or will it automatically use 1, and 2?
Thanks | 2013/07/10 | [
"https://Stackoverflow.com/questions/17578280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497454/"
] | All the other answers are some version of "make a closure". OK, that works. I think closures are cool, and languages that support them are cool...
However: there is a much cleaner way to do this, IMO. Simply use the image object to store what you need, and access it in the load handler via "`this`":
```
imageObj = new Image();
imageObj.x = 1;
imageObj.y = 2;
imageObj.onload = function() {
context.drawImage(this, this.x, this.y);
};
imageObj.src = ".....";
```
This is a very general technique, and I use it all the time in many objects in the DOM. (I especially use it when I have, say, four buttons and I want them to all share an "onclick" handler; I have the handler pull a bit of custom data out of the button to do THAT button's particular action.)
One warning: you have to be careful not to use a property of the object that the object class itself has a special meaning or use. (For example: you can't use `imageObj.src` for any old custom use; you have to leave it for the source URL.) But, in the general case, how are you to know how a given object uses all its properties? Strictly speaking, you can't. So to make this approach as safe as possible:
* Wrap up all your custom data in a single object
* Assign that object to a property that is unusual/unlikely to be used by the object itself.
In that regard, using "x" and "y" are a little risky as some Javascript implementation in some browser may use those properties when dealing with the Image object. But this is probably safe:
```
imageObj = new Image();
imageObj.myCustomData = {x: 1, y: 2};
imageObj.onload = function() {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
};
imageObj.src = ".....";
```
Another advantage to this approach: it can save a lot of memory if you are creating a lot of a given object -- because you can now share a single instance of the onload handler. Consider this, using closures:
```
// closure based solution -- creates 1000 anonymous functions for "onload"
for (var i=0; i<1000; i++) {
var imageObj = new Image();
var x = i*20;
var y = i*10;
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
imageObj.src = ".....";
}
```
Compare to shared-onload function, with your custom data tucked away in the Image object:
```
// custom data in the object -- creates A SINGLE "onload" function
function myImageOnload () {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
}
for (var i=0; i<1000; i++) {
imageObj = new Image();
imageObj.myCustomData = {x: i*20, y: i*10};
imageObj.onload = myImageOnload;
imageObj.src = ".....";
}
```
Much memory saved and may run a skosh faster since you aren't creating all those anonymous functions. (In this example, the onload function is a one-liner.... but I've had 100-line onload functions, and a 1000 of them would surely be considered spending a lot of memory for no good reason.)
*UPDATE*: See [use of 'data-\*' attribute](https://stackoverflow.com/q/17184918/701435) for a standard (and "standards approved") way to do this, in lieu of my ad-hoc suggestion to use `myCustomData`. | Make a small function that handles it. Local variables will hold the correct scope.
```
function loadImage( src, x, y) {
var imageObj = new Image();
imageObj.src = src;
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
}
var x = 1,
y = 2;
loadImage("foo.png", x, y);
x = 3;
y = 4;
``` |
17,578,280 | When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?
```
x = 1;
y = 2;
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
x = 3;
y = 4;
```
In here, I want to use the x and y values that were set at the time I set the src of the image (i.e. 1 and 2). In the code above, by the time the onload function would finish, x and y could be 3 and 4.
Is there a way I can pass values into the onload function, or will it automatically use 1, and 2?
Thanks | 2013/07/10 | [
"https://Stackoverflow.com/questions/17578280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497454/"
] | Make a private scope closure that will store x & y values:
```
imageObj.onload = (function(x,y){
return function() {
context.drawImage(imageObj, x, y);
};
})(x,y);
``` | You could use an anonymous function
```
x = 1;
y = 2;
(function(xValue, yValue){
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, xValue, yValue);
};
})(x,y);
x = 3;
y = 4;
``` |
17,578,280 | When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?
```
x = 1;
y = 2;
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
x = 3;
y = 4;
```
In here, I want to use the x and y values that were set at the time I set the src of the image (i.e. 1 and 2). In the code above, by the time the onload function would finish, x and y could be 3 and 4.
Is there a way I can pass values into the onload function, or will it automatically use 1, and 2?
Thanks | 2013/07/10 | [
"https://Stackoverflow.com/questions/17578280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497454/"
] | All the other answers are some version of "make a closure". OK, that works. I think closures are cool, and languages that support them are cool...
However: there is a much cleaner way to do this, IMO. Simply use the image object to store what you need, and access it in the load handler via "`this`":
```
imageObj = new Image();
imageObj.x = 1;
imageObj.y = 2;
imageObj.onload = function() {
context.drawImage(this, this.x, this.y);
};
imageObj.src = ".....";
```
This is a very general technique, and I use it all the time in many objects in the DOM. (I especially use it when I have, say, four buttons and I want them to all share an "onclick" handler; I have the handler pull a bit of custom data out of the button to do THAT button's particular action.)
One warning: you have to be careful not to use a property of the object that the object class itself has a special meaning or use. (For example: you can't use `imageObj.src` for any old custom use; you have to leave it for the source URL.) But, in the general case, how are you to know how a given object uses all its properties? Strictly speaking, you can't. So to make this approach as safe as possible:
* Wrap up all your custom data in a single object
* Assign that object to a property that is unusual/unlikely to be used by the object itself.
In that regard, using "x" and "y" are a little risky as some Javascript implementation in some browser may use those properties when dealing with the Image object. But this is probably safe:
```
imageObj = new Image();
imageObj.myCustomData = {x: 1, y: 2};
imageObj.onload = function() {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
};
imageObj.src = ".....";
```
Another advantage to this approach: it can save a lot of memory if you are creating a lot of a given object -- because you can now share a single instance of the onload handler. Consider this, using closures:
```
// closure based solution -- creates 1000 anonymous functions for "onload"
for (var i=0; i<1000; i++) {
var imageObj = new Image();
var x = i*20;
var y = i*10;
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
imageObj.src = ".....";
}
```
Compare to shared-onload function, with your custom data tucked away in the Image object:
```
// custom data in the object -- creates A SINGLE "onload" function
function myImageOnload () {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
}
for (var i=0; i<1000; i++) {
imageObj = new Image();
imageObj.myCustomData = {x: i*20, y: i*10};
imageObj.onload = myImageOnload;
imageObj.src = ".....";
}
```
Much memory saved and may run a skosh faster since you aren't creating all those anonymous functions. (In this example, the onload function is a one-liner.... but I've had 100-line onload functions, and a 1000 of them would surely be considered spending a lot of memory for no good reason.)
*UPDATE*: See [use of 'data-\*' attribute](https://stackoverflow.com/q/17184918/701435) for a standard (and "standards approved") way to do this, in lieu of my ad-hoc suggestion to use `myCustomData`. | You could use an anonymous function
```
x = 1;
y = 2;
(function(xValue, yValue){
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, xValue, yValue);
};
})(x,y);
x = 3;
y = 4;
``` |
17,578,280 | When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?
```
x = 1;
y = 2;
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
x = 3;
y = 4;
```
In here, I want to use the x and y values that were set at the time I set the src of the image (i.e. 1 and 2). In the code above, by the time the onload function would finish, x and y could be 3 and 4.
Is there a way I can pass values into the onload function, or will it automatically use 1, and 2?
Thanks | 2013/07/10 | [
"https://Stackoverflow.com/questions/17578280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497454/"
] | All the other answers are some version of "make a closure". OK, that works. I think closures are cool, and languages that support them are cool...
However: there is a much cleaner way to do this, IMO. Simply use the image object to store what you need, and access it in the load handler via "`this`":
```
imageObj = new Image();
imageObj.x = 1;
imageObj.y = 2;
imageObj.onload = function() {
context.drawImage(this, this.x, this.y);
};
imageObj.src = ".....";
```
This is a very general technique, and I use it all the time in many objects in the DOM. (I especially use it when I have, say, four buttons and I want them to all share an "onclick" handler; I have the handler pull a bit of custom data out of the button to do THAT button's particular action.)
One warning: you have to be careful not to use a property of the object that the object class itself has a special meaning or use. (For example: you can't use `imageObj.src` for any old custom use; you have to leave it for the source URL.) But, in the general case, how are you to know how a given object uses all its properties? Strictly speaking, you can't. So to make this approach as safe as possible:
* Wrap up all your custom data in a single object
* Assign that object to a property that is unusual/unlikely to be used by the object itself.
In that regard, using "x" and "y" are a little risky as some Javascript implementation in some browser may use those properties when dealing with the Image object. But this is probably safe:
```
imageObj = new Image();
imageObj.myCustomData = {x: 1, y: 2};
imageObj.onload = function() {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
};
imageObj.src = ".....";
```
Another advantage to this approach: it can save a lot of memory if you are creating a lot of a given object -- because you can now share a single instance of the onload handler. Consider this, using closures:
```
// closure based solution -- creates 1000 anonymous functions for "onload"
for (var i=0; i<1000; i++) {
var imageObj = new Image();
var x = i*20;
var y = i*10;
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
imageObj.src = ".....";
}
```
Compare to shared-onload function, with your custom data tucked away in the Image object:
```
// custom data in the object -- creates A SINGLE "onload" function
function myImageOnload () {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
}
for (var i=0; i<1000; i++) {
imageObj = new Image();
imageObj.myCustomData = {x: i*20, y: i*10};
imageObj.onload = myImageOnload;
imageObj.src = ".....";
}
```
Much memory saved and may run a skosh faster since you aren't creating all those anonymous functions. (In this example, the onload function is a one-liner.... but I've had 100-line onload functions, and a 1000 of them would surely be considered spending a lot of memory for no good reason.)
*UPDATE*: See [use of 'data-\*' attribute](https://stackoverflow.com/q/17184918/701435) for a standard (and "standards approved") way to do this, in lieu of my ad-hoc suggestion to use `myCustomData`. | Make a private scope closure that will store x & y values:
```
imageObj.onload = (function(x,y){
return function() {
context.drawImage(imageObj, x, y);
};
})(x,y);
``` |
45,666,502 | I'm new to this site so hopefully I'm phrasing my question correctly.
I'm working through some introductory Android programming. What allows me to call the `Toast.makeText` method, but I cannot do the same for the `setGravity` method immediately after? Why can I reference the first non-static method, but not the next? I'm also new to using anonymous inner classes.
```
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(quizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT.show();
Toast.setGravity(0, 0 ,0);
}
});
``` | 2017/08/14 | [
"https://Stackoverflow.com/questions/45666502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8459833/"
] | You have to create Toast class object
```
public void ShowToast(String message){
Toast t = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
OR
// Toast t = new Toast(getContext()); if custom view require
t.setDuration(Toast.LENGTH_LONG);
t.setText(message);
t.setGravity(Gravity.RIGHT,0,0);
t.show();
}
``` | ```
Toast toast = Toast.makeText(getApplicationContext(),
"text", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
```
`makeText` return a toast object. |
45,666,502 | I'm new to this site so hopefully I'm phrasing my question correctly.
I'm working through some introductory Android programming. What allows me to call the `Toast.makeText` method, but I cannot do the same for the `setGravity` method immediately after? Why can I reference the first non-static method, but not the next? I'm also new to using anonymous inner classes.
```
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(quizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT.show();
Toast.setGravity(0, 0 ,0);
}
});
``` | 2017/08/14 | [
"https://Stackoverflow.com/questions/45666502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8459833/"
] | You have to create Toast class object
```
public void ShowToast(String message){
Toast t = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
OR
// Toast t = new Toast(getContext()); if custom view require
t.setDuration(Toast.LENGTH_LONG);
t.setText(message);
t.setGravity(Gravity.RIGHT,0,0);
t.show();
}
``` | Static methods can be accessed by using their class name. Like: `Classname.staticMethod();`
So, here in `Toast` class, we have `makeText()` method and `setGravity()` method. But `makeText()` method is a static method. So, we can access it by their class name. Just like below:
```
Toast.makeText()
```
But `setGravity()` method is not a static method. So, we can't call it by using their class name.
If you have to call `setGravity()` method then you have to create an object of `Toast` class.
```
Toast t = new Toast(getContext());
t.setDuration(Toast.LENGTH_SHORT);
t.setText(message);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
``` |
16,972,295 | So i'm trying to create a simple String struct which will contain the text of the string and the size of it, at least for now. However I'm having issues allocating my struct. Right now i'm simply trying to get a size of 1 character to work, but its simply crashing at this point and i don't know what i'm doing wrong with the allocation, please help.
```
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char* text;
int size;
}String;
String* getString();
int main(int argc, char** argv){
String* str1 = getString();
printf("%s",str1->text);
free(str1);
return 0;
}
String* getString(){
String* str = (String*)malloc(sizeof(String));
scanf("%s",str->text);
str->size++;
return str;
}
``` | 2013/06/06 | [
"https://Stackoverflow.com/questions/16972295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998810/"
] | You need to allocate memory for the structure but also for `text` string.
```
scanf("%s",str->text);
```
`str->text` is an uninitialized pointer. | ```
int main(int argc, char** argv){
String* str1 = getString();
printf("%s",str1->text);
free(str1->text);
free(str1);
return 0;
}
String* getString(){
String* str = (String*)malloc(sizeof(String));//for struct
str->size = 16;//initialize
str->text = (char*)malloc(sizeof(char)*str->size);//for input text
int ch, len;
while(EOF!=(ch=fgetc(stdin)) && ch != '\n'){
str->text[len++]=ch;
if(str->size==len){
str->text = realloc(str->text, sizeof(char)*(len+=16));
}
}
str->text[len++]='\0';
str->text = realloc(str->text, sizeof(char)*(str->size=len));
return str;
}
``` |
16,972,295 | So i'm trying to create a simple String struct which will contain the text of the string and the size of it, at least for now. However I'm having issues allocating my struct. Right now i'm simply trying to get a size of 1 character to work, but its simply crashing at this point and i don't know what i'm doing wrong with the allocation, please help.
```
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char* text;
int size;
}String;
String* getString();
int main(int argc, char** argv){
String* str1 = getString();
printf("%s",str1->text);
free(str1);
return 0;
}
String* getString(){
String* str = (String*)malloc(sizeof(String));
scanf("%s",str->text);
str->size++;
return str;
}
``` | 2013/06/06 | [
"https://Stackoverflow.com/questions/16972295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998810/"
] | You don't allocate any memory for `str->text`. You leave it uninitialized, so your program invokes undefined behavior.
You need to allocate memory for it using `str->text = malloc(MAX_SIZE);` where `MAX_SIZE` is the maximal size for the string. Alternatively, if your strings will be short, you may use a regular, fixed-szie array instead.
Furthermore, you probably do not want to use `scanf()` for scanning strings. One particular reason is that `%s` makes `scanf()` stop at the first whitespace character. Another reason is that it's not trivial to prevent `scanf()` from writing past the buffer if it's too small.. How about using `fgets()` instead?
```
fgets(str->text, MAX_SIZE, stdin);
```
is a better and safer approach. | ```
int main(int argc, char** argv){
String* str1 = getString();
printf("%s",str1->text);
free(str1->text);
free(str1);
return 0;
}
String* getString(){
String* str = (String*)malloc(sizeof(String));//for struct
str->size = 16;//initialize
str->text = (char*)malloc(sizeof(char)*str->size);//for input text
int ch, len;
while(EOF!=(ch=fgetc(stdin)) && ch != '\n'){
str->text[len++]=ch;
if(str->size==len){
str->text = realloc(str->text, sizeof(char)*(len+=16));
}
}
str->text[len++]='\0';
str->text = realloc(str->text, sizeof(char)*(str->size=len));
return str;
}
``` |
1,614,501 | >
> Find the last $4$ digits of $2016^{2016}$.
>
>
>
Technically I was able to solve this question by I used Wolfram Alpha and modular arithmetic so the worst I had to do was raise a $4$ digit number to the $9$th power. I would do $2016^2 \equiv 4256^2 \equiv \cdots$
and then continue using the prime factorization of $2016$. I am wondering if there is a better way to solve this. | 2016/01/16 | [
"https://math.stackexchange.com/questions/1614501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/297795/"
] | $$\begin{align}(2000+16)^{2016}&\equiv 2016\cdot 2000\cdot 16^{2015} + 16^{2016}&\pmod{10000}\\
&\equiv 2000+16^{2016}&\pmod{10000}
\end{align}$$
So you need to find the last four digits of $16^{2016}$ and add $2000$.
You can actually reduce the exponent modulo $500$, because $16^{2016}\equiv 16^{16}\pmod{625}$ and $16^{2016}\equiv 0\equiv 16^{16}\pmod{16}$.
So you need to compute $16^{16}\mod{10000}$. This can be done by repeated squaring:
$$16^2=256\\
16^4=256^2\equiv 5536\pmod{10000}\\
16^8\equiv 5536^2\equiv 7296\pmod{10000}\\
16^{16}\equiv 7276^2\equiv 1616\pmod{10000}\\
$$
So the result is $2000+1616=3616$. | You can afford to work modulo $16=2^4$ and modulo $625=5^4$ separately. The basis $2016$ is a multiple of $16$ and therefore so are all its powers.
We also know that $2016\equiv141$ modulo $625.$
To take the $2016$-th power note that $141$ is invertible modulo $625$ (because it is relatively prime with $5$) and therefore its $500$-th power is equivalent to $1$ modulo $625$ (the multiplicative group modulo $625$ has order $5^3.(5-1)=500$). Thus we can limit ourselves to the $16$-th power.
To evaluate $141^{16}$ modulo $625$ notice that $141=5^3+16$ so
$$\eqalign{141^{16}=\sum\_{i=0}^{16}{16\choose i}5^{3i}16^{16-i}
&\equiv16^{16}+16.16^{15}.125\\
&\equiv16^{16}+1.125\\
16^{16}=(3.5+1)^{16}=\sum\_{i=0}^{16}{16\choose i}3^i5^i
&\equiv 1+16.3.5+8.15.3^2.5^2+8.5.14.3^3.5^3\\
&\equiv1+48.5+216.125\\
&\equiv1+48.5+1.125=366\\
141^{16}&\equiv366+125=491\\
}$$
This means we are looking for a number between $0$ and $9999$ that is a multiple of $16$ and that is $491$ more than a multiple of $625.$ Since $625\equiv1$ and $491\equiv11$ modulo 16 the solution should be $(16-11).625+491=3616.$ |
1,614,501 | >
> Find the last $4$ digits of $2016^{2016}$.
>
>
>
Technically I was able to solve this question by I used Wolfram Alpha and modular arithmetic so the worst I had to do was raise a $4$ digit number to the $9$th power. I would do $2016^2 \equiv 4256^2 \equiv \cdots$
and then continue using the prime factorization of $2016$. I am wondering if there is a better way to solve this. | 2016/01/16 | [
"https://math.stackexchange.com/questions/1614501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/297795/"
] | You can afford to work modulo $16=2^4$ and modulo $625=5^4$ separately. The basis $2016$ is a multiple of $16$ and therefore so are all its powers.
We also know that $2016\equiv141$ modulo $625.$
To take the $2016$-th power note that $141$ is invertible modulo $625$ (because it is relatively prime with $5$) and therefore its $500$-th power is equivalent to $1$ modulo $625$ (the multiplicative group modulo $625$ has order $5^3.(5-1)=500$). Thus we can limit ourselves to the $16$-th power.
To evaluate $141^{16}$ modulo $625$ notice that $141=5^3+16$ so
$$\eqalign{141^{16}=\sum\_{i=0}^{16}{16\choose i}5^{3i}16^{16-i}
&\equiv16^{16}+16.16^{15}.125\\
&\equiv16^{16}+1.125\\
16^{16}=(3.5+1)^{16}=\sum\_{i=0}^{16}{16\choose i}3^i5^i
&\equiv 1+16.3.5+8.15.3^2.5^2+8.5.14.3^3.5^3\\
&\equiv1+48.5+216.125\\
&\equiv1+48.5+1.125=366\\
141^{16}&\equiv366+125=491\\
}$$
This means we are looking for a number between $0$ and $9999$ that is a multiple of $16$ and that is $491$ more than a multiple of $625.$ Since $625\equiv1$ and $491\equiv11$ modulo 16 the solution should be $(16-11).625+491=3616.$ | Allow me give a different answer from the three ones above and easy to achieve with a calculator, please. This direct procedure can be applied to similar calculations.
One can simply use one or both properties, $A^{abc}=(A^a)^{bc}\equiv(B)^{bc}\pmod{M}$ and $A^n=A^r\cdot A^s\equiv(B)\cdot (C)\pmod{M}$ where $r+s=n$, iterating the process according to convenience of exponents.$$\*\*\*\*\*\*$$
$2016^{2016}=(2^5\cdot3^2\cdot7)^{2016}=(2^{2^5\cdot3^2\cdot5\cdot7})(3^{2^6\cdot3^2\cdot7})(7^{2^5\cdot3^2\cdot7})$
Calculating separately each of the three factors, we have
$2^{2^5\cdot3^2\cdot5\cdot7}\equiv(8368)^{6\cdot6\cdot 8}\equiv (9024)^{6\cdot 8}\equiv (8976)^8\equiv6176\pmod{ 10^4} $
$3^{2^6\cdot3^2\cdot7}\equiv(3203)^{8\cdot8\cdot3}\equiv(3761)^{8\cdot3}\equiv(8881)^3\equiv1841\pmod{ 10^4} $
$7^{2^5\cdot3^2\cdot7}\equiv(4007)^{4\cdot4\cdot6}\equiv(5649)^{4\cdot4}\equiv(2401)^4\equiv9601\pmod{ 10^4} $
Hence $$2016^{2016}\equiv6176\cdot1841\cdot9601\equiv\color{red}{3616}\pmod{ 10^4} $$ |
1,614,501 | >
> Find the last $4$ digits of $2016^{2016}$.
>
>
>
Technically I was able to solve this question by I used Wolfram Alpha and modular arithmetic so the worst I had to do was raise a $4$ digit number to the $9$th power. I would do $2016^2 \equiv 4256^2 \equiv \cdots$
and then continue using the prime factorization of $2016$. I am wondering if there is a better way to solve this. | 2016/01/16 | [
"https://math.stackexchange.com/questions/1614501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/297795/"
] | $$\begin{align}(2000+16)^{2016}&\equiv 2016\cdot 2000\cdot 16^{2015} + 16^{2016}&\pmod{10000}\\
&\equiv 2000+16^{2016}&\pmod{10000}
\end{align}$$
So you need to find the last four digits of $16^{2016}$ and add $2000$.
You can actually reduce the exponent modulo $500$, because $16^{2016}\equiv 16^{16}\pmod{625}$ and $16^{2016}\equiv 0\equiv 16^{16}\pmod{16}$.
So you need to compute $16^{16}\mod{10000}$. This can be done by repeated squaring:
$$16^2=256\\
16^4=256^2\equiv 5536\pmod{10000}\\
16^8\equiv 5536^2\equiv 7296\pmod{10000}\\
16^{16}\equiv 7276^2\equiv 1616\pmod{10000}\\
$$
So the result is $2000+1616=3616$. | Since $2016$ is a multiple of $16$, we shall look at the $2016^ {2016}$ modular $625$.
Well, following from [Euler`s Theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem), $2016^{2016} \equiv 2016^{16} \pmod {625}$. Note that $2016^ {15}=(2000+16)^ {15} \equiv16^ {15} \pmod {625}$, following from the [Binomial theorem](https://en.wikipedia.org/wiki/Binomial_theorem). However, $16^ {15}=2^ {60} \equiv 399^6 \equiv (400-1)^6$, which calculated through the binomial theorem, is $101$. This gives us that $2016^ {16} \equiv 101\*2016 \equiv 491 \pmod {625}$.
Combining this with the upper result gives us $3616$. |
1,614,501 | >
> Find the last $4$ digits of $2016^{2016}$.
>
>
>
Technically I was able to solve this question by I used Wolfram Alpha and modular arithmetic so the worst I had to do was raise a $4$ digit number to the $9$th power. I would do $2016^2 \equiv 4256^2 \equiv \cdots$
and then continue using the prime factorization of $2016$. I am wondering if there is a better way to solve this. | 2016/01/16 | [
"https://math.stackexchange.com/questions/1614501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/297795/"
] | Since $2016$ is a multiple of $16$, we shall look at the $2016^ {2016}$ modular $625$.
Well, following from [Euler`s Theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem), $2016^{2016} \equiv 2016^{16} \pmod {625}$. Note that $2016^ {15}=(2000+16)^ {15} \equiv16^ {15} \pmod {625}$, following from the [Binomial theorem](https://en.wikipedia.org/wiki/Binomial_theorem). However, $16^ {15}=2^ {60} \equiv 399^6 \equiv (400-1)^6$, which calculated through the binomial theorem, is $101$. This gives us that $2016^ {16} \equiv 101\*2016 \equiv 491 \pmod {625}$.
Combining this with the upper result gives us $3616$. | Allow me give a different answer from the three ones above and easy to achieve with a calculator, please. This direct procedure can be applied to similar calculations.
One can simply use one or both properties, $A^{abc}=(A^a)^{bc}\equiv(B)^{bc}\pmod{M}$ and $A^n=A^r\cdot A^s\equiv(B)\cdot (C)\pmod{M}$ where $r+s=n$, iterating the process according to convenience of exponents.$$\*\*\*\*\*\*$$
$2016^{2016}=(2^5\cdot3^2\cdot7)^{2016}=(2^{2^5\cdot3^2\cdot5\cdot7})(3^{2^6\cdot3^2\cdot7})(7^{2^5\cdot3^2\cdot7})$
Calculating separately each of the three factors, we have
$2^{2^5\cdot3^2\cdot5\cdot7}\equiv(8368)^{6\cdot6\cdot 8}\equiv (9024)^{6\cdot 8}\equiv (8976)^8\equiv6176\pmod{ 10^4} $
$3^{2^6\cdot3^2\cdot7}\equiv(3203)^{8\cdot8\cdot3}\equiv(3761)^{8\cdot3}\equiv(8881)^3\equiv1841\pmod{ 10^4} $
$7^{2^5\cdot3^2\cdot7}\equiv(4007)^{4\cdot4\cdot6}\equiv(5649)^{4\cdot4}\equiv(2401)^4\equiv9601\pmod{ 10^4} $
Hence $$2016^{2016}\equiv6176\cdot1841\cdot9601\equiv\color{red}{3616}\pmod{ 10^4} $$ |
1,614,501 | >
> Find the last $4$ digits of $2016^{2016}$.
>
>
>
Technically I was able to solve this question by I used Wolfram Alpha and modular arithmetic so the worst I had to do was raise a $4$ digit number to the $9$th power. I would do $2016^2 \equiv 4256^2 \equiv \cdots$
and then continue using the prime factorization of $2016$. I am wondering if there is a better way to solve this. | 2016/01/16 | [
"https://math.stackexchange.com/questions/1614501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/297795/"
] | $$\begin{align}(2000+16)^{2016}&\equiv 2016\cdot 2000\cdot 16^{2015} + 16^{2016}&\pmod{10000}\\
&\equiv 2000+16^{2016}&\pmod{10000}
\end{align}$$
So you need to find the last four digits of $16^{2016}$ and add $2000$.
You can actually reduce the exponent modulo $500$, because $16^{2016}\equiv 16^{16}\pmod{625}$ and $16^{2016}\equiv 0\equiv 16^{16}\pmod{16}$.
So you need to compute $16^{16}\mod{10000}$. This can be done by repeated squaring:
$$16^2=256\\
16^4=256^2\equiv 5536\pmod{10000}\\
16^8\equiv 5536^2\equiv 7296\pmod{10000}\\
16^{16}\equiv 7276^2\equiv 1616\pmod{10000}\\
$$
So the result is $2000+1616=3616$. | Allow me give a different answer from the three ones above and easy to achieve with a calculator, please. This direct procedure can be applied to similar calculations.
One can simply use one or both properties, $A^{abc}=(A^a)^{bc}\equiv(B)^{bc}\pmod{M}$ and $A^n=A^r\cdot A^s\equiv(B)\cdot (C)\pmod{M}$ where $r+s=n$, iterating the process according to convenience of exponents.$$\*\*\*\*\*\*$$
$2016^{2016}=(2^5\cdot3^2\cdot7)^{2016}=(2^{2^5\cdot3^2\cdot5\cdot7})(3^{2^6\cdot3^2\cdot7})(7^{2^5\cdot3^2\cdot7})$
Calculating separately each of the three factors, we have
$2^{2^5\cdot3^2\cdot5\cdot7}\equiv(8368)^{6\cdot6\cdot 8}\equiv (9024)^{6\cdot 8}\equiv (8976)^8\equiv6176\pmod{ 10^4} $
$3^{2^6\cdot3^2\cdot7}\equiv(3203)^{8\cdot8\cdot3}\equiv(3761)^{8\cdot3}\equiv(8881)^3\equiv1841\pmod{ 10^4} $
$7^{2^5\cdot3^2\cdot7}\equiv(4007)^{4\cdot4\cdot6}\equiv(5649)^{4\cdot4}\equiv(2401)^4\equiv9601\pmod{ 10^4} $
Hence $$2016^{2016}\equiv6176\cdot1841\cdot9601\equiv\color{red}{3616}\pmod{ 10^4} $$ |
7,757,506 | I have the following code:
```
<tr>
<td class="add_border_bold" nowrap="nowrap">Schedule Saved (days)</td>
<td width="100%" class="add_border">
<%# Eval("schedule_saved_days", "{0:0,0}")%>
</td>
</tr>
<tr>
<td class="add_border_bold" nowrap="nowrap">Scheduled Saved in Months</td>
<td width="100%" class="add_border">
<%# Eval("schedule_saved_days", "{0:0,0}")%>
</td>
</tr>
```
What the requirement is, is to display the second 'schedule saved' in months, rather than days (for some reason they can't figure it out based on days). previously in coldfusion i had just been dividing the number by 30. i had tried a couple different things like `<%# Eval("schedule_saved_days"/30, "{0:0,0.00}")%>` and `<%# Eval("schedule_saved_days/30)%>` just to get something to work. i'm sure this is a quick fix and my google-fu is failing me. Thanks in advance. | 2011/10/13 | [
"https://Stackoverflow.com/questions/7757506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397344/"
] | Try something like this:
```
<%#(Convert.ToDecimal(Eval("schedule_saved_days")) / 30).ToString("0,0")%>
``` | I think something like this is what you are after:
```
<%# (Eval("schedule_saved_days") / 30).ToString("0,0")%>
``` |
7,757,506 | I have the following code:
```
<tr>
<td class="add_border_bold" nowrap="nowrap">Schedule Saved (days)</td>
<td width="100%" class="add_border">
<%# Eval("schedule_saved_days", "{0:0,0}")%>
</td>
</tr>
<tr>
<td class="add_border_bold" nowrap="nowrap">Scheduled Saved in Months</td>
<td width="100%" class="add_border">
<%# Eval("schedule_saved_days", "{0:0,0}")%>
</td>
</tr>
```
What the requirement is, is to display the second 'schedule saved' in months, rather than days (for some reason they can't figure it out based on days). previously in coldfusion i had just been dividing the number by 30. i had tried a couple different things like `<%# Eval("schedule_saved_days"/30, "{0:0,0.00}")%>` and `<%# Eval("schedule_saved_days/30)%>` just to get something to work. i'm sure this is a quick fix and my google-fu is failing me. Thanks in advance. | 2011/10/13 | [
"https://Stackoverflow.com/questions/7757506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397344/"
] | Try something like this:
```
<%#(Convert.ToDecimal(Eval("schedule_saved_days")) / 30).ToString("0,0")%>
``` | You will need to cast it as an integer first and then divide by 30
```
<%# ((int)Eval("schedule_saved_days", "{0:0,0}")/30).tostring() %>
``` |
58,909,925 | I need to call a function when modal close. My code as follows,
```
function openModal(divName) {
$("#"+divName+"Modal").modal({
overlayClose: false,
closeHTML: "<a href='#' title='Close' class='modal-close'>X</a>",
onShow: function (dialog) {
$('#simplemodal-container').css({ 'width': 'auto', 'height': 'auto', 'padding-bottom': '1000px' });
var tmpW = $('#simplemodal-container').width() / 2
var tmpH = $('#simplemodal-container').height() / 2
$('#simplemodal-container').css({ 'margin-left': tmpW * -1, 'margin-top': tmpH * -1 });
},
close:onClose,
onClose: ModalClose(),
opacity: 50,
persist: true
});
}
```
I tried two ways to call a function as follows, but both not working
1st way
```
function onClose() {
alert('called');
}
```
2nd way
```
$('.resetbutton').click(function () {
alert('called');
}
``` | 2019/11/18 | [
"https://Stackoverflow.com/questions/58909925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3703534/"
] | For `Grouper` need datetimes, so format of datetimes is changed by [`MultiIndex.set_levels`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.set_levels.html) after aggregation and also added `closed='left'` for left closing bins:
```
df1['date'] = pd.to_datetime(df1['date'])
df2 = df1.groupby([pd.Grouper(key='date', freq='W-MON', closed='left'),
'Company',
'Email'])['Email'].count()
new = ((df2.index.levels[0] - pd.to_timedelta(7, unit='d')).strftime('%B%d') + ' - '+
df2.index.levels[0].strftime('%B%d') )
df2.index = df2.index.set_levels(new, level=0)
print (df2)
date Company Email
October07 - October14 abc [email protected] 2
[email protected] 1
def [email protected] 1
xyz [email protected] 1
October14 - October21 abc [email protected] 1
def [email protected] 1
xyz [email protected] 1
[email protected] 1
Name: Email, dtype: int64
```
For first DataFrame use `sum` per first and second levels and reshape by [`Series.unstack`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html):
```
df3 = df2.sum(level=[0,1]).unstack(fill_value=0)
print (df3)
Company abc def xyz
date
October07 - October14 3 1 1
October14 - October21 1 1 2
``` | 1. Add a column that maps the date to a week
2. Do something with grouping: i.e. `df.groupby(df.week).count()` |
1,996,482 | I thought I would write some quick code to download the number of "fans" a Facebook page has.
For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case either. Surely it is possible to have some wildcard between the two matching bits?
The text I'd like to match against is "**6 of X fans**", where X is an arbitrary number of fans a page has - I would like to get this number.
I was thinking of polling this data intermittently and writing to a file but I haven't gotten around to that yet. I'm also wondering if this is headed in the right direction, as the code seems pretty clunky. :)
```
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
for lines in fbhandle.readlines():
ms = compiled.match(lines)
print ms #debugging
if ms: break
#ms.group()
print ms
fbhandle.close()
``` | 2010/01/03 | [
"https://Stackoverflow.com/questions/1996482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207201/"
] | ```
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
ms = compiled.search(fbhandle.read())
print ms.group(1).strip()
fbhandle.close()
```
You needed to use `re.search()` instead. Using `re.match()` tries to match the pattern against the *whole* document, but really you're just trying to match a piece inside the document. The code above prints: `79,110`. Of course, this will probably be a different number by the time it gets run by someone else. | don't need regex
```
import urllib
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
for line in fbhandle.readlines():
line=line.rstrip().split("</span>")
for item in line:
if ">Fans<" in item:
rind=item.rindex("<span>")
print "-->",item[rind:].split()[2]
```
output
```
$ ./python.py
--> 79,133
``` |
1,996,482 | I thought I would write some quick code to download the number of "fans" a Facebook page has.
For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case either. Surely it is possible to have some wildcard between the two matching bits?
The text I'd like to match against is "**6 of X fans**", where X is an arbitrary number of fans a page has - I would like to get this number.
I was thinking of polling this data intermittently and writing to a file but I haven't gotten around to that yet. I'm also wondering if this is headed in the right direction, as the code seems pretty clunky. :)
```
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
for lines in fbhandle.readlines():
ms = compiled.match(lines)
print ms #debugging
if ms: break
#ms.group()
print ms
fbhandle.close()
``` | 2010/01/03 | [
"https://Stackoverflow.com/questions/1996482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207201/"
] | ```
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
ms = compiled.search(fbhandle.read())
print ms.group(1).strip()
fbhandle.close()
```
You needed to use `re.search()` instead. Using `re.match()` tries to match the pattern against the *whole* document, but really you're just trying to match a piece inside the document. The code above prints: `79,110`. Of course, this will probably be a different number by the time it gets run by someone else. | Evan Fosmark already gave a good answer. This is just more info.
You have this line:
```
pattern = "6 of(.*)fans"
```
In general, this isn't a good regular expression. If the input text was:
"6 of 99 fans in the whole galaxy of fans"
Then the match group (the stuff inside the parentheses) would be:
" 99 fans in the whole galaxy of "
So, we want a pattern that will just grab what you want, even with a silly input text like the above.
In this case, it doesn't really matter if you match the white space, because when you convert a string to an integer, white space is ignored. But let's write the pattern to ignore white space.
With the `*` wildcard, it is possible to match a string of length zero. In this case I think you always want a non-empty match, so you want to use `+` to match one or more characters.
Python has non-greedy matching available, so you could rewrite with that. Older programs with regular expressions may not have non-greedy matching, so I'll also give a pattern that doesn't require non-greedy.
So, the non-greedy pattern:
```
pattern = "6 of\s+(.+?)\s+fans"
```
The other one:
```
pattern = "6 of\s+(\S+)\s+fans"
```
`\s` means "any white space" and will match a space, a tab, and a few other characters (such as "form feed"). `\S` means "any non-white-space" and matches anything that `\s` would *not* match.
The first pattern does better than your first pattern with the silly input text:
"6 of 99 fans in the whole galaxy of fans"
It would return a match group of just `99`.
But try this other silly input text:
"6 of 99 crazed fans"
It would return a match group of `99 crazed`.
The second pattern would not match at all, because the word "crazed" isn't the word "fans".
Hmm. Here's one last pattern that should always do the right thing even with silly input texts:
```
pattern = "6 of\D*?(\d+)\D*?fans"
```
`\d` matches any digit (`'0'` to `'9'`). `\D` matches any non-digit.
This will successfully match anything that is remotely non-ambiguous:
"6 of 99 fans in the whole galaxy of fans"
The match group will be `99`.
"6 of 99 crazed fans"
The match group will be `99`.
"6 of 99 41 fans"
It will not match, because there was a second number in there.
To learn more about Python regular expressions, you can read [various](http://www.amk.ca/python/howto/regex/) [web](http://diveintopython.net/regular_expressions/index.html) [pages](http://docs.python.org/library/re.html). For a quick reminder, inside the Python interpreter, do:
```
>>> import re
>>> help(re)
```
When you are "scraping" text from a web page, you might sometimes run afoul of HTML codes. In general, regular expressions are not a good tool for disregarding HTML or XML markup (see [here](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)); you would probably do better to use [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) to parse the HTML and extract the text, followed by a regular expression to grab the text you really wanted.
I hope this was interesting and/or educational. |
1,996,482 | I thought I would write some quick code to download the number of "fans" a Facebook page has.
For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case either. Surely it is possible to have some wildcard between the two matching bits?
The text I'd like to match against is "**6 of X fans**", where X is an arbitrary number of fans a page has - I would like to get this number.
I was thinking of polling this data intermittently and writing to a file but I haven't gotten around to that yet. I'm also wondering if this is headed in the right direction, as the code seems pretty clunky. :)
```
import urllib
import re
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
pattern = "6 of(.*)fans" #this wild card doesnt appear to work?
compiled = re.compile(pattern)
for lines in fbhandle.readlines():
ms = compiled.match(lines)
print ms #debugging
if ms: break
#ms.group()
print ms
fbhandle.close()
``` | 2010/01/03 | [
"https://Stackoverflow.com/questions/1996482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207201/"
] | Evan Fosmark already gave a good answer. This is just more info.
You have this line:
```
pattern = "6 of(.*)fans"
```
In general, this isn't a good regular expression. If the input text was:
"6 of 99 fans in the whole galaxy of fans"
Then the match group (the stuff inside the parentheses) would be:
" 99 fans in the whole galaxy of "
So, we want a pattern that will just grab what you want, even with a silly input text like the above.
In this case, it doesn't really matter if you match the white space, because when you convert a string to an integer, white space is ignored. But let's write the pattern to ignore white space.
With the `*` wildcard, it is possible to match a string of length zero. In this case I think you always want a non-empty match, so you want to use `+` to match one or more characters.
Python has non-greedy matching available, so you could rewrite with that. Older programs with regular expressions may not have non-greedy matching, so I'll also give a pattern that doesn't require non-greedy.
So, the non-greedy pattern:
```
pattern = "6 of\s+(.+?)\s+fans"
```
The other one:
```
pattern = "6 of\s+(\S+)\s+fans"
```
`\s` means "any white space" and will match a space, a tab, and a few other characters (such as "form feed"). `\S` means "any non-white-space" and matches anything that `\s` would *not* match.
The first pattern does better than your first pattern with the silly input text:
"6 of 99 fans in the whole galaxy of fans"
It would return a match group of just `99`.
But try this other silly input text:
"6 of 99 crazed fans"
It would return a match group of `99 crazed`.
The second pattern would not match at all, because the word "crazed" isn't the word "fans".
Hmm. Here's one last pattern that should always do the right thing even with silly input texts:
```
pattern = "6 of\D*?(\d+)\D*?fans"
```
`\d` matches any digit (`'0'` to `'9'`). `\D` matches any non-digit.
This will successfully match anything that is remotely non-ambiguous:
"6 of 99 fans in the whole galaxy of fans"
The match group will be `99`.
"6 of 99 crazed fans"
The match group will be `99`.
"6 of 99 41 fans"
It will not match, because there was a second number in there.
To learn more about Python regular expressions, you can read [various](http://www.amk.ca/python/howto/regex/) [web](http://diveintopython.net/regular_expressions/index.html) [pages](http://docs.python.org/library/re.html). For a quick reminder, inside the Python interpreter, do:
```
>>> import re
>>> help(re)
```
When you are "scraping" text from a web page, you might sometimes run afoul of HTML codes. In general, regular expressions are not a good tool for disregarding HTML or XML markup (see [here](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)); you would probably do better to use [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) to parse the HTML and extract the text, followed by a regular expression to grab the text you really wanted.
I hope this was interesting and/or educational. | don't need regex
```
import urllib
fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft')
for line in fbhandle.readlines():
line=line.rstrip().split("</span>")
for item in line:
if ">Fans<" in item:
rind=item.rindex("<span>")
print "-->",item[rind:].split()[2]
```
output
```
$ ./python.py
--> 79,133
``` |
28,664,098 | I'm extremely new to code writing, so please forgive any ignorance on my part. I have a simple bit of code in which I would like to make the visibility of a couple of "outerCircle" divs turn off when the user clicks anywhere on the page. I have tried several ways, but it's just not working. If anyone has a suggestion, I would greatly appreciate it. Here is what I have so far:
```
<body onload = "startBlink()" onclick = "onOff()">
<p id = "title">Click anywhere to turn the outer circles on or off.</p>
<div class = "container" onclick = "onOff()">
<div class = "outerCircle" id = "outerLeftCircle">
<div class = "innerCircle" id = "innerLeftCircle">
</div>
</div>
<div class = "outerCircle" id = "outerRightCircle">
<div class = "innerCircle" id = "innerRightCircle">
</div>
</div>
</div><!-- Closes the container div -->
<script>
// This function blinks the innerCircle div //
function startBlink(){
var colors = ["white","black"];
var i = 0;
setInterval(function() {
$(".innerCircle").css("background-color", colors[i]);
i = (i+1)%colors.length;
}, 400);
}
// This function turns the outerCircle divs on or off //
function onOff() {
alert("Entering function now");
if (getElementById(".outerCircle").style.visibility = "visible") {
getElementById(".outerCircle").style.visibility = "hidden";
getElementById(".outerLeftCircle").style.visibility = "hidden";
getElementById(".outerRightCircle").style.visibility = "hidden";
} else {
getElementById(".outerCircle").style.visibility = "visible";
getElementById(".outerLeftCircle").style.visibility = "visible";
getElementById(".outerRightCircle").style.visibility = "visible";
}
}
</script>
``` | 2015/02/22 | [
"https://Stackoverflow.com/questions/28664098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4484550/"
] | edited my answer since I've been learning a thing or two these last couple of weeks ;)
you need an apostrophe around to: and cc: lists with more than one recipient
you also need an apostrophe around any main body text or attachments you're going to send
if you put an apostrophe into your VBA editor, it just comments it out, so you can get away with that by using Chr(39)
also, as the documentation suggests, you need
attachment='file:///c:/test.txt'
which includes the file:///
I've included an example from something I've been working on below
```
Dim reportTB As Object
Set reportTB = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
reportTB.Run "thunderbird.exe -compose to=bfx_" & LCase(show) & "[email protected],subject=[" & show & "] EOD Report " _
& prjDate & ",body=" & Chr(39) & "Hi " & UCase(show) & "ers,<br><br>Today's end of day report is attached.<br>" & _
"Any questions let me know.<br><br>Edi " & Chr(39) & ",attachment=" & Chr(39) & reportPath & Chr(39), windowStyle, waitOnReturn
```
Hope that helps :) | Write proper programs. You can't send attachments with mailto. The standard only allows one parameter (although everyone accepts many).
```
Set emailObj = CreateObject("CDO.Message")
emailObj.From = "[email protected]"
emailObj.To = "[email protected]"
emailObj.Subject = "Test CDO"
emailObj.TextBody = "Test CDO"
emailObj.AddAttachment "C:/Users/User/Desktop/err.fff"
Set emailConfig = emailObj.Configuration
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "dc"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Password1"
emailConfig.Fields.Update
emailObj.Send
If err.number = 0 then
Msgbox "Done"
Else
Msgbox err.number & " " & err.description
err.clear
End If
``` |
13,357,583 | Which Platforms are supported for the IBM Social Business Toolkit SDK? Can I run the SDK on an IBM Domino/XWork server? | 2012/11/13 | [
"https://Stackoverflow.com/questions/13357583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1167759/"
] | The following platforms are supported:
* WebSphere Application Server 7
* WebSphere Portal 8
* Domino Server 8.5
* Tomcat 7
So yes, you can use the SDK on an IBM Domino/XWork Server. | The SDK should work with minimal amount of work on any J2EE server.
The WebSphere Application Server, Portal 8, Domino 8.5, Tomcat 7 are the tested versions. |
2,535,958 | I have obtained the crosshair cursor from NSCursor crosshairCursor. Then, how can i change
to it. I don't want to call enclosingScrollView to setDocumentCursor as
[[view enclosingScrollView] setDocumentCursor:crosshaircursor ]; | 2010/03/29 | [
"https://Stackoverflow.com/questions/2535958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276989/"
] | I found out an easy way to do this:
setStyle("arrowButtonWidth", 0);
In my custom combobox, I set the initial width of the arrow button to 0.
Then in the List change event,
```
addEventListener(ListEvent.CHANGE, changeHandler);
```
if the size of the dataprovider is greater than 1, the arrow width is set back to (say) 20
```
setStyle("arrowButtonWidth", 20);
```
This approach is much simpler than the above approaches. If you know any pitfall of my approach, please share. | How about creating a simple custom canvas with both components (textinput and combo) with two states.
You display the textinput in one state and the combo in the other state?
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
<mx:states>
<mx:State name="combo">
<mx:RemoveChild target="{textinput1}"/>
<mx:AddChild position="lastChild">
<mx:ComboBox x="48" y="10"></mx:ComboBox>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:TextInput x="48" y="10" id="textinput1"/>
<mx:Label x="10" y="12" text="Text"/>
</mx:Canvas>
``` |
2,535,958 | I have obtained the crosshair cursor from NSCursor crosshairCursor. Then, how can i change
to it. I don't want to call enclosingScrollView to setDocumentCursor as
[[view enclosingScrollView] setDocumentCursor:crosshaircursor ]; | 2010/03/29 | [
"https://Stackoverflow.com/questions/2535958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276989/"
] | I found out an easy way to do this:
setStyle("arrowButtonWidth", 0);
In my custom combobox, I set the initial width of the arrow button to 0.
Then in the List change event,
```
addEventListener(ListEvent.CHANGE, changeHandler);
```
if the size of the dataprovider is greater than 1, the arrow width is set back to (say) 20
```
setStyle("arrowButtonWidth", 20);
```
This approach is much simpler than the above approaches. If you know any pitfall of my approach, please share. | You could also provide a custom button skin for either case, which would be accessible by changing the styleName. This would potentially be lighter weight than user294702's solution.
For example, using dummy names for source and symbols:
```
.comboBoxWithArrow {
up-skin: Embed(source="graphics.swf",symbol="comboArrowUp");
down-skin: Embed(source="graphics.swf",symbol="comboArrowDown");
over-skin: Embed(source="graphics.swf",symbol="comboArrowOver");
disabled-skin: Embed(source="graphics.swf",symbol="comboArrowDisabled");
/* and any other skin states you want to support */
}
.comboBoxWithoutArrow {
up-skin: Embed(source="graphics.swf",symbol="comboNoArrowUp");
down-skin: Embed(source="graphics.swf",symbol="comboNoArrowDown");
over-skin: Embed(source="graphics.swf",symbol="comboNoArrowOver");
disabled-skin: Embed(source="graphics.swf",symbol="comboNoArrowDisabled");
/* and any other skin states you want to support */
}
```
If your conditions warrant it, set the styleName to the one that shows the arrow, otherwise set it to the one that shows no arrow. |
274,229 | How can we convert a .tif with .tfw .htm into a raster KML/KMZ file to open in google earth? I have a .tif file along with a .tfw and .htm files. I wanted to open it in Google Earth. Converting the .tif into a raster in KML/KMZ format will solve the problem. I was working in MATLAB mapping toolbox and did not find a solution in there. A Matlab or any opensource solution will work. | 2018/03/09 | [
"https://gis.stackexchange.com/questions/274229",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/116129/"
] | You can use [`ST_Dimension`](https://postgis.net/docs/ST_Dimension.html), which returns the largest dimension of a GeometryCollection's components.
For an undoubtedly excellent reason that's well-rooted in thoughtfully-drafted specifications, [`ST_Dimension`](https://postgis.net/docs/ST_Dimension.html) produces dimensions starting at `0`, while [`ST_CollectionExtract`](https://postgis.net/docs/ST_CollectionExtract.html) accepts dimensions beginning with `1`. (In other words, [`ST_Dimension`](https://postgis.net/docs/ST_Dimension.html) uses `2` to indicate a polygon, while [`ST_CollectionExtract`](https://postgis.net/docs/ST_CollectionExtract.html) uses `3` to indicate a polygon.) So to extract the highest-dimension geometries from a GeometryCollection, you would use:
```
SELECT ST_CollectionExtract(geom, 1 + ST_Dimension(geom))
FROM my_data;
``` | I think there must be a more elegant way of doing this, but one approach would be to combine three UNION SELECTS with three CASE statements testing for each geomety type, combined with an ST\_IsEmpty test returning -1 if the type is not found, and then use the max of the result of that in a final select. This returns a MultiPolygon, as I used the union of the test input geometries in the subquery extracts. This would need tweaking to deal with @user30148's question
```
WITH geoms (geom) AS
(VALUES
(ST_Makepoint(0,0)),
(ST_Buffer(ST_Makepoint(1, 10), 2)),
(ST_Buffer(ST_Makepoint(50, 50), 5))),
collection(geom) AS (
SELECT ST_Union(geom)
FROM geoms
),
extracts(geom_type) AS (
SELECT CASE
WHEN NOT ST_Isempty(ST_CollectionExtract(geom, 3))
THEN 3
ELSE -1 END
FROM collection
UNION
SELECT CASE
WHEN NOT ST_Isempty(ST_CollectionExtract(geom, 2))
THEN 2
ELSE -1
END
FROM collection
UNION
SELECT CASE
WHEN NOT ST_Isempty(ST_CollectionExtract(geom, 1))
THEN 1
ELSE -1 END
FROM collection
),
max_type(geom_type) AS (
SELECT max(geom_type) FROM extracts
)
SELECT ST_CollectionExtract(geom, geom_type)
FROM collection, max_type;
``` |
41,505,806 | ```
create table abc(name character(n), name1 character varying(n), name2 text);
```
In the above query what is the limit of 'n'?
```
create table abc(name character(), name1 character varying(), name2 text);
```
In the above query what it will take if we not specify any value to 'n'? | 2017/01/06 | [
"https://Stackoverflow.com/questions/41505806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6853242/"
] | [Quote from the manual](https://www.postgresql.org/docs/current/static/datatype-character.html)
>
> The notations `varchar(n)` and `char(n)` are aliases for `character varying(n)` and `character(n)`, respectively. `character` without length specifier is equivalent to `character(1)`. If `character varying` is used without length specifier, the type accepts strings of any size.
>
>
>
and further down:
>
> In any case, the longest possible character string that can be stored is about 1 GB
>
>
> | While creating table the limit of 'n' for CHARACTER and CHARACTER VARYING datatype is,
```
MIN MAX
CHARACTER(n) --> 1 to 10485760 characters(not bytes)
CHARACTER VARYING(n) --> 1 to 10485760 characters(not bytes)
```
* character() if you do not specify the length it take default as character(1) when you create the table, but you can leave the column values empty.
* character varying() if you do not specify the length it will create the column with no errors, you can insert values from 0 to 10485760 characters to the column.
* For `text` datatype you cannot specify the length, you can insert values from 0 to 10485760 characters to the column. |
5,333,734 | I am messing around trying to write a small web crawler. I parse out a url from some html and sometimes I get a php redirect page. I am looking for a way to get the uri of the redirected page.
I am trying to use System.Net.WebRequest to get a a stream using code like this
```
WebRequest req = WebRequest.Create(link);
Stream s = req.GetResponse().GetResponseStream();
StreamReader st = new StreamReader(WebRequest.Create(link).GetResponse().GetResponseStream());
```
The problem is that the link is a PHP redirect, so the stream is always null. How would I get the URI to the page the php is redirecting? | 2011/03/17 | [
"https://Stackoverflow.com/questions/5333734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/582080/"
] | ```
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(link);
req.AllowAutoRedirect = true;
reg.AutomaticDecompression = DecompressionMethods.GZip;
StreamReader _st = new StreamReader(_req.GetResponseStream(), System.Text.Encoding.GetEncoding(req.CharacterSet));
```
the AllowAutoRedirect will automatically take you to the new URI; if that is you're desired effect. The AutomaticDecompression will auto decompress compressed responses. Also you should be executing the get response stream part in a try catch block. I my exp it throws alot of WebExceptions.
Since you're experimenting with this technology make sure you read the data with the correct encoding. If you attempt to get data from a japanese site without using Unicode then the data will be invalid. | Check the "Location" header from the response - it should contain the new URL. |
2,921,389 | I am creating a doc file and writing a text containing ^m in it and facing issue. Does this ^m is a special character for doc file ? If I replace ^m with some other characters (like ^m with >m or any other) then It works fine. I faced this issue with other characters too like ^a and few other. What could be the solution ? | 2010/05/27 | [
"https://Stackoverflow.com/questions/2921389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276279/"
] | ^M -- as in: Control-M -- is often used to type a 'carriage return' character (ASCII-code 13 in decimal, 0D in hex). | It could be that it is evaluated as an logical expression. Try to escape it either prepending ' before it, or \ . |
53,773,278 | I created two Rectangles. I want to add events on them. For example when mouse hover on one, the hovered one will change color, can do resize or drag them(rectangles) to other place...
I was just wondering if I could control the drawn graphic, or it will like *Microsoft Paint* that after you painted, the object can not be operate unless you clear canvas and do redraw.
Is it possible to control a drawn graphic, thanks for any suggestion.
**Simple code of my drawn graphics**
```
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create rectangle.
Rectangle rect1 = new Rectangle(20, 20, 250, 250);
Rectangle rect2 = new Rectangle(70, 70, 150, 150);
// Draw rectangle to screen.
e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rect1);
e.Graphics.FillRectangle(Brushes.LightBlue, rect2);
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53773278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10309167/"
] | Also, you can create your own control like:
```
class RectangleControl : Control
{
public void FillRectangle(Color color)
{
this.BackColor = color;
}
}
```
Then :
```
private void Form1_Paint(object sender, PaintEventArgs e)
{
RectangleControl rect1 = new RectangleControl() { Parent = this, Left = 20, Top = 20, Width = 250, Height = 250 };
rect1.FillRectangle(Color.DeepSkyBlue);
RectangleControl rect2 = new RectangleControl() { Parent = rect1, Left = 50, Top = 50, Width = 150, Height = 150 };
rect2.FillRectangle(Color.LightBlue);
rect1.MouseHover += Rect1_MouseHover;
rect2.MouseLeave += Rect2_MouseLeave;
}
private void Rect2_MouseLeave(object sender, EventArgs e)
{
(sender as RectangleControl).BackColor = Color.Yellow;
}
private void Rect1_MouseHover(object sender, EventArgs e)
{
(sender as RectangleControl).BackColor = Color.LightBlue;
}
``` | You can use Panel control instead.
Just add 2 panel controls as you would like them to be arranged and add 2 event handlers:
```
private void panel1_MouseHover(object sender, EventArgs e)
{
panel1.BackColor = Color.Yellow;
}
private void panel1_MouseLeave(object sender, EventArgs e)
{
panel1.BackColor = Color.LightBlue;
}
``` |
53,773,278 | I created two Rectangles. I want to add events on them. For example when mouse hover on one, the hovered one will change color, can do resize or drag them(rectangles) to other place...
I was just wondering if I could control the drawn graphic, or it will like *Microsoft Paint* that after you painted, the object can not be operate unless you clear canvas and do redraw.
Is it possible to control a drawn graphic, thanks for any suggestion.
**Simple code of my drawn graphics**
```
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create rectangle.
Rectangle rect1 = new Rectangle(20, 20, 250, 250);
Rectangle rect2 = new Rectangle(70, 70, 150, 150);
// Draw rectangle to screen.
e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rect1);
e.Graphics.FillRectangle(Brushes.LightBlue, rect2);
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53773278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10309167/"
] | Also, you can create your own control like:
```
class RectangleControl : Control
{
public void FillRectangle(Color color)
{
this.BackColor = color;
}
}
```
Then :
```
private void Form1_Paint(object sender, PaintEventArgs e)
{
RectangleControl rect1 = new RectangleControl() { Parent = this, Left = 20, Top = 20, Width = 250, Height = 250 };
rect1.FillRectangle(Color.DeepSkyBlue);
RectangleControl rect2 = new RectangleControl() { Parent = rect1, Left = 50, Top = 50, Width = 150, Height = 150 };
rect2.FillRectangle(Color.LightBlue);
rect1.MouseHover += Rect1_MouseHover;
rect2.MouseLeave += Rect2_MouseLeave;
}
private void Rect2_MouseLeave(object sender, EventArgs e)
{
(sender as RectangleControl).BackColor = Color.Yellow;
}
private void Rect1_MouseHover(object sender, EventArgs e)
{
(sender as RectangleControl).BackColor = Color.LightBlue;
}
``` | You can monitor the `MouseMove`.
Here's code using `MouseMove` and some brush values used by the rectangles.
```
using System.Drawing;
using System.Windows.Forms;
namespace Question_Answer_WinForms_App
{
public partial class Form1 : Form
{
public Brush outerRectangleBrush = Brushes.DeepSkyBlue;
public Brush innerRectangleBrush = Brushes.LightBlue;
public Form1()
{
InitializeComponent();
Paint += Form1_Paint;
MouseMove += Form1_MouseMove;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
var isWithinOuterRectangle = e.Location.X >= 20
&& e.Location.X <= 250 + 20
&& e.Location.Y >= 20
&& e.Location.Y <= 250 + 20;
var isWithinInnerRectangle = e.Location.X >= 70
&& e.Location.X <= 150 + 70
&& e.Location.Y >= 70
&& e.Location.Y <= 150 + 70;
if (isWithinOuterRectangle)
{
if (isWithinInnerRectangle)
{
outerRectangleBrush = Brushes.DeepSkyBlue;
innerRectangleBrush = Brushes.Red;
Refresh();
}
else
{
outerRectangleBrush = Brushes.Red;
innerRectangleBrush = Brushes.LightBlue;
Refresh();
}
}
else
{
outerRectangleBrush = Brushes.DeepSkyBlue;
innerRectangleBrush = Brushes.LightBlue;
Refresh();
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create rectangle.
Rectangle rect1 = new Rectangle(20, 20, 250, 250);
Rectangle rect2 = new Rectangle(70, 70, 150, 150);
// Draw rectangle to screen.
e.Graphics.FillRectangle(outerRectangleBrush, rect1);
e.Graphics.FillRectangle(innerRectangleBrush, rect2);
}
}
}
```
[](https://i.stack.imgur.com/A5lkj.png)
[](https://i.stack.imgur.com/HnV7L.png)
[](https://i.stack.imgur.com/jKll6.png) |
53,773,278 | I created two Rectangles. I want to add events on them. For example when mouse hover on one, the hovered one will change color, can do resize or drag them(rectangles) to other place...
I was just wondering if I could control the drawn graphic, or it will like *Microsoft Paint* that after you painted, the object can not be operate unless you clear canvas and do redraw.
Is it possible to control a drawn graphic, thanks for any suggestion.
**Simple code of my drawn graphics**
```
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create rectangle.
Rectangle rect1 = new Rectangle(20, 20, 250, 250);
Rectangle rect2 = new Rectangle(70, 70, 150, 150);
// Draw rectangle to screen.
e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rect1);
e.Graphics.FillRectangle(Brushes.LightBlue, rect2);
}
``` | 2018/12/14 | [
"https://Stackoverflow.com/questions/53773278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10309167/"
] | Also, you can create your own control like:
```
class RectangleControl : Control
{
public void FillRectangle(Color color)
{
this.BackColor = color;
}
}
```
Then :
```
private void Form1_Paint(object sender, PaintEventArgs e)
{
RectangleControl rect1 = new RectangleControl() { Parent = this, Left = 20, Top = 20, Width = 250, Height = 250 };
rect1.FillRectangle(Color.DeepSkyBlue);
RectangleControl rect2 = new RectangleControl() { Parent = rect1, Left = 50, Top = 50, Width = 150, Height = 150 };
rect2.FillRectangle(Color.LightBlue);
rect1.MouseHover += Rect1_MouseHover;
rect2.MouseLeave += Rect2_MouseLeave;
}
private void Rect2_MouseLeave(object sender, EventArgs e)
{
(sender as RectangleControl).BackColor = Color.Yellow;
}
private void Rect1_MouseHover(object sender, EventArgs e)
{
(sender as RectangleControl).BackColor = Color.LightBlue;
}
``` | @FJF, writing a ms-paint like application is not a complicated task. Windows Forms applications are using GDI+ to render graphics. so you can write a simple paint application using WindowsForms.
@nexolini uses a panel to do some draws. actually Ms-Paint does the same somehow. Ms-Paint is a Single-Layer Editor. So you can't resize all objects anytime you wanted (but as I said before you can assume that you have a panel for each newly drawn Shapes; Something like what Ms-Paint does).
**So what is the problem?**
Ms-Paint doesn't tracks your mouse movements and it doesn't needed (as it's a single layer). You can do all of it's tasks using these Answers.
**e.g:** for adding a Fill Color tool you can use a getpixel and putpixel to do a recursive algorithm on you image. and you are not needed to know which shape you are working on.
all the other tasks could be implemented easy.
for multi-layer Editors I will prefer to use a more powerful framework (but it's also could be implemented in Windows forms in a bad way), Like WPF. WPF uses DirectX to render your graphics and you are able to write an smooth Editor. WPF is designed to handle your graphical request so it does better on graphics.
@Reza\_Aghaei 's comments are useful for Windows Forms. |
17,519,572 | Can not figure out why this error keeps getting thrown:
```
-[__NSCFString bytes]: unrecognized selector sent to instance 0xc3eb200
```
for this code:
```
- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict {
empty = NO;
for (NSDictionary *valueDictionary in [dict objectForKey:@"Contacts"]) {
if ([[valueDictionary objectForKey:@"Empty"] isEqualToString:@"YES"]){
empty = YES;
contactsArray = [[NSMutableArray alloc] init];
}else{
Thecontacts = [valueDictionary objectForKey:@"Contacts"];
}
dataRepresentingSavedArray = Thecontacts;
if (dataRepresentingSavedArray != nil) {
**Causes Error->** NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
contactsArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
}
}
[table reloadData];
}
```
The value for [valueDictionary objectForKey:@"Contacts"] is
```
<62706c69 73743030 d4010203 0405082b 2c542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976 6572d106 0754726f 6f748001 ab090a11 1718191a 2228292a 55246e75 6c6cd20b 0c0d0e56 24636c61 73735a4e 532e6f62 6a656374 738006a2 0f108002 8007d20b 0c0d1380 06a31415 16800380 0480055b 416e6472 65772044 756e6e5f 1018616e 64726577 4064756e 6e2d6361 72616261 6c692e63 6f6d5661 63636570 74d21b1c 1d215824 636c6173 7365735a 24636c61 73736e61 6d65a31e 1f205e4e 534d7574 61626c65 41727261 79574e53 41727261 79584e53 4f626a65 63745e4e 534d7574 61626c65 41727261 79d20b0c 0d248006 a3252627 80088009 800a5e4a 6f686e20 4170706c 65736565 645f1016 4a6f686e 2d417070 6c657365 6564406d 61632e63 6f6d5561 6c657274 12000186 a05f100f 4e534b65 79656441 72636869 76657200 08001100 16001f00 28003200 35003a00 3c004800 4e005300 5a006500 67006a00 6c006e00 73007500 79007b00 7d007f00 8b00a600 ad00b200 bb00c600 ca00d900 e100ea00 f900fe01 00010401 06010801 0a011901 32013801 3d000000 00000002 01000000 00000000 2d000000 00000000 00000000 00000001 4f>
```
I have been playing with the code and are close to final resolution it is nasty, but it will work until i find a work around. SO oldSavedArray prints the array but when i go to print this
```
contactsArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
```
i receive this.
```
[__NSCFString count]: unrecognized selector sent to instance 0xabab970
```
the output of oldSavedArray is
(
(
"John Appleseed",
"[email protected]",
alert
),
(
"Andrew Dunn",
"[email protected]",
accept
)
)
```
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[AsyncURLConnection request:url completeBlock:^(NSData *data) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (![myString isEqualToString:@"0"]) {
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myString] forKey:@"savedArray"];
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"savedArray"]];
contactsArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
[table reloadData];
}else{
contactsArray = [[NSMutableArray alloc] init];
}
});
});
} errorBlock:^(NSError *errorss) {
}];
``` | 2013/07/08 | [
"https://Stackoverflow.com/questions/17519572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663192/"
] | The error message shows that
```
Thecontacts = [valueDictionary objectForKey:@"Contacts"];
```
returns a `NSString` object, not a `NSData` object as you expected. I assume that you created
the JSON using something like
```
[NSString stringWithFormat:@"%@", Contacts]
```
which uses the `description` method of `NSData` and returns a string like
```
<62706c69 73743030 d4010203 0405082b ... >
```
or perhaps SBJson does that implicitly. You *could* parse that string and convert
it back to `NSData`. But that would be a fragile approach because the actual
`description` format of `NSData` is not documented and might change in the future.
Note that JSON does not know "raw binary data", only dictionaries, arrays, strings and numbers. You should convert the `NSData` to `NSString` (using one of the publicly available
Base64 converters) and store the Base64 string in the JSON. | Not applicable for the case above but I got the exact same message when I omitted the external parameter name from init declaration. I am new to Objective C/Swift world so the concept of different parameter name externally and internally is novel still and easy to overlook, I am posting here as a convenience to those who search for the title of this post, as I did.
```
//Non working code, compiles but throws unrecognized selector exception message when unarchiver is called. Programmer's error.
required init(decoder: NSCoder) {
//...... unarchiving code goes here.
}
//Working code
required init(coder decoder: NSCoder) {
//Same unarchiving code went here.
}
//Client code, same in both cases
let mArchiveName = NSKeyedArchiver.archivedDataWithRootObject(origMyObject)
let restoredMyObject = NSKeyedUnarchiver.unarchiveObjectWithData(mArchiveName) as! MyObject
``` |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | As of Laravel 5.4, whenever you use `foreach` or `for` within blade files you will now have access to a [$loop variable](https://laravel.com/docs/5.4/blade#the-loop-variable). The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here:
```
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
``` | There is two way to do this:
1- if your $key is numeric you can use:
```
@foreach($aboutcontent as $key => $about)
@if($key == 0)
@continue
@endif
code
@endforeach
```
2- if a $key is not numeric
use @loop->first as a condition |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | There is two way to do this:
1- if your $key is numeric you can use:
```
@foreach($aboutcontent as $key => $about)
@if($key == 0)
@continue
@endif
code
@endforeach
```
2- if a $key is not numeric
use @loop->first as a condition | Alternatively, you can just remove the first element from the array before iterating:
```
@php
array_shift($aboutcontent);
@endphp
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
```
The advantage is that you do not need any conditions to verify you are not the in the first iteration. The disadvantage is that you might need the first element within the same view, but that we don't know from your example.
**Note** It might make more sense to remove the first element from the array *before* you pass on the data to the view.
For reference, see:
* <http://php.net/manual/en/function.array-shift.php>
* <https://laravel.com/docs/5.4/blade#php> |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | As of Laravel 5.4, whenever you use `foreach` or `for` within blade files you will now have access to a [$loop variable](https://laravel.com/docs/5.4/blade#the-loop-variable). The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here:
```
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
``` | You need some kind of a counter if you want to do that in blade:
```
<?php $count = 0;?>
@foreach
@if($count>1)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif
$count++
@endforeach
```
EDIT:
I like the answer provided by Mark Baker in the comment better
```
@foreach(array_slice($aboutcontent, 1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | Try This :
```
@foreach($aboutcontent as $key => $about)
@if($key > 0){
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif;
@endforeach
``` | Alternatively, you can just remove the first element from the array before iterating:
```
@php
array_shift($aboutcontent);
@endphp
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
```
The advantage is that you do not need any conditions to verify you are not the in the first iteration. The disadvantage is that you might need the first element within the same view, but that we don't know from your example.
**Note** It might make more sense to remove the first element from the array *before* you pass on the data to the view.
For reference, see:
* <http://php.net/manual/en/function.array-shift.php>
* <https://laravel.com/docs/5.4/blade#php> |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | As of Laravel 5.4, whenever you use `foreach` or `for` within blade files you will now have access to a [$loop variable](https://laravel.com/docs/5.4/blade#the-loop-variable). The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here:
```
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
``` | Assuming that the `$aboutcontents` is numeric array just use the good old fashioned `for` loop instead of your new fangled `foreach`
```
// Notice you start at 1 and your first
// elem is 0 so... ta da... skipped
@for ($i = 1; $i < count($aboutcontents); $i++){
$about = $aboutcontents[$i]; //This is the object
//now use $about as you would
}
```
*Note: I have not used Larvel or blades but based on the docs this should be doable* |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | You need some kind of a counter if you want to do that in blade:
```
<?php $count = 0;?>
@foreach
@if($count>1)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif
$count++
@endforeach
```
EDIT:
I like the answer provided by Mark Baker in the comment better
```
@foreach(array_slice($aboutcontent, 1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | Try this
```
@foreach($aboutcontent->slice(1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | Try This :
```
@foreach($aboutcontent as $key => $about)
@if($key > 0){
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif;
@endforeach
``` | Assuming that the `$aboutcontents` is numeric array just use the good old fashioned `for` loop instead of your new fangled `foreach`
```
// Notice you start at 1 and your first
// elem is 0 so... ta da... skipped
@for ($i = 1; $i < count($aboutcontents); $i++){
$about = $aboutcontents[$i]; //This is the object
//now use $about as you would
}
```
*Note: I have not used Larvel or blades but based on the docs this should be doable* |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | Alternatively, you can just remove the first element from the array before iterating:
```
@php
array_shift($aboutcontent);
@endphp
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
```
The advantage is that you do not need any conditions to verify you are not the in the first iteration. The disadvantage is that you might need the first element within the same view, but that we don't know from your example.
**Note** It might make more sense to remove the first element from the array *before* you pass on the data to the view.
For reference, see:
* <http://php.net/manual/en/function.array-shift.php>
* <https://laravel.com/docs/5.4/blade#php> | Try this
```
@foreach($aboutcontent->slice(1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | As of Laravel 5.4, whenever you use `foreach` or `for` within blade files you will now have access to a [$loop variable](https://laravel.com/docs/5.4/blade#the-loop-variable). The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here:
```
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
``` | Try this
```
@foreach($aboutcontent->slice(1) as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` |
38,896,260 | I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
```
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
``` | 2016/08/11 | [
"https://Stackoverflow.com/questions/38896260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5875799/"
] | As of Laravel 5.4, whenever you use `foreach` or `for` within blade files you will now have access to a [$loop variable](https://laravel.com/docs/5.4/blade#the-loop-variable). The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here:
```
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
``` | Try This :
```
@foreach($aboutcontent as $key => $about)
@if($key > 0){
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endif;
@endforeach
``` |
13,828,661 | I am having trouble with an hw problem in my CS class. The problem has to do with creating a class in python. Heres the prompt
Your class should be named Student, and you should define the following methods:
`__init__`: This method initializes a Student object.
Parameters: a name, a GPA, and a number of units taken
• Should initialize instance variables for name, GPA, and units based on
the information that was passed in. If the GPA or number of units is negative, sets it to 0. (Donʼt worry about non-numeric values in this method.)
update: This method updates the instance variables of the Student object if the Student takes a new class.
• Parameters: units for the new class, grade points earned (as a number) in the new class.
• Should modify the instance variable for units to add the units for the new class
• Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.)
get\_gpa: This method should return the studentʼs GPA.
get\_name: This method should return the studentʼs name.
**Heres what i have**
```
class Student:
def__init__(self,name,GPA,units):
if units <0:
units=0
if GPA<0:
GPA=0
self.name=name
self.GPA=GPA
self.units=units
def update(newunits,GPE):
```
thats all i can come up with | 2012/12/11 | [
"https://Stackoverflow.com/questions/13828661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786698/"
] | Let’s go through some points which will hopefully help you:
### Constructor (`__init__`)
>
> If the GPA or number of units is negative, sets it to 0.
>
>
>
So you probably want to check each separately:
```
if units < 0:
units = 0
if GPA < 0:
GPA = 0
```
### Update method
Methods in general take a reference to the current object as the first argument, named `self` per convention (just as in `__init__`). So your update method declaration should look like this:
```
def update(self, newunits, GPE):
...
```
>
> Should modify the instance variable for units to add the units for the new class
>
>
>
Just as you did in the constructor, you can access instance variables using `self.varname`. So you probably want to do something like this:
```
self.units += newunits
```
>
> Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.)
>
>
>
Just as you update `self.units` you have to update `self.GPA` here. Unfortunately, I have no idea what a GPA is and how it is calculated, so I can only guess:
```
self.GPA = ((self.GPA * oldunits) + (GPE * newunits)) / self.units
```
Note that I introduced a new local variable `oldunits` here that simply stores the units temporarily from *before* it was updated (so `oldunits = self.units - newunits` after updating).
### get\_gpa and get\_name
These are simple getters that just return a value from the object. Here you have an example for the **units**, i.e. you should figure it out for the actual wanted values yourself:
```
def get_units (self):
return self.units
```
Note that it’s rather unpythonic to have getters (`get_x` methods), as you would just expect people to access the properties directly (while handling them with care). | I'll help you to complete the question, but let me point out a little mistake first:
```
if units <0 and GPA <0:
units=0
GPA=0
```
This will set units and GPA to zero only if they are both negative. You'll want to set each to zero if it's negative, even if the other is not. Change it to:
```
if units < 0: units = 0
if GPA < 0: GPA = 0
```
Concerning your update method, the correct signature would be:
```
def update(self, newunits, GPE):
```
Python object methods should always start with self.
Now, I'm not sure about how to calculate the GPA (we use a different system were I live), but according to some quite google queries, your update method should be something like:
```
def update(self, newunits, GPE):
GPE_earned_before = self.GPA * self.units
total_GPE = GPE_earned_before + GPE
self.GPA = total_GPE / (self.units + newunits)
self.units += newunits
```
I used a lot of variables here, to make things clear, but this can be shortened to:
```
def update(self, newunits, GPE):
self.GPA = (self.GPA * self.units + GPE) / (self.units + newunits)
self.units += newunits
``` |
10,830,183 | I have a working node.js / express based server and am using jade for templating. Usually there is no problem but a couple of times every day I get an error message when requsting any page. The error is 'failed to locate view'. I don't know why i get this error since it worked fine just minutes before.
The question however is how I can force a crash on this event, for example:
```
res.render('index.jade', {info: 'msg'}, function(error, ok) {
if (error)
throw new Error('');
// Proceed with response
};
```
How would I do this? And how would I proceed with the response?
thank you. | 2012/05/31 | [
"https://Stackoverflow.com/questions/10830183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306716/"
] | You can add an error handling middleware.
```
app.use(function handleJadeErrors(err, req, res, next) {
// identify the errors you care about
if (err.message === 'failed to locate view') {
// do something sensible, such as logging and then crashing
// or returning something more useful to the client
} else {
// just pass it on to other error middleware
next(err);
}
});
``` | Try this:
```
app.use(function (req, res, next) {
fs.exists(__dirname + '/views/' + req.url.substring(1) + '.jade', function (exists) {
if(!exists) {
console.log(err);
return next();
}
res.render(req.url.substring(1), { title: "No Controller", user: req.session.user });
}
});
``` |
10,965,285 | I am trying to loop over an array. However, I would like to add a 15 second delay between each array value. This will write value 1 to console, then count down 15 seconds and write value 2 to console, and so on.
I'm not sure exactly how to do this. My code as of now just outputs the numbers 15 all the way to 1 on the console at once with no actual count down and no array values.
array
```
["l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11", "l12", "l13", "l14", "l15", "l16"]
```
code
```
var adArray = [];
// get links with class adfu
var adfuClass = document.getElementsByClassName('adfu');
for (var i = 0; i < adfuClass.length; i++) {
var ids = adfuClass[i].id
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class ad30
var ad30Class = document.getElementsByClassName('ad30');
for (var i = 0; i < ad30Class.length; i++) {
var ids = ad30Class[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class adf
var adfClass = document.getElementsByClassName('adf');
for (var i = 0; i < adfClass.length; i++) {
var ids = adfClass[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// loop through array with all new ids
for (var i = 0, l = adArray.length; i < l; i++) {
var counter = 15;
var countDown = setTimeout(function() {
console.log(counter);
if (counter == 0) {
console.log(adArray[i]);
}
counter--;
}, 1000);
}
``` | 2012/06/09 | [
"https://Stackoverflow.com/questions/10965285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320596/"
] | ```
// loop through array with all new ids
var i = 0, l = adArray.length;
(function iterator() {
console.log(adArray[i]);
if(++i<l) {
setTimeout(iterator, 15000);
}
})();
```
Something like this? | There's a really simple pattern for this type of iterator, using closure scope to store a `loop` counter and a nested `looper()` function which runs the `setTimeout()` iterator. The `looper()` function actually iterates the `loop` count, so there is no need for a `for` or `do`/`while` construct. I use this pattern often, and it works really well.
**EDIT**: Modified the condition to check for `loop > 1`, not `loop > 0`, which logged `Loop count: 0`. This can be tweaked, and technically, the `looper()` here runs 16 times.
```
(function(){
var loop = 15;
var looper = function(){
console.log('Loop count: ' + loop);
if (loop > 1) {
loop--;
} else {
console.log('Loop end.');
return;
}
setTimeout(looper, 15000);
};
looper();
})();
```
<http://jsfiddle.net/userdude/NV7HU/2> |
10,965,285 | I am trying to loop over an array. However, I would like to add a 15 second delay between each array value. This will write value 1 to console, then count down 15 seconds and write value 2 to console, and so on.
I'm not sure exactly how to do this. My code as of now just outputs the numbers 15 all the way to 1 on the console at once with no actual count down and no array values.
array
```
["l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11", "l12", "l13", "l14", "l15", "l16"]
```
code
```
var adArray = [];
// get links with class adfu
var adfuClass = document.getElementsByClassName('adfu');
for (var i = 0; i < adfuClass.length; i++) {
var ids = adfuClass[i].id
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class ad30
var ad30Class = document.getElementsByClassName('ad30');
for (var i = 0; i < ad30Class.length; i++) {
var ids = ad30Class[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class adf
var adfClass = document.getElementsByClassName('adf');
for (var i = 0; i < adfClass.length; i++) {
var ids = adfClass[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// loop through array with all new ids
for (var i = 0, l = adArray.length; i < l; i++) {
var counter = 15;
var countDown = setTimeout(function() {
console.log(counter);
if (counter == 0) {
console.log(adArray[i]);
}
counter--;
}, 1000);
}
``` | 2012/06/09 | [
"https://Stackoverflow.com/questions/10965285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320596/"
] | ```
// loop through array with all new ids
var i = 0, l = adArray.length;
(function iterator() {
console.log(adArray[i]);
if(++i<l) {
setTimeout(iterator, 15000);
}
})();
```
Something like this? | Use this function to make it easier to run:
```
function loopArr(arr, callback, time, infinite){
console.log('loop run');
var i=0,
total=arr.length-1;
var loop=function(){
// RUN CODE
console.log('loop arr['+i+']');
callback( arr[i] );
if (i < total ) {
i++;
} else { // LOOP END
console.log('loop end!');
if(!infinite) return;
i=0 //restart
}
setTimeout( loop, time);
}
loop()
}
```
To use this function execute this:
```
loopArr(arr, callback, time, infinite)
```
Where:
* **arr** is the array we need to loop, it could be a jQuery selector
* **callback** is the executed function with one argument returned which is the selected item
* **time** is the timeout needed for delay
* **infinite** is set **true** or **false** if we need the code to repeat itself forever
---
**Example** using [animate.css](http://daneden.github.io/animate.css/) :
```
var imgShowHide = function(elm){
var elm = $(elm); // select the item arr[i] via jQuery
elm.css('animation-duration','2s').show()
.addClass('animated bounceInRight')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
elm.removeClass('animated bounceInRight')
.addClass('animated bounceInLeft')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
elm.removeClass('animated bounceInLeft').hide()
})
});
}
// RUN
loopArr( $('#images > img'), imgShowHide, 4000, true);
``` |
10,965,285 | I am trying to loop over an array. However, I would like to add a 15 second delay between each array value. This will write value 1 to console, then count down 15 seconds and write value 2 to console, and so on.
I'm not sure exactly how to do this. My code as of now just outputs the numbers 15 all the way to 1 on the console at once with no actual count down and no array values.
array
```
["l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11", "l12", "l13", "l14", "l15", "l16"]
```
code
```
var adArray = [];
// get links with class adfu
var adfuClass = document.getElementsByClassName('adfu');
for (var i = 0; i < adfuClass.length; i++) {
var ids = adfuClass[i].id
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class ad30
var ad30Class = document.getElementsByClassName('ad30');
for (var i = 0; i < ad30Class.length; i++) {
var ids = ad30Class[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// get links with class adf
var adfClass = document.getElementsByClassName('adf');
for (var i = 0; i < adfClass.length; i++) {
var ids = adfClass[i].id;
var newIds = ids.replace(/tg_/i, "l");
adArray.push(newIds);
}
// loop through array with all new ids
for (var i = 0, l = adArray.length; i < l; i++) {
var counter = 15;
var countDown = setTimeout(function() {
console.log(counter);
if (counter == 0) {
console.log(adArray[i]);
}
counter--;
}, 1000);
}
``` | 2012/06/09 | [
"https://Stackoverflow.com/questions/10965285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320596/"
] | There's a really simple pattern for this type of iterator, using closure scope to store a `loop` counter and a nested `looper()` function which runs the `setTimeout()` iterator. The `looper()` function actually iterates the `loop` count, so there is no need for a `for` or `do`/`while` construct. I use this pattern often, and it works really well.
**EDIT**: Modified the condition to check for `loop > 1`, not `loop > 0`, which logged `Loop count: 0`. This can be tweaked, and technically, the `looper()` here runs 16 times.
```
(function(){
var loop = 15;
var looper = function(){
console.log('Loop count: ' + loop);
if (loop > 1) {
loop--;
} else {
console.log('Loop end.');
return;
}
setTimeout(looper, 15000);
};
looper();
})();
```
<http://jsfiddle.net/userdude/NV7HU/2> | Use this function to make it easier to run:
```
function loopArr(arr, callback, time, infinite){
console.log('loop run');
var i=0,
total=arr.length-1;
var loop=function(){
// RUN CODE
console.log('loop arr['+i+']');
callback( arr[i] );
if (i < total ) {
i++;
} else { // LOOP END
console.log('loop end!');
if(!infinite) return;
i=0 //restart
}
setTimeout( loop, time);
}
loop()
}
```
To use this function execute this:
```
loopArr(arr, callback, time, infinite)
```
Where:
* **arr** is the array we need to loop, it could be a jQuery selector
* **callback** is the executed function with one argument returned which is the selected item
* **time** is the timeout needed for delay
* **infinite** is set **true** or **false** if we need the code to repeat itself forever
---
**Example** using [animate.css](http://daneden.github.io/animate.css/) :
```
var imgShowHide = function(elm){
var elm = $(elm); // select the item arr[i] via jQuery
elm.css('animation-duration','2s').show()
.addClass('animated bounceInRight')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
elm.removeClass('animated bounceInRight')
.addClass('animated bounceInLeft')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
elm.removeClass('animated bounceInLeft').hide()
})
});
}
// RUN
loopArr( $('#images > img'), imgShowHide, 4000, true);
``` |
20,319,104 | In my C++ code I use templates a lot.. that might be an understatement. The end result is that the type names take more than 4096 characters and watching the GCC output is painful to say the least.
In several debugging packages like GDB or Valgrind one can request that C++ types not be demangled. Is there a similar way to force G++ to output **only** mangled type names, cutting on all the unecessary output?
Clarification
-------------
Because of the first answer that was given I see that the question isn't clear. Consider the following MWE:
```
template <typename T>
class A
{
public:
T foo;
};
template <typename T>
class B
{
};
template <typename T>
class C
{
public:
void f(void)
{
this->foo = T(1);
this->bar = T(2);
}
};
typedef C< B< B< B< B< A<int> > > > > > myType;
int main(int argc, char** argv)
{
myType err;
err.f();
return 0;
};
```
The error in the line `this->bar = T(2);` is an error only when an object of type `C<myType>` is instantiated and the method `C::f()` called. Therefore, G++ returns an error message along these lines:
```
test.cpp: In instantiation of ‘void C<T>::f() [with T = B<B<B<B<A<int> > > > >]’:
test.cpp:33:8: required from here
test.cpp:21:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’
this->foo = T(1);
^
test.cpp:21:14: note: candidates are:
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B()
class B
^
test.cpp:11:7: note: candidate expects 0 arguments, 1 provided
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&)
test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’
test.cpp:21:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘foo’
this->foo = T(1);
^
test.cpp:23:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’
this->bar = T(2);
^
test.cpp:23:14: note: candidates are:
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B()
class B
^
test.cpp:11:7: note: candidate expects 0 arguments, 1 provided
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&)
test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’
test.cpp:23:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘bar’
this->bar = T(2);
```
The type names are irritating here, but make it impossible to read when the complete type name takes hundreds of characters. Is there a way to ask GCC for mangled type names instead of the full names, or to limit their length somehow?
STLFilt
-------
Unfortunately, `STLFilt` only makes the output prettier; the length doesn't change. In fact, the fact that the output is broken into multiple lines makes the whole thing worse, because the output takes more space. | 2013/12/02 | [
"https://Stackoverflow.com/questions/20319104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3055685/"
] | This will never work. When you make the template class:
```
B<A<int> >
```
this class no longer has the function f() within its definition. If you compile this with clang++ you'll get the error (where test is of type `B<A<int> >`):
```
error: no member named 'f' in 'B<A<int> >'
test.f();
~~~~ ^
```
Try using clang++ if you want slightly more readable errors. | You could use `typedef`:
```
typedef queue<int> IntQueue;
```
Obviously, at this example you removed only 2 characters of the type name, but with more complex examples this will narrow down even more chars and will improve readability of your code.
Also, this may help the auto-completing feature of your IDE (if you use one). |
20,319,104 | In my C++ code I use templates a lot.. that might be an understatement. The end result is that the type names take more than 4096 characters and watching the GCC output is painful to say the least.
In several debugging packages like GDB or Valgrind one can request that C++ types not be demangled. Is there a similar way to force G++ to output **only** mangled type names, cutting on all the unecessary output?
Clarification
-------------
Because of the first answer that was given I see that the question isn't clear. Consider the following MWE:
```
template <typename T>
class A
{
public:
T foo;
};
template <typename T>
class B
{
};
template <typename T>
class C
{
public:
void f(void)
{
this->foo = T(1);
this->bar = T(2);
}
};
typedef C< B< B< B< B< A<int> > > > > > myType;
int main(int argc, char** argv)
{
myType err;
err.f();
return 0;
};
```
The error in the line `this->bar = T(2);` is an error only when an object of type `C<myType>` is instantiated and the method `C::f()` called. Therefore, G++ returns an error message along these lines:
```
test.cpp: In instantiation of ‘void C<T>::f() [with T = B<B<B<B<A<int> > > > >]’:
test.cpp:33:8: required from here
test.cpp:21:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’
this->foo = T(1);
^
test.cpp:21:14: note: candidates are:
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B()
class B
^
test.cpp:11:7: note: candidate expects 0 arguments, 1 provided
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&)
test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’
test.cpp:21:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘foo’
this->foo = T(1);
^
test.cpp:23:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’
this->bar = T(2);
^
test.cpp:23:14: note: candidates are:
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B()
class B
^
test.cpp:11:7: note: candidate expects 0 arguments, 1 provided
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&)
test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’
test.cpp:23:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘bar’
this->bar = T(2);
```
The type names are irritating here, but make it impossible to read when the complete type name takes hundreds of characters. Is there a way to ask GCC for mangled type names instead of the full names, or to limit their length somehow?
STLFilt
-------
Unfortunately, `STLFilt` only makes the output prettier; the length doesn't change. In fact, the fact that the output is broken into multiple lines makes the whole thing worse, because the output takes more space. | 2013/12/02 | [
"https://Stackoverflow.com/questions/20319104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3055685/"
] | People are suffering from this particular shortcoming of C++ error reporting for ages. :)
However, more verbose error reports are generally better for complex problem solving. Thus, a better approach is to let g++ to spit out the long and verbose error message and then use a stand alone error parser to make the output more readable.
There used to be a decent error parser here: <http://www.bdsoft.com/tools/stlfilt.html> (unfortunately, no longer in development).
See also this near duplicate: [Deciphering C++ template error messages](https://stackoverflow.com/questions/47980/deciphering-c-template-error-messages) | You could use `typedef`:
```
typedef queue<int> IntQueue;
```
Obviously, at this example you removed only 2 characters of the type name, but with more complex examples this will narrow down even more chars and will improve readability of your code.
Also, this may help the auto-completing feature of your IDE (if you use one). |
20,319,104 | In my C++ code I use templates a lot.. that might be an understatement. The end result is that the type names take more than 4096 characters and watching the GCC output is painful to say the least.
In several debugging packages like GDB or Valgrind one can request that C++ types not be demangled. Is there a similar way to force G++ to output **only** mangled type names, cutting on all the unecessary output?
Clarification
-------------
Because of the first answer that was given I see that the question isn't clear. Consider the following MWE:
```
template <typename T>
class A
{
public:
T foo;
};
template <typename T>
class B
{
};
template <typename T>
class C
{
public:
void f(void)
{
this->foo = T(1);
this->bar = T(2);
}
};
typedef C< B< B< B< B< A<int> > > > > > myType;
int main(int argc, char** argv)
{
myType err;
err.f();
return 0;
};
```
The error in the line `this->bar = T(2);` is an error only when an object of type `C<myType>` is instantiated and the method `C::f()` called. Therefore, G++ returns an error message along these lines:
```
test.cpp: In instantiation of ‘void C<T>::f() [with T = B<B<B<B<A<int> > > > >]’:
test.cpp:33:8: required from here
test.cpp:21:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’
this->foo = T(1);
^
test.cpp:21:14: note: candidates are:
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B()
class B
^
test.cpp:11:7: note: candidate expects 0 arguments, 1 provided
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&)
test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’
test.cpp:21:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘foo’
this->foo = T(1);
^
test.cpp:23:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’
this->bar = T(2);
^
test.cpp:23:14: note: candidates are:
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B()
class B
^
test.cpp:11:7: note: candidate expects 0 arguments, 1 provided
test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&)
test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’
test.cpp:23:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘bar’
this->bar = T(2);
```
The type names are irritating here, but make it impossible to read when the complete type name takes hundreds of characters. Is there a way to ask GCC for mangled type names instead of the full names, or to limit their length somehow?
STLFilt
-------
Unfortunately, `STLFilt` only makes the output prettier; the length doesn't change. In fact, the fact that the output is broken into multiple lines makes the whole thing worse, because the output takes more space. | 2013/12/02 | [
"https://Stackoverflow.com/questions/20319104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3055685/"
] | People are suffering from this particular shortcoming of C++ error reporting for ages. :)
However, more verbose error reports are generally better for complex problem solving. Thus, a better approach is to let g++ to spit out the long and verbose error message and then use a stand alone error parser to make the output more readable.
There used to be a decent error parser here: <http://www.bdsoft.com/tools/stlfilt.html> (unfortunately, no longer in development).
See also this near duplicate: [Deciphering C++ template error messages](https://stackoverflow.com/questions/47980/deciphering-c-template-error-messages) | This will never work. When you make the template class:
```
B<A<int> >
```
this class no longer has the function f() within its definition. If you compile this with clang++ you'll get the error (where test is of type `B<A<int> >`):
```
error: no member named 'f' in 'B<A<int> >'
test.f();
~~~~ ^
```
Try using clang++ if you want slightly more readable errors. |
336,838 | I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others? | 2011/09/17 | [
"https://superuser.com/questions/336838",
"https://superuser.com",
"https://superuser.com/users/97637/"
] | [`compress`](http://en.wikipedia.org/wiki/Compress) (the Unix command, ported to Linux and others) itself only has one file extension that is used for its output, and that is `.z`
There are other compression algorithms (and their associated programs) that compress files differently for different results.
Some popular programs include:
* [Gzip](http://en.wikipedia.org/wiki/Gzip) which has the extension `.gz`
* [Bzip](http://en.wikipedia.org/wiki/Bzip2) which has the extension `.bz2`
* [Rar](http://en.wikipedia.org/wiki/Rar) which has the extension `.rar`
* [Zip](http://en.wikipedia.org/wiki/ZIP_%28file_format%29) which has the extension `.zip`
* [7-zip](http://en.wikipedia.org/wiki/7z) which has the extension `.7z`
* and many more...
Generally newer archivers will use better compression algorithms, usually at the cost of taking longer (requiring more CPU time) to compress or requiring more memory or both.
As a general rule though, the newer the program, the newer it's algorithms and therefore the better its compression will be. `compress` is as old as the hills and its compression ratios tend to be a lot worse than more modern programs like 7-zip. | While `.z` is the oldest, as old as Unix, the most prevalent compression format is `.zip` because it is the only format supported natively by all versions and flavors of Windows since Windows 98. |
336,838 | I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others? | 2011/09/17 | [
"https://superuser.com/questions/336838",
"https://superuser.com",
"https://superuser.com/users/97637/"
] | [`compress`](http://en.wikipedia.org/wiki/Compress) (the Unix command, ported to Linux and others) itself only has one file extension that is used for its output, and that is `.z`
There are other compression algorithms (and their associated programs) that compress files differently for different results.
Some popular programs include:
* [Gzip](http://en.wikipedia.org/wiki/Gzip) which has the extension `.gz`
* [Bzip](http://en.wikipedia.org/wiki/Bzip2) which has the extension `.bz2`
* [Rar](http://en.wikipedia.org/wiki/Rar) which has the extension `.rar`
* [Zip](http://en.wikipedia.org/wiki/ZIP_%28file_format%29) which has the extension `.zip`
* [7-zip](http://en.wikipedia.org/wiki/7z) which has the extension `.7z`
* and many more...
Generally newer archivers will use better compression algorithms, usually at the cost of taking longer (requiring more CPU time) to compress or requiring more memory or both.
As a general rule though, the newer the program, the newer it's algorithms and therefore the better its compression will be. `compress` is as old as the hills and its compression ratios tend to be a lot worse than more modern programs like 7-zip. | I prefer compressing my data using \*.rar with WinRAR as it is completely customizable. I use it because I can choose how much I want to compress it and I can set passwords to protect my archive. If I'm doing something involving disk images, I'll compress to \*.iso or \*.daa using PowerISO.
Whenever I'm not on one of my own computers, I compress it using Windows 7's built-in \*.zip compressor. On Ubuntu, I will probably compress in \*.tar.gz or \*.zip. |
336,838 | I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others? | 2011/09/17 | [
"https://superuser.com/questions/336838",
"https://superuser.com",
"https://superuser.com/users/97637/"
] | [`compress`](http://en.wikipedia.org/wiki/Compress) (the Unix command, ported to Linux and others) itself only has one file extension that is used for its output, and that is `.z`
There are other compression algorithms (and their associated programs) that compress files differently for different results.
Some popular programs include:
* [Gzip](http://en.wikipedia.org/wiki/Gzip) which has the extension `.gz`
* [Bzip](http://en.wikipedia.org/wiki/Bzip2) which has the extension `.bz2`
* [Rar](http://en.wikipedia.org/wiki/Rar) which has the extension `.rar`
* [Zip](http://en.wikipedia.org/wiki/ZIP_%28file_format%29) which has the extension `.zip`
* [7-zip](http://en.wikipedia.org/wiki/7z) which has the extension `.7z`
* and many more...
Generally newer archivers will use better compression algorithms, usually at the cost of taking longer (requiring more CPU time) to compress or requiring more memory or both.
As a general rule though, the newer the program, the newer it's algorithms and therefore the better its compression will be. `compress` is as old as the hills and its compression ratios tend to be a lot worse than more modern programs like 7-zip. | If its linux based, .tar.gz or .tar.bz - otherwise known as your humble tarball. In windows, .zip - natively supported since windows XP. You also often encounter .rar (especially with files from slightly dubious sources) and .7z (windows/open source software most often).
If you want to be ABSOLUTELY sure your file will be opened by most modern OSes (and some not so modern ones), .zip is the safe choice.
Efficiency depends on the filetype in many cases - for example lrzip works best with VERY large files, text files always compress very well, but compressed audio dosen't, and compression ratio is often traded off for processor and ram usage- as such, there is no 'best' file format for compression |
336,838 | I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others? | 2011/09/17 | [
"https://superuser.com/questions/336838",
"https://superuser.com",
"https://superuser.com/users/97637/"
] | While `.z` is the oldest, as old as Unix, the most prevalent compression format is `.zip` because it is the only format supported natively by all versions and flavors of Windows since Windows 98. | I prefer compressing my data using \*.rar with WinRAR as it is completely customizable. I use it because I can choose how much I want to compress it and I can set passwords to protect my archive. If I'm doing something involving disk images, I'll compress to \*.iso or \*.daa using PowerISO.
Whenever I'm not on one of my own computers, I compress it using Windows 7's built-in \*.zip compressor. On Ubuntu, I will probably compress in \*.tar.gz or \*.zip. |
336,838 | I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others? | 2011/09/17 | [
"https://superuser.com/questions/336838",
"https://superuser.com",
"https://superuser.com/users/97637/"
] | If its linux based, .tar.gz or .tar.bz - otherwise known as your humble tarball. In windows, .zip - natively supported since windows XP. You also often encounter .rar (especially with files from slightly dubious sources) and .7z (windows/open source software most often).
If you want to be ABSOLUTELY sure your file will be opened by most modern OSes (and some not so modern ones), .zip is the safe choice.
Efficiency depends on the filetype in many cases - for example lrzip works best with VERY large files, text files always compress very well, but compressed audio dosen't, and compression ratio is often traded off for processor and ram usage- as such, there is no 'best' file format for compression | While `.z` is the oldest, as old as Unix, the most prevalent compression format is `.zip` because it is the only format supported natively by all versions and flavors of Windows since Windows 98. |
336,838 | I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others? | 2011/09/17 | [
"https://superuser.com/questions/336838",
"https://superuser.com",
"https://superuser.com/users/97637/"
] | If its linux based, .tar.gz or .tar.bz - otherwise known as your humble tarball. In windows, .zip - natively supported since windows XP. You also often encounter .rar (especially with files from slightly dubious sources) and .7z (windows/open source software most often).
If you want to be ABSOLUTELY sure your file will be opened by most modern OSes (and some not so modern ones), .zip is the safe choice.
Efficiency depends on the filetype in many cases - for example lrzip works best with VERY large files, text files always compress very well, but compressed audio dosen't, and compression ratio is often traded off for processor and ram usage- as such, there is no 'best' file format for compression | I prefer compressing my data using \*.rar with WinRAR as it is completely customizable. I use it because I can choose how much I want to compress it and I can set passwords to protect my archive. If I'm doing something involving disk images, I'll compress to \*.iso or \*.daa using PowerISO.
Whenever I'm not on one of my own computers, I compress it using Windows 7's built-in \*.zip compressor. On Ubuntu, I will probably compress in \*.tar.gz or \*.zip. |
1,124,217 | This is the answer I can come up with. I get the complete opposite of what I'm supposed to get. My mistake is probably in the first part, could anyone help me out?
$$\left|x^2+x+1\right|\:\ge \left|x^2+x\right|-\left|1\right|\ge \left|x^2\right|-\left|x\right|-\left|1\right|\:=\:x^2\:-\left|x\right|-1
$$
and
$$
\frac{1}{\left|x^2+x+1\right|}\:=\:\:\:\frac{x^2\:-\left|x\right|-1}{\left|x^2+x+1\right|\left(x^2\:-\left|x\right|-1\right)}\:\:\:\le \:\frac{\left|x^2+x+1\right|}{\left|x^2+x+1\right|\left(x^2\:-\left|x\right|-1\right)}\:=\:\frac{1}{x^2\:-\left|x\right|-1}
$$ | 2015/01/28 | [
"https://math.stackexchange.com/questions/1124217",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/174613/"
] | If $f(g(b))=b$ for all $b$, then in particular for $b:=f(a)$ we also have $f(g(f(a))=f(a)$ for all $a$. Now, using that $f$ is injective we arrive at $g(f(a)=a$. | The relation $\forall b \in B, f(g(b)) = b$ implies that $f$ is surjective, since for any $b\in B$, the element $g(b) \in A$ is sent to it by $f$. Thus $f$ is both an injection and a surjection, and therefore a bijection. |
1,124,217 | This is the answer I can come up with. I get the complete opposite of what I'm supposed to get. My mistake is probably in the first part, could anyone help me out?
$$\left|x^2+x+1\right|\:\ge \left|x^2+x\right|-\left|1\right|\ge \left|x^2\right|-\left|x\right|-\left|1\right|\:=\:x^2\:-\left|x\right|-1
$$
and
$$
\frac{1}{\left|x^2+x+1\right|}\:=\:\:\:\frac{x^2\:-\left|x\right|-1}{\left|x^2+x+1\right|\left(x^2\:-\left|x\right|-1\right)}\:\:\:\le \:\frac{\left|x^2+x+1\right|}{\left|x^2+x+1\right|\left(x^2\:-\left|x\right|-1\right)}\:=\:\frac{1}{x^2\:-\left|x\right|-1}
$$ | 2015/01/28 | [
"https://math.stackexchange.com/questions/1124217",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/174613/"
] | If $f(g(b))=b$ for all $b$, then in particular for $b:=f(a)$ we also have $f(g(f(a))=f(a)$ for all $a$. Now, using that $f$ is injective we arrive at $g(f(a)=a$. | Yes. From the stated assumptions, it is straightforward to prove that $f$ is surjective, as follows.
Let $b \in B$. Then since $f(g(b)) = b$, $b$ is in the image of $f$. |
2,689,794 | I'm currently building an Excel 2003 app that requires a horribly complex form and am worried about limitations on the number of controls. It currently has 154 controls (counted using `Me.Controls.Count` - this should be accurate, right?) but is probably only about a third complete. The workflow really fits a single form, but I guess I can split it up if I really have to.
I see evidence in a Google search that VB6 (this usually includes VBA) has a hard limit of 254 controls in a form. However, I created a dummy form with well over 1200 controls which still loaded and appeared to work just fine.
I did get some 'out of memory' errors when trying to add specific combinations of controls though, say 800 buttons and 150 labels, leading me to think that any limit might be affected by the memory requirements of each type of control.
Does anyone have any information that might help ensure that I or, more importantly, other users with differing environments don't run into any memory issues with such a large form? | 2010/04/22 | [
"https://Stackoverflow.com/questions/2689794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67361/"
] | Most MSForms controls are windowless (as in they are not true windows, rather they are drawn directly by the VBA Forms engine as graphical objects) which are "light-weight" by comparison. This means you can dump more onto a Userform than you could using equivalent non-MSForms controls on a VB6 form.
I don't know what the upper limit is, but it will either be an absolute limit or a limit imposed by available resources, so if you can add 1,200 without encountering either of those & excel is behaving itself in terms of memory use you should be ok.
That said, that number of controls still seems an awful lot to present to the user at once! | No hard n soft rule...
----------------------
---
There is no definite number of controls that VBA will limit you to.
It is entirely dependent on the system you run it on.
As a general rule of thumb:
* Reduce the number of controls.
* Use grid controls instead of arrays of buttons.
* Split it into logical forms for further simplicity.
* Use [lightweight controls](http://support.microsoft.com/kb/184687) (handle-less controls) as they consume less memory.
Apart from this, if you still are using more than 100 controls on the screen (as you say you are) then its time you hired a new UI designer for the project.
GoodLUCK!!
**PS**: Do try and split the form up, if possible.
I can't imagine using any software that throws up 154 controls in one screen.
(MS-WORD comes pretty close ;-) )
---
**UPDATE:** Some stuff for your reference below...
>
> * <http://support.microsoft.com/kb/q177842/>
>
>
> |
2,689,794 | I'm currently building an Excel 2003 app that requires a horribly complex form and am worried about limitations on the number of controls. It currently has 154 controls (counted using `Me.Controls.Count` - this should be accurate, right?) but is probably only about a third complete. The workflow really fits a single form, but I guess I can split it up if I really have to.
I see evidence in a Google search that VB6 (this usually includes VBA) has a hard limit of 254 controls in a form. However, I created a dummy form with well over 1200 controls which still loaded and appeared to work just fine.
I did get some 'out of memory' errors when trying to add specific combinations of controls though, say 800 buttons and 150 labels, leading me to think that any limit might be affected by the memory requirements of each type of control.
Does anyone have any information that might help ensure that I or, more importantly, other users with differing environments don't run into any memory issues with such a large form? | 2010/04/22 | [
"https://Stackoverflow.com/questions/2689794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67361/"
] | No hard n soft rule...
----------------------
---
There is no definite number of controls that VBA will limit you to.
It is entirely dependent on the system you run it on.
As a general rule of thumb:
* Reduce the number of controls.
* Use grid controls instead of arrays of buttons.
* Split it into logical forms for further simplicity.
* Use [lightweight controls](http://support.microsoft.com/kb/184687) (handle-less controls) as they consume less memory.
Apart from this, if you still are using more than 100 controls on the screen (as you say you are) then its time you hired a new UI designer for the project.
GoodLUCK!!
**PS**: Do try and split the form up, if possible.
I can't imagine using any software that throws up 154 controls in one screen.
(MS-WORD comes pretty close ;-) )
---
**UPDATE:** Some stuff for your reference below...
>
> * <http://support.microsoft.com/kb/q177842/>
>
>
> | I try to stay away from userforms that are this big. I much prefer to use the spreadsheet to handle the data collection for things this big. If there are dependencies, then I hide/unhide rows as necessary, or use multiple sheets. I find it is an easier solution (sometimes). |
2,689,794 | I'm currently building an Excel 2003 app that requires a horribly complex form and am worried about limitations on the number of controls. It currently has 154 controls (counted using `Me.Controls.Count` - this should be accurate, right?) but is probably only about a third complete. The workflow really fits a single form, but I guess I can split it up if I really have to.
I see evidence in a Google search that VB6 (this usually includes VBA) has a hard limit of 254 controls in a form. However, I created a dummy form with well over 1200 controls which still loaded and appeared to work just fine.
I did get some 'out of memory' errors when trying to add specific combinations of controls though, say 800 buttons and 150 labels, leading me to think that any limit might be affected by the memory requirements of each type of control.
Does anyone have any information that might help ensure that I or, more importantly, other users with differing environments don't run into any memory issues with such a large form? | 2010/04/22 | [
"https://Stackoverflow.com/questions/2689794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67361/"
] | Most MSForms controls are windowless (as in they are not true windows, rather they are drawn directly by the VBA Forms engine as graphical objects) which are "light-weight" by comparison. This means you can dump more onto a Userform than you could using equivalent non-MSForms controls on a VB6 form.
I don't know what the upper limit is, but it will either be an absolute limit or a limit imposed by available resources, so if you can add 1,200 without encountering either of those & excel is behaving itself in terms of memory use you should be ok.
That said, that number of controls still seems an awful lot to present to the user at once! | There is no hard limit for the maximum number of controls on a form. As mentioned in another answer, this will vary based on your hardware, Excel version, and operating system.
Sadly, I have had too much experience at building VBA forms with too many controls. :(
I can say, that once you get above about 200 controls, you may start noticing some strange/intermittent occurrences/errors.
One thing I have found, completely by trial and error, is that the Frame control, typically used to hold groups of radio buttons, seems to cause more problems than any other control. If I create forms without any Frame controls, I can get more controls on that form before running into trouble.
I have found that no matter how many controls you need, they can usually by categorized into different groups. If a particular group or category is going to contain more than a dozen controls (including labels) it is almost always better to have button for that category that will launch a sub-form. This really helps to reduce the complexity of the main form. |
2,689,794 | I'm currently building an Excel 2003 app that requires a horribly complex form and am worried about limitations on the number of controls. It currently has 154 controls (counted using `Me.Controls.Count` - this should be accurate, right?) but is probably only about a third complete. The workflow really fits a single form, but I guess I can split it up if I really have to.
I see evidence in a Google search that VB6 (this usually includes VBA) has a hard limit of 254 controls in a form. However, I created a dummy form with well over 1200 controls which still loaded and appeared to work just fine.
I did get some 'out of memory' errors when trying to add specific combinations of controls though, say 800 buttons and 150 labels, leading me to think that any limit might be affected by the memory requirements of each type of control.
Does anyone have any information that might help ensure that I or, more importantly, other users with differing environments don't run into any memory issues with such a large form? | 2010/04/22 | [
"https://Stackoverflow.com/questions/2689794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67361/"
] | Most MSForms controls are windowless (as in they are not true windows, rather they are drawn directly by the VBA Forms engine as graphical objects) which are "light-weight" by comparison. This means you can dump more onto a Userform than you could using equivalent non-MSForms controls on a VB6 form.
I don't know what the upper limit is, but it will either be an absolute limit or a limit imposed by available resources, so if you can add 1,200 without encountering either of those & excel is behaving itself in terms of memory use you should be ok.
That said, that number of controls still seems an awful lot to present to the user at once! | I try to stay away from userforms that are this big. I much prefer to use the spreadsheet to handle the data collection for things this big. If there are dependencies, then I hide/unhide rows as necessary, or use multiple sheets. I find it is an easier solution (sometimes). |
2,689,794 | I'm currently building an Excel 2003 app that requires a horribly complex form and am worried about limitations on the number of controls. It currently has 154 controls (counted using `Me.Controls.Count` - this should be accurate, right?) but is probably only about a third complete. The workflow really fits a single form, but I guess I can split it up if I really have to.
I see evidence in a Google search that VB6 (this usually includes VBA) has a hard limit of 254 controls in a form. However, I created a dummy form with well over 1200 controls which still loaded and appeared to work just fine.
I did get some 'out of memory' errors when trying to add specific combinations of controls though, say 800 buttons and 150 labels, leading me to think that any limit might be affected by the memory requirements of each type of control.
Does anyone have any information that might help ensure that I or, more importantly, other users with differing environments don't run into any memory issues with such a large form? | 2010/04/22 | [
"https://Stackoverflow.com/questions/2689794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67361/"
] | There is no hard limit for the maximum number of controls on a form. As mentioned in another answer, this will vary based on your hardware, Excel version, and operating system.
Sadly, I have had too much experience at building VBA forms with too many controls. :(
I can say, that once you get above about 200 controls, you may start noticing some strange/intermittent occurrences/errors.
One thing I have found, completely by trial and error, is that the Frame control, typically used to hold groups of radio buttons, seems to cause more problems than any other control. If I create forms without any Frame controls, I can get more controls on that form before running into trouble.
I have found that no matter how many controls you need, they can usually by categorized into different groups. If a particular group or category is going to contain more than a dozen controls (including labels) it is almost always better to have button for that category that will launch a sub-form. This really helps to reduce the complexity of the main form. | I try to stay away from userforms that are this big. I much prefer to use the spreadsheet to handle the data collection for things this big. If there are dependencies, then I hide/unhide rows as necessary, or use multiple sheets. I find it is an easier solution (sometimes). |
21,376,200 | I am using open cv and C++. I have 2 face images which contain marker points on them. I have already found the coordinates of the marker points. Now I need to align those 2 face images based on those coordinates. The 2 images may not be necessarily of the same height, that is why I can't figure out how to start aligning them, what should be done etc. | 2014/01/27 | [
"https://Stackoverflow.com/questions/21376200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3217694/"
] | In your case, you cannot apply the homography based alignment procedure. Why not? Because it does not fit in this use case. It was designed to align flat surfaces. Faces (3D objects) with markers at different places and depths are clearly no planar surface.
Instead, you can:
1. try to match the markers between images then interpolate the displacement field of the other pixels. Classical ways of doing it will include [moving least squares](http://faculty.cs.tamu.edu/schaefer/research/mls.pdf) interpolation or [RBF](http://hal.archives-ouvertes.fr/docs/00/09/47/64/PDF/Bartoli_Zisserman_BMVC04.pdf)'s;
2. otherwise, a more "Face Processing" way of doing it would be to use the decomposition of faces images between a texture and a face model (like [AAM](http://en.wikipedia.org/wiki/Active_appearance_model) does) and work using the decomposition of your faces in this setup. | Define "align".
Or rather, notice that there does not exist a unique warp of the face-side image that matches the overlapping parts of the frontal one - meaning that there are infinite such warps.
So you need to better specify what your goal is, and what extra information you have, in addition to the images and a few matched points on them. For example, is your camera setup calibrated? I.e do you know the focal lengths of the cameras and their relative position and poses?
Are you trying to build a texture map (e.g. a projective one) so you can plaster a "merged" face image on top of a 3d model that you already have? Then you may want to look into cylindrical or spherical maps, and build a cylindrical or spherical projection of your images from their calibrated poses.
Or are you trying to reconstruct the whole 3d shape of the head based on those 2 views? Obviously you can do this only over the small strip where the two images overlap, and they quality of the images you posted seems a little too poor for that.
Or...? |
1,400,937 | Suppose there is a bash file named "`uploadme`" in the `/usr/bin` folder.
*I am using that file as a command*, and passing the **file names** as a **command line argument**, in any subdirectory of my home directory.
Suppose I am in the directory directory`/home/John/documents/`. In that directory, there is only one file that exists, named "Hello.txt". I will use the command as:
```
uploadme Hello.txt
```
So, the bash file will get one argument as "Hello.txt", but **I want the full path of the file without mentioning it in the argument.**
How can we do that? | 2022/04/05 | [
"https://askubuntu.com/questions/1400937",
"https://askubuntu.com",
"https://askubuntu.com/users/1584541/"
] | The tool `realpath` does that:
```
echo $(realpath "$1")
``` | There is an environment variable named `PWD` that holds the name of the current/working directory. Also, the command `pwd` prints the current directory.
So you can get the full path to the passed argument in your script with `$PWD/$1`. |
1,400,937 | Suppose there is a bash file named "`uploadme`" in the `/usr/bin` folder.
*I am using that file as a command*, and passing the **file names** as a **command line argument**, in any subdirectory of my home directory.
Suppose I am in the directory directory`/home/John/documents/`. In that directory, there is only one file that exists, named "Hello.txt". I will use the command as:
```
uploadme Hello.txt
```
So, the bash file will get one argument as "Hello.txt", but **I want the full path of the file without mentioning it in the argument.**
How can we do that? | 2022/04/05 | [
"https://askubuntu.com/questions/1400937",
"https://askubuntu.com",
"https://askubuntu.com/users/1584541/"
] | There is an environment variable named `PWD` that holds the name of the current/working directory. Also, the command `pwd` prints the current directory.
So you can get the full path to the passed argument in your script with `$PWD/$1`. | If you're trying to get the path to the command, rather than to the file argument, you can use the `which` command. If, inside the scripted command, you want to know where the command is (rather than the current working directory or the full path to a parameter file), you can look at `which $0` (for scripts) or `argv[0]` (for compiled programs). |
1,400,937 | Suppose there is a bash file named "`uploadme`" in the `/usr/bin` folder.
*I am using that file as a command*, and passing the **file names** as a **command line argument**, in any subdirectory of my home directory.
Suppose I am in the directory directory`/home/John/documents/`. In that directory, there is only one file that exists, named "Hello.txt". I will use the command as:
```
uploadme Hello.txt
```
So, the bash file will get one argument as "Hello.txt", but **I want the full path of the file without mentioning it in the argument.**
How can we do that? | 2022/04/05 | [
"https://askubuntu.com/questions/1400937",
"https://askubuntu.com",
"https://askubuntu.com/users/1584541/"
] | The tool `realpath` does that:
```
echo $(realpath "$1")
``` | You can use `readlink -f`:
```
readlink -f "$1"
``` |
1,400,937 | Suppose there is a bash file named "`uploadme`" in the `/usr/bin` folder.
*I am using that file as a command*, and passing the **file names** as a **command line argument**, in any subdirectory of my home directory.
Suppose I am in the directory directory`/home/John/documents/`. In that directory, there is only one file that exists, named "Hello.txt". I will use the command as:
```
uploadme Hello.txt
```
So, the bash file will get one argument as "Hello.txt", but **I want the full path of the file without mentioning it in the argument.**
How can we do that? | 2022/04/05 | [
"https://askubuntu.com/questions/1400937",
"https://askubuntu.com",
"https://askubuntu.com/users/1584541/"
] | The tool `realpath` does that:
```
echo $(realpath "$1")
``` | If you're trying to get the path to the command, rather than to the file argument, you can use the `which` command. If, inside the scripted command, you want to know where the command is (rather than the current working directory or the full path to a parameter file), you can look at `which $0` (for scripts) or `argv[0]` (for compiled programs). |
1,400,937 | Suppose there is a bash file named "`uploadme`" in the `/usr/bin` folder.
*I am using that file as a command*, and passing the **file names** as a **command line argument**, in any subdirectory of my home directory.
Suppose I am in the directory directory`/home/John/documents/`. In that directory, there is only one file that exists, named "Hello.txt". I will use the command as:
```
uploadme Hello.txt
```
So, the bash file will get one argument as "Hello.txt", but **I want the full path of the file without mentioning it in the argument.**
How can we do that? | 2022/04/05 | [
"https://askubuntu.com/questions/1400937",
"https://askubuntu.com",
"https://askubuntu.com/users/1584541/"
] | You can use `readlink -f`:
```
readlink -f "$1"
``` | If you're trying to get the path to the command, rather than to the file argument, you can use the `which` command. If, inside the scripted command, you want to know where the command is (rather than the current working directory or the full path to a parameter file), you can look at `which $0` (for scripts) or `argv[0]` (for compiled programs). |
54,140,610 | I have a `<ul>`, which has many `<li>` , each of which contains an anchor tag. The xpath of the list elements looks like the one:
`String xpath = "//*[@id='page']/section[8]/div/div/div[2]/div/ul/li[";`
`String part2 = "]/a";`
My task involves clicking on each of those links, coming back to the homepage, and then clicking on another link.
At this moment, my webpage contains 5 such elements. To click on each element, I repeat the following inside a for loop:
`driver.findElement(By.xpath(part1 + i + part2)).click();` followed by `driver.navigate().back();`
The problem is I have hardcoded the value 5. It can be 6 some other day, or can have any number of links anyday.
What logic can I use to check the size of the ul? **The problem is that I cannot use a `java.util.List` to store the links beforehand.** | 2019/01/11 | [
"https://Stackoverflow.com/questions/54140610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2451763/"
] | Are you allowed to store their count? :)
```
int len = driver.findElements(By.xpath("//*[@id='page']/section[8]/div/div/div[2]/div/ul/li/a").size()
```
`findElements` will find all elements matching the locator (note the plural), return as a List, on which you you get the size (length).
So now you'll know the upper bound of the loop. | Since you mentioned each `<li>` tag has one anchor tag. That means the number of `<li>` and `<a>` tags are same. You can use `driver.findElements` to get a list of all `<li>` tags and save them in an ArrayList and can easily get the size of the `<li>` tags. This value would be the iterator value for you in the loop you are already using. |
67,920,614 | So I have read mutliple articles regarding this issue, but none worked for my case.
What happens:
When you toggle the keyboard by clicking an entry, on Android the whole layout is shifted up by as much as the keyboard is big. iOS simply renderes the keyboard on top. This is ofc terrible, and especially for the chat application I am building right now completely hiding the entry editor field where the user types on. Inacceptable.
There are some solutions (allthoug I really wonder why such a basic thing isnt included into xamarin.ios already)
**1.) Putting your layout into a scrollview.**
This works. Simply wrap everything into a scrollview, and the keyboard will push everything up. Great, right?
No. In some instances you cannot wrap things into a scrollview: My chat is one example. Since the chat view is a scrollview itself, the outter layers cannot be a scrollview. I mean, they can: but then you have two scrollviews on top of each other leading to scroll issues and both interfering with one another. ALSO: values like `height="180"` dont work inside a scrollview anymore because the height isnt a fixed value.
**2) Using a plugin**
There are many nuget plugins that should work but with the newest iOS they just dont anymore. Some still do, but on few occasions (when the enter button is pressed to disable keyboard) the layout doesnt scroll back down well enough leaving a blank space. So these do not work at all or well enough.
**3) Adding a layout that is inflated when the keyboard is triggered**
This is what I did as a workaround (that isnt good either):
At the bottom of my layout where my entry field for the chat is I added this layout:
```
<Grid Grid.Column="1" Grid.Row="2" x:Name="keyboardLayout" IsVisible="false" >
<Grid.RowDefinitions>
<RowDefinition Height="300"/>
</Grid.RowDefinitions>
<BoxView BackgroundColor="Transparent"/>
</Grid>
```
It is a fixed layout with a height of 300. Now I can listen to keyboard change events:
```
if (Device.RuntimePlatform == Device.iOS)
{
// Android does it well by itself, iOS is special again
var keyboardService = Xamarin.Forms.DependencyService.Get<IKeyboardService>();
keyboardService.KeyboardIsHidden += delegate
{
keyboardLayout.IsVisible = false;
};
keyboardService.KeyboardIsShown += delegate
{
keyboardLayout.IsVisible = true;
};
}
```
With a complicated interface (that I am posting if someone wants it), I can listen to change keyboard events. If the keyboard is visible, I simply update the UI with the layout.
This works, but the fixed size of 300 is an issue.
To this day I still dont really know how fixed values in XAML work (input wanted...!), for smaller margins they seem to be equal on every phone, but for higher values (> 50) they differ too much.
So my solution is just about good enough for older iPhones (6, 7). But leaves a bit of an empty space between the keyboard and the entry filed on newer iPhones with longer screens (11, 12).
In summary: no solution is ideal.
**What we need**
Either an important xamarin update facing this issue (which wont happen anytime soon), or someone who knows how to get the height of the keyboard in pixels, translate that into XAML values, and fill them in in regards to the phone used. Then my solution (number 3) would work always, everywhere (still a workaround, but bulletproof).
Is there anybody out there, who knows how to
a.) get the height of the shown keyboard in pixels
and (and most important)
b.) konws how to translate pixels into `Height="xxx"`
Thank you for comming to my ted talk ;) | 2021/06/10 | [
"https://Stackoverflow.com/questions/67920614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15801387/"
] | You can create class that extend grid in shared code firstly.
```
public class KeyboardView: Grid{}
```
Then create a custom renderer to do the resize control.
```
[assembly: ExportRenderer(typeof(KeyboardView), typeof(KeyboardViewRenderer))]
namespace KeyboardSample.iOS.Renderers
{
public class KeyboardViewRenderer : ViewRenderer
{
NSObject _keyboardShowObserver;
NSObject _keyboardHideObserver;
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
RegisterForKeyboardNotifications();
}
if (e.OldElement != null)
{
UnregisterForKeyboardNotifications();
}
}
void RegisterForKeyboardNotifications()
{
if (_keyboardShowObserver == null)
_keyboardShowObserver = UIKeyboard.Notifications.ObserveWillShow(OnKeyboardShow);
if (_keyboardHideObserver == null)
_keyboardHideObserver = UIKeyboard.Notifications.ObserveWillHide(OnKeyboardHide);
}
void OnKeyboardShow(object sender, UIKeyboardEventArgs args)
{
NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
CGSize keyboardSize = result.RectangleFValue.Size;
if (Element != null)
{
Element.Margin = new Thickness(0, 0, 0, keyboardSize.Height); //push the entry up to keyboard height when keyboard is activated
}
}
void OnKeyboardHide(object sender, UIKeyboardEventArgs args)
{
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
}
void UnregisterForKeyboardNotifications()
{
if (_keyboardShowObserver != null)
{
_keyboardShowObserver.Dispose();
_keyboardShowObserver = null;
}
if (_keyboardHideObserver != null)
{
_keyboardHideObserver.Dispose();
_keyboardHideObserver = null;
}
}
}
}
```
Finally, adding content inside KeyboardView.
You can take a look this thread:
[adjust and move the content of a page up slightly when the keyboard appears in an Entry control Xamarin Forms](https://stackoverflow.com/questions/68103011/adjust-and-move-the-content-of-a-page-up-slightly-when-the-keyboard-appears-in-a/68110827#68110827) | Install **Xamarin.IQKeyboardManager** nuget package in Xamarin.Forms iOS project only.
Add below code in AppDelegate.cs before Forms.init()
```
IQKeyboardManager.SharedManager.Enable = true;
IQKeyboardManager.SharedManager.KeyboardDistanceFromTextField = 20;
```
When you click on entry, it will shift UI up as you mentioned in your question for Android. |
1,978,657 | Is there any predefined UIViewController/NavigationController in the IPhone API as same as "Info" in "Phone/Mobile" application?
For example, suppose I received a call or dialed a number, which is not stored in address book. Then later I wanna see the details of that number, IPhone navigates me to the "Info" view when I click the "Detail disclosure button" in the calls table view. Exactly I want the same "Info" ViewController. Before going to design my customized UIViewController I just wanna know, is there any predefined ViewController in the API?
P:S: I searched the address book API, but unfortunately I didn't notice any such contoller.
Regards,
Prathap. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1978657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233177/"
] | no, you don't have something this specific in the API.
if you want that kind of viewcontroller, you'll have to roll your own. | After going through the API, I found that "ABUnknownPersonViewController" is suitable to serve the purpose. And also "ABPersonViewController" can be used to display the if you get a contact details (if that contact exists in the Address Book).
Thanks refulgentis and Brad Larson for your comments.
refulgentis, as I said above, "Info" is an "UIViewController" not "UITableViewController".
Regards,
Prathap. |
1,978,657 | Is there any predefined UIViewController/NavigationController in the IPhone API as same as "Info" in "Phone/Mobile" application?
For example, suppose I received a call or dialed a number, which is not stored in address book. Then later I wanna see the details of that number, IPhone navigates me to the "Info" view when I click the "Detail disclosure button" in the calls table view. Exactly I want the same "Info" ViewController. Before going to design my customized UIViewController I just wanna know, is there any predefined ViewController in the API?
P:S: I searched the address book API, but unfortunately I didn't notice any such contoller.
Regards,
Prathap. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1978657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233177/"
] | no, you don't have something this specific in the API.
if you want that kind of viewcontroller, you'll have to roll your own. | Not really. Use a `UITableViewController` in the "grouped" style (`UITableViewStyleGrouped`) and initialize your cells with the `UITableViewCellStyleValue2` style, adding a custom `tableHeaderView` if necessary to contain any title / non-listworthy information. |
1,978,657 | Is there any predefined UIViewController/NavigationController in the IPhone API as same as "Info" in "Phone/Mobile" application?
For example, suppose I received a call or dialed a number, which is not stored in address book. Then later I wanna see the details of that number, IPhone navigates me to the "Info" view when I click the "Detail disclosure button" in the calls table view. Exactly I want the same "Info" ViewController. Before going to design my customized UIViewController I just wanna know, is there any predefined ViewController in the API?
P:S: I searched the address book API, but unfortunately I didn't notice any such contoller.
Regards,
Prathap. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1978657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233177/"
] | It's just a UITableViewController with a complex header view and a different text color for the cell's textLabel. | After going through the API, I found that "ABUnknownPersonViewController" is suitable to serve the purpose. And also "ABPersonViewController" can be used to display the if you get a contact details (if that contact exists in the Address Book).
Thanks refulgentis and Brad Larson for your comments.
refulgentis, as I said above, "Info" is an "UIViewController" not "UITableViewController".
Regards,
Prathap. |
1,978,657 | Is there any predefined UIViewController/NavigationController in the IPhone API as same as "Info" in "Phone/Mobile" application?
For example, suppose I received a call or dialed a number, which is not stored in address book. Then later I wanna see the details of that number, IPhone navigates me to the "Info" view when I click the "Detail disclosure button" in the calls table view. Exactly I want the same "Info" ViewController. Before going to design my customized UIViewController I just wanna know, is there any predefined ViewController in the API?
P:S: I searched the address book API, but unfortunately I didn't notice any such contoller.
Regards,
Prathap. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1978657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233177/"
] | It's just a UITableViewController with a complex header view and a different text color for the cell's textLabel. | Not really. Use a `UITableViewController` in the "grouped" style (`UITableViewStyleGrouped`) and initialize your cells with the `UITableViewCellStyleValue2` style, adding a custom `tableHeaderView` if necessary to contain any title / non-listworthy information. |
1,978,657 | Is there any predefined UIViewController/NavigationController in the IPhone API as same as "Info" in "Phone/Mobile" application?
For example, suppose I received a call or dialed a number, which is not stored in address book. Then later I wanna see the details of that number, IPhone navigates me to the "Info" view when I click the "Detail disclosure button" in the calls table view. Exactly I want the same "Info" ViewController. Before going to design my customized UIViewController I just wanna know, is there any predefined ViewController in the API?
P:S: I searched the address book API, but unfortunately I didn't notice any such contoller.
Regards,
Prathap. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1978657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233177/"
] | After going through the API, I found that "ABUnknownPersonViewController" is suitable to serve the purpose. And also "ABPersonViewController" can be used to display the if you get a contact details (if that contact exists in the Address Book).
Thanks refulgentis and Brad Larson for your comments.
refulgentis, as I said above, "Info" is an "UIViewController" not "UITableViewController".
Regards,
Prathap. | Not really. Use a `UITableViewController` in the "grouped" style (`UITableViewStyleGrouped`) and initialize your cells with the `UITableViewCellStyleValue2` style, adding a custom `tableHeaderView` if necessary to contain any title / non-listworthy information. |
28,922,247 | I'm working on cleaning up the tags of mp3s that contain the web links. I tried the regular expression that clears up the web-links
```
(\w+)*(\s|\-)(\w+\.(\w+))
with
$1
```
However, when I try using the same on the file, the extension is replaced. How do I make the extension here, .mp3 as an exception with the above regex?
I have tried using [this](https://stackoverflow.com/questions/1141848/regex-to-match-url) but the replace takes more time | 2015/03/08 | [
"https://Stackoverflow.com/questions/28922247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003393/"
] | based on your examples, use this pattern
```
\s-\s\S+(?=\.)
```
and replace w/ nothing
```
\s # <whitespace character>
- # "-"
\s # <whitespace character>
\S # <not a whitespace character>
+ # (one or more)(greedy)
(?= # Look-Ahead
\. # "."
) # End of Look-Ahead
```
[Demo](https://regex101.com/r/yW4aZ3/219) | If you replace by the first group only, sthi will only be the name of the file, extension not included.
Your regex do not actually catch the extension, it stops after the top level domain (.com) of the website.
You should use:
```
(\w+)(\s\-\s)(\w+\.\w+.\w+)(\.\w+)
```

[Debuggex Demo](https://www.debuggex.com/r/CiI2RgeKam20_gbQ)
and replace everything by groups 1 and 4. Reminds that usually the group 0 is containing the whole string matched by the regular expression.
More details, on the example "MySong - www.mysite.com.mp3:
```
(\w+) // 1. will match "MySong", replace by ([\w\s]+) to match "My Song"
(\s\-\s) // 2. will match " - "
(\w+\.\w+.\w+) // 3. will match "www.mysite.com". You may want to let "www." be optional by replacing by "([\w+\.]?\w+.\w+)
(\.\w+) // 4. the '.mp3" extension
``` |
53,744,017 | I have the following User entity that contains list of friends, that is the list of the same entitities.
```
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String surname;
List<User> friends;
}
```
How is the correct way to map this relation in the Hibernate?
In native SQL tables it is resolved by creating second table that define relation beetwen users. | 2018/12/12 | [
"https://Stackoverflow.com/questions/53744017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9505054/"
] | Here you can use the following example:
```
@Entity
@Table(name = "users")
class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String surname;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_friends")
Set<User> friends;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Set<User> getFriends() {
return friends;
}
public void setFriends(Set<User> friends) {
this.friends = friends;
}
public void addFriend(User u) {
if (this.friends == null) {
this.friends = new HashSet();
}
this.friends.add(u);
}
}
```
persistence.xml :
```
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="deneme" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.deneme.User</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://127.0.0.1;databaseName=springbootdb"/>
<property name="javax.persistence.jdbc.user" value="emre"/>
<property name="javax.persistence.jdbc.password" value="asdf_1234"/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.ddl-generation" value="auto"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
```
main :
```
public class Main {
public static void main(String[] args) {
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "deneme");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
User u = new User();
u.setName("test");
u.setSurname("test");
User uf = new User();
uf.setName("fri");
uf.setSurname("fri");
u.addFriend(uf);
entitymanager.persist(u);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
```
Generated sql:
```
Hibernate: insert into users (name, surname) values (?, ?)
Hibernate: insert into users (name, surname) values (?, ?)
Hibernate: insert into user_friends (User_id, friends_id) values (?, ?)
```
Screenshot from database:
[](https://i.stack.imgur.com/lzD2k.png) | You must add appropriate `@OneToMany` and `@ManyToOne` annotations. You must introduce a new field which would work as a parent.
```
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String surname;
@ManyToOne
private User parentUser;
@OneToMany(mappedBy = "parentUser")
List<User> friends;
}
``` |
27,351,274 | I've got two select queries I need to combine into one result.
```
/* Count of all classes students have passed */
/* A */
SELECT COUNT(TECH_ID) as Number1, ct.SUBJ, ct.COU_NBR
FROM [ISRS].[ST_COU] st
JOIN [ISRS].[CT_COU_SQL] ct
ON st.COU_ID = ct.COU_ID
WHERE GRADE = 'A' OR Grade = 'B' or Grade = 'C'
GROUP BY ct.SUBJ, ct.COU_NBR
/* Total Count of all students who needed to take a course */
/* B */
SELECT COUNT(TECH_ID) as Number2, ec.SUBJ, ec.COU_NBR
FROM [dbo].[ST_MAJOR_COMMENT] st JOIN [dbo].[Emphasis_Class] ec
ON st.MAJOR = ec.Emphasis
GROUP BY ec.SUBJ, ec.COU_NBR
```
I need SUBJ, COU\_NBR, sum(B - A) | 2014/12/08 | [
"https://Stackoverflow.com/questions/27351274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4335893/"
] | If I understand your requirement correctly, you want the footer to sit at the bottom of the content box.
One solution is to make the content box `position:relative` and move the footer inside it, so that its `position:absolute` will bind it to the content box, and the `bottom:0` will achieve the desired effect of having it sit against the bottom of said content box.
See <http://jsfiddle.net/wn6uvske/5/>.
HTML:
```
<div id="wrapper">
<div id="sidebar"></div>
<div id="body-content">
<div class="header">
<div class="navbar navbar-default" role="navigation">
<div class="container">
<ul class="nav navbar-nav navbar-right">
<li><a href="#" class="menu-toggle">Toggle Menu</a>
</li>
</ul>
</div>
</div>
</div>
<div class="main">
<div class="content container">
<p>Content</p>
<div class="footer"> <!-- moved up into content container -->
<p>Footer</p>
</div>
</div>
</div>
</div>
</div>
```
(relevant) CSS:
```
.main .content {
height: 2000px;
background-color: aquamarine;
padding-bottom:80px;
position:relative;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 80px;
background-color: beige;
}
``` | you can use the sticky footer trick. Wrap all of your content in a wrapper excluding the footer, set `min-height:100%` and `margin: -(footer height)` on said wrapper to keep it at the bottom:
[FIDDLE](http://jsfiddle.net/wn6uvske/6/)
**UPDATE**
You can take the `header` section out and use CSS `calc()` to adjust the height:
[NEW FIDDLE](http://jsfiddle.net/wn6uvske/7/) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.