qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | This seems to be a bug in the documentation. The actual format should be "HH:MM:SS Mmm DD, YYYY PST" (e.g. "08:30:06 Apr 19, 2017 PDT") | Actually, I think the right format is: yyyy-MM-ddTHH:MM:ssZ
The case is important. |
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | Actually in PHP you need to use date("Y-m-d\TH:i:s\Z") . That will result in something that looks like 2012-04-30T00:05:47Z -- I didn't notice a difference between urlencoded and non.
Where are you guys finding this info? This information is elusive in their documentation and cost me an hour or two of hunting and trying stuff. The only place I see this format is in the TIMESTAMP field. Having a hard time with the PayPal NVP API's PROFILESTARTDATE for CreateRecurringPaymentsProfile and a "Subscription start date should be valid" error. | Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
Where TZD = time zone designator (Z or +hh:mm or -hh:mm)
Example
1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time.
1994-11-05T13:15:30Z corresponds to the same instant.
<https://www.w3.org/TR/NOTE-datetime> |
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | This seems to be a bug in the documentation. The actual format should be "HH:MM:SS Mmm DD, YYYY PST" (e.g. "08:30:06 Apr 19, 2017 PDT") | this is the correct format according to their documentation - 2010-03-27T12:34:49Z
so it is - YYYY-MM-DDTHH:MM:SSZ (I don't know what the T in the middle and Z is but it's constant for all the dates)
I've created PayPal NVP library in Java, so if you want to check how it works, or use it,
you are more than welcome. it's on sourceforge - payapal-nvp.sourceforge.net |
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | For php, the syntax is `date("G:i:s M m, Y T");` | Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
Where TZD = time zone designator (Z or +hh:mm or -hh:mm)
Example
1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time.
1994-11-05T13:15:30Z corresponds to the same instant.
<https://www.w3.org/TR/NOTE-datetime> |
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | This seems to be a bug in the documentation. The actual format should be "HH:MM:SS Mmm DD, YYYY PST" (e.g. "08:30:06 Apr 19, 2017 PDT") | For php, the syntax is `date("G:i:s M m, Y T");` |
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | this is the correct format according to their documentation - 2010-03-27T12:34:49Z
so it is - YYYY-MM-DDTHH:MM:SSZ (I don't know what the T in the middle and Z is but it's constant for all the dates)
I've created PayPal NVP library in Java, so if you want to check how it works, or use it,
you are more than welcome. it's on sourceforge - payapal-nvp.sourceforge.net | Actually, I think the right format is: yyyy-MM-ddTHH:MM:ssZ
The case is important. |
908,077 | I'm looking at the PayPal `IPN docs`, and it says the `datetime` stamps of their strings are formatted as:
```
HH:MM:SS DD Mmm YY, YYYY PST
```
So year is specified twice?
Once in double digits, and another with 4 digits?
This looks bizarre. | 2009/05/25 | [
"https://Stackoverflow.com/questions/908077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73398/"
] | This seems to be a bug in the documentation. The actual format should be "HH:MM:SS Mmm DD, YYYY PST" (e.g. "08:30:06 Apr 19, 2017 PDT") | Actually in PHP you need to use date("Y-m-d\TH:i:s\Z") . That will result in something that looks like 2012-04-30T00:05:47Z -- I didn't notice a difference between urlencoded and non.
Where are you guys finding this info? This information is elusive in their documentation and cost me an hour or two of hunting and trying stuff. The only place I see this format is in the TIMESTAMP field. Having a hard time with the PayPal NVP API's PROFILESTARTDATE for CreateRecurringPaymentsProfile and a "Subscription start date should be valid" error. |
63,770,877 | I am working on SQL Server and I have two tables TableMaster and TableValidator. They both share 5 columns but no IDs. I need to find in TableValidator all those records that are not on the TableMaster to eventually insert them into TableMaster. If the values of all those 5 columns are identical on both then that is the same record.
For example:
TableMaster
```
JobCode | Location | Code1 | Code2 | Code3 | Other column...
>100333 USA A112 TR 0057
100987 TAR A112 TR 0098
>220999 PUR R100 LK 0098
...
```
TableValidator
```
JobCode | Location | Code1 | Code2 | Code3 | Other column...
100333 USA A100 NS 0057
100987 TAR A112 TR 0098
>220999 PUR R100 LK 0098
220999 PUR R100 LK 1009
220999 PUR R100 LK 3305
>100333 USA A112 TR 0057
...
```
As you can see in this tables only two records are identical. I need to identify those on TableValidator that are not on the TableMaster in order to insert them back into TableMaster. | 2020/09/07 | [
"https://Stackoverflow.com/questions/63770877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6273079/"
] | You can simply use `NOT EXISTS()` as
```
INSERT INTO MasterTable (JobCode, Location, Code1, Code2, Code3)
SELECT JobCode, Location, Code1, Code2, Code3
FROM ValidatorTable VT
WHERE NOT EXISTS(
SELECT 1
FROM MasterTable MT
WHERE VT.JobCode = MT.JobCode
AND VT.Location = MT.Location
AND VT.Code1 = MT.Code1
AND VT.Code2 = MT.Code2
AND VT.Code3 = MT.Code3
);
```
Here is a `[db-fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=cd10b487e1916af8a0ae344ff5a699c0)` | Try the below?
```
Select A.JobCode From TableValidator A
Left join TableMaster B on A.JobCode = B.JobCode
Where B.JobCode is null
--OR
Select A.JobCode From TableValidator A
Where not Exists(Select 1 From TableMaster B where A.JobCode = B.JobCode)
``` |
1,736,287 | With Windows Presentation Foundation, if I have an HWND, how can I capture it's window as an image that I can manipulate and display? | 2009/11/15 | [
"https://Stackoverflow.com/questions/1736287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76322/"
] | You can:
1. `CreateBitmap()` to create a hBitmap
2. Call `GetDC()` on the hWnd
3. `BitBlt()` the contents to the hBitmap
4. `ReleaseDC()`
5. Call `Imaging.CreateBitmapSourceFromHBitmap()` to create a managed `BitmapSource`
6. `DeleteObject()` on the hBitmap
7. Use the `BitmapSource` as desired
Steps 1-4 and 6 use the Win32 API (GDI to be precise), Steps 5 and 7 are done using WPF | While above answer is great, this would have saved a ton of time too:
**Using section:**
```
using System;
using System.Windows;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
```
**Code:**
```
/// <summary>
/// Captures screenshot using WINAPI.
/// </summary>
static public class CaptureScreenshot
{
/// <summary>
/// Capture the screenshot.
/// <param name="area">Area of screenshot.</param>
/// <returns>Bitmap source that can be used e.g. as background.</returns>
/// </summary>
public static BitmapSource Capture(Rect area)
{
IntPtr screenDC = GetDC(IntPtr.Zero);
IntPtr memDC = CreateCompatibleDC(screenDC);
IntPtr hBitmap = CreateCompatibleBitmap(screenDC, (int)SystemParameters.VirtualScreenWidth, (int)SystemParameters.VirtualScreenHeight);
SelectObject(memDC, hBitmap); // Select bitmap from compatible bitmap to memDC
// TODO: BitBlt may fail horribly
BitBlt(memDC, 0, 0, (int)area.Width, (int)area.Height, screenDC, (int)area.X, (int)area.Y, TernaryRasterOperations.SRCCOPY);
BitmapSource bsource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
ReleaseDC(IntPtr.Zero, screenDC);
ReleaseDC(IntPtr.Zero, memDC);
return bsource;
}
#region WINAPI DLL Imports
[DllImport("gdi32.dll", ExactSpelling = true, PreserveSig = true, SetLastError = true)]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateBitmap(int nWidth, int nHeight, uint cPlanes, uint cBitsPerPel, IntPtr lpvBits);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
private enum TernaryRasterOperations : uint
{
/// <summary>dest = source</summary>
SRCCOPY = 0x00CC0020,
/// <summary>dest = source OR dest</summary>
SRCPAINT = 0x00EE0086,
/// <summary>dest = source AND dest</summary>
SRCAND = 0x008800C6,
/// <summary>dest = source XOR dest</summary>
SRCINVERT = 0x00660046,
/// <summary>dest = source AND (NOT dest)</summary>
SRCERASE = 0x00440328,
/// <summary>dest = (NOT source)</summary>
NOTSRCCOPY = 0x00330008,
/// <summary>dest = (NOT src) AND (NOT dest)</summary>
NOTSRCERASE = 0x001100A6,
/// <summary>dest = (source AND pattern)</summary>
MERGECOPY = 0x00C000CA,
/// <summary>dest = (NOT source) OR dest</summary>
MERGEPAINT = 0x00BB0226,
/// <summary>dest = pattern</summary>
PATCOPY = 0x00F00021,
/// <summary>dest = DPSnoo</summary>
PATPAINT = 0x00FB0A09,
/// <summary>dest = pattern XOR dest</summary>
PATINVERT = 0x005A0049,
/// <summary>dest = (NOT dest)</summary>
DSTINVERT = 0x00550009,
/// <summary>dest = BLACK</summary>
BLACKNESS = 0x00000042,
/// <summary>dest = WHITE</summary>
WHITENESS = 0x00FF0062
}
[DllImport("gdi32.dll")]
private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
#endregion
}
```
Notice that this takes screenshot of given area in the screen and not of window. It works for my purposes, you probably have to modify it for yours :) |
399,464 | I'm often creating PDF files from web pages in MacOS X (10.6) and very often I have the problem that the automatically proposed file name (based on the name of the web page) contains many special characters.
So I wonder: is there an easy way (apple script, shell script, OS X service) which takes a string (like this file name) and converts it by
* removing all spaces and other special characters (also those which might be allowed in OS X, but forbidden in Windows or Linux!! as I'm often transferring files to our PC)
* maybe starting each word (after a removed space) with an uppercase letter
* ... what else could be important?
I'm using Quicksilver, so maybe it could be possible to create a command which makes it possible to replace the current text selection (in the file save as... dialog) by a converted string. | 2012/03/11 | [
"https://superuser.com/questions/399464",
"https://superuser.com",
"https://superuser.com/users/92184/"
] | You can create an Automator service to do this in all applications that support services (which is almost all of them).
---
Open Automator and select to create a *Service* that receives *selected text* in *any application* and check *Output replaces selected text*.
Add a single *Run Shell Script* action from the library, and paste the following script code:
```
sed 's|[^a-zA-Z0-9]||g'
```
This specific script, a simple `sed` substitution will remove all non alpha-numeric characters from the file name. It uses `a-zA-Z0-9` as a whitelist of allowed characters, add to it as desired.
You can do other actions as well, and chain them together. For example, `tr [A-Z] [a-z]` will lowercase everything, and `sed 's|[^a-zA-Z0-9]||g' | tr [A-Z] [a-z]` will combine the two.
Save as e.g. *Sanitize Filename*, and optionally assign a keyboard shortcut in *System Preferences » Keyboard » Keyboard Shortcuts » Services*. You should be able to invoke services using Quicksilver as well, just type their name.
---
Whenever you're in a *Save as…* or similar dialog, select the suggested file name (it's selected by default):

Invoke the service *Program Menu » Services » Sanitize Filename* (or use the keyboard shortcut you invoked). It will pipe the file name through the script, and use its output to replace the selection.

---
For title-casing and removing bad characters (I also keep underscore, dot and hyphen in), the following script code seems to mostly work for me:
```
perl -ane 'foreach $wrd(@F){print ucfirst($wrd)." ";}' | sed 's|[^a-zA-Z0-9_.-]||g'
```
 | Same idea as Daniel had. Create a *Service* in *Automator*. Replace the *Run Shell Script* shell with `/usr/bin/ruby`, and add the following:
```
input, output = STDIN.read, ""
input.each("\s") {|word| output << word.capitalize}
puts output.gsub!(/[^0-9A-Za-z\-]/, '')
```
This will get you the capitalization and you can do a bit more, of course, if you know Ruby. You could trigger the Service using QuickSilver but you would need to activate your browser using AppleScript before, I guess.
 |
155,161 | I noticed that there are a list of Platforms/Vendors for which a CVE can be applied for.
What happens if I find a CVE for a proprietary platform (that is commercially available), is there a way to get a CVE assigned for it? | 2017/03/28 | [
"https://security.stackexchange.com/questions/155161",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/12253/"
] | Different vendors require different steps to be taken in order to get a CVE ID assigned for vulnerabilities.
If you check [the MITRE CVE ID Request page here](https://cve.mitre.org/cve/request_id.html) then you can follow the instructions to request an ID after locating the correct CVE Numbering Authority.
If the vendor is not specifically mentioned in any of the tables and a relevant CNA is not listed then you have to contact MITRE directly to request a CVE ID by [filling out the form here](https://cveform.mitre.org/). | I think the main thing here is to make sure you follow Responsible Disclosure:
From [wikipedia](https://en.wikipedia.org/wiki/Responsible_disclosure):
>
> Responsible disclosure is a computer security term describing a vulnerability disclosure model. It is like full disclosure, with the addition that all stakeholders agree to allow a period of time for the vulnerability to be patched before publishing the details.
>
>
>
If you just go and publish details of the vulnerability without giving the vendor enough time to put out a patch, you will actually be doing more damage than good because you will be enabling attackers to hack otherwise secure systems.
If this is your first time disclosing a vuln and it all seems a bit overwhelming then, as Ross Smith says, the MITRE organization than runs the CVE database can act as the mediator between you and the vendor. |
2,382,723 | I have been looking at the definition of a 'branch' of a complex function. The typical definition I am getting is as follows:
>
> ...branches $f\_1(z)$, $f\_2(z)$, $...$ of $f(z)$ each defined as a single-valued continuous function throughout its range of definition. Each branch assumes one set of the function values of $f(z)$. (Korn & Korn, 2013; pg 193)
>
>
>
(a similar definition is given [here](http://mathworld.wolfram.com/Branch.html))
The problem with these definition is that there is an ambiguity of what we call a branch, and by these definitions we should have an infinite number. e.g. we could have a branch defined for $0\le \theta \lt 2\pi$ and another for $0.001\le \theta \lt 2\pi+0.001$.
My question is; is their a name for the set of branches $f\_i$ such that they don't overlap in this way? | 2017/08/04 | [
"https://math.stackexchange.com/questions/2382723",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/203397/"
] | Let $f:U\to \mathbb C$ and $g:V\to\mathbb C$ be analytic on connected open sets $U,V$. They are branches of the same function if there is a sequence of open connected subsets, $U=W\_1,W\_2,\dots,V=W\_n$ and analytic functions $f\_i:W\_i\to \mathbb C$ such that $f\_1=f,f\_n=g$ and $W\_{i}\cap W\_{i+1}$ is non-empty, and $f\_{i}(x)=f\_{i+1}(x)$ for all $x\in W\_{i}\cap W\_{i+1}$.
So, it can be seen as the transitive closure of the relationship on analytic functions $f,g$ defined by:
>
> $fRg$ iff $\mathrm{domain }(f) \cap\mathrm{domain}(g)\neq \emptyset$ and $f(x)=g(x)$ for all $x\in \mathrm{domain }(f) \cap\mathrm{domain}(g)$.
>
>
>
You can use this set to define something called the Riemann manifold of a function, $f$.
Given analytic $f$, we take $X$ to be the set of all pairs $(g,x)$ where $g$ is a branch of $f$ and $x\in\mathrm{domain}(g)$. We define a relationship $(g\_1,x)\sim (g\_2,y)$ if $x=y$ and $g\_1(z)=g\_2(z)$ for all $x$ where both are defined.
Then $M=X/\sim$ is the Riemann manifold of $f$.
Then there is a natural map $M\to\mathbb C$ defined as $(g,x)\mapsto x$, and the function $(g,x)\mapsto g(x)$ which is the "lift" of $f$ from $\mathbb C$ to $M$. | Echoing @Andrew D. Hwang's good answer, I'd agree that a big part of the common problem in parsing discussion about "branches" is that the vocabulary to talk about many of these basic complex analysis notions is out-of-date and/or vague, even though the *ideas* go back at least to Riemann, c. 1850's.
Somewhat contrary to common textbook portrayals of "the principal branch of ...", this is very much just *convention*, and does not often express any genuine mathematical fact. As in the other answers, as one can say in various ways, one has some sort of *local* description of some holomorphic function(s), ambiguous up to ... sign? permutation of solutions of algebraic equation? linear combinations of solutions of ODE's... ? but/and we can specify *local* "solutions/sections/whatever" on sufficiently small neighborhoods away from some "bad points" ("ramified points"? "branch points"?) The question one may wish to address is about sticking together *local* solutions to give a (relatively) *global* solution on as large an open set as possible.
Naturally, already in easy examples, there is *not* a unique maximal such, despite a sort of traditional impulse to try to make it be so.
What we're doing is looking for "sections" of a *sheaf* (the aggregate of the local pieces and possible glue-ings together whether they match) on varying open subsets of $\mathbb C$. The seeming ambiguities are not really avoidable, since for a given open, the set/vectorspace/whatever of possible "sections on that open" is not often a single thing.
(Indeed, the various discrepancies about things fitting together produce various "cohomology theories": DeRham, Cech, and Grothendieck's understanding that many of these are derived functors of the "sections" functor, as in his Tohoku J. paper from long ago...)
Operationally, one point is to not (foolhardily) attempt to over-simplify things that do not admit much further simplification. There are complexities there that are genuine, not just issues with notation or terminology. |
2,382,723 | I have been looking at the definition of a 'branch' of a complex function. The typical definition I am getting is as follows:
>
> ...branches $f\_1(z)$, $f\_2(z)$, $...$ of $f(z)$ each defined as a single-valued continuous function throughout its range of definition. Each branch assumes one set of the function values of $f(z)$. (Korn & Korn, 2013; pg 193)
>
>
>
(a similar definition is given [here](http://mathworld.wolfram.com/Branch.html))
The problem with these definition is that there is an ambiguity of what we call a branch, and by these definitions we should have an infinite number. e.g. we could have a branch defined for $0\le \theta \lt 2\pi$ and another for $0.001\le \theta \lt 2\pi+0.001$.
My question is; is their a name for the set of branches $f\_i$ such that they don't overlap in this way? | 2017/08/04 | [
"https://math.stackexchange.com/questions/2382723",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/203397/"
] | "Branch" is a slightly tricky term to pin down. Literally, a branch of a function is just a holomorphic function in some non-empty open subset of the complex plane, or a continuous extension to the closure.
That alone, however, misses a substantial cultural subtext: If $f$ is holomorphic, a *branch of inverse* is a left inverse defined on some open subset $V = f(U)$ of the image of $f$, namely, a holomorphic bijection $g:V \to U$ such that $(g \circ f)(z) = z$ for all $z$ in $U$.
For instance:
* A *branch of logarithm* is a left inverse of the complex exponential. Customarily, one fixes an even integer $k$ and takes $U$ to be the set of $z$ whose imaginary part is between $(k - 1)\pi i$ and $(k + 1)\pi i$, and $V$ to be the *slit plane*, with the non-positive reals removed.
* A *branch of square root* is a left inverse of the complex squaring function. Customarily, one takes $U$ to be either the right or left open half-plane, and $V$ to be the slit plane.
A bit more generally, if $P(z, w) = 0$ is an analytic relation, a *branch of $w$* is a holomorphic function $f$ defined in some open set $U$ satisfying $P(z, f(z)) = 0$ for all $z$ in $U$.
For instance:
* If $P(z, w) = z - \exp w$, then a branch of $w$ is a branch of $\log$.
* If $P(z, w) = z - w^{2}$, a branch of $w$ is a branch of square root.
* If $P(z, w) = z^{2} + w^{2} - 1$, a *branch of $w = \sqrt{1 - z^{2}}$* is an open set $U \subset \mathbf{C}$ not containing $\pm 1$ and a holomorphic function $f:U \to \mathbf{C}$ satisfying $z^{2} + f(z)^{2} - 1 = 0$ for all $z$ in $U$. | Echoing @Andrew D. Hwang's good answer, I'd agree that a big part of the common problem in parsing discussion about "branches" is that the vocabulary to talk about many of these basic complex analysis notions is out-of-date and/or vague, even though the *ideas* go back at least to Riemann, c. 1850's.
Somewhat contrary to common textbook portrayals of "the principal branch of ...", this is very much just *convention*, and does not often express any genuine mathematical fact. As in the other answers, as one can say in various ways, one has some sort of *local* description of some holomorphic function(s), ambiguous up to ... sign? permutation of solutions of algebraic equation? linear combinations of solutions of ODE's... ? but/and we can specify *local* "solutions/sections/whatever" on sufficiently small neighborhoods away from some "bad points" ("ramified points"? "branch points"?) The question one may wish to address is about sticking together *local* solutions to give a (relatively) *global* solution on as large an open set as possible.
Naturally, already in easy examples, there is *not* a unique maximal such, despite a sort of traditional impulse to try to make it be so.
What we're doing is looking for "sections" of a *sheaf* (the aggregate of the local pieces and possible glue-ings together whether they match) on varying open subsets of $\mathbb C$. The seeming ambiguities are not really avoidable, since for a given open, the set/vectorspace/whatever of possible "sections on that open" is not often a single thing.
(Indeed, the various discrepancies about things fitting together produce various "cohomology theories": DeRham, Cech, and Grothendieck's understanding that many of these are derived functors of the "sections" functor, as in his Tohoku J. paper from long ago...)
Operationally, one point is to not (foolhardily) attempt to over-simplify things that do not admit much further simplification. There are complexities there that are genuine, not just issues with notation or terminology. |
43,853,743 | I need to sum all digits in a given string. So for I've got this
```
public static void main(String[] args) {
Scanner odczyt = new Scanner(System.in);
System.out.println("Input string");
String ciag = odczyt.nextLine();
int suma = 0;
for (int i = 0; i < ciag.length(); i++) {
if (Character.isDigit(ciag.charAt(i))) {
suma += ciag.charAt(i);
}
}
System.out.println(suma);
}
```
When I input:
>
> "Ala got 3 apples and 1 orange"
>
>
>
the output is 100 instead of 4. What should I change to make it count only digits? | 2017/05/08 | [
"https://Stackoverflow.com/questions/43853743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7981922/"
] | The problem occurs here:
```
suma += ciag.charAt(i);
```
you're adding the character code rather than the digit itself.
change it to this:
```
suma += Integer.parseInt(ciag.charAt(i)+"");
``` | That is because you are adding the ascii code of numbers. Just subtract '0' from the char number as shown below:
suma += ciag.charAt(i)-'0'; |
65,340,738 | I am creating an Input Dialog using kivymd. Whenever I try to fetch the text from the text field, it doesn't output the text, rather it seems like the text is not there. (the dialog just pops up ok and the buttons are working fine).
part of the kivy code
=====================
```
<Content>
MDTextField:
id: pin
pos_hint: {"center_x": 0.5, "center_y": 0.5}
color_mode: 'custom'
line_color_focus: [0,0,1,1]
```
part of the python code
=======================
```py
class Content(FloatLayout):
pass
class MenuScreen(Screen):
def __init__(self, **kwargs):
super(MenuScreen, self).__init__(**kwargs)
def show_confirmation_dialog(self):
# if not self.dialog:
self.dialog = MDDialog(
title="Enter Pin",
type="custom",
content_cls=Content(),
buttons=[
MDFlatButton(
text="cancel",on_release=self.callback
),
MDRaisedButton(
text="[b]ok[/b]",
on_release=self.ok,
markup=True,
),
],
size_hint_x=0.7,
auto_dismiss=False,
)
self.dialog.open()
def callback(self, *args):
self.dialog.dismiss()
def ok(self, *args):
pin = Content().ids.pin.text
if pin == "":
toast("enter pin")
else:
toast(f"pin is {pin}")
``` | 2020/12/17 | [
"https://Stackoverflow.com/questions/65340738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14284845/"
] | Go to your Canvas and change the **Render Mode** from **Screen Space-Overlay** to **Screen Space-Camera**. I think that should fix your problem. | Yes, chage your setting to **Screen Space-Camera** but use these settings (under render camera put your camera):
[](https://i.stack.imgur.com/vSrxk.png) |
13,714,517 | I'm not the best at php coding, just learning it. But i was wondering why I keep getting a variable passed to each() is not an array or object warning. I know there is a similar thread that I had used for this code but that post was not resolved so I am hoping it can be the error is one line 46 where it states -
>
> while(list($key,$val) = each($\_POST['checkbox'])) {
>
>
>
the whole code is
```
<?php
$host = 'localhost'; // Host name
$username = 'root'; // Mysql username
$password = ''; // Mysql password
$db_name = 'forms'; // Database name
$tbl_name = 'members'; // Table name
// Connect to server and select databse.
mysql_connect($host, $username, $password) or die('cannot connect');
mysql_select_db($db_name) or die('cannot select DB');
$sql = 'SELECT * FROM `'.$tbl_name.'`';
$result = mysql_query($sql);?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result)): ?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<? echo $rows['id']; ?>]" type="checkbox" id="checkbox[<? echo $rows['id']; ?>]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['Member ID']; ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['firstname']); ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['lastname']); ?></td>
</tr>
<?php endwhile; ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if ($_POST['delete']) {
$i = 0;
while(list($key,$val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id= '$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=delete_member3.php">';
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
```
Please help me resolve this. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13714517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874551/"
] | `Reducer` is apparently typed as `<A, B, C, D>`. Just because A and C happen to be provided by the same type doesn't make it impossible (and should work in C# as far as I know).
Edit: to clarify -- you can have a method with more than one parameter of the same type: `public void foo(String a, String b)`. One wouldn't say this was ambiguous. Generic types are parameters on the class, and can be used in a similar fashion. Think of a `Map<String, String>` -- you may have one String that represents an ID pointing to another String as a username. | The same way that you pass an argument to two method parameters, you can substitute two type parameters by a single type argument. For instance, if `Reducer` is declared as `class Reducer<A, B, C, D>`, then `Reducer<Text, IntWritable, Text, IntWritable>` is a valid type.
However, if the type parameters have different constraints, e.g., different `super` and `extends` constraints, you may not be able to use the same type argument for both type parameters. |
13,714,517 | I'm not the best at php coding, just learning it. But i was wondering why I keep getting a variable passed to each() is not an array or object warning. I know there is a similar thread that I had used for this code but that post was not resolved so I am hoping it can be the error is one line 46 where it states -
>
> while(list($key,$val) = each($\_POST['checkbox'])) {
>
>
>
the whole code is
```
<?php
$host = 'localhost'; // Host name
$username = 'root'; // Mysql username
$password = ''; // Mysql password
$db_name = 'forms'; // Database name
$tbl_name = 'members'; // Table name
// Connect to server and select databse.
mysql_connect($host, $username, $password) or die('cannot connect');
mysql_select_db($db_name) or die('cannot select DB');
$sql = 'SELECT * FROM `'.$tbl_name.'`';
$result = mysql_query($sql);?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result)): ?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<? echo $rows['id']; ?>]" type="checkbox" id="checkbox[<? echo $rows['id']; ?>]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['Member ID']; ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['firstname']); ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['lastname']); ?></td>
</tr>
<?php endwhile; ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if ($_POST['delete']) {
$i = 0;
while(list($key,$val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id= '$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=delete_member3.php">';
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
```
Please help me resolve this. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13714517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874551/"
] | The same way that you pass an argument to two method parameters, you can substitute two type parameters by a single type argument. For instance, if `Reducer` is declared as `class Reducer<A, B, C, D>`, then `Reducer<Text, IntWritable, Text, IntWritable>` is a valid type.
However, if the type parameters have different constraints, e.g., different `super` and `extends` constraints, you may not be able to use the same type argument for both type parameters. | The two `Text`s refer to *different* type parameters. For instance if `Reducer` had the declaration
```
public class Reducer<A, B, C, D> {
```
then in `Reducer<Text, IntWritable, Text, IntWritable>`, the first `Text` would refer to type parameter `A` and the second to `C` - so the compiler can distinguish between them. |
13,714,517 | I'm not the best at php coding, just learning it. But i was wondering why I keep getting a variable passed to each() is not an array or object warning. I know there is a similar thread that I had used for this code but that post was not resolved so I am hoping it can be the error is one line 46 where it states -
>
> while(list($key,$val) = each($\_POST['checkbox'])) {
>
>
>
the whole code is
```
<?php
$host = 'localhost'; // Host name
$username = 'root'; // Mysql username
$password = ''; // Mysql password
$db_name = 'forms'; // Database name
$tbl_name = 'members'; // Table name
// Connect to server and select databse.
mysql_connect($host, $username, $password) or die('cannot connect');
mysql_select_db($db_name) or die('cannot select DB');
$sql = 'SELECT * FROM `'.$tbl_name.'`';
$result = mysql_query($sql);?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result)): ?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<? echo $rows['id']; ?>]" type="checkbox" id="checkbox[<? echo $rows['id']; ?>]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['Member ID']; ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['firstname']); ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['lastname']); ?></td>
</tr>
<?php endwhile; ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if ($_POST['delete']) {
$i = 0;
while(list($key,$val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id= '$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=delete_member3.php">';
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
```
Please help me resolve this. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13714517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874551/"
] | `Reducer` is apparently typed as `<A, B, C, D>`. Just because A and C happen to be provided by the same type doesn't make it impossible (and should work in C# as far as I know).
Edit: to clarify -- you can have a method with more than one parameter of the same type: `public void foo(String a, String b)`. One wouldn't say this was ambiguous. Generic types are parameters on the class, and can be used in a similar fashion. Think of a `Map<String, String>` -- you may have one String that represents an ID pointing to another String as a username. | The two `Text`s refer to *different* type parameters. For instance if `Reducer` had the declaration
```
public class Reducer<A, B, C, D> {
```
then in `Reducer<Text, IntWritable, Text, IntWritable>`, the first `Text` would refer to type parameter `A` and the second to `C` - so the compiler can distinguish between them. |
3,207,385 | I came across this question in one of the linear algebra textbooks:
Proof the linear independence of the following set $\{f\_i ∣ i\in\mathbb{N}\}$, such that $f\_i : \mathbb{N}\to\mathbb{Q}$ defined as follows:
For $n\in\mathbb{N}$, $$f\_i (n) =
\begin{cases}
-n & \text{for }n \geq i \\
0 & \text{for }n < i \end{cases} $$
What would be an appropriate approach to check the independence of this infinite set? I thought long about it but was unable to come up with anything.
Any help would be appreciated.
Thanks! | 2019/04/29 | [
"https://math.stackexchange.com/questions/3207385",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/669697/"
] | I assume that in your class $0\notin \Bbb N$ (as otherwise the claim is clearly false).
Assume $\sum\_i c\_i f\_i=0$ with almost all $c\_i=0$.
For any $n>1$, we have
$$ 0=\sum\_i c\_if\_i(n)-\sum\_i c\_if\_i(n-1)=\sum\_i c\_i(f\_i(n)-f\_i(n-1))=-nc\_n,$$
hence $c\_n=0$. Thus $0=\sum\_i c\_if\_i(1)=c\_1f\_1(1)=-c\_1$ and also $c\_1=0$. | Consider the series
$$\sum\_{i=1}^\infty \alpha\_i f\_i (n)$$ for scalars $\alpha\_1, \alpha\_2, \dots$.
We aim to prove that this series is never zero unless all scalars are zero.
First note that $\forall i \in \mathbb{N} \space \exists n \in \mathbb{N}$ such that $n \geq i$. So $\forall n \in \mathbb{N} \space $$\sum\_{i=1}^\infty f\_i (n) \neq 0$ because all terms are either zero or negative and there exists a term where $n \geq i$ and so $f\_i(n) = -n \neq 0$.
So the series cannot be zero by virtue of all of the function values being zero.
The only other way that this series could be zero is if some of the scalars $\alpha\_1, \alpha\_2, \dots$ are negative and so there is some cancellation in the terms. But since ($\forall i \in \mathbb{N} \space \exists j \in \mathbb{N}$ such that $\forall k>j, j>i$), there are an infinite number of terms in the series less than any given nonzero term, so no matter how small a sum $f\_i + f\_{i+1} + f\_{i+2} + \dots + f\_{i+a}$ ($a \in \mathbb{N}$) is, there will always exist a term in the series that is less than this sum. In this way, we can never ‘cancel out’ all of the terms.
So $\sum\_{i=1}^\infty \alpha\_i f\_i (n) \neq 0$ for scalars $a\_1, a\_2, \dots$ unless $\alpha\_i = 0 \space \forall i \in \mathbb{N}$.
So the elements of $\{f\_i | i \in \mathbb{N}\}$ are linearly independent since the only solution to this equation is where all of the scalars are zero. |
3,207,385 | I came across this question in one of the linear algebra textbooks:
Proof the linear independence of the following set $\{f\_i ∣ i\in\mathbb{N}\}$, such that $f\_i : \mathbb{N}\to\mathbb{Q}$ defined as follows:
For $n\in\mathbb{N}$, $$f\_i (n) =
\begin{cases}
-n & \text{for }n \geq i \\
0 & \text{for }n < i \end{cases} $$
What would be an appropriate approach to check the independence of this infinite set? I thought long about it but was unable to come up with anything.
Any help would be appreciated.
Thanks! | 2019/04/29 | [
"https://math.stackexchange.com/questions/3207385",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/669697/"
] | View each function as an infinite vector
$$v\_i = \left( \begin{array}{c} f\_i (1)\\ f\_i (2) \\ f\_i (3)\\ \vdots \end{array}\right) = \left( \begin{array}{c} 0\\0\\\vdots\\0\\-i\\ -i-1\\-i-2\\\vdots\end{array}\right)$$
in $\prod\_{n\in\mathbb{N}}\mathbb{N} $, and show that the $v\_i $ are linearly independent (this is more natural way to view it in my opinion). For example, for $i=5$, $v\_i = (0,0,0,0,-5,-6,-7,...)$
Then to check linear Independence, we check that the following is true only when all coefficients $a\_i $ are zero:
$$ \sum\_{i\geq 1} a\_i v\_i = \left( \begin{array}{c}
-a\_1 \\
-2(a\_1 + a\_2) \\
-3 (a\_1 + a\_2 + a\_3) \\
\vdots
\end{array}\right)
=
\left( \begin{array}{c} 0 \\ 0 \\ 0 \\ \vdots \end{array}\right)$$
But that's clear, since if we solve for the first entry we get $a\_1 = 0$. Substituting that into the next entry we get $a\_2 = 0$. Continuing to infinity, we see that $$ a\_i = 0 \qquad \mbox{ for all } i\geq 1$$ | I assume that in your class $0\notin \Bbb N$ (as otherwise the claim is clearly false).
Assume $\sum\_i c\_i f\_i=0$ with almost all $c\_i=0$.
For any $n>1$, we have
$$ 0=\sum\_i c\_if\_i(n)-\sum\_i c\_if\_i(n-1)=\sum\_i c\_i(f\_i(n)-f\_i(n-1))=-nc\_n,$$
hence $c\_n=0$. Thus $0=\sum\_i c\_if\_i(1)=c\_1f\_1(1)=-c\_1$ and also $c\_1=0$. |
3,207,385 | I came across this question in one of the linear algebra textbooks:
Proof the linear independence of the following set $\{f\_i ∣ i\in\mathbb{N}\}$, such that $f\_i : \mathbb{N}\to\mathbb{Q}$ defined as follows:
For $n\in\mathbb{N}$, $$f\_i (n) =
\begin{cases}
-n & \text{for }n \geq i \\
0 & \text{for }n < i \end{cases} $$
What would be an appropriate approach to check the independence of this infinite set? I thought long about it but was unable to come up with anything.
Any help would be appreciated.
Thanks! | 2019/04/29 | [
"https://math.stackexchange.com/questions/3207385",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/669697/"
] | View each function as an infinite vector
$$v\_i = \left( \begin{array}{c} f\_i (1)\\ f\_i (2) \\ f\_i (3)\\ \vdots \end{array}\right) = \left( \begin{array}{c} 0\\0\\\vdots\\0\\-i\\ -i-1\\-i-2\\\vdots\end{array}\right)$$
in $\prod\_{n\in\mathbb{N}}\mathbb{N} $, and show that the $v\_i $ are linearly independent (this is more natural way to view it in my opinion). For example, for $i=5$, $v\_i = (0,0,0,0,-5,-6,-7,...)$
Then to check linear Independence, we check that the following is true only when all coefficients $a\_i $ are zero:
$$ \sum\_{i\geq 1} a\_i v\_i = \left( \begin{array}{c}
-a\_1 \\
-2(a\_1 + a\_2) \\
-3 (a\_1 + a\_2 + a\_3) \\
\vdots
\end{array}\right)
=
\left( \begin{array}{c} 0 \\ 0 \\ 0 \\ \vdots \end{array}\right)$$
But that's clear, since if we solve for the first entry we get $a\_1 = 0$. Substituting that into the next entry we get $a\_2 = 0$. Continuing to infinity, we see that $$ a\_i = 0 \qquad \mbox{ for all } i\geq 1$$ | Consider the series
$$\sum\_{i=1}^\infty \alpha\_i f\_i (n)$$ for scalars $\alpha\_1, \alpha\_2, \dots$.
We aim to prove that this series is never zero unless all scalars are zero.
First note that $\forall i \in \mathbb{N} \space \exists n \in \mathbb{N}$ such that $n \geq i$. So $\forall n \in \mathbb{N} \space $$\sum\_{i=1}^\infty f\_i (n) \neq 0$ because all terms are either zero or negative and there exists a term where $n \geq i$ and so $f\_i(n) = -n \neq 0$.
So the series cannot be zero by virtue of all of the function values being zero.
The only other way that this series could be zero is if some of the scalars $\alpha\_1, \alpha\_2, \dots$ are negative and so there is some cancellation in the terms. But since ($\forall i \in \mathbb{N} \space \exists j \in \mathbb{N}$ such that $\forall k>j, j>i$), there are an infinite number of terms in the series less than any given nonzero term, so no matter how small a sum $f\_i + f\_{i+1} + f\_{i+2} + \dots + f\_{i+a}$ ($a \in \mathbb{N}$) is, there will always exist a term in the series that is less than this sum. In this way, we can never ‘cancel out’ all of the terms.
So $\sum\_{i=1}^\infty \alpha\_i f\_i (n) \neq 0$ for scalars $a\_1, a\_2, \dots$ unless $\alpha\_i = 0 \space \forall i \in \mathbb{N}$.
So the elements of $\{f\_i | i \in \mathbb{N}\}$ are linearly independent since the only solution to this equation is where all of the scalars are zero. |
60,617,513 | The company I work for wants a file uploader. The file uploader not only has to upload files, but it also has to prevent certain files from being uploaded. The company contracted another company to build this site. I am a Mobile Developer learning Angular. How do I prevent certain files from being uploaded?
Here is a copy of the HTML file.
```html
<div [hidden]="documentation.get('uploadMethod').value !== 'upload'">
<div ng2FileDrop [uploader]="uploader">
<span [hidden]="uploader.queue.length > 0 || (documentation.controls['fileUpload'].errors?.required && documentation.controls['fileUpload'].touched)">Drag Files Here</span><br>
<table>
<tbody>
<tr *ngFor="let item of uploader.queue">
<td>{{item.file.name}}</td>
<td>
{{item.file.size / 1024 >= 1000 ? (item.file.size / 1024 / 1024).toFixed(2) : (item.file.size / 1024).toFixed(2)}}
{{item.file.size / 1000 >= 1000 ? 'mb' : 'kb'}}</td>
<td>
<button mat-raised-button (click)="removeItem(item)">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<button mat-button (click)="saveDocumentation()">Upload all</button>
<button mat-button (click)="removeAll()">Remove all</button>
<div
[hidden]="uploader.progress < 1 || !(uploader.progress <= 100 && uploader.progress >= 0)">
<div>{{uploader.progress}}</div>
</div>
</div>
</div>
``` | 2020/03/10 | [
"https://Stackoverflow.com/questions/60617513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951977/"
] | You need to use the accept attribute of HTML element. You will pass a string of comma separated file types.
```
<input type="file" id="profile_pic" name="profile_pic"
accept=".jpg, .jpeg, .png">
```
Use this for the accept attribute guide - <https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept>
And for ngng2FileDrop (Credit goes to Z. Bagley)
```
<div ng2FileDrop [uploader]="uploader"
[ng2FileDropSupportedFileTypes]="supportedFileTypes">
</div>
```
where supportedFileTypes is an array of file types.
Documentation link - <https://github.com/leewinder/ng2-file-drop> | Two things to note: first, in a normal input upload you can utilize the `accept` parameter: <https://www.w3schools.com/tags/att_input_accept.asp>. Second, you can't actually completely prevent uploads like this from the front, but you can disable them using the package you have used. If you want to completely disable (not just make it harder for front-end users) you will also need to handle this on the back-end.
Example, as taken from <https://github.com/leewinder/ng2-file-drop>:
```
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'my-custom-component',
template: `<!-- my_custom.component.html -->
<!-- Set criteria for only image types under 1MB in size-->
<div ng2FileDrop class="custom-component-drop-zone"
[ng2FileDropSupportedFileTypes]="supportedFileTypes"
[ng2FileDropMaximumSizeBytes]="maximumFileSizeInBytes"
(ng2FileDropFileAccepted)="dragFileAccepted($event)"
</div>`
styles: [`
.custom-component-drop-zone {
width: 300px;
height: 300px;
}
`]
})
export class MyCustomComponent {
// Required criteria for all files (only image types under 1MB in size)
private supportedFileTypes: string[] = ['image/png', 'image/jpeg', 'image/gif'];
private maximumFileSizeInBytes: number = 1e+6;
// File being dragged has been dropped and is valid
private dragFileAccepted(acceptedFile: Ng2FileDropAcceptedFile) {
// Any files passed through here will have met the requested criteria
}
}
```
You are specifically looking to add the `[ng2FileDropSupportedFileTypes]="supportedFileTypes"` in your HTML, and then create a list of accepted file types in your TypeScript Component: `supportedFileTypes: string[] = ['image/png', 'image/jpeg', 'image/gif'];` |
56,542,236 | Here is my problem. I've built the following `ListView`
```
<ListView Grid.Row="1" x:Name="messageList" BorderThickness="0"
ItemsSource="{Binding MySource}"
HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<WrapPanel Grid.Row="0" Grid.Column="0">
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.SenderId}"
/>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.DeliverDate}"
/>
</WrapPanel>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.MsgText}"
Grid.Row="1" Grid.Column="0"
TextWrapping="WrapWithOverflow">
</TextBlock>
<WrapPanel Grid.Row="0" Grid.Column="1">
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.SenderId}"
/>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.DeliverDate}"
/>
</WrapPanel>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.MsgText}"
Grid.Row="1" Grid.Column="1"
TextWrapping="WrapWithOverflow">
</TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
For each element of `MySource` only 1 between Received and Sent will be not null. The `ListView`is working as i expect, placing the element on the left or the right of the screen, but the `TextBlock` that contain the `MsgText` get all the available space (so the whole row) if the message is too long. How can i limit it to stay only in one half of the parent Grid and make the text overflow eventually?
**EDIT**: I added an image showing my problem. The 4th message should overflow, but it doesn't
[](https://i.stack.imgur.com/wLqO7.jpg) | 2019/06/11 | [
"https://Stackoverflow.com/questions/56542236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6474054/"
] | It took me few minutes to produce [mcve](https://stackoverflow.com/help/minimal-reproducible-example), but the missing part of the puzzle is this:
```
<Grid MaxWidth="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
```
That would limit maximum width of all `Grid`s (each item has one) and let wrapping happens. Otherwise `Grid` is [asking](https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/layout#measuring-and-arranging-children) for a width to fit whole item in one line and `ListView` is ok with it, but then you will see horizontal scrollbar (the most hated control by users including me).
---
MCVE:
```
public partial class MainWindow : Window
{
public class Item
{
public string Received { get; set; }
public string Sent { get; set; }
}
public List<Item> Items { get; }
public MainWindow()
{
InitializeComponent();
Items = new List<Item>
{
new Item { Received = "1111 111 11 111 11 1" },
new Item { Received = "2222 2 22 2 2 222222222 2 222222 22222222 222222222222 2" },
new Item { Sent = "333333333 3333333 333 33333 3 3 33 333333333 3333" },
new Item { Received = "444444444444444 444 44444444444444 44 4 44444444444444444 4 4 4444444444 4 444 444444444444" },
};
DataContext = this;
}
}
```
Screenshot:
[](https://i.stack.imgur.com/LeZkl.png)
Xaml:
```
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid MaxWidth="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Received}"
TextWrapping="WrapWithOverflow" />
<TextBlock Grid.Column="1"
Text="{Binding Sent}"
TextWrapping="WrapWithOverflow" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
``` | The problem is that your grid (and the width of the column) is calculated for each element of your list, so it takes the most space possible. I propose a backup solution, I did not find better but the result is there.
This is to place 2 ListView in 2 columns of a grid and then have the Received element in one and the Sent in the other.
```
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListView Grid.Column="0" x:Name="messageListReceived" BorderThickness="0"
ItemsSource="{Binding MySource}"
HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0">
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.SenderId}"
/>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.DeliverDate}"
/>
</WrapPanel>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Received.MsgText}"
Grid.Row="1"
TextWrapping="WrapWithOverflow">
</TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ListView Grid.Column="1" x:Name="messageListSent" BorderThickness="0"
ItemsSource="{Binding MySource}"
HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0">
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.SenderId}"
/>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.DeliverDate}"
/>
</WrapPanel>
<TextBlock Margin="2"
VerticalAlignment="Center"
Text="{Binding Sent.MsgText}"
Grid.Row="1"
TextWrapping="WrapWithOverflow">
</TextBlock>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
``` |
6,008,304 | I am using lua to administrate a firewall server and want to obfuscate sensible variables such as login data. I have tried luac but the variable content is still easily readable. Is there any way to encrypt/decrypt these sensible data? | 2011/05/15 | [
"https://Stackoverflow.com/questions/6008304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752297/"
] | I'm assuming you have a lua script which contains both the commands to send as well as any "secret data", and you want to be able to run this script without having to type in anything interactively.
If so, the script itself must be able to decrypt your secret data in order to use it - and if an attacker can read the script, he can do the same steps to decrypt your data (or run it in a debugger or similar). Thus, it is impossible to **really** hide the secret data in your script. Use your systems file permissions to ensure nobody but you and the process that executes it can read the script.
That said, if you do not want to hinder real attackers, but only want to avoid casual lookers reading the password, any encoding scheme will do - from simple Rot13 over Base64 to hex-encoding. But you should be conscious that this is not a security measure. | If you're allowed to use compiled libraries (ie. LuaRocks), you can use the [Kepler MD5](http://www.keplerproject.org/md5) library to encrypt/decrypt the data- and if you can have the script prompt for a password, you can even make it (reasonably) secure. (If you can't prompt for a password, as Paulo says, obfuscation is the best you can hope for.) |
14,814,658 | I have a string:
`The disk 'virtual memory' also known as 'Virtual Memory' has exceeded the maximum utilization threshold of 95 Percent.`
I need to search every time in this string word `The disk` and if found then I need to extract only phrase in `'*' also known as '*'` and put it in a variable `MONITOR`
In other words I want to search and put the value to
```
MONITOR="'virtual memory' also known as Virtual Memory'"
```
How can I do it using `awk`? | 2013/02/11 | [
"https://Stackoverflow.com/questions/14814658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061705/"
] | Here's a snippet that does what you describe. You should put it in `$(...)` to assign it to the $MONITOR variable:
```
$ awk '/The disk '\''.*'\'' also known as '\''.*'\'' has exceeded/ {gsub(/The disk /,"");gsub(/ has exceeded.*$/,"");print}' input.txt
```
The two problems with awk in this case is
* it doesn't have submatch extraction on its regexes (which is why my solution uses `gsub()` in the body to get rid of the first and last part of the line.
* To use the quotes in your awk regex in a shell script you need the `'\''` sequence to scape it (more info [here](https://stackoverflow.com/questions/9899001/how-to-escape-single-quote-in-awk-inside-printf)) | It might be a little easier with `sed` than `awk`:
```
string="The disk 'virtual memory' also known as 'Virtual Memory' has exceeded the maximum utilization threshold of 95 Percent."
MONITOR=$(echo "$string" | sed -n "/The disk \('[^']*' also known as '[^']*'\) .*/s//\1/p")
```
If `awk` is necessary, then:
```
MONITOR=$(echo "$string" | awk "/The disk '[^']*' also known as '[^']*'/ {
print \$3, \$4, \$5, \$6, \$7, \$8, \$9; } {}')
```
The empty braces `{}` matches any line and prints nothing, so `awk` only processes lines that match the regex. Note that this assumes each disk has a name with two words in it. You need to use more powerful processing (`gsub` function, for example) to do regex-based substitution. This is not `awk`'s forte; `sed` is easier to use for that task.
Both commands are set up to handle multiple lines of data interspersed with non-matching lines (but also work on single lines containing the matching information). It would also not be very difficult to just print the names between quotes on separate lines, so that you have less dissection to do afterwards (to get the two space-separated names). |
46,523,857 | [](https://i.stack.imgur.com/fmk8w.jpg)
I open the `Message-Fragment` from `Activity-A` and then open the `Camera-Fragment` from `Message-Fragment`. Now current fragment is `Camera-Fragment` and i have media-slider on it. Now I have two options, one is `ImagePreview-Fragment` that is opened if I click the image item on media-slider. Other is `VideoPreview-Activity` that is opened if click the video item on media-slider. So there is one condition of clicking video-item. If I click the video-item on media-slider and video size is bigger than 10 MB, I open the `VideoTrim-Activity` and when trim is completed i call the `VideoPreview-Activity`.
I'm sending a media from `VideoPreview-Activity` or `ImagePreview-Fragment`. So when I send the media I want to return back to the `Message-Fragment` with data.
How can I return back to `Message-Fragment` from `VideoPreview-Activity` (opened from Camera-Fragment) and `VideoPreview-Activity` (opened from `VideoTrim-Activity`). Also if you can help me about how to return back from `ImagePreview-Fragment` to `Message-Fragment` I would be much appreciated. These are seperated questions. Hope you can help.
I open the fragments with adding to backstack `addToBackStack(fragmentTag)`.
Edited : VideoPreview-Fragment must be VideoPreview-Activity
and VidoTrim-Fragment must be VideoTrim-Activity. these are the activities. like you see on the image. | 2017/10/02 | [
"https://Stackoverflow.com/questions/46523857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583237/"
] | If I understand everything correctly I think I have a solution. I will ignore all other aspects of the navigation and just focus on the fact you want to go from `VideoPreviewActivity` to the `MainActivity` and adjust the fragment stack, and that this is being triggered from a done button (or something similar) but NOT the back button.
The simple way would be to use the activity result functions `startActivityForResult` which would allow you to use a `onActivityResult` function in the main activity to pass the information back. However you may potentially navigate to the `VideoPreviewActivity` via the `VideoTrimActivity` so you would have to pass this information back through two activities which would be a bit messy.
So my proposed solution has a few steps.
Instead of calling `finish()` on the `VideoPreviewActivity` fire an intent to create the `MainActivity`
```
Intent intent = new Intent(context, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra()//Add your return data here
startActivity(intent)
```
Instead of starting a new `MainActivity` this will return you to the previous one and finish all the activities sat above it in the task task.
Add this function to the `MainActivity`.
```
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
```
Then in the `onStart` function you can check your intent to see if there is data in there returned from `VideoPreview` and remove the fragments you no longer need.
```
if (getIntent().hasExtra(YOUR_DATA)) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager(). popBackStackImmediate("MESSAGE_TAG", 0);
}
```
Where "MESSAGE\_TAG" is the tag used in the `ft.addToBackStack("MESSAGE_TAG")` call.
This will clear all of the fragments with an `addToBackStack` in the transaction. The `MessageFragment` will start its lifecycle calls again and you can access the data from
```
getActivity().getIntent()
``` | Try this,
First take the framelayout in ActivityA,
```
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
Create method in activityA
```
public void openFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, null).commit();
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment, backStateName);
fragmentTransaction.addToBackStack(backStateName);
fragmentTransaction.commit();
}
```
After this done in your mainactivity and then overide the method like
```
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 2 * 1000);
}
} else {
getSupportFragmentManager().popBackStackImmediate();
int c = getSupportFragmentManager().getBackStackEntryCount();
}
}
```
Use in this way,
```
Fragment fragment;
fragment = new FS_PLKit_Calculator();
((FS_Home) getActivity()).openFragment(fragment);
```
try this way you can maintain backstack of your flow. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | No, training with hand grippers won't help you execute barre chords. Firstly, time spent squeezing grippers is time that you could be using to actually practise barre chords. Secondly, the physical action is markedly different and not about finger placement and subtleties of pressure. But hey, you could end up with a really impressive handshake, and all the other musicians will ask you to carry their gear. It's early days; hang in there and your barre chords will improve. | I don't find those hand-grippers very effective in teaching you how to make your barre chords sound better. The truth is, a large part of getting your barre chords to sound good comes from good technique. There are quite a number of tiny details that will help you achieve a good sounding barre chord with minimal effort. Many people think that in order to get your barre chords down, you need quite a lot of strength, and that is not true at all. Remember that precision beats power. Focus on getting the details of the technique correct.
Another thing that may be preventing you from getting your barre chords down is your guitar's set up. If your strings are too far away from the fretboard, you're going to have a really tough time getting your chords to sound good. Make sure your guitar is properly set up. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | No. Simple answer. Your hands could be stronger than a weightlifter's and still not play barre chords, or any other chords, well.
Actually, hardly any finger strength is needed. Putting fingers as close as possible to the fretwire helps, accurate fingering helps, and a good action helps. If the strings are a long way above the fingerbaord, strength will help, but a better solution is to improve the action, or change guitars.
If any muscles help, it's the arm muscles, as they should be used a little as levers, using the thumb as a fulcrum point - which also doesn't need to be clamped to the neck. | No, training with hand grippers won't help you execute barre chords. Firstly, time spent squeezing grippers is time that you could be using to actually practise barre chords. Secondly, the physical action is markedly different and not about finger placement and subtleties of pressure. But hey, you could end up with a really impressive handshake, and all the other musicians will ask you to carry their gear. It's early days; hang in there and your barre chords will improve. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | No, training with hand grippers won't help you execute barre chords. Firstly, time spent squeezing grippers is time that you could be using to actually practise barre chords. Secondly, the physical action is markedly different and not about finger placement and subtleties of pressure. But hey, you could end up with a really impressive handshake, and all the other musicians will ask you to carry their gear. It's early days; hang in there and your barre chords will improve. | Grippers (hand squeezing exercisers) won't get you anywhere. It may sound trite, but the best exercise for improving your barre chords is to play barre chords. Work on correct technique and position, and eventually you'll see marked improvement. You can try to focus on 'power chords' initially (i.e. just the lowest 3 notes, the root, 5th and octave) but don't let this become a crutch. If you're like me, it's the notes that ought to be fretted by the index finger that are likely giving you trouble, but soon you'll come to 'grips' (forgive the pun) with the required touch to properly voice the notes and whole new worlds of playing joy and success will open up for you.
Don't worry about voicing that high E string when playing an 'A' shape barre chord, almost no one gets their ring finger to back-bend sufficiently to let that high E string ring out while playing an 'A'-shape barre chord (eg x57775 for a D chord, most players wind up playing x5777x for this, unintentionally muting that high E string.)
One last thing, don't fall into the bad habit of trying to 're-inforce' your index finger by overlapping your middle finger on top of it. You're gonna need that middle finger elsewhere soon enough, and unlearning bad habits is much harder once they're ingrained.
Have fun and keep practicing. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | No. Simple answer. Your hands could be stronger than a weightlifter's and still not play barre chords, or any other chords, well.
Actually, hardly any finger strength is needed. Putting fingers as close as possible to the fretwire helps, accurate fingering helps, and a good action helps. If the strings are a long way above the fingerbaord, strength will help, but a better solution is to improve the action, or change guitars.
If any muscles help, it's the arm muscles, as they should be used a little as levers, using the thumb as a fulcrum point - which also doesn't need to be clamped to the neck. | I don't find those hand-grippers very effective in teaching you how to make your barre chords sound better. The truth is, a large part of getting your barre chords to sound good comes from good technique. There are quite a number of tiny details that will help you achieve a good sounding barre chord with minimal effort. Many people think that in order to get your barre chords down, you need quite a lot of strength, and that is not true at all. Remember that precision beats power. Focus on getting the details of the technique correct.
Another thing that may be preventing you from getting your barre chords down is your guitar's set up. If your strings are too far away from the fretboard, you're going to have a really tough time getting your chords to sound good. Make sure your guitar is properly set up. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | It turns out that strength is not what is needed to improve your ability to finger barre chords, or any chords. It's mostly about precise placement and using the minimum amount of force to hold it down.
It's not necessarily that equal pressure is correct. You just need the right amount of pressure for each fret and string. | guitars are all about practice, practice and practice. so yeah if you are performing for someone use them, if you are practicing then don't because today you might not be able to do it but even if you try 15 minutes a day( not at a go) try to hold the chord, check if each string is ringing, if not readjust your position(chances are that it is still not ringing), still you practice shifting and strumming, keep on doing it without losing hope and magically one fine day you will get up and notice that you have done it. it might take anywhere between a week to two months. I couldn't press the b string whenever I had the shape of e major for 3 months! so its just a matter of time. for some its less, for some its more. playing guitar has nothing to do with talent. but what comes after playing is. you can play each song you listen for the first time in first go but you may never be able to compose some( I know that cause I don't have the musician in me ) but nothing should ever stop you. if you believe you can, you will end up doing it some day and that might just not be today. Good Luck! |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | It turns out that strength is not what is needed to improve your ability to finger barre chords, or any chords. It's mostly about precise placement and using the minimum amount of force to hold it down.
It's not necessarily that equal pressure is correct. You just need the right amount of pressure for each fret and string. | I don't find those hand-grippers very effective in teaching you how to make your barre chords sound better. The truth is, a large part of getting your barre chords to sound good comes from good technique. There are quite a number of tiny details that will help you achieve a good sounding barre chord with minimal effort. Many people think that in order to get your barre chords down, you need quite a lot of strength, and that is not true at all. Remember that precision beats power. Focus on getting the details of the technique correct.
Another thing that may be preventing you from getting your barre chords down is your guitar's set up. If your strings are too far away from the fretboard, you're going to have a really tough time getting your chords to sound good. Make sure your guitar is properly set up. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | It turns out that strength is not what is needed to improve your ability to finger barre chords, or any chords. It's mostly about precise placement and using the minimum amount of force to hold it down.
It's not necessarily that equal pressure is correct. You just need the right amount of pressure for each fret and string. | No. Simple answer. Your hands could be stronger than a weightlifter's and still not play barre chords, or any other chords, well.
Actually, hardly any finger strength is needed. Putting fingers as close as possible to the fretwire helps, accurate fingering helps, and a good action helps. If the strings are a long way above the fingerbaord, strength will help, but a better solution is to improve the action, or change guitars.
If any muscles help, it's the arm muscles, as they should be used a little as levers, using the thumb as a fulcrum point - which also doesn't need to be clamped to the neck. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | No. Simple answer. Your hands could be stronger than a weightlifter's and still not play barre chords, or any other chords, well.
Actually, hardly any finger strength is needed. Putting fingers as close as possible to the fretwire helps, accurate fingering helps, and a good action helps. If the strings are a long way above the fingerbaord, strength will help, but a better solution is to improve the action, or change guitars.
If any muscles help, it's the arm muscles, as they should be used a little as levers, using the thumb as a fulcrum point - which also doesn't need to be clamped to the neck. | Grippers (hand squeezing exercisers) won't get you anywhere. It may sound trite, but the best exercise for improving your barre chords is to play barre chords. Work on correct technique and position, and eventually you'll see marked improvement. You can try to focus on 'power chords' initially (i.e. just the lowest 3 notes, the root, 5th and octave) but don't let this become a crutch. If you're like me, it's the notes that ought to be fretted by the index finger that are likely giving you trouble, but soon you'll come to 'grips' (forgive the pun) with the required touch to properly voice the notes and whole new worlds of playing joy and success will open up for you.
Don't worry about voicing that high E string when playing an 'A' shape barre chord, almost no one gets their ring finger to back-bend sufficiently to let that high E string ring out while playing an 'A'-shape barre chord (eg x57775 for a D chord, most players wind up playing x5777x for this, unintentionally muting that high E string.)
One last thing, don't fall into the bad habit of trying to 're-inforce' your index finger by overlapping your middle finger on top of it. You're gonna need that middle finger elsewhere soon enough, and unlearning bad habits is much harder once they're ingrained.
Have fun and keep practicing. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | It turns out that strength is not what is needed to improve your ability to finger barre chords, or any chords. It's mostly about precise placement and using the minimum amount of force to hold it down.
It's not necessarily that equal pressure is correct. You just need the right amount of pressure for each fret and string. | No, training with hand grippers won't help you execute barre chords. Firstly, time spent squeezing grippers is time that you could be using to actually practise barre chords. Secondly, the physical action is markedly different and not about finger placement and subtleties of pressure. But hey, you could end up with a really impressive handshake, and all the other musicians will ask you to carry their gear. It's early days; hang in there and your barre chords will improve. |
59,065 | First of all I just started doing barre chords after learning ordinary non-barre chords. Problem is they don't sound so well, so my question is, will training with hand grippers help me achieve this? Because I've been applying equal pressure and they still sound a bit off, only a bit off. | 2017/07/09 | [
"https://music.stackexchange.com/questions/59065",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/42610/"
] | No, training with hand grippers won't help you execute barre chords. Firstly, time spent squeezing grippers is time that you could be using to actually practise barre chords. Secondly, the physical action is markedly different and not about finger placement and subtleties of pressure. But hey, you could end up with a really impressive handshake, and all the other musicians will ask you to carry their gear. It's early days; hang in there and your barre chords will improve. | guitars are all about practice, practice and practice. so yeah if you are performing for someone use them, if you are practicing then don't because today you might not be able to do it but even if you try 15 minutes a day( not at a go) try to hold the chord, check if each string is ringing, if not readjust your position(chances are that it is still not ringing), still you practice shifting and strumming, keep on doing it without losing hope and magically one fine day you will get up and notice that you have done it. it might take anywhere between a week to two months. I couldn't press the b string whenever I had the shape of e major for 3 months! so its just a matter of time. for some its less, for some its more. playing guitar has nothing to do with talent. but what comes after playing is. you can play each song you listen for the first time in first go but you may never be able to compose some( I know that cause I don't have the musician in me ) but nothing should ever stop you. if you believe you can, you will end up doing it some day and that might just not be today. Good Luck! |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | **If** constructs like `[ php ]`, `[/*comment/*php]` (or other crazy stuff) are not allowed, you can use this:
```
/\[php\](.*?)\[\/php\]/
```
The first matched group will be the text inside the tags. I think the regex is quite intuitive, except for the `?`: it will be lazy and match text only until the first closing tag, so that if you have `[php]...[/php] [php]...[/php]` the regex will not match `...[/php] [php]...` (that is, between the first `[php]` and the second `[/php]`) | You can search for string between these tags eg
```
\[PHP\](.+[^\b\[])\[/PHP\]
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | I think `"\[php\](.*?)\[\/php\]"` would do the trick.
Edit: you may or may not need the double quotes-- not sure how you're ultimately using the regex string. | **If** constructs like `[ php ]`, `[/*comment/*php]` (or other crazy stuff) are not allowed, you can use this:
```
/\[php\](.*?)\[\/php\]/
```
The first matched group will be the text inside the tags. I think the regex is quite intuitive, except for the `?`: it will be lazy and match text only until the first closing tag, so that if you have `[php]...[/php] [php]...[/php]` the regex will not match `...[/php] [php]...` (that is, between the first `[php]` and the second `[/php]`) |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | ```
<?php
$s = "Lorem ipsum dolor sit amet, [php]functionName(args1, args2)[/php] ok.";
echo preg_replace("/\[php\][^\[]+\[\/php\]/", "seems to work", $s) . "\n";
// prints => Lorem ipsum dolor sit amet, seems to work ok.
?>
``` | If you're using WordPress, but sure to look into the shortcode API.
<http://codex.wordpress.org/Shortcode_API>
And if not consider grabbing its code. It was written so it could be used in any app. |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | Try this:
```
$start_tag ='\\\\[php\\\\]\\\\s*';
$function ='((\\\\w+)\\\\s*\\\\(([^)]*)\\\\)';
$end_tag ='\\\\s*\\\\[\\\\/php\\\\]';
$re='/(' . $start_tag . $function . $end_tag . ')/';
```
which is:
```
( # start capture group #1 - full match
\[ # literal '['
php # literal 'php'
\] # literal ']'
\s* # optional whitespace
( # start capture group #2 - full function
( # start capture group #3 - function name
\w+ # one or more word chars [A-Za-z0-9_]
) # end capture group #3
\( # literal '('
( # start capture group #4 - function arguments
[^)]* # zero or more non-')' chars
) # end capture group #4
\) # literal ')'
) # end capture group #2
\s* # optional whitespace
\[ # literal '['
php # literal 'php'
\] # literal ']'
) # end capture group #1
``` | You can search for string between these tags eg
```
\[PHP\](.+[^\b\[])\[/PHP\]
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | I think `"\[php\](.*?)\[\/php\]"` would do the trick.
Edit: you may or may not need the double quotes-- not sure how you're ultimately using the regex string. | You can search for string between these tags eg
```
\[PHP\](.+[^\b\[])\[/PHP\]
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | I think `"\[php\](.*?)\[\/php\]"` would do the trick.
Edit: you may or may not need the double quotes-- not sure how you're ultimately using the regex string. | ```
<?php
$s = "Lorem ipsum dolor sit amet, [php]functionName(args1, args2)[/php] ok.";
echo preg_replace("/\[php\][^\[]+\[\/php\]/", "seems to work", $s) . "\n";
// prints => Lorem ipsum dolor sit amet, seems to work ok.
?>
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | I think `"\[php\](.*?)\[\/php\]"` would do the trick.
Edit: you may or may not need the double quotes-- not sure how you're ultimately using the regex string. | Try this:
```
$start_tag ='\\\\[php\\\\]\\\\s*';
$function ='((\\\\w+)\\\\s*\\\\(([^)]*)\\\\)';
$end_tag ='\\\\s*\\\\[\\\\/php\\\\]';
$re='/(' . $start_tag . $function . $end_tag . ')/';
```
which is:
```
( # start capture group #1 - full match
\[ # literal '['
php # literal 'php'
\] # literal ']'
\s* # optional whitespace
( # start capture group #2 - full function
( # start capture group #3 - function name
\w+ # one or more word chars [A-Za-z0-9_]
) # end capture group #3
\( # literal '('
( # start capture group #4 - function arguments
[^)]* # zero or more non-')' chars
) # end capture group #4
\) # literal ')'
) # end capture group #2
\s* # optional whitespace
\[ # literal '['
php # literal 'php'
\] # literal ']'
) # end capture group #1
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | ```
<?php
$s = "Lorem ipsum dolor sit amet, [php]functionName(args1, args2)[/php] ok.";
echo preg_replace("/\[php\][^\[]+\[\/php\]/", "seems to work", $s) . "\n";
// prints => Lorem ipsum dolor sit amet, seems to work ok.
?>
``` | try using
```
\[php\](.*)\[\/php\]
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | ```
<?php
$s = "Lorem ipsum dolor sit amet, [php]functionName(args1, args2)[/php] ok.";
echo preg_replace("/\[php\][^\[]+\[\/php\]/", "seems to work", $s) . "\n";
// prints => Lorem ipsum dolor sit amet, seems to work ok.
?>
``` | Try this:
```
$start_tag ='\\\\[php\\\\]\\\\s*';
$function ='((\\\\w+)\\\\s*\\\\(([^)]*)\\\\)';
$end_tag ='\\\\s*\\\\[\\\\/php\\\\]';
$re='/(' . $start_tag . $function . $end_tag . ')/';
```
which is:
```
( # start capture group #1 - full match
\[ # literal '['
php # literal 'php'
\] # literal ']'
\s* # optional whitespace
( # start capture group #2 - full function
( # start capture group #3 - function name
\w+ # one or more word chars [A-Za-z0-9_]
) # end capture group #3
\( # literal '('
( # start capture group #4 - function arguments
[^)]* # zero or more non-')' chars
) # end capture group #4
\) # literal ')'
) # end capture group #2
\s* # optional whitespace
\[ # literal '['
php # literal 'php'
\] # literal ']'
) # end capture group #1
``` |
6,359,617 | As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
`[php]functionName(args1, args2)[/php]`
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern `[php]anything[/php]`.
Sorry if this is a basic question, but I suck at Regular Expressions! | 2011/06/15 | [
"https://Stackoverflow.com/questions/6359617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367401/"
] | If you're using WordPress, but sure to look into the shortcode API.
<http://codex.wordpress.org/Shortcode_API>
And if not consider grabbing its code. It was written so it could be used in any app. | try using
```
\[php\](.*)\[\/php\]
``` |
48,118,038 | I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>
``` | 2018/01/05 | [
"https://Stackoverflow.com/questions/48118038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178525/"
] | You're looking for [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval).
`setTimeout` runs your function once after x milliseconds.
`setInterval` runs your function every x milliseconds.
Be sure to store your interval in a variable you can access (`var timer = setInterval(fn, ms)`) and then clear it when you want to stop the interval (`clearInterval(timer)`). | This will clear interval whenever you click the button and the race starts from the begining.
Also no ned to set the `top` at every call, just `left` is enough.
Happy racing!!!
```js
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var interval;
var race = function() {
clearInterval(interval);
var delay = 100, x=0;
interval = setInterval(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
});
x = $("#car").offset().left;
}, delay);
};
```
```html
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.jpg"></div>
``` |
48,118,038 | I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>
``` | 2018/01/05 | [
"https://Stackoverflow.com/questions/48118038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178525/"
] | You're looking for [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval).
`setTimeout` runs your function once after x milliseconds.
`setInterval` runs your function every x milliseconds.
Be sure to store your interval in a variable you can access (`var timer = setInterval(fn, ms)`) and then clear it when you want to stop the interval (`clearInterval(timer)`). | **You should use** recursive setTimeout() **not** setInterval().
See why here --> <https://develoger.com/settimeout-vs-setinterval-cff85142555b>
This is how I like to approach this problem, with the function bellow you can pass number of iterations, time in between and actually callback.
1. How many times? (you can set infinity)
2. For how much to delay (in seconds)
3. And to do WHAT?
See working example here --> <https://jsfiddle.net/nmitic/bbr6y2a4/>
```
const repeat = (numberOfIterations, timeBetweenItereation, stuffToRepeat) => {
let iterationCounter = 0;
const repeater = () => {
setTimeout( () => {
stuffToRepeat();
iterationCounter++;
if (iterationCounter >= numberOfIterations && numberOfIterations
!== Infinity) {
return;
};
if (iterationCounter >= numberOfIterations) {
return;
};
repeater();
}, 1000 * timeBetweenItereation);
};
repeater();
};
``` |
48,118,038 | I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>
``` | 2018/01/05 | [
"https://Stackoverflow.com/questions/48118038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178525/"
] | Why are you using variables instead of standard functions? Anyway, you can call your function recursively from within the `setTimeout` function until a condition is met. Try this:
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
function race() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
if (x < 200) //Specify where you want the movement to end.
race();
}, delay);
}
</script>
</body>
</html>
``` | This will clear interval whenever you click the button and the race starts from the begining.
Also no ned to set the `top` at every call, just `left` is enough.
Happy racing!!!
```js
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var interval;
var race = function() {
clearInterval(interval);
var delay = 100, x=0;
interval = setInterval(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
});
x = $("#car").offset().left;
}, delay);
};
```
```html
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.jpg"></div>
``` |
48,118,038 | I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>
``` | 2018/01/05 | [
"https://Stackoverflow.com/questions/48118038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178525/"
] | **You should use** recursive setTimeout() **not** setInterval().
See why here --> <https://develoger.com/settimeout-vs-setinterval-cff85142555b>
This is how I like to approach this problem, with the function bellow you can pass number of iterations, time in between and actually callback.
1. How many times? (you can set infinity)
2. For how much to delay (in seconds)
3. And to do WHAT?
See working example here --> <https://jsfiddle.net/nmitic/bbr6y2a4/>
```
const repeat = (numberOfIterations, timeBetweenItereation, stuffToRepeat) => {
let iterationCounter = 0;
const repeater = () => {
setTimeout( () => {
stuffToRepeat();
iterationCounter++;
if (iterationCounter >= numberOfIterations && numberOfIterations
!== Infinity) {
return;
};
if (iterationCounter >= numberOfIterations) {
return;
};
repeater();
}, 1000 * timeBetweenItereation);
};
repeater();
};
``` | This will clear interval whenever you click the button and the race starts from the begining.
Also no ned to set the `top` at every call, just `left` is enough.
Happy racing!!!
```js
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var interval;
var race = function() {
clearInterval(interval);
var delay = 100, x=0;
interval = setInterval(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
});
x = $("#car").offset().left;
}, delay);
};
```
```html
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.jpg"></div>
``` |
48,118,038 | I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>
``` | 2018/01/05 | [
"https://Stackoverflow.com/questions/48118038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178525/"
] | Why are you using variables instead of standard functions? Anyway, you can call your function recursively from within the `setTimeout` function until a condition is met. Try this:
```html
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
function race() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
if (x < 200) //Specify where you want the movement to end.
race();
}, delay);
}
</script>
</body>
</html>
``` | **You should use** recursive setTimeout() **not** setInterval().
See why here --> <https://develoger.com/settimeout-vs-setinterval-cff85142555b>
This is how I like to approach this problem, with the function bellow you can pass number of iterations, time in between and actually callback.
1. How many times? (you can set infinity)
2. For how much to delay (in seconds)
3. And to do WHAT?
See working example here --> <https://jsfiddle.net/nmitic/bbr6y2a4/>
```
const repeat = (numberOfIterations, timeBetweenItereation, stuffToRepeat) => {
let iterationCounter = 0;
const repeater = () => {
setTimeout( () => {
stuffToRepeat();
iterationCounter++;
if (iterationCounter >= numberOfIterations && numberOfIterations
!== Infinity) {
return;
};
if (iterationCounter >= numberOfIterations) {
return;
};
repeater();
}, 1000 * timeBetweenItereation);
};
repeater();
};
``` |
66,862,650 | I found some code that uses a decorator as an instance variable in a class...
I tried to replicate this in plain Javascript, but it doesn't work.
This is the Typescript:
```
export function ObservableProperty() {
return (obj: Observable, key: string) => {
let storedValue = obj[key];
Object.defineProperty(obj, key, {
get: function () {
return storedValue;
},
set: function (value) {
if (storedValue === value) {
return;
}
storedValue = value;
this.notify({
eventName: Observable.propertyChangeEvent,
propertyName: key,
object: this,
value
});
},
enumerable: true,
configurable: true
});
};
}
```
Then, in the class:
```
export class MyClass extends Observable {
@ObservableProperty() public theBoolValue: boolean;
…
```
I tried all sorts of ways to instantiate my JS-variable - always get errors…
Like:
```
@ObservableProperty
this.theBoolValue = false;
```
Is this even possible? | 2021/03/29 | [
"https://Stackoverflow.com/questions/66862650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424706/"
] | Decorators are a TypeScript thing, not a JavaScript thing ([yet](https://github.com/tc39/proposal-decorators))
Looking at the [TypeScript Docs](https://www.typescriptlang.org/docs/handbook/decorators.html), you can take their example (or even your example for that matter), and throw it in their Playground to get a the JavaScript equivalent.
[For example](https://www.typescriptlang.org/play?ssl=19&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABMGAnAzlAFASkQbwChFEIF04AbAUwDpK4BzLAIhQ2xwC5kBDaOKgCeiagDdelELyjUAJixwBuYolTUoIVElCRYCRFii9UjDT15ghAGkQAHVHDvVUUIQGlqQnplQwwjLZy1OgQfnZQgjwACo7OrkIAIiFhMBGCeEQkJGRgFDT0TKzsmLg8EJI0CsqqAL4qtYSEutDwSOjUuXK4BKq5%20XQMzCwdXWV8AsKiElIy8ooqJOqa2sjgrQZGJmZQFla2Dk4ubp7eiL7%20gYjBoeGRqDFxx0kpdxm92aTkVINFI50IbrcUiVeY1Ej1QiNQgQSi8dDoRAAUQAHrwALZ2GgAYThCI%20iAAAiVOKpCaNAbhVOiNAALOBAgiNWpAA), here is the TypeScript example:
```
function first() {
console.log("first(): factory evaluated");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("first(): called");
};
}
function second() {
console.log("second(): factory evaluated");
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("second(): called");
};
}
class ExampleClass {
@first()
@second()
method() {}
}
```
And that boils down to this in JavaScript:
```
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
function first() {
console.log("first(): factory evaluated");
return function (target, propertyKey, descriptor) {
console.log("first(): called");
};
}
function second() {
console.log("second(): factory evaluated");
return function (target, propertyKey, descriptor) {
console.log("second(): called");
};
}
class ExampleClass {
method() { }
}
__decorate([
first(),
second(),
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], ExampleClass.prototype, "method", null);
``` | Decorators are still a proposal, and have not yet officially been added to JS. They're currently undergoing a major redesign and they will be quite different from the current TypeScript implementation, which is based on the first version of the proposal. You can follow progress on the proposal here:
<https://github.com/tc39/proposal-decorators>
You could also use Babel to try decorators in JS in the meantime, but this is also based on the older proposal (even with the `legacy` option turned off...since decorators are actually now in a third version).
<https://babeljs.io/docs/en/babel-plugin-proposal-decorators>
So keep in mind that this is only a stopgap measure and that the code probably won't ever work natively in browsers in the future—you'll need to refactor it to match the new decorators proposal whenever it's completed. |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Even `i` is in global scope after the loop value of `i` would be array length so it would be like `array[array.length]` which will be `undefined`. To make it work append the value of `i` at that point along with string.
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
Or in case the array is not in global scope then you have to append the value itself as a string argument(wrap with quotes).
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test('${allBlocks[i]}')">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
***FYI :*** `document.body.innerHTML +=...` is a really bad idea since it will always recreate DOM elements which will remove any attached event handler, properties,etc... So always keep a variable within the loop to keep the HTML string and then update content finally(in your case). | Maybe what you need is string interpolation
```
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(${allBlocks[i]})">Link</p>`;
}
function test(n){
alert(n);
}
```
This will pass the value of `allblocks[i]` instead of just a string |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Even `i` is in global scope after the loop value of `i` would be array length so it would be like `array[array.length]` which will be `undefined`. To make it work append the value of `i` at that point along with string.
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
Or in case the array is not in global scope then you have to append the value itself as a string argument(wrap with quotes).
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test('${allBlocks[i]}')">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
***FYI :*** `document.body.innerHTML +=...` is a really bad idea since it will always recreate DOM elements which will remove any attached event handler, properties,etc... So always keep a variable within the loop to keep the HTML string and then update content finally(in your case). | ..because `allBlocks[i]` is undefined. You need the value of `i` to be rendered in your HTML.
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks['+i+'])">Link</p>';
}
function test(n){
alert(n);
}
``` |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Because your code in the click handler is
```
test(allBlocks[i])
```
It would appear your code is at global scope, which is the only reason it's not throwing an error. When the click occurs, `i` has the value `allBlocks.length`, which is beyond the end of the array. Accessing an array entry that isn't there results in `undefined`.
The minimum change is to use string concatenation to put the value of `i` in the click handler rather than `i`:
```
document.body.innerHTML += '<p id="" onclick="test(allBlocks[' + i + '])">Link</p>';
```
However, rather than doing that, I'd suggest modern event handling via `addEventListener`:
```
for (let i = 0; i < allBlocks.length; i++) {
// ^^^---- Note
const p = document.createElement("p");
p.textContent = "Link";
p.addEventListener("click", test.bind(null, allBlocks[i]));
document.body.appendChild(p);
}
```
---
Side note: `element.innerHTML += ...` is never a good idea. It forces the browser to loop through the entire contents of `element`, building up an HTML string for the DOM structure it contains, and then pass that string to the JavaScript layer; then the JavaScript layer has to add to the string and pass it back to the browser; then the browser has to parse the HTML, creating a bunch of new, replacement elements, wipe out the contents of `element`, and replace it with those new elements. Other than being a lot of unnecessary work, it also destroys any event handlers on the elements, any state information, etc. | Even `i` is in global scope after the loop value of `i` would be array length so it would be like `array[array.length]` which will be `undefined`. To make it work append the value of `i` at that point along with string.
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
Or in case the array is not in global scope then you have to append the value itself as a string argument(wrap with quotes).
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test('${allBlocks[i]}')">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
***FYI :*** `document.body.innerHTML +=...` is a really bad idea since it will always recreate DOM elements which will remove any attached event handler, properties,etc... So always keep a variable within the loop to keep the HTML string and then update content finally(in your case). |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Even `i` is in global scope after the loop value of `i` would be array length so it would be like `array[array.length]` which will be `undefined`. To make it work append the value of `i` at that point along with string.
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
Or in case the array is not in global scope then you have to append the value itself as a string argument(wrap with quotes).
```js
let allBlocks = ["one", "two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test('${allBlocks[i]}')">Link</p>`;
}
function test(n) {
alert(n);
}
```
---
***FYI :*** `document.body.innerHTML +=...` is a really bad idea since it will always recreate DOM elements which will remove any attached event handler, properties,etc... So always keep a variable within the loop to keep the HTML string and then update content finally(in your case). | `i` is acting as a global variable. Also you can use template literals
```js
let allBlocks = ["one", "two"];
for (let i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
``` |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Maybe what you need is string interpolation
```
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(${allBlocks[i]})">Link</p>`;
}
function test(n){
alert(n);
}
```
This will pass the value of `allblocks[i]` instead of just a string | ..because `allBlocks[i]` is undefined. You need the value of `i` to be rendered in your HTML.
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks['+i+'])">Link</p>';
}
function test(n){
alert(n);
}
``` |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Because your code in the click handler is
```
test(allBlocks[i])
```
It would appear your code is at global scope, which is the only reason it's not throwing an error. When the click occurs, `i` has the value `allBlocks.length`, which is beyond the end of the array. Accessing an array entry that isn't there results in `undefined`.
The minimum change is to use string concatenation to put the value of `i` in the click handler rather than `i`:
```
document.body.innerHTML += '<p id="" onclick="test(allBlocks[' + i + '])">Link</p>';
```
However, rather than doing that, I'd suggest modern event handling via `addEventListener`:
```
for (let i = 0; i < allBlocks.length; i++) {
// ^^^---- Note
const p = document.createElement("p");
p.textContent = "Link";
p.addEventListener("click", test.bind(null, allBlocks[i]));
document.body.appendChild(p);
}
```
---
Side note: `element.innerHTML += ...` is never a good idea. It forces the browser to loop through the entire contents of `element`, building up an HTML string for the DOM structure it contains, and then pass that string to the JavaScript layer; then the JavaScript layer has to add to the string and pass it back to the browser; then the browser has to parse the HTML, creating a bunch of new, replacement elements, wipe out the contents of `element`, and replace it with those new elements. Other than being a lot of unnecessary work, it also destroys any event handlers on the elements, any state information, etc. | Maybe what you need is string interpolation
```
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(${allBlocks[i]})">Link</p>`;
}
function test(n){
alert(n);
}
```
This will pass the value of `allblocks[i]` instead of just a string |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Because your code in the click handler is
```
test(allBlocks[i])
```
It would appear your code is at global scope, which is the only reason it's not throwing an error. When the click occurs, `i` has the value `allBlocks.length`, which is beyond the end of the array. Accessing an array entry that isn't there results in `undefined`.
The minimum change is to use string concatenation to put the value of `i` in the click handler rather than `i`:
```
document.body.innerHTML += '<p id="" onclick="test(allBlocks[' + i + '])">Link</p>';
```
However, rather than doing that, I'd suggest modern event handling via `addEventListener`:
```
for (let i = 0; i < allBlocks.length; i++) {
// ^^^---- Note
const p = document.createElement("p");
p.textContent = "Link";
p.addEventListener("click", test.bind(null, allBlocks[i]));
document.body.appendChild(p);
}
```
---
Side note: `element.innerHTML += ...` is never a good idea. It forces the browser to loop through the entire contents of `element`, building up an HTML string for the DOM structure it contains, and then pass that string to the JavaScript layer; then the JavaScript layer has to add to the string and pass it back to the browser; then the browser has to parse the HTML, creating a bunch of new, replacement elements, wipe out the contents of `element`, and replace it with those new elements. Other than being a lot of unnecessary work, it also destroys any event handlers on the elements, any state information, etc. | ..because `allBlocks[i]` is undefined. You need the value of `i` to be rendered in your HTML.
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks['+i+'])">Link</p>';
}
function test(n){
alert(n);
}
``` |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | `i` is acting as a global variable. Also you can use template literals
```js
let allBlocks = ["one", "two"];
for (let i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
``` | ..because `allBlocks[i]` is undefined. You need the value of `i` to be rendered in your HTML.
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks['+i+'])">Link</p>';
}
function test(n){
alert(n);
}
``` |
55,618,061 | I do not understand why after clicking the link "undefined" is shown. Does anyone know why?
```js
let allBlocks = ["one","two"];
for (i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += '<p id="" onclick="test(allBlocks[i])">Link</p>';
}
function test(n){
alert(n);
}
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55618061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11341802/"
] | Because your code in the click handler is
```
test(allBlocks[i])
```
It would appear your code is at global scope, which is the only reason it's not throwing an error. When the click occurs, `i` has the value `allBlocks.length`, which is beyond the end of the array. Accessing an array entry that isn't there results in `undefined`.
The minimum change is to use string concatenation to put the value of `i` in the click handler rather than `i`:
```
document.body.innerHTML += '<p id="" onclick="test(allBlocks[' + i + '])">Link</p>';
```
However, rather than doing that, I'd suggest modern event handling via `addEventListener`:
```
for (let i = 0; i < allBlocks.length; i++) {
// ^^^---- Note
const p = document.createElement("p");
p.textContent = "Link";
p.addEventListener("click", test.bind(null, allBlocks[i]));
document.body.appendChild(p);
}
```
---
Side note: `element.innerHTML += ...` is never a good idea. It forces the browser to loop through the entire contents of `element`, building up an HTML string for the DOM structure it contains, and then pass that string to the JavaScript layer; then the JavaScript layer has to add to the string and pass it back to the browser; then the browser has to parse the HTML, creating a bunch of new, replacement elements, wipe out the contents of `element`, and replace it with those new elements. Other than being a lot of unnecessary work, it also destroys any event handlers on the elements, any state information, etc. | `i` is acting as a global variable. Also you can use template literals
```js
let allBlocks = ["one", "two"];
for (let i = 0; i < allBlocks.length; i++) {
document.body.innerHTML += `<p id="" onclick="test(allBlocks[${i}])">Link</p>`;
}
function test(n) {
alert(n);
}
``` |
1,892,851 | I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame .
HINT: birthList is a list of Birth objects.
but I will find this exception why?
Please help me:(
Manager class:
```
public Manager class{
Logger logger = Logger.getLogger(this.getClass().getName());
private static Connection conn = DBManager.getConnection();
private static Admin admin;
public static void addToBirthListFromMySQL() throws SQLException {
try{
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable");
Birth list1;
while (rs.next()) {
String s1 = rs.getString(2);
if (rs.wasNull()) {
s1 = null;
}
String s2 = rs.getString(3);
if (rs.wasNull()) {
s2 = null;
}
String s3 = rs.getString(4);
if (rs.wasNull()) {
s3 = null;
}
String s4 = rs.getString(5);
if (rs.wasNull()) {
s4 = null;
}
String s5 = rs.getString(6);
if (rs.wasNull()) {
s5 = null;
}
String s6 = rs.getString(7);
if (rs.wasNull()) {
s6 = null;
}
list1 = new Birth(s1, s2, s3, s4, s5, s6);
admin.birthList.add(list1);
}
}
catch(SQLException e){
}
}
```
My Frame:
```
public class BirthList extends javax.swing.JFrame {
private Admin admin;
/** Creates new form BirthList */
public BirthList(Admin admin) {
initComponents();
this.admin = admin;
try {
Manager.addToBirthListFromMySQL();
} catch (SQLException ex) {
Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex);
}
fillTable();
}
public void fillTable() {
String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"};
List<Birth> birth = admin.getBirthList();
Object[][] data = new Object[birth.size()][columNames.length];
for (int i = 0; i < data.length; i++) {
Birth birth1 = birth.get(i);
data[i][0] = birth1.getName();
data[i][1] = birth1.getFamily();
data[i][2] = birth1.getFatherName();
data[i][3] = birth1.getMotherName();
data[i][4] = birth1.getDateOfBirth();
data[i][5] = birth1.getPlaceOfBirth();
}
DefaultTableModel model = new DefaultTableModel(data, columNames);
jTable1.setModel(model);
}
public boolean isCellEditable(int row, int col) {
return true;
}
}
```
stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.Manager.addToBirthListFromMySQL(Manager.java:272)
at AdminGUI.BirthList.(BirthList.java:35)
at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127)
at AdminGUI.BirthFrame.access$000(BirthFrame.java:21)
at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
**line 272 is :admin.birthList.add(list1);**
\*\*I also debug my project and the result was :
**debug:
Listening on javadebug
User program running
Debugger stopped on uncompilable source code.**
\*I also print my object admin with system.out.println(admin) and the result was:
classes.Admin@20be79\* | 2009/12/12 | [
"https://Stackoverflow.com/questions/1892851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124339/"
] | At first glance, I would say your `Admin` instance is null, causing the NPE in the `addToBirthListFromMySQL()` method
```
public BirthList(Admin admin) {
initComponents(); // where do you set this.admin to the parameter 'admin' ?
```
You also need to initialize the static variable `admin` of your static object `Manager`
```
public BirthList(Admin admin) {
this.admin = admin
Manager.admin = admin
initComponents();
```
(note: you may want to not call your parameter with the same name than internal variables)
---
>
> **I also debug my project and the result was** :
>
>
>
```
debug: Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\lib\sunrsasign.jar
Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\classes**
```
**Make sure you are not using the 1.6 compiler and the 1.5 runtime to execute/debug your program.**
See [this thread](http://forums.sun.com/thread.jspa?threadID=5306288):
>
> Here is a list of possibilities for future users:
>
>
> 1. Committed to the Repository. (probably not)
> 2. Re-Set all of my responsible environment variables...
>
> a. `set path="D:\...\JDK1.5\bin"`
>
> b. `set classpath="D:\...\JDK1.5\bin"`
>
> c. `set java_home="D:\...\JDK1.5"`
> 3. Re-set all of my Dependencies on my project. (`Project Properties->Libraries`).
>
>
> | It's hard to tell because the line numbers in the stack trace don't seem to match your code, but do you ever set the "private static Admin admin;" variable in Manager to a non-null value? |
1,892,851 | I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame .
HINT: birthList is a list of Birth objects.
but I will find this exception why?
Please help me:(
Manager class:
```
public Manager class{
Logger logger = Logger.getLogger(this.getClass().getName());
private static Connection conn = DBManager.getConnection();
private static Admin admin;
public static void addToBirthListFromMySQL() throws SQLException {
try{
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable");
Birth list1;
while (rs.next()) {
String s1 = rs.getString(2);
if (rs.wasNull()) {
s1 = null;
}
String s2 = rs.getString(3);
if (rs.wasNull()) {
s2 = null;
}
String s3 = rs.getString(4);
if (rs.wasNull()) {
s3 = null;
}
String s4 = rs.getString(5);
if (rs.wasNull()) {
s4 = null;
}
String s5 = rs.getString(6);
if (rs.wasNull()) {
s5 = null;
}
String s6 = rs.getString(7);
if (rs.wasNull()) {
s6 = null;
}
list1 = new Birth(s1, s2, s3, s4, s5, s6);
admin.birthList.add(list1);
}
}
catch(SQLException e){
}
}
```
My Frame:
```
public class BirthList extends javax.swing.JFrame {
private Admin admin;
/** Creates new form BirthList */
public BirthList(Admin admin) {
initComponents();
this.admin = admin;
try {
Manager.addToBirthListFromMySQL();
} catch (SQLException ex) {
Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex);
}
fillTable();
}
public void fillTable() {
String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"};
List<Birth> birth = admin.getBirthList();
Object[][] data = new Object[birth.size()][columNames.length];
for (int i = 0; i < data.length; i++) {
Birth birth1 = birth.get(i);
data[i][0] = birth1.getName();
data[i][1] = birth1.getFamily();
data[i][2] = birth1.getFatherName();
data[i][3] = birth1.getMotherName();
data[i][4] = birth1.getDateOfBirth();
data[i][5] = birth1.getPlaceOfBirth();
}
DefaultTableModel model = new DefaultTableModel(data, columNames);
jTable1.setModel(model);
}
public boolean isCellEditable(int row, int col) {
return true;
}
}
```
stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.Manager.addToBirthListFromMySQL(Manager.java:272)
at AdminGUI.BirthList.(BirthList.java:35)
at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127)
at AdminGUI.BirthFrame.access$000(BirthFrame.java:21)
at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
**line 272 is :admin.birthList.add(list1);**
\*\*I also debug my project and the result was :
**debug:
Listening on javadebug
User program running
Debugger stopped on uncompilable source code.**
\*I also print my object admin with system.out.println(admin) and the result was:
classes.Admin@20be79\* | 2009/12/12 | [
"https://Stackoverflow.com/questions/1892851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124339/"
] | Instead of hunting the root cause in the dark, I think it's better to explain how and why NPE's are caused and how they can be avoided, so that the OP can apply the newly gained knowledge to hunt his/her own trivial problem.
Look, object references (the variables) can contain either a fullworthy `Object` or simply *nothing*, which is `null`.
```
SomeObject someObject1 = new SomeObject(); // References something.
SomeObject someObject2 = null; // References nothing.
```
Now, if you're trying to access *nothing* (`null`), then you will undoubtely get a `NullPointerException`, simply because `null` doesn't have any variables or methods.
```
someObject1.doSomething(); // Works fine.
someObject2.doSomething(); // Throws NullPointerException.
```
Workarounding this is fairly simple. It can be done in basically two ways: either by instantiating it or just by ignoring it.
```
if (someObject2 == null) {
someObject2 = new SomeObject();
}
someObject2.doSomething(); // No NPE anymore!
```
or
```
if (someObject2 != null) {
someObject2.doSomething(); // No NPE anymore!
}
```
In case of a NPE, the first line number of the stacktrace points the exact line where the it is been caused. You told literally "line 272 is `admin.birthList.add(list1);`". This line contains **two** places where object references are been accessed/invoked (using the dot `.` operator). The first being `admin.birthList` and the second being `birthList.add(list1)`. It's up to you to find out if one or both caused the NPE. If it is the first invocation, then `admin` is simply `null`. If it is the second invocation, then `birthList` is simply `null`. You can fix it by instantiating it with a fullworthy object.
**Edit:** If you have a hard time in determining the root cause (as turns out from comments), then you need to learn debugging. Run a debugger or just do "poor man's debugging" with help of a `System.out.println()` of every variable before accessing/invoking them. First look at line where the NPE is caused. If this is for example
```
admin.birthList.add(list1);
```
then you need to change it as follows to nail down the root cause:
```
System.out.println("admin: " + admin);
List<Birth> birthList = admin.birthList;
System.out.println("birthList: " + birthList);
birthList.add(list1);
```
check if any of them prints `null`. Alternatively you can also do:
```
if (admin == null) throw new NullPointerException("admin is null!");
List<Birth> birthList = admin.birthList;
if (birthList == null) throw new NullPointerException("birthList is null!");
birthList.add(list1);
```
you can also separate the individual invocations over separate lines so that you have enough to the line number to know which reference is null.
```
List<Birth> birthList = admin.birthList; // If NPE line points here, then admin is null.
birthList.add(list1); // If NPE line points here, then birthList is null.
``` | It's hard to tell because the line numbers in the stack trace don't seem to match your code, but do you ever set the "private static Admin admin;" variable in Manager to a non-null value? |
1,892,851 | I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame .
HINT: birthList is a list of Birth objects.
but I will find this exception why?
Please help me:(
Manager class:
```
public Manager class{
Logger logger = Logger.getLogger(this.getClass().getName());
private static Connection conn = DBManager.getConnection();
private static Admin admin;
public static void addToBirthListFromMySQL() throws SQLException {
try{
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable");
Birth list1;
while (rs.next()) {
String s1 = rs.getString(2);
if (rs.wasNull()) {
s1 = null;
}
String s2 = rs.getString(3);
if (rs.wasNull()) {
s2 = null;
}
String s3 = rs.getString(4);
if (rs.wasNull()) {
s3 = null;
}
String s4 = rs.getString(5);
if (rs.wasNull()) {
s4 = null;
}
String s5 = rs.getString(6);
if (rs.wasNull()) {
s5 = null;
}
String s6 = rs.getString(7);
if (rs.wasNull()) {
s6 = null;
}
list1 = new Birth(s1, s2, s3, s4, s5, s6);
admin.birthList.add(list1);
}
}
catch(SQLException e){
}
}
```
My Frame:
```
public class BirthList extends javax.swing.JFrame {
private Admin admin;
/** Creates new form BirthList */
public BirthList(Admin admin) {
initComponents();
this.admin = admin;
try {
Manager.addToBirthListFromMySQL();
} catch (SQLException ex) {
Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex);
}
fillTable();
}
public void fillTable() {
String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"};
List<Birth> birth = admin.getBirthList();
Object[][] data = new Object[birth.size()][columNames.length];
for (int i = 0; i < data.length; i++) {
Birth birth1 = birth.get(i);
data[i][0] = birth1.getName();
data[i][1] = birth1.getFamily();
data[i][2] = birth1.getFatherName();
data[i][3] = birth1.getMotherName();
data[i][4] = birth1.getDateOfBirth();
data[i][5] = birth1.getPlaceOfBirth();
}
DefaultTableModel model = new DefaultTableModel(data, columNames);
jTable1.setModel(model);
}
public boolean isCellEditable(int row, int col) {
return true;
}
}
```
stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.Manager.addToBirthListFromMySQL(Manager.java:272)
at AdminGUI.BirthList.(BirthList.java:35)
at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127)
at AdminGUI.BirthFrame.access$000(BirthFrame.java:21)
at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
**line 272 is :admin.birthList.add(list1);**
\*\*I also debug my project and the result was :
**debug:
Listening on javadebug
User program running
Debugger stopped on uncompilable source code.**
\*I also print my object admin with system.out.println(admin) and the result was:
classes.Admin@20be79\* | 2009/12/12 | [
"https://Stackoverflow.com/questions/1892851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124339/"
] | Instead of hunting the root cause in the dark, I think it's better to explain how and why NPE's are caused and how they can be avoided, so that the OP can apply the newly gained knowledge to hunt his/her own trivial problem.
Look, object references (the variables) can contain either a fullworthy `Object` or simply *nothing*, which is `null`.
```
SomeObject someObject1 = new SomeObject(); // References something.
SomeObject someObject2 = null; // References nothing.
```
Now, if you're trying to access *nothing* (`null`), then you will undoubtely get a `NullPointerException`, simply because `null` doesn't have any variables or methods.
```
someObject1.doSomething(); // Works fine.
someObject2.doSomething(); // Throws NullPointerException.
```
Workarounding this is fairly simple. It can be done in basically two ways: either by instantiating it or just by ignoring it.
```
if (someObject2 == null) {
someObject2 = new SomeObject();
}
someObject2.doSomething(); // No NPE anymore!
```
or
```
if (someObject2 != null) {
someObject2.doSomething(); // No NPE anymore!
}
```
In case of a NPE, the first line number of the stacktrace points the exact line where the it is been caused. You told literally "line 272 is `admin.birthList.add(list1);`". This line contains **two** places where object references are been accessed/invoked (using the dot `.` operator). The first being `admin.birthList` and the second being `birthList.add(list1)`. It's up to you to find out if one or both caused the NPE. If it is the first invocation, then `admin` is simply `null`. If it is the second invocation, then `birthList` is simply `null`. You can fix it by instantiating it with a fullworthy object.
**Edit:** If you have a hard time in determining the root cause (as turns out from comments), then you need to learn debugging. Run a debugger or just do "poor man's debugging" with help of a `System.out.println()` of every variable before accessing/invoking them. First look at line where the NPE is caused. If this is for example
```
admin.birthList.add(list1);
```
then you need to change it as follows to nail down the root cause:
```
System.out.println("admin: " + admin);
List<Birth> birthList = admin.birthList;
System.out.println("birthList: " + birthList);
birthList.add(list1);
```
check if any of them prints `null`. Alternatively you can also do:
```
if (admin == null) throw new NullPointerException("admin is null!");
List<Birth> birthList = admin.birthList;
if (birthList == null) throw new NullPointerException("birthList is null!");
birthList.add(list1);
```
you can also separate the individual invocations over separate lines so that you have enough to the line number to know which reference is null.
```
List<Birth> birthList = admin.birthList; // If NPE line points here, then admin is null.
birthList.add(list1); // If NPE line points here, then birthList is null.
``` | At first glance, I would say your `Admin` instance is null, causing the NPE in the `addToBirthListFromMySQL()` method
```
public BirthList(Admin admin) {
initComponents(); // where do you set this.admin to the parameter 'admin' ?
```
You also need to initialize the static variable `admin` of your static object `Manager`
```
public BirthList(Admin admin) {
this.admin = admin
Manager.admin = admin
initComponents();
```
(note: you may want to not call your parameter with the same name than internal variables)
---
>
> **I also debug my project and the result was** :
>
>
>
```
debug: Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\lib\sunrsasign.jar
Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\classes**
```
**Make sure you are not using the 1.6 compiler and the 1.5 runtime to execute/debug your program.**
See [this thread](http://forums.sun.com/thread.jspa?threadID=5306288):
>
> Here is a list of possibilities for future users:
>
>
> 1. Committed to the Repository. (probably not)
> 2. Re-Set all of my responsible environment variables...
>
> a. `set path="D:\...\JDK1.5\bin"`
>
> b. `set classpath="D:\...\JDK1.5\bin"`
>
> c. `set java_home="D:\...\JDK1.5"`
> 3. Re-set all of my Dependencies on my project. (`Project Properties->Libraries`).
>
>
> |
1,892,851 | I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame .
HINT: birthList is a list of Birth objects.
but I will find this exception why?
Please help me:(
Manager class:
```
public Manager class{
Logger logger = Logger.getLogger(this.getClass().getName());
private static Connection conn = DBManager.getConnection();
private static Admin admin;
public static void addToBirthListFromMySQL() throws SQLException {
try{
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable");
Birth list1;
while (rs.next()) {
String s1 = rs.getString(2);
if (rs.wasNull()) {
s1 = null;
}
String s2 = rs.getString(3);
if (rs.wasNull()) {
s2 = null;
}
String s3 = rs.getString(4);
if (rs.wasNull()) {
s3 = null;
}
String s4 = rs.getString(5);
if (rs.wasNull()) {
s4 = null;
}
String s5 = rs.getString(6);
if (rs.wasNull()) {
s5 = null;
}
String s6 = rs.getString(7);
if (rs.wasNull()) {
s6 = null;
}
list1 = new Birth(s1, s2, s3, s4, s5, s6);
admin.birthList.add(list1);
}
}
catch(SQLException e){
}
}
```
My Frame:
```
public class BirthList extends javax.swing.JFrame {
private Admin admin;
/** Creates new form BirthList */
public BirthList(Admin admin) {
initComponents();
this.admin = admin;
try {
Manager.addToBirthListFromMySQL();
} catch (SQLException ex) {
Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex);
}
fillTable();
}
public void fillTable() {
String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"};
List<Birth> birth = admin.getBirthList();
Object[][] data = new Object[birth.size()][columNames.length];
for (int i = 0; i < data.length; i++) {
Birth birth1 = birth.get(i);
data[i][0] = birth1.getName();
data[i][1] = birth1.getFamily();
data[i][2] = birth1.getFatherName();
data[i][3] = birth1.getMotherName();
data[i][4] = birth1.getDateOfBirth();
data[i][5] = birth1.getPlaceOfBirth();
}
DefaultTableModel model = new DefaultTableModel(data, columNames);
jTable1.setModel(model);
}
public boolean isCellEditable(int row, int col) {
return true;
}
}
```
stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.Manager.addToBirthListFromMySQL(Manager.java:272)
at AdminGUI.BirthList.(BirthList.java:35)
at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127)
at AdminGUI.BirthFrame.access$000(BirthFrame.java:21)
at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
**line 272 is :admin.birthList.add(list1);**
\*\*I also debug my project and the result was :
**debug:
Listening on javadebug
User program running
Debugger stopped on uncompilable source code.**
\*I also print my object admin with system.out.println(admin) and the result was:
classes.Admin@20be79\* | 2009/12/12 | [
"https://Stackoverflow.com/questions/1892851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124339/"
] | At first glance, I would say your `Admin` instance is null, causing the NPE in the `addToBirthListFromMySQL()` method
```
public BirthList(Admin admin) {
initComponents(); // where do you set this.admin to the parameter 'admin' ?
```
You also need to initialize the static variable `admin` of your static object `Manager`
```
public BirthList(Admin admin) {
this.admin = admin
Manager.admin = admin
initComponents();
```
(note: you may want to not call your parameter with the same name than internal variables)
---
>
> **I also debug my project and the result was** :
>
>
>
```
debug: Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\lib\sunrsasign.jar
Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\classes**
```
**Make sure you are not using the 1.6 compiler and the 1.5 runtime to execute/debug your program.**
See [this thread](http://forums.sun.com/thread.jspa?threadID=5306288):
>
> Here is a list of possibilities for future users:
>
>
> 1. Committed to the Repository. (probably not)
> 2. Re-Set all of my responsible environment variables...
>
> a. `set path="D:\...\JDK1.5\bin"`
>
> b. `set classpath="D:\...\JDK1.5\bin"`
>
> c. `set java_home="D:\...\JDK1.5"`
> 3. Re-set all of my Dependencies on my project. (`Project Properties->Libraries`).
>
>
> | If line 272 of `Manager.java` is:
```
admin.birthList.add(list1);
```
and if `admin` is not `null` which is my understanding of your updates, then the conclusion seems pretty obvious: `birthlist` is `null` and the code breaks when you call the `add()` method on it.
My guess is that your `Admin` class looks something like this:
```
public class Admin {
public List<Birth> birthList; //the visibility seems to be public
...
}
```
and you never initialize the `birthList` class attribute. So either initialize it inline, in the constructor, in an `init()` method, etc but do it somewhere. For example, inline:
```
public class Admin {
public List<Birth> birthList = new ArrayList<Birth>();
...
}
```
Actually, I'm not sure how you instantiate and set the `Admin` static instance of your `Manager` class but this is another story. |
1,892,851 | I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame .
HINT: birthList is a list of Birth objects.
but I will find this exception why?
Please help me:(
Manager class:
```
public Manager class{
Logger logger = Logger.getLogger(this.getClass().getName());
private static Connection conn = DBManager.getConnection();
private static Admin admin;
public static void addToBirthListFromMySQL() throws SQLException {
try{
Statement stmt = conn.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable");
Birth list1;
while (rs.next()) {
String s1 = rs.getString(2);
if (rs.wasNull()) {
s1 = null;
}
String s2 = rs.getString(3);
if (rs.wasNull()) {
s2 = null;
}
String s3 = rs.getString(4);
if (rs.wasNull()) {
s3 = null;
}
String s4 = rs.getString(5);
if (rs.wasNull()) {
s4 = null;
}
String s5 = rs.getString(6);
if (rs.wasNull()) {
s5 = null;
}
String s6 = rs.getString(7);
if (rs.wasNull()) {
s6 = null;
}
list1 = new Birth(s1, s2, s3, s4, s5, s6);
admin.birthList.add(list1);
}
}
catch(SQLException e){
}
}
```
My Frame:
```
public class BirthList extends javax.swing.JFrame {
private Admin admin;
/** Creates new form BirthList */
public BirthList(Admin admin) {
initComponents();
this.admin = admin;
try {
Manager.addToBirthListFromMySQL();
} catch (SQLException ex) {
Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex);
}
fillTable();
}
public void fillTable() {
String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"};
List<Birth> birth = admin.getBirthList();
Object[][] data = new Object[birth.size()][columNames.length];
for (int i = 0; i < data.length; i++) {
Birth birth1 = birth.get(i);
data[i][0] = birth1.getName();
data[i][1] = birth1.getFamily();
data[i][2] = birth1.getFatherName();
data[i][3] = birth1.getMotherName();
data[i][4] = birth1.getDateOfBirth();
data[i][5] = birth1.getPlaceOfBirth();
}
DefaultTableModel model = new DefaultTableModel(data, columNames);
jTable1.setModel(model);
}
public boolean isCellEditable(int row, int col) {
return true;
}
}
```
stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.Manager.addToBirthListFromMySQL(Manager.java:272)
at AdminGUI.BirthList.(BirthList.java:35)
at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127)
at AdminGUI.BirthFrame.access$000(BirthFrame.java:21)
at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
**line 272 is :admin.birthList.add(list1);**
\*\*I also debug my project and the result was :
**debug:
Listening on javadebug
User program running
Debugger stopped on uncompilable source code.**
\*I also print my object admin with system.out.println(admin) and the result was:
classes.Admin@20be79\* | 2009/12/12 | [
"https://Stackoverflow.com/questions/1892851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124339/"
] | Instead of hunting the root cause in the dark, I think it's better to explain how and why NPE's are caused and how they can be avoided, so that the OP can apply the newly gained knowledge to hunt his/her own trivial problem.
Look, object references (the variables) can contain either a fullworthy `Object` or simply *nothing*, which is `null`.
```
SomeObject someObject1 = new SomeObject(); // References something.
SomeObject someObject2 = null; // References nothing.
```
Now, if you're trying to access *nothing* (`null`), then you will undoubtely get a `NullPointerException`, simply because `null` doesn't have any variables or methods.
```
someObject1.doSomething(); // Works fine.
someObject2.doSomething(); // Throws NullPointerException.
```
Workarounding this is fairly simple. It can be done in basically two ways: either by instantiating it or just by ignoring it.
```
if (someObject2 == null) {
someObject2 = new SomeObject();
}
someObject2.doSomething(); // No NPE anymore!
```
or
```
if (someObject2 != null) {
someObject2.doSomething(); // No NPE anymore!
}
```
In case of a NPE, the first line number of the stacktrace points the exact line where the it is been caused. You told literally "line 272 is `admin.birthList.add(list1);`". This line contains **two** places where object references are been accessed/invoked (using the dot `.` operator). The first being `admin.birthList` and the second being `birthList.add(list1)`. It's up to you to find out if one or both caused the NPE. If it is the first invocation, then `admin` is simply `null`. If it is the second invocation, then `birthList` is simply `null`. You can fix it by instantiating it with a fullworthy object.
**Edit:** If you have a hard time in determining the root cause (as turns out from comments), then you need to learn debugging. Run a debugger or just do "poor man's debugging" with help of a `System.out.println()` of every variable before accessing/invoking them. First look at line where the NPE is caused. If this is for example
```
admin.birthList.add(list1);
```
then you need to change it as follows to nail down the root cause:
```
System.out.println("admin: " + admin);
List<Birth> birthList = admin.birthList;
System.out.println("birthList: " + birthList);
birthList.add(list1);
```
check if any of them prints `null`. Alternatively you can also do:
```
if (admin == null) throw new NullPointerException("admin is null!");
List<Birth> birthList = admin.birthList;
if (birthList == null) throw new NullPointerException("birthList is null!");
birthList.add(list1);
```
you can also separate the individual invocations over separate lines so that you have enough to the line number to know which reference is null.
```
List<Birth> birthList = admin.birthList; // If NPE line points here, then admin is null.
birthList.add(list1); // If NPE line points here, then birthList is null.
``` | If line 272 of `Manager.java` is:
```
admin.birthList.add(list1);
```
and if `admin` is not `null` which is my understanding of your updates, then the conclusion seems pretty obvious: `birthlist` is `null` and the code breaks when you call the `add()` method on it.
My guess is that your `Admin` class looks something like this:
```
public class Admin {
public List<Birth> birthList; //the visibility seems to be public
...
}
```
and you never initialize the `birthList` class attribute. So either initialize it inline, in the constructor, in an `init()` method, etc but do it somewhere. For example, inline:
```
public class Admin {
public List<Birth> birthList = new ArrayList<Birth>();
...
}
```
Actually, I'm not sure how you instantiate and set the `Admin` static instance of your `Manager` class but this is another story. |
18,814,496 | I have a JSON witch looks something like this
```
{
"English": "en",
"Francais": "fr",
"German": "gm"
}
```
Now I need to print this data in HTML structure witch looks like this
```
<ul id="links">
<li class="home">
<a href="#"></a>
</li>
<li class="languages">
<a href="#">EN</a> ------ > FIRST LANGUAGE FROM JSON
<ul class="available"> ----> OTHERS
<li><a href="#">DE</a></li>
<li><a href="#">IT</a></li>
<li><a href="#">FR</a></li>
</ul>
</li>
</ul>
```
In javascript I know how to get data and print all data in the same structure but how to do it in structure shown in example ?
in Javascript I'm getting data with
```
$.getJSON('js/languages.json', function(data) {
console.log(data);
/* $.each(data, function(key, val) {
console.log(val);
});*/
});
``` | 2013/09/15 | [
"https://Stackoverflow.com/questions/18814496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590328/"
] | Use [jQuery template](http://plugins.jquery.com/loadTemplate/) to bind the Html. [Some Sample](http://weblogs.asp.net/hajan/archive/2010/12/14/jquery-templates-supported-tags.aspx) | Something like that:
```
var getBlock = function(skipLang) {
var str = '\
<ul id="links">\
<li class="home">\
<a href="#"></a>\
</li>\
<li class="languages">\
<a href="#">' + data[skipLang] + '</a>\
<ul class="available">\
';
for(var lang in data) {
if(lang != skipLang) {
str += '<li><a href="#">' + lang + '</a></li>';
}
}
str += '</ul></li></ul>';
return str;
}
var html = '';
for(var lang in data) {
html += getBlock(lang);
}
``` |
18,814,496 | I have a JSON witch looks something like this
```
{
"English": "en",
"Francais": "fr",
"German": "gm"
}
```
Now I need to print this data in HTML structure witch looks like this
```
<ul id="links">
<li class="home">
<a href="#"></a>
</li>
<li class="languages">
<a href="#">EN</a> ------ > FIRST LANGUAGE FROM JSON
<ul class="available"> ----> OTHERS
<li><a href="#">DE</a></li>
<li><a href="#">IT</a></li>
<li><a href="#">FR</a></li>
</ul>
</li>
</ul>
```
In javascript I know how to get data and print all data in the same structure but how to do it in structure shown in example ?
in Javascript I'm getting data with
```
$.getJSON('js/languages.json', function(data) {
console.log(data);
/* $.each(data, function(key, val) {
console.log(val);
});*/
});
``` | 2013/09/15 | [
"https://Stackoverflow.com/questions/18814496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590328/"
] | Use [jQuery template](http://plugins.jquery.com/loadTemplate/) to bind the Html. [Some Sample](http://weblogs.asp.net/hajan/archive/2010/12/14/jquery-templates-supported-tags.aspx) | Although using templating engine is an option for simpler code, for this case you can directly run a for loop and assign HTML within javascript code easily.
HTML part is going to be something like this
```
<ul id="links">
<li class="home">
<a href="#">home</a>
</li>
<li class="languages">
<ul class="available">
</ul>
</li>
</ul>
```
And JS part is like this:
```
var data = {
"English": "en",
"Francais": "fr",
"German": "gm"
};
var $liLanguages = $('li.languages');
var $ulAvailable = $('ul.available');
var selectedLanguage = '';
for(var index in data) {
if(selectedLanguage == '') {
selectedLanguage = data[index];
$liLanguages.prepend("<a href='#'>" + data[index].toUpperCase() + "</a>");
}
else {
$ulAvailable.append("<li><a href='#'>" + data[index].toUpperCase() + "</a></li>");
}
}
```
Here is [the jsfiddle related](http://jsfiddle.net/3D4A8/1/).
Hope this helps. |
18,814,496 | I have a JSON witch looks something like this
```
{
"English": "en",
"Francais": "fr",
"German": "gm"
}
```
Now I need to print this data in HTML structure witch looks like this
```
<ul id="links">
<li class="home">
<a href="#"></a>
</li>
<li class="languages">
<a href="#">EN</a> ------ > FIRST LANGUAGE FROM JSON
<ul class="available"> ----> OTHERS
<li><a href="#">DE</a></li>
<li><a href="#">IT</a></li>
<li><a href="#">FR</a></li>
</ul>
</li>
</ul>
```
In javascript I know how to get data and print all data in the same structure but how to do it in structure shown in example ?
in Javascript I'm getting data with
```
$.getJSON('js/languages.json', function(data) {
console.log(data);
/* $.each(data, function(key, val) {
console.log(val);
});*/
});
``` | 2013/09/15 | [
"https://Stackoverflow.com/questions/18814496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590328/"
] | Use [jQuery template](http://plugins.jquery.com/loadTemplate/) to bind the Html. [Some Sample](http://weblogs.asp.net/hajan/archive/2010/12/14/jquery-templates-supported-tags.aspx) | Here is a bit that will get you two new objects, one for the first object property/value and another for the remaining. Still not clear what is done with it once you have it, but let me know if it helps:
```
// This can be replaced with existing data or updated to var langs = data;
var langs = {"English": "en", "Francais": "fr","German": "gm" };
// jQuery map only works on objects after 1.6, heads up
var lang_keys = $.map( langs, function( value, key ) {
return key;
});
// Now that you have an array of the keys, you can use plain-ol shift()
var primary_lang_key = lang_keys.shift();
// create and populate an object just for your first language:
var primary_lang = {};
primary_lang[primary_lang_key] = langs[primary_lang_key];
// Thanks to shift, we know that populating this object with lang_keys will
// only have remaining items:
var other_langs = {};
$.map( lang_keys, function( lang_key ) {
other_langs[lang_key] = langs[lang_key];
});
console.log(other_langs);
``` |
43,177,742 | Not sure why my \*ngFor loop is printing nothing out. I have the following code in an html file:
```
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Company</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<!-- NGFOR ATTEMPTED HERE -- no content printed -->
<ng-template *ngFor="let xb of tempData">
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>{{ xb.name }}</td>
<td>{{ xb.email }}</td>
<td>{{ xb.company }}</td>
<td>{{ xb.status }}</td>
</tr>
<!-- other content -->
</ng-template>
</tbody>
</table>
```
Then, in my simple component I have the following:
```
import { Component } from '@angular/core';
@Component({
selector: 'my-profile-exhibitors',
templateUrl: './profile-exhibitors.component.html',
styleUrls: ['./profile-exhibitors.component.scss']
})
export class ProfileExhibitorsComponent {
public tempData: any = [
{
'name': 'name1',
'email': 'email1@gmail',
'company': 'company',
'status': 'Complete'
},
{
'name': 'name2',
'email': 'email2@gmail',
'company': 'company',
'status': 'Incomplete'
}
];
constructor() {}
}
```
When I run this code, I get zero output. Even weirder is that when I select the element using debug tools I see this:
[](https://i.stack.imgur.com/9Vlch.png)
Looks like it correctly recognizes my object, but then outputs nothing. | 2017/04/03 | [
"https://Stackoverflow.com/questions/43177742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409312/"
] | I think what you want is
```ts
<ng-container *ngFor="let xb of tempData">
```
or
```ts
<ng-template ngFor let-xb [ngForOf]="tempData">
``` | For getting index as well: `<ng-template ngFor let-xb [ngForOf]="tempData" let-index="index">` |
16,883,875 | In this code I want to increment `index` to put it to each `yield`ing result.
```
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
```
Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise? | 2013/06/02 | [
"https://Stackoverflow.com/questions/16883875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369759/"
] | The `zipWithIndex` method on most sequence-like collections will give you a zero-based index, incrementing with each element:
```
for ((str, index) <- splitToStrings(text).zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
``` | Because initially index is set to 0, thus your condition `index != 0` is never executes to true and index is never got incremented. ~~Maybe you don't need this condition? Maybe you can count results afterwards?~~ Now I see that index is used within loop. Then you have to either use [@BenJames answer](https://stackoverflow.com/a/16883955/298389) or go recursive. |
16,883,875 | In this code I want to increment `index` to put it to each `yield`ing result.
```
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
```
Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise? | 2013/06/02 | [
"https://Stackoverflow.com/questions/16883875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369759/"
] | Because initially index is set to 0, thus your condition `index != 0` is never executes to true and index is never got incremented. ~~Maybe you don't need this condition? Maybe you can count results afterwards?~~ Now I see that index is used within loop. Then you have to either use [@BenJames answer](https://stackoverflow.com/a/16883955/298389) or go recursive. | ```
splitToStrings(text).foldLeft(0,List[Word]){(a,b) => {
if(a._1!=0) (a._1+1,new Word(str, UNKNOWN_FORM, index) :: b)
else (a._1,new Word(str, UNKNOWN_FORM, index) :: b)
}}
```
I am using `foldLeft` here with a tuple as: starting base with `index = 0` and an empty `List`. I then iterate over each element.
Above `a` is this tuple. I check the `index` value and increment it. Else I dont add the `index`. And I add the new `Word` to the list.
Ultimately in the end you get a tuple containing the index value and the total List containing all Words. |
16,883,875 | In this code I want to increment `index` to put it to each `yield`ing result.
```
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
```
Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise? | 2013/06/02 | [
"https://Stackoverflow.com/questions/16883875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369759/"
] | Because initially index is set to 0, thus your condition `index != 0` is never executes to true and index is never got incremented. ~~Maybe you don't need this condition? Maybe you can count results afterwards?~~ Now I see that index is used within loop. Then you have to either use [@BenJames answer](https://stackoverflow.com/a/16883955/298389) or go recursive. | `zipWithIndex` will copy and create a new collection, so better make it lazy when the collection is potentially large
```
for ((str, index) <- splitToStrings(text).view.zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
```
In fact, if you are working with an indexed sequence, then a more efficient way is to use `indices`, which produces the range of all indices of this sequence.
```
val strs = splitToStrings(text)
for(i <- strs.indices) yield {
new Word(strs(i), UNKNOWN_FORM, i )
}
``` |
16,883,875 | In this code I want to increment `index` to put it to each `yield`ing result.
```
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
```
Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise? | 2013/06/02 | [
"https://Stackoverflow.com/questions/16883875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369759/"
] | The `zipWithIndex` method on most sequence-like collections will give you a zero-based index, incrementing with each element:
```
for ((str, index) <- splitToStrings(text).zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
``` | ```
splitToStrings(text).foldLeft(0,List[Word]){(a,b) => {
if(a._1!=0) (a._1+1,new Word(str, UNKNOWN_FORM, index) :: b)
else (a._1,new Word(str, UNKNOWN_FORM, index) :: b)
}}
```
I am using `foldLeft` here with a tuple as: starting base with `index = 0` and an empty `List`. I then iterate over each element.
Above `a` is this tuple. I check the `index` value and increment it. Else I dont add the `index`. And I add the new `Word` to the list.
Ultimately in the end you get a tuple containing the index value and the total List containing all Words. |
16,883,875 | In this code I want to increment `index` to put it to each `yield`ing result.
```
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
```
Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise? | 2013/06/02 | [
"https://Stackoverflow.com/questions/16883875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369759/"
] | The `zipWithIndex` method on most sequence-like collections will give you a zero-based index, incrementing with each element:
```
for ((str, index) <- splitToStrings(text).zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
``` | `zipWithIndex` will copy and create a new collection, so better make it lazy when the collection is potentially large
```
for ((str, index) <- splitToStrings(text).view.zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
```
In fact, if you are working with an indexed sequence, then a more efficient way is to use `indices`, which produces the range of all indices of this sequence.
```
val strs = splitToStrings(text)
for(i <- strs.indices) yield {
new Word(strs(i), UNKNOWN_FORM, i )
}
``` |
16,883,875 | In this code I want to increment `index` to put it to each `yield`ing result.
```
var index=0
for(str <- splitToStrings(text) ) yield {
if (index != 0) index += 1 // but index is equal to `0` all the time
new Word(str, UNKNOWN_FORM, index )
}
```
Why I can not change `index` ? And what the best way to implement this logic then, trying to be concise? | 2013/06/02 | [
"https://Stackoverflow.com/questions/16883875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369759/"
] | `zipWithIndex` will copy and create a new collection, so better make it lazy when the collection is potentially large
```
for ((str, index) <- splitToStrings(text).view.zipWithIndex)
yield new Word(str, UNKNOWN_FORM, index)
```
In fact, if you are working with an indexed sequence, then a more efficient way is to use `indices`, which produces the range of all indices of this sequence.
```
val strs = splitToStrings(text)
for(i <- strs.indices) yield {
new Word(strs(i), UNKNOWN_FORM, i )
}
``` | ```
splitToStrings(text).foldLeft(0,List[Word]){(a,b) => {
if(a._1!=0) (a._1+1,new Word(str, UNKNOWN_FORM, index) :: b)
else (a._1,new Word(str, UNKNOWN_FORM, index) :: b)
}}
```
I am using `foldLeft` here with a tuple as: starting base with `index = 0` and an empty `List`. I then iterate over each element.
Above `a` is this tuple. I check the `index` value and increment it. Else I dont add the `index`. And I add the new `Word` to the list.
Ultimately in the end you get a tuple containing the index value and the total List containing all Words. |
3,115,948 | In my iphone app,I want to let the user upload an image to his facebook photo Album and publish a story at the same time.The story's media field contains the uploaded image's url.I successly uploaded the photo and got the result's "link" and "src\_small" property.But when I use FBStreamDialog to publish the story,I got:
[](https://i.stack.imgur.com/kEOVp.png)
(source: [sinaimg.cn](http://ss10.sinaimg.cn/orignal/5d84b24ag89d4c79cbcb9&690))
At last,I find this:[http://developers.facebook.com/live\_status#msg\_625](https://developers.facebook.com/status/dashboard/#msg_625),it says:
```
We no longer allow stream stories to contain images that are hosted on the fbcdn.net domain. The images associated with these URLs aren't always optimized for stream stories and occasionally resulted in errors, leading to a poor user experience. Make sure your stream attachments don't reference images with this domain. You should host the images locally.
```
It seems that I can't finish my job,What's your solution? thanks in advance! | 2010/06/25 | [
"https://Stackoverflow.com/questions/3115948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/355393/"
] | you can't use that picture or the picture from facebook itself
you can upload the picture on other servers or upload it to online photo sharing like picasa | I got this functionality to work with ShareKit - it's really good:
<http://www.getsharekit.com/>
It's also open source, so you can see how they do it inside...
Good luck! |
37,770,348 | I'm really interested in interrupting incremental lists of items created in Rmarkdown with RStudio, to show plots and figures, then retake the list highlighting. This is quite straightforward in Latex, but I couldn't figure out how to achieve the same result using Rmarkdown. Below is some beamer example.
```
---
title: "Sample Document"
author: "Author"
output:
beamer_presentation:
fonttheme: structurebold
highlight: pygments
incremental: yes
keep_tex: yes
theme: AnnArbor
toc: true
slide_level: 3
---
# Some stuff 1
### Some very important stuff
- More detail on stuff 1
- More detail on stuff 1
- More detail on stuff 1
# The following chart should appear between the first and second item above
```{r, prompt=TRUE}
summary(iris[, "Sepal.Length"])
# Stuff 2
### There are other kinds of stuff?
```{r, prompt=TRUE}
summary(mtcars[, "cyl"])
```
[](https://i.stack.imgur.com/O0Dz2.png)
[](https://i.stack.imgur.com/QMKCG.png)
[](https://i.stack.imgur.com/3XtpV.png)
[](https://i.stack.imgur.com/CXieu.png) | 2016/06/12 | [
"https://Stackoverflow.com/questions/37770348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/792000/"
] | first - you do not need the comma in the select, second - ensure that this is the only element with the id of status, third - simply check the $status value in each option and echo selected if it is.
```
echo "<select name = 'status' id = 'status'>
<option value='Interested'";
if($status == "Interested"){echo " selected";}
echo">Interested</option>
<option value='Not Interested' ";
if($status == "Not Interested"){echo " selected";}
echo">Not Interested</option>
</select><br>";
``` | Change this
```
echo "<select name = 'status', id = status>
<option value='Interested'>Interested</option>
<option value='Not Interested'>Not Interested</option>
</select><br>";
```
to this
```
// Set the selected attributes based on the value of status
$interested = ($status === 'Interested') ? ' selected' : '';
$notInterested = ($interested === '') ? ' selected' : '';
echo <<< SELECT
<select name="status" id="status">
<option$interested>Interested</option>
<option$notInterested>Not Interested</option>
</select>
SELECT;
```
You don't need the value attribute if the value is the same as the text.
If there were more than two options, I recommend a loop like this:
```
<?php foreach ($options as $o) : ?>
<option<?php if ($o === $optionValue) ?> selected<?php endif ?>><?= optionValue ?></option>
<?php endforeach ?>
``` |
37,770,348 | I'm really interested in interrupting incremental lists of items created in Rmarkdown with RStudio, to show plots and figures, then retake the list highlighting. This is quite straightforward in Latex, but I couldn't figure out how to achieve the same result using Rmarkdown. Below is some beamer example.
```
---
title: "Sample Document"
author: "Author"
output:
beamer_presentation:
fonttheme: structurebold
highlight: pygments
incremental: yes
keep_tex: yes
theme: AnnArbor
toc: true
slide_level: 3
---
# Some stuff 1
### Some very important stuff
- More detail on stuff 1
- More detail on stuff 1
- More detail on stuff 1
# The following chart should appear between the first and second item above
```{r, prompt=TRUE}
summary(iris[, "Sepal.Length"])
# Stuff 2
### There are other kinds of stuff?
```{r, prompt=TRUE}
summary(mtcars[, "cyl"])
```
[](https://i.stack.imgur.com/O0Dz2.png)
[](https://i.stack.imgur.com/QMKCG.png)
[](https://i.stack.imgur.com/3XtpV.png)
[](https://i.stack.imgur.com/CXieu.png) | 2016/06/12 | [
"https://Stackoverflow.com/questions/37770348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/792000/"
] | first - you do not need the comma in the select, second - ensure that this is the only element with the id of status, third - simply check the $status value in each option and echo selected if it is.
```
echo "<select name = 'status' id = 'status'>
<option value='Interested'";
if($status == "Interested"){echo " selected";}
echo">Interested</option>
<option value='Not Interested' ";
if($status == "Not Interested"){echo " selected";}
echo">Not Interested</option>
</select><br>";
``` | since the default is the first option `Interested`, then `if ($status === "Not Interested")` set the [`option` attribute `selected`](http://www.w3schools.com/tags/att_option_selected.asp)
```
<?php
if ($status === "Not Interested") $selected = "selected";
else $selected = "";
echo "<select name = 'status', id = status>
<option value='Interested'>Interested</option>
<option value='Not Interested' $selected>Not Interested</option>
</select><br>";
``` |
14,789,226 | I'm really confused right now. I'm using following code in another project without any problems:
```
public class ReadOnlyTable<T extends Model> implements ReadOnly<T> {
protected at.viswars.database.framework.core.DatabaseTable datasource;
private boolean debug = true;
protected ReadOnlyTable() {
initTable();
}
protected void reloadDataSource() {
initTable();
}
private void initTable() {
boolean readOnlyClass = false;
if (getClass().getSuperclass().equals(ReadOnlyTable.class)) readOnlyClass = true;
Class<T> dataClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
```
The last line will run without problems. Now i made a second project and as i had problems with reading out the Class i tried to do the most simple case possible:
```
public class GenericObject<T> implements IGenericObject<T> {
public GenericObject() {
init();
}
private void init() {
Class<T> clazz = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
```
}
This class is instanciated here:
```
GenericObject<String> go = new GenericObject<String>();
```
In my second example i will always receive following error message:
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
What i am missing?? This drives me crazy. Any help is appreciated! | 2013/02/09 | [
"https://Stackoverflow.com/questions/14789226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2057248/"
] | It is impossible to retrieve `String` from `go`. The type parameter of an object instantiation expression (`new GenericObject<String>()`) is not present anywhere at runtime. This is type erasure.
The technique you are trying to use concerns when a *class* or *interface* extends or implements another class or interface with a specific type argument. e.g. `class Something extends GenericObject<String>`. Then it is possible to get this *declaration information* from the class object. This is completely unrelated to what you are doing. | You are calling `getGenericSuperclass()`, but your class does not have a *generic* superclass. Its superclass is `Object`, which cannot be cast to `ParameterizedType` as the error says.
You probably want to use `getGenericInterfaces()[0]`, since your class only implements an interface.
More info in here: <http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getGenericInterfaces()> |
56,924,735 | I don't know how to resolve this problem,can someone help me.
```
The following packages have unmet dependencies:
testdisk : Depends: libntfs-3g861
E: Unable to correct problems, you have held broken packages.
``` | 2019/07/07 | [
"https://Stackoverflow.com/questions/56924735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10576808/"
] | Can you try after changing your template like this:
```
<ul class="nav navbar-nav">
<li><a [routerLink]='["/search"]'>Search <span class="slider"></span></a></li>
<li *ngIf="isLoggedIn$ | async"><a (click)="logout()">Logout</a></li>
</ul>
```
Notice the `async` pipe to unwrap the observable value.
Notice in the stackblitz example shared by you - Observable value was unwrapped using `async` pipe -
```
<mat-toolbar color="primary" *ngIf="isLoggedIn$ | async as isLoggedIn">
``` | to your last comment, this is happening because the service is being re-initialized and your observable are being reset. Add this to your constructor
```
if(localStorage.getItem('currentUser') != null)
this.loggedIn.next(true);
```
This worked for me. |
723,613 | A practice question for my analysis midterm is as follows:
Give an example of a function $f:[a, b] \to\ \mathbb R$ such that $f \in R[a, c] \forall c \in\ [a, b)$ but $$f \notin R[a, b]$$
I can't think of any examples. Any help is much appreciated. Thanks in advance. | 2014/03/23 | [
"https://math.stackexchange.com/questions/723613",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/114014/"
] | $$f(x)=\left\{\begin{array}{ccc}\frac1{1-x}&\mathrm{if}&x\in[0,1)\\0&\mathrm{if}&x=1\end{array}\right.$$ | Consider the function f(x) = 1/(1 - x) on [0, 1]. You can assign f(1) = any number. |
9,246,871 | I'm trying to delete the folder `mapeditor` from my Java engine on GitHub here (https://github.com/UrbanTwitch/Mystik-RPG)
I'm on Git Bash.. messing around with `rm` and `-rf`but I can't seem to do it. How do I remove `mapeditor` folder from `Mystik-RPG` completely?
Thanks. | 2012/02/12 | [
"https://Stackoverflow.com/questions/9246871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272501/"
] | From the `Mystik-RPG` folder:
```
git rm -rf mapeditor
``` | You need to `git rm` the folder, then `git commit` the removal. Finally, `git push` your new commit to github.
Just deleting the folder won't tell git you wish to have it removed - that would put it into the "tracked but missing" state. You want it to transition to the "untracked" state, which is what `git rm` is for. |
46,787,270 | I'm using JavaMail to the handle emails. Subject is encoded in following charset:
`Subject: =?x-mac-ce?Q?Wdro=BFenia_znaku_CE?=`
How to decode this using a JavaMail. | 2017/10/17 | [
"https://Stackoverflow.com/questions/46787270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087407/"
] | Windows [seems to use](https://msdn.microsoft.com/en-us/library/ms537500(v=vs.85).aspx) `x-mac-ce` as an alias for `Windows-1250` codepage (matching the CP1250 JDK charset).
**JavaMail** maintains a map of "MIME to Java" charset aliases internally, as resolved with the
[MimeUtility.javaCharset](http://grepcode.com/file/repo1.maven.org/maven2/javax.mail/mail/1.4.1/javax/mail/internet/MimeUtility.java#MimeUtility.javaCharset%28java.lang.String%29) method, to handle cases like that.
Unfortunately there is no [mapping](http://grepcode.com/file/repo1.maven.org/maven2/javax.mail/mail/1.4.1/javax/mail/internet/MimeUtility.java#1210) for `x-mac-ce` (at least as of JavaMail 1.6.0), and (AFAIK) there is no extension API provided, to add it.
So the best you can do at the moment is decode the subject line in your application code, like that:
```
MimeUtility.decodeText(
m.getSubject().replace("x-mac-ce","CP1250")
)
```
**Test**
```
m.setSubject("=?x-mac-ce?Q?Wdro=BFenia_znaku_CE?=");
System.out.printf(
MimeUtility.decodeText(
m.getSubject().replace("x-mac-ce","CP1250")
)
);
>>Wdrożenia znaku CE
```
**Note**
I've first incorrectly identified the encoding as [Macintosh Central European encoding](https://en.wikipedia.org/wiki/Macintosh_Central_European_encoding) (`x-MacCentralEurope` Java Charset), which does not fully match CP1250, and seems to be a transposed version of it (i.e. 0xBF matches 0xFB e.t.c.). | Obviously x-mac-ce is a non-standard charset. JavaMail depends on the JDK to handle conversion of charset encodings to Unicode strings. If, as described above, x-mac-ce is equivlanet to the CP1250 charset, the JavaMail FAQ explains [how to use the JDK's facilities to map unknown charsets to known charsets](https://javaee.github.io/javamail/FAQ#unsupen). |
10,019,594 | I have a database with an email field, and it cycles through the database to grab all the transactions concerning a certain email address.
Users putting in lowercase letters when their email is stored with a couple capitals is causing it not to show their transactions. When I modify it to match perfect case with the other emails, it works.
How can I modify this so that it correctly compares with the email field and case doesn't matter? Is it going to be in changing how the email gets stored?
```
$result = mysql_query("SELECT * FROM `example_orders` WHERE `buyer_email`='$useremail';") or die(mysql_error());
```
Thanks ahead of time! | 2012/04/04 | [
"https://Stackoverflow.com/questions/10019594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871966/"
] | A mixed PHP/MySQL solution:
```
$result = mysql_query("
SELECT *
FROM example_orders
WHERE LOWER(buyer_email) = '" . strtolower($useremail) . "';
") or die(mysql_error());
```
What it does is converting both sides of the comparison to lowercase. This is not very efficient, because the use of `LOWER` will prevent MySQL from using indexes for searching.
**A more efficient, pure SQL solution:**
```
$result = mysql_query("
SELECT *
FROM example_orders
WHERE buyer_email = '$useremail' COLLATE utf8_general_ci;
") or die(mysql_error());
```
In this case, we are forcing the use of a case-insensitive collation for the comparison. You wouldn't need that if the column had a case-insensitive collation in the first place.
Here is how to change the column collation, as suggested by Basti in a comment:
```
ALTER TABLE `example_orders`
CHANGE `buyer_email` `buyer_email` VARCHAR( 100 )
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
```
If you choose to do that, you can run the query without `COLLATE utf8_general_ci`. | If you do `WHERE buyer_email LIKE '...'` it'll by default do a case-insensitive match.
With e-mail fields, though, I prefer to lowercase the e-mail address when I insert it into the DB. |
10,019,594 | I have a database with an email field, and it cycles through the database to grab all the transactions concerning a certain email address.
Users putting in lowercase letters when their email is stored with a couple capitals is causing it not to show their transactions. When I modify it to match perfect case with the other emails, it works.
How can I modify this so that it correctly compares with the email field and case doesn't matter? Is it going to be in changing how the email gets stored?
```
$result = mysql_query("SELECT * FROM `example_orders` WHERE `buyer_email`='$useremail';") or die(mysql_error());
```
Thanks ahead of time! | 2012/04/04 | [
"https://Stackoverflow.com/questions/10019594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871966/"
] | Uh... you realize that email addresses are case *sensitive*, right? From [RFC 2821](https://www.ietf.org/rfc/rfc2821.txt):
>
> Verbs and argument values (e.g., "TO:" or "to:" in the RCPT command
>
> and extension name keywords) are not case sensitive, with the sole
>
> exception in this specification of a mailbox local-part (SMTP
>
> Extensions may explicitly specify case-sensitive elements). That is,
> a command verb, an argument value other than a mailbox local-part,
>
> and free form text MAY be encoded in upper case, lower case, or any
>
> mixture of upper and lower case with no impact on its meaning. This
>
> is NOT true of a mailbox local-part. *The local-part of a mailbox
>
> MUST BE treated as case sensitive.* Therefore, SMTP implementations
>
> MUST take care to preserve the case of mailbox local-parts. Mailbox
>
> domains are not case sensitive. In particular, for some hosts the
>
> user "smith" is different from the user "Smith". However, exploiting
> the case sensitivity of mailbox local-parts impedes interoperability
>
> and is discouraged.
>
>
>
(emphasis added) | If you do `WHERE buyer_email LIKE '...'` it'll by default do a case-insensitive match.
With e-mail fields, though, I prefer to lowercase the e-mail address when I insert it into the DB. |
10,019,594 | I have a database with an email field, and it cycles through the database to grab all the transactions concerning a certain email address.
Users putting in lowercase letters when their email is stored with a couple capitals is causing it not to show their transactions. When I modify it to match perfect case with the other emails, it works.
How can I modify this so that it correctly compares with the email field and case doesn't matter? Is it going to be in changing how the email gets stored?
```
$result = mysql_query("SELECT * FROM `example_orders` WHERE `buyer_email`='$useremail';") or die(mysql_error());
```
Thanks ahead of time! | 2012/04/04 | [
"https://Stackoverflow.com/questions/10019594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871966/"
] | A mixed PHP/MySQL solution:
```
$result = mysql_query("
SELECT *
FROM example_orders
WHERE LOWER(buyer_email) = '" . strtolower($useremail) . "';
") or die(mysql_error());
```
What it does is converting both sides of the comparison to lowercase. This is not very efficient, because the use of `LOWER` will prevent MySQL from using indexes for searching.
**A more efficient, pure SQL solution:**
```
$result = mysql_query("
SELECT *
FROM example_orders
WHERE buyer_email = '$useremail' COLLATE utf8_general_ci;
") or die(mysql_error());
```
In this case, we are forcing the use of a case-insensitive collation for the comparison. You wouldn't need that if the column had a case-insensitive collation in the first place.
Here is how to change the column collation, as suggested by Basti in a comment:
```
ALTER TABLE `example_orders`
CHANGE `buyer_email` `buyer_email` VARCHAR( 100 )
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
```
If you choose to do that, you can run the query without `COLLATE utf8_general_ci`. | Uh... you realize that email addresses are case *sensitive*, right? From [RFC 2821](https://www.ietf.org/rfc/rfc2821.txt):
>
> Verbs and argument values (e.g., "TO:" or "to:" in the RCPT command
>
> and extension name keywords) are not case sensitive, with the sole
>
> exception in this specification of a mailbox local-part (SMTP
>
> Extensions may explicitly specify case-sensitive elements). That is,
> a command verb, an argument value other than a mailbox local-part,
>
> and free form text MAY be encoded in upper case, lower case, or any
>
> mixture of upper and lower case with no impact on its meaning. This
>
> is NOT true of a mailbox local-part. *The local-part of a mailbox
>
> MUST BE treated as case sensitive.* Therefore, SMTP implementations
>
> MUST take care to preserve the case of mailbox local-parts. Mailbox
>
> domains are not case sensitive. In particular, for some hosts the
>
> user "smith" is different from the user "Smith". However, exploiting
> the case sensitivity of mailbox local-parts impedes interoperability
>
> and is discouraged.
>
>
>
(emphasis added) |
229,587 | Related to the following question but looking for a PyQGIS method:
[QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order)
---
The following is a simple setup containing a group with three layers.
[](https://i.stack.imgur.com/GV5pZ.png)
The code I use adds a new layer at the **end of this group**:
```
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
[](https://i.stack.imgur.com/kK1Hq.png)
In the *Layer Order Panel*, the newly added layer is at the end.
[](https://i.stack.imgur.com/pbexP.png)
---
Is it possible to move this to the top **without moving the layer in the *Layers Panel***? | 2017/02/23 | [
"https://gis.stackexchange.com/questions/229587",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25814/"
] | You can set layer order in the `Layer Order Panel` "**manually**" using `QgsLayerTreeCanvasBridge.setCustomLayerOrder()` method, which receives an ordered list of layer ids. For instance (assuming you just loaded `vlayer`):
```
bridge = iface.layerTreeCanvasBridge()
order = bridge.customLayerOrder()
order.insert( 0, order.pop( order.index( vlayer.id() ) ) ) # vlayer to the top
bridge.setCustomLayerOrder( order )
```
---
To **automatically** move newly added layers to the top of `Layer Order Panel`, you could use the `legendLayersAdded` SIGNAL (this signal is appropriate because it's emitted after the `Layer Order Panel` gets the new layer) from `QgsMapLayerRegistry` and reorder layers in this way:
```
def rearrange( layers ):
order = iface.layerTreeCanvasBridge().customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
iface.layerTreeCanvasBridge().setCustomLayerOrder( order )
QgsMapLayerRegistry.instance().legendLayersAdded.connect( rearrange )
```
---
NOTE: Since you're loading your `vlayer` calling `QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)`, that `False` parameter prevents the `legendLayersAdded` SIGNAL from being emitted. So, the automatic approach won't work for your case and you will need to rearrange layers manually (first approach of this answer). | I am not so familiar with pyqgis, but when I changed the line in your code from
```
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
to
```
group.insertChildNode(0, QgsLayerTreeLayer(vlayer))
```
It was intserted at the top of the group, not the bottom. |
229,587 | Related to the following question but looking for a PyQGIS method:
[QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order)
---
The following is a simple setup containing a group with three layers.
[](https://i.stack.imgur.com/GV5pZ.png)
The code I use adds a new layer at the **end of this group**:
```
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
[](https://i.stack.imgur.com/kK1Hq.png)
In the *Layer Order Panel*, the newly added layer is at the end.
[](https://i.stack.imgur.com/pbexP.png)
---
Is it possible to move this to the top **without moving the layer in the *Layers Panel***? | 2017/02/23 | [
"https://gis.stackexchange.com/questions/229587",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25814/"
] | Hi sorry I can't comment, but the method "bridge.customLayerOrder()" doesn't exist in QGis 3.x
I've found maybe a substitute command:
```
bridge = iface.layerTreeCanvasBridge()
bridge.rootGroup().customLayerOrder()
```
From <https://qgis.org/api/classQgsLayerTree.html#aab7a55f2e61f0ff1dbea6ceb89e8b366>:
>
> The order in which layers will be rendered on the canvas.
> Will only be used if the property hasCustomLayerOrder is true. If you need the current layer order that is active, prefer using layerOrder().
>
>
>
Hope to be useful to others.
Riccardo | I am not so familiar with pyqgis, but when I changed the line in your code from
```
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
to
```
group.insertChildNode(0, QgsLayerTreeLayer(vlayer))
```
It was intserted at the top of the group, not the bottom. |
229,587 | Related to the following question but looking for a PyQGIS method:
[QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order)
---
The following is a simple setup containing a group with three layers.
[](https://i.stack.imgur.com/GV5pZ.png)
The code I use adds a new layer at the **end of this group**:
```
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
[](https://i.stack.imgur.com/kK1Hq.png)
In the *Layer Order Panel*, the newly added layer is at the end.
[](https://i.stack.imgur.com/pbexP.png)
---
Is it possible to move this to the top **without moving the layer in the *Layers Panel***? | 2017/02/23 | [
"https://gis.stackexchange.com/questions/229587",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25814/"
] | Based on this (old) question and some other research, I've successfully added a handler to my QGIS 3.10 project to move all newly added layers to the top of the custom layer order. Here's the relevant project macro code with v3 object references.
```
from qgis.core import QgsProject
from qgis.utils import iface
def openProject():
global layersToTopHandler # keep so can disconnect() it in closeProject()
def layersToTopHandler( layers ):
# moves last len(layers) layers to top of custom layer order
# note pays no attention to what is in the list given, always moves bottom layers
# intended as a legendLayersAdded signal handler so the new layers have just been put at bottom!
rg = iface.layerTreeCanvasBridge().rootGroup()
if rg.hasCustomLayerOrder():
# Only do anything if custom layer order is turned on
order = rg.customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
rg.setCustomLayerOrder( order )
QgsProject.instance().legendLayersAdded.connect( layersToTopHandler )
def saveProject():
pass
def closeProject():
QgsProject.instance().legendLayersAdded.disconnect(layersToTopHandler)
# needed since otherwise signal would go to slot even when change projects
```
**Edit**: My answer originally didn't have the `global` line and just a `disconnect()` in `closeProject()`. This subtly failed in 3.10.2 (making it impossible to add layers in a subsequently opened project) since the argument-less `disconnect()` would also clobber some core slots on this signal. There may be more elegant ways to keep track of our own slot than to globalize the event handler itself but this seems to work. Note it's tempting to not bother disconnecting, assuming closing the project and opening a new one will reinitialize everything, but slots/signals stay persistent! | I am not so familiar with pyqgis, but when I changed the line in your code from
```
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
to
```
group.insertChildNode(0, QgsLayerTreeLayer(vlayer))
```
It was intserted at the top of the group, not the bottom. |
229,587 | Related to the following question but looking for a PyQGIS method:
[QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order)
---
The following is a simple setup containing a group with three layers.
[](https://i.stack.imgur.com/GV5pZ.png)
The code I use adds a new layer at the **end of this group**:
```
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
[](https://i.stack.imgur.com/kK1Hq.png)
In the *Layer Order Panel*, the newly added layer is at the end.
[](https://i.stack.imgur.com/pbexP.png)
---
Is it possible to move this to the top **without moving the layer in the *Layers Panel***? | 2017/02/23 | [
"https://gis.stackexchange.com/questions/229587",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25814/"
] | You can set layer order in the `Layer Order Panel` "**manually**" using `QgsLayerTreeCanvasBridge.setCustomLayerOrder()` method, which receives an ordered list of layer ids. For instance (assuming you just loaded `vlayer`):
```
bridge = iface.layerTreeCanvasBridge()
order = bridge.customLayerOrder()
order.insert( 0, order.pop( order.index( vlayer.id() ) ) ) # vlayer to the top
bridge.setCustomLayerOrder( order )
```
---
To **automatically** move newly added layers to the top of `Layer Order Panel`, you could use the `legendLayersAdded` SIGNAL (this signal is appropriate because it's emitted after the `Layer Order Panel` gets the new layer) from `QgsMapLayerRegistry` and reorder layers in this way:
```
def rearrange( layers ):
order = iface.layerTreeCanvasBridge().customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
iface.layerTreeCanvasBridge().setCustomLayerOrder( order )
QgsMapLayerRegistry.instance().legendLayersAdded.connect( rearrange )
```
---
NOTE: Since you're loading your `vlayer` calling `QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)`, that `False` parameter prevents the `legendLayersAdded` SIGNAL from being emitted. So, the automatic approach won't work for your case and you will need to rearrange layers manually (first approach of this answer). | Hi sorry I can't comment, but the method "bridge.customLayerOrder()" doesn't exist in QGis 3.x
I've found maybe a substitute command:
```
bridge = iface.layerTreeCanvasBridge()
bridge.rootGroup().customLayerOrder()
```
From <https://qgis.org/api/classQgsLayerTree.html#aab7a55f2e61f0ff1dbea6ceb89e8b366>:
>
> The order in which layers will be rendered on the canvas.
> Will only be used if the property hasCustomLayerOrder is true. If you need the current layer order that is active, prefer using layerOrder().
>
>
>
Hope to be useful to others.
Riccardo |
229,587 | Related to the following question but looking for a PyQGIS method:
[QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order)
---
The following is a simple setup containing a group with three layers.
[](https://i.stack.imgur.com/GV5pZ.png)
The code I use adds a new layer at the **end of this group**:
```
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
[](https://i.stack.imgur.com/kK1Hq.png)
In the *Layer Order Panel*, the newly added layer is at the end.
[](https://i.stack.imgur.com/pbexP.png)
---
Is it possible to move this to the top **without moving the layer in the *Layers Panel***? | 2017/02/23 | [
"https://gis.stackexchange.com/questions/229587",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25814/"
] | You can set layer order in the `Layer Order Panel` "**manually**" using `QgsLayerTreeCanvasBridge.setCustomLayerOrder()` method, which receives an ordered list of layer ids. For instance (assuming you just loaded `vlayer`):
```
bridge = iface.layerTreeCanvasBridge()
order = bridge.customLayerOrder()
order.insert( 0, order.pop( order.index( vlayer.id() ) ) ) # vlayer to the top
bridge.setCustomLayerOrder( order )
```
---
To **automatically** move newly added layers to the top of `Layer Order Panel`, you could use the `legendLayersAdded` SIGNAL (this signal is appropriate because it's emitted after the `Layer Order Panel` gets the new layer) from `QgsMapLayerRegistry` and reorder layers in this way:
```
def rearrange( layers ):
order = iface.layerTreeCanvasBridge().customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
iface.layerTreeCanvasBridge().setCustomLayerOrder( order )
QgsMapLayerRegistry.instance().legendLayersAdded.connect( rearrange )
```
---
NOTE: Since you're loading your `vlayer` calling `QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)`, that `False` parameter prevents the `legendLayersAdded` SIGNAL from being emitted. So, the automatic approach won't work for your case and you will need to rearrange layers manually (first approach of this answer). | Based on this (old) question and some other research, I've successfully added a handler to my QGIS 3.10 project to move all newly added layers to the top of the custom layer order. Here's the relevant project macro code with v3 object references.
```
from qgis.core import QgsProject
from qgis.utils import iface
def openProject():
global layersToTopHandler # keep so can disconnect() it in closeProject()
def layersToTopHandler( layers ):
# moves last len(layers) layers to top of custom layer order
# note pays no attention to what is in the list given, always moves bottom layers
# intended as a legendLayersAdded signal handler so the new layers have just been put at bottom!
rg = iface.layerTreeCanvasBridge().rootGroup()
if rg.hasCustomLayerOrder():
# Only do anything if custom layer order is turned on
order = rg.customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
rg.setCustomLayerOrder( order )
QgsProject.instance().legendLayersAdded.connect( layersToTopHandler )
def saveProject():
pass
def closeProject():
QgsProject.instance().legendLayersAdded.disconnect(layersToTopHandler)
# needed since otherwise signal would go to slot even when change projects
```
**Edit**: My answer originally didn't have the `global` line and just a `disconnect()` in `closeProject()`. This subtly failed in 3.10.2 (making it impossible to add layers in a subsequently opened project) since the argument-less `disconnect()` would also clobber some core slots on this signal. There may be more elegant ways to keep track of our own slot than to globalize the event handler itself but this seems to work. Note it's tempting to not bother disconnecting, assuming closing the project and opening a new one will reinitialize everything, but slots/signals stay persistent! |
229,587 | Related to the following question but looking for a PyQGIS method:
[QGIS Layer Order Panel - add layers at top of layer order](https://gis.stackexchange.com/questions/180943/qgis-layer-order-panel-add-layers-at-top-of-layer-order)
---
The following is a simple setup containing a group with three layers.
[](https://i.stack.imgur.com/GV5pZ.png)
The code I use adds a new layer at the **end of this group**:
```
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup('Main group')
vlayer = QgsVectorLayer('LineString?crs=epsg:27700', 'vlayer', 'memory')
QgsMapLayerRegistry.instance().addMapLayer(vlayer, False)
group.insertChildNode(-1, QgsLayerTreeLayer(vlayer))
```
[](https://i.stack.imgur.com/kK1Hq.png)
In the *Layer Order Panel*, the newly added layer is at the end.
[](https://i.stack.imgur.com/pbexP.png)
---
Is it possible to move this to the top **without moving the layer in the *Layers Panel***? | 2017/02/23 | [
"https://gis.stackexchange.com/questions/229587",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25814/"
] | Hi sorry I can't comment, but the method "bridge.customLayerOrder()" doesn't exist in QGis 3.x
I've found maybe a substitute command:
```
bridge = iface.layerTreeCanvasBridge()
bridge.rootGroup().customLayerOrder()
```
From <https://qgis.org/api/classQgsLayerTree.html#aab7a55f2e61f0ff1dbea6ceb89e8b366>:
>
> The order in which layers will be rendered on the canvas.
> Will only be used if the property hasCustomLayerOrder is true. If you need the current layer order that is active, prefer using layerOrder().
>
>
>
Hope to be useful to others.
Riccardo | Based on this (old) question and some other research, I've successfully added a handler to my QGIS 3.10 project to move all newly added layers to the top of the custom layer order. Here's the relevant project macro code with v3 object references.
```
from qgis.core import QgsProject
from qgis.utils import iface
def openProject():
global layersToTopHandler # keep so can disconnect() it in closeProject()
def layersToTopHandler( layers ):
# moves last len(layers) layers to top of custom layer order
# note pays no attention to what is in the list given, always moves bottom layers
# intended as a legendLayersAdded signal handler so the new layers have just been put at bottom!
rg = iface.layerTreeCanvasBridge().rootGroup()
if rg.hasCustomLayerOrder():
# Only do anything if custom layer order is turned on
order = rg.customLayerOrder()
for layer in layers: # How many layers we need to move
order.insert( 0, order.pop() ) # Last layer to first position
rg.setCustomLayerOrder( order )
QgsProject.instance().legendLayersAdded.connect( layersToTopHandler )
def saveProject():
pass
def closeProject():
QgsProject.instance().legendLayersAdded.disconnect(layersToTopHandler)
# needed since otherwise signal would go to slot even when change projects
```
**Edit**: My answer originally didn't have the `global` line and just a `disconnect()` in `closeProject()`. This subtly failed in 3.10.2 (making it impossible to add layers in a subsequently opened project) since the argument-less `disconnect()` would also clobber some core slots on this signal. There may be more elegant ways to keep track of our own slot than to globalize the event handler itself but this seems to work. Note it's tempting to not bother disconnecting, assuming closing the project and opening a new one will reinitialize everything, but slots/signals stay persistent! |
56,194,991 | Consider the following numbers:
```
1000.10
1000.11
1000.113
```
I would like to get these to print out in python as:
```
1,000.10
1,000.11
1,000.11
```
The following transformations almost do this, except that whenever the second digit to the right of the decimal point is a zero, the zero is elided and as a result that number doesn't line up properly.
This is my attempt:
```
for n in [1000.10, 1000.11, 1000.112]:
nf = '%.2f' %n # nf is a 2 digit decimal number, but a string
nff = float(nf) # nff is a float which the next transformation needs
n_comma = f'{nff:,}' # this puts the commas in
print('%10s' %n_comma)
1,000.1
1,000.11
1,000.11
```
Is there a way to avoid eliding the ending zero in the first number? | 2019/05/18 | [
"https://Stackoverflow.com/questions/56194991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399754/"
] | You want the format specifier `',.2f'`. `,`, as you noted, performs comma separation of thousands, while `.2f` specifies that two digits are to be retained:
```
print([f'{number:,.2f}' for number in n])
```
Output:
```
['1,000.10', '1,000.11', '1,000.11']
``` | You can simply use `f'{n:,.2f}'` to combine the thusand separator and the 2 decimal digits format specifiers:
```
for n in [1000.10, 1000.11, 1000.112]:
print(f'{n:,.2f}')
```
Outputs
```
1,000.10
1,000.11
1,000.11
``` |
56,194,991 | Consider the following numbers:
```
1000.10
1000.11
1000.113
```
I would like to get these to print out in python as:
```
1,000.10
1,000.11
1,000.11
```
The following transformations almost do this, except that whenever the second digit to the right of the decimal point is a zero, the zero is elided and as a result that number doesn't line up properly.
This is my attempt:
```
for n in [1000.10, 1000.11, 1000.112]:
nf = '%.2f' %n # nf is a 2 digit decimal number, but a string
nff = float(nf) # nff is a float which the next transformation needs
n_comma = f'{nff:,}' # this puts the commas in
print('%10s' %n_comma)
1,000.1
1,000.11
1,000.11
```
Is there a way to avoid eliding the ending zero in the first number? | 2019/05/18 | [
"https://Stackoverflow.com/questions/56194991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399754/"
] | You want the format specifier `',.2f'`. `,`, as you noted, performs comma separation of thousands, while `.2f` specifies that two digits are to be retained:
```
print([f'{number:,.2f}' for number in n])
```
Output:
```
['1,000.10', '1,000.11', '1,000.11']
``` | You might be able to do it like this:
```
num = 100.0
print(str(num) + "0")
```
So you print the number as a string plus 0 at the end.
Update:
So that it doesn’t do this to all numbers, try doing something like:
```
if num == 1000.10:
#add the zero
elif num == 1000.20:
#again, add the zero
#and so on and so on...
```
So if the number has a zero at the end (its decimal values are .10, .20, .30, etc.), add one, and if not, don’t. |
47,384,766 | I know this question has been asked already.
However, when I follow the answer given to that question it doesn't work.
This is my JS function and the relevant HTML
```js
function myFunction() {
document.getElementById("submit").innerHTML = "LOADING...";
}
```
```html
<input class="textbox" type="number" id="number">
<button onclick="myFunction(document.getElementById("number").value)" class="Button" >Submit</button>
<p id="submit"></p>
<script type ="text/javascript" src="../src/index.js"></script>
``` | 2017/11/20 | [
"https://Stackoverflow.com/questions/47384766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7870395/"
] | You have to config your web server to response `index.html` when receive requests like `/place/66bb50b7a5`
[vue-router doc](https://router.vuejs.org/en/essentials/history-mode.html) have example configurations for Apache, nginx, IIS...
For MAMP (apache):
1. create an file name `.htaccess` in your MAMP `htdocs` folder
2. paste apache configuration from vue-router doc
`.htaccess`:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
``` | I've had the same problem and I've solved it.
my case in apache:
1. create `.htaccess` file in the same folder as index.html
2. copy-paste the following script, and all works charmly.
```
<IfModule mod_rewrite.c>
Rew/riteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
```
Previously I found this script on [github](https://gist.github.com/mariojankovic/e39cce4fed0db39e21e29a1585fd2155) |
64,195 | If one has built a kasher sukkah, with its own completed skhakh but there is a tree branch that leans against the skhakh, is it still kasher? | 2015/09/27 | [
"https://judaism.stackexchange.com/questions/64195",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/9045/"
] | There are many details found in the Shulchan Aruch siman 626.
If the branch only provides a minority of the shade etc. In one situation having the branch mixed in with the kosher schach is actually beneficial.
But according to one opinion in the Shulchan Aruch, one should never under any circumstances have any branch above the schach.
If you rule with Ramma or straight Shulchan Aruch will come into play here, so again, see the details there. | Since the living branch covers only a small part of the succa, you can just not sit under the branch. Most succot (these days) are so large that a small area of invalid roof does not invalidate the whole succa. (See Succah 13b, I think.) |
69,274 | I have disabled the touchscreen on my official 7" display by adding the below line to my /boot/config.txt
```
# disable the touchscreen
disable_touchscreen=1
```
While this works, it also eliminates all ability to programmatically control the display. Everything under /sys/class/backlight disappears.
Is there a way to disable the touchscreen that will still allow the control of the rest of the display functions? | 2017/07/02 | [
"https://raspberrypi.stackexchange.com/questions/69274",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/69672/"
] | If you're using your screen with X server (GUI), then you can simply find its ID in the output of `xinput --list` and disable it with `xinput disable <ID>`. Your touchscreen will still generate input events, but your X server will not forward those events to the applications.
You will want to execute the `xinput disable <ID>` command at startup to make the change permanent. | yes indeed it's possible, if I remember correctly there's a pin dedicated to the touchscreen functionality, if you unplug it you'll loose the ability. |
24,681,229 | Does anyone know how to associate a floating IP address with a load balancer in a heat template? I can create a load balancer on an instance (or a bunch of instances, but starting small) in heat; and can associate a floating IP address to the load balancer in Horizon, but I can't figure out how to do it through heat. | 2014/07/10 | [
"https://Stackoverflow.com/questions/24681229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/833982/"
] | I just had to find the answer to this question myself.
It turns out that the `vip` attribute of an `OS::Neutron::Pool` resource contains a few more keys than are documented [here](http://docs.openstack.org/developer/heat/template_guide/openstack.html#OS::Neutron::Pool-hot). In particular, the `vip` attribute contains a `port_id`, which is the address of the Neutron port associated with this pool.
Since we have a Neutron port id, we can use that to associate a floating ip address like this:
```
type: "OS::Neutron::Pool"
properties:
protocol: HTTP
monitors:
- {get_resource: monitor}
subnet_id: {get_resource: fixed_subnet}
lb_method: ROUND_ROBIN
vip:
protocol_port: 80
lb_floating:
type: "OS::Neutron::FloatingIP"
properties:
floating_network_id:
get_param: external_network_id
port_id:
get_attr: [pool, vip, port_id]
```
That `get_attr` call is getting the `port_id` attribute of the `vip` attribute of the `pool` resource. | I had the same question in regard to Octavia rather then Neutron, however Larsks answer did point me in the right direction.
The `OS::Octavia::LoadBalancer` object has a `vip_port_id` attribute which can be accessed in the same way:
```
port_id:
get_attr: [lb1, vip_port_id]
``` |
21,668,250 | I'm trying to make a program that will get the user input of a new file name, create the file, and write to it. It works but it will only write the first word of the string to the file. How can i get it to write the full string? thanks.
```
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = " ";
string f = " ";
string w = " ";
cout <<"What is the name of the file you would like to write to? " <<endl;
cin >>f;
ofstream myStream(f,ios_base::ate|ios_base::out);
cout <<"What would you like to write to " <<f <<" ? ";
cin >>w;
myStream <<w;
if (myStream.bad())
{
myStream <<"A serious error has occured.";
myStream.close();
break;
}
}
}
``` | 2014/02/10 | [
"https://Stackoverflow.com/questions/21668250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150762/"
] | According to [this post](https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin), you should consult [this reference](http://www.cplusplus.com/reference/fstream/fstream/) to use a method like getline().
Also, when you are writing out I recommend that you flush the output (cout.flush()) before ending the program, especially in this case, since I presume you are ending the program with a ctrl-C break.
In formulating a suggestion, I will read data into char\*, and convert them to "string" in case you will use them elsewhere in your program.
I tested this code in MS Visual C++ Express.
```
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
for (;;)
{
char *myFile = new char[200]; // modified this line
//added this line
char *myInput = new char[200];
string f = " ";
string w = " ";
cout << "What is the name of the file you would like to write to? " << endl;
cin.getline(myFile, 200);//modified this line
f = (myFile);//added this line
cin.clear(); //added this line
ofstream myStream(f, ios_base::ate | ios_base::out);
cout << "What would you like to write to " << f << " ? ";
cin.getline(myInput, 200);//edited this line
w = string(myInput);//added this line
myStream << w;
myStream.flush();//added this line
if (myStream.bad())
{
myStream << "A serious error has occured.";
myStream.close();
break;
}
delete myFile;
delete myInput;
}
}
``` | You have to use `std::getline()` to read the entire line:
```
std::getline(std::cin >> std::ws, w);
```
The `>> std::ws` part gets rid of leading whitespace which is needed because the newline left in the stream from the previous extraction will prevent `std::getline()` from fully consuming the input.
When inserting data into the stream you need to make sure it gets flushed (because, as the other answer said, you're probably using `Ctrl+C` to terminate the program and you may not see output during the program run). You can use the `std::flush` manipulator to flush the output:
```
myStream << w << std::flush;
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.