qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
95,285 | If $R$ is an algebra without a unit, then the standard unitisation $R^\sharp$ can have maximal one-sided ideals other than $R$. Thus, it is natural to ask about the following. Let $R$ be an algebra without a unit (over a field with char 0 if it does matter).
Is there a unital algebra $A$ such that $R$ is the unique maximal right ideal in $A$?
EDIT: Assume $R$ has a faithful representation $\pi$ on a vector space $V$ (over $K$), what if we consider $A=\pi(R)+KI$? | 2012/04/26 | [
"https://mathoverflow.net/questions/95285",
"https://mathoverflow.net",
"https://mathoverflow.net/users/23242/"
] | Hi, here are some references taken from *Algebraic geometry I. Schemes.* by Gortz and Wedhorn, Appendix E. These are generally scattered in EGAIV as far as I remember. Anyway, Kazuma Shimomoto recently pointed out to me this appendix.
**EDIT:** I originally misread what Gortz and Wedhorn were saying, and got the references wrong. Here are corrected references:
**EDIT:** As Mohan and Laurent Moret-Bailly point out, you really *need* the properness. Otherwise, imagine that the *bad* locus (for example, the singular/non-normal locus) is like a hyperbola that goes to infinity near the special fiber.
1). This is Appendix E.1(11). They reference EGAIV, 12.2.1
2). I don't see this in their list... You could try checking out EGA.
3). Normality is Appendix E.1(20). They reference EGAIV 12.2.4. Smoothness is Appendix E.1(18), again see EGAIV 12.2.4.
Of course, they are talking about geometric normality etc, but in your case, the residue field at the special point is $\mathbb{C}$, so if the special fiber is normal it is geometrically normal.
In particular, they state the openness of the statements for a proper flat map.
**EDIT: A different approach:** Let me also state a different approach to some of these questions.
I say that an open property $P$ *deforms* if for a local ring $(R, \mathfrak{m})$ and if there exists a regular element $0 \neq f \in \mathfrak{m}$ such that $R/f$ satisfies property $P$ then $R$ also satisfies property $P$.
Regularity, Cohen-Macaulayness, Gorensteinness all deform for more or less obvious reasons. Normality is pretty easy and I know it's in EGA somewhere... (it's also in a paper of R. Heitmann where he actually shows the statement for semi-normality, it follows from regularity and S\_n computations). In fact, if $R/f$ is reduced or integral, then so is $R$.
Just for completeness, let me mention that rational singularities also deform (a result of Elkik). Log canonical and log terminal singularities do not deform in this way unless additional assumptions on $R$ are made (for example, if $R$ is Gorenstein). In general, see *Inversion of adjunction*. A recent theorem of Kovacs and myself proves it for Du Bois singularities (see the arXiv). As far as I know, this is an open question for weak-normality.
Anyway, why is this relevant? Well, let's say we have an open condition (like being reduced, being smooth, being normal, being Cohen-Macaulay, having rational singularities). Then suppose that $\pi : Y \to C$ is a flat map over a smooth pointed curve $0 \in C$. If the special fiber $Y\_0$ saties a property $P$, and $P$ deforms, then $Y$ satisfies property $P$ in a neighborhood of $Y\_0$. Indeed, work locally, modding out by the equation defining the special fiber is just modding out by some regular element.
$\bullet$ If $\pi$ is now proper, then this implies that the non-$P$-locus has closed image in $C$ under $\pi$. In particular, it only messes up a few fibers and the generic fiber is $P$ (in fact the total space $Y$ is also $P$ is one is willing to remove a couple points from $C$). At this point, you can use Bertini's theorem to obtain that the "nearby" closed fibers of $\pi$ also satisfy $P$. | I think that the answer for 2) is negative. Let $C$ be the union of the axises in the plane and $p:C \to \mathbb A ^1$ be given by $p(x,y)=x+y$. the fiber of $0$ is "irreducible" but non-reduced (i.e. its reduction is irreducible), but the generic fiber is reducible.
Another counterexample is $X=[(x,y,z) \in \mathbb A ^3|,x(x-yz)=0 ]$ and $\phi:X\to \mathbb A^1$ is defined by $\phi(x,y,z)=z$. Here the generic fiber is not only not irreducible but also not locally irreducible. |
1,956,345 | I am confirming about creating activity.
My Manifest.xml is like this :
```
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ThirdActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
```
You can see property `action android:name=` property is `"android.intent.action.MAIN"` and
`category android:name=` is `"android.intent.category.LAUNCHER"` for all activities.
When the application starts up, it calls **FirstActivity**.
Then calls useless Activity such as ThirdActivity or SecondActivity.
In this case, is my `manifest.xml` correct?
Or, do I need to set another property to Second and Third activity?
If so, what is that?
I wonder `manifest.xml` file is right for my case.
Please advise. | 2009/12/24 | [
"https://Stackoverflow.com/questions/1956345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227889/"
] | Try this config:
```
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
<activity android:name=".ThirdActivity" android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
``` | Think of an [`Intent`](http://developer.android.com/guide/topics/fundamentals.html) as message used to start an `Activity` to do something. So I can create an `Intent` to view a web page and an application with an Activity which knows how to view a web page - most likely the browser - can intercept his Intent as act on it.
You tell Android which Activities can act on which Intents using the `<intent-filter>` part of your Manifest.
The [`MAIN`](http://developer.android.com/reference/android/content/Intent.html#ACTION_MAIN) `Intent` is a special one. This is sent to an application when it is launched and basically it says "Go!" So the `Activity` which shoud be displayed first needs to intercept this by having a correctly defined `<intent-filter>`.
As you had all three Activities with `MAIN` in their filter they all responded to the request to start your application. So you should have that `<intent-filter>` only for `FirstActivity`. |
1,956,345 | I am confirming about creating activity.
My Manifest.xml is like this :
```
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ThirdActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
```
You can see property `action android:name=` property is `"android.intent.action.MAIN"` and
`category android:name=` is `"android.intent.category.LAUNCHER"` for all activities.
When the application starts up, it calls **FirstActivity**.
Then calls useless Activity such as ThirdActivity or SecondActivity.
In this case, is my `manifest.xml` correct?
Or, do I need to set another property to Second and Third activity?
If so, what is that?
I wonder `manifest.xml` file is right for my case.
Please advise. | 2009/12/24 | [
"https://Stackoverflow.com/questions/1956345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227889/"
] | Try this config:
```
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
<activity android:name=".ThirdActivity" android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
``` | One of the other problems with using
`<category android:name="android.intent.category.LAUNCHER" />` for more than one activity is that the Phone's launcher menu will display more than one icon...
**From the docs:**
>
> CATEGORY\_LAUNCHER The activity can
> be the initial activity of a task and
> is listed in the top-level application
> launcher.
>
>
> |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | If you're not loading cross domain then you could just load in using jquery ajax call
<http://docs.jquery.com/Ajax/load>
```
$(document).ready(function () {
$("#content").load("page.html");
});
```
and replace your iframe with
```
<div id="content"></div>
``` | That's "[clickjacking](http://en.wikipedia.org/wiki/Clickjacking)", isn't it?
Nothing is likely to work long term, as browsers (rightly) see this as a security threat to be prevented. |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | That's "[clickjacking](http://en.wikipedia.org/wiki/Clickjacking)", isn't it?
Nothing is likely to work long term, as browsers (rightly) see this as a security threat to be prevented. | You probably need to add margin:auto; to your iFrame or the floating div.
This will make it fill the screen 100%.
Example:
```
.width {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
width:250px;
height:150px;
margin:auto;
}
```
To fix it to the left of the browser you can use:
```
margin:auto auto auto 0;
```
Good luck! |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | This worked for me:
* add the overlay div with a high z-index and absolute position
* make the iframe also positioned absolute
* add the iframe inside a div
The div with the overlay:
```
<div style="z-index:99;position:absolute;top:0;right:0">
...overlay html...
</div>
```
The iframe:
```
<style>
iframe {
position: absolute;
border: none;
box-sizing: border-box;
width: 100%;
height: 100%;
}
</style>
<div>
<iframe src="http://..."> </iframe>
</div>
``` | You could wrap your iframe in a div with a low Z-index and then lay a div over it with a higher z-index. |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | That's "[clickjacking](http://en.wikipedia.org/wiki/Clickjacking)", isn't it?
Nothing is likely to work long term, as browsers (rightly) see this as a security threat to be prevented. | You could wrap your iframe in a div with a low Z-index and then lay a div over it with a higher z-index. |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | That's "[clickjacking](http://en.wikipedia.org/wiki/Clickjacking)", isn't it?
Nothing is likely to work long term, as browsers (rightly) see this as a security threat to be prevented. | with this code I get a double scrollbar on the right on the right.
One for the website and one for the i-frame.
```
<style>
iframe {
position: absolute;
border: none;
box-sizing: border-box;
width: 100%;
height: 100%;
}
</style>
<div>
<iframe src="http://..."> </iframe>
</div>
``` |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | That's "[clickjacking](http://en.wikipedia.org/wiki/Clickjacking)", isn't it?
Nothing is likely to work long term, as browsers (rightly) see this as a security threat to be prevented. | This worked for me:
* add the overlay div with a high z-index and absolute position
* make the iframe also positioned absolute
* add the iframe inside a div
The div with the overlay:
```
<div style="z-index:99;position:absolute;top:0;right:0">
...overlay html...
</div>
```
The iframe:
```
<style>
iframe {
position: absolute;
border: none;
box-sizing: border-box;
width: 100%;
height: 100%;
}
</style>
<div>
<iframe src="http://..."> </iframe>
</div>
``` |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | You probably need to add margin:auto; to your iFrame or the floating div.
This will make it fill the screen 100%.
Example:
```
.width {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
width:250px;
height:150px;
margin:auto;
}
```
To fix it to the left of the browser you can use:
```
margin:auto auto auto 0;
```
Good luck! | with this code I get a double scrollbar on the right on the right.
One for the website and one for the i-frame.
```
<style>
iframe {
position: absolute;
border: none;
box-sizing: border-box;
width: 100%;
height: 100%;
}
</style>
<div>
<iframe src="http://..."> </iframe>
</div>
``` |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | If you're not loading cross domain then you could just load in using jquery ajax call
<http://docs.jquery.com/Ajax/load>
```
$(document).ready(function () {
$("#content").load("page.html");
});
```
and replace your iframe with
```
<div id="content"></div>
``` | You could wrap your iframe in a div with a low Z-index and then lay a div over it with a higher z-index. |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | with this code I get a double scrollbar on the right on the right.
One for the website and one for the i-frame.
```
<style>
iframe {
position: absolute;
border: none;
box-sizing: border-box;
width: 100%;
height: 100%;
}
</style>
<div>
<iframe src="http://..."> </iframe>
</div>
``` | You could wrap your iframe in a div with a low Z-index and then lay a div over it with a higher z-index. |
2,094,668 | I'm making a widget similar to the uservoice widgets, except I want the content of the page to be in an iFrame rather than the widget appear via javascript.
How can I have a full page (width/height 100%) iFrame with a div fixed to the left of the browser, an example (using javascript rather than css/html) is here: <http://uservoice.com/demo>
I want that widget to appear natively on the page, and the content be loaded via iFrame.
Any ideas? I can't make the iFrame fill the entire page, and also have the appear on top. I've played with z-indexes to no luck. Code example:
```
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
#widget {
left: 0px;
position: absolute;
top: 50%;
display: block;
z-index:100001;
width: 25px;
}
#content {
z-index:1;
}
</style>
</head>
<body>
<div id="widget">
widget
</div>
<iframe frameborder="0" id="content" src="http://www.google.com/" width="100%" height="100%"></iframe>
</body>
</html>
``` | 2010/01/19 | [
"https://Stackoverflow.com/questions/2094668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248231/"
] | If you're not loading cross domain then you could just load in using jquery ajax call
<http://docs.jquery.com/Ajax/load>
```
$(document).ready(function () {
$("#content").load("page.html");
});
```
and replace your iframe with
```
<div id="content"></div>
``` | This worked for me:
* add the overlay div with a high z-index and absolute position
* make the iframe also positioned absolute
* add the iframe inside a div
The div with the overlay:
```
<div style="z-index:99;position:absolute;top:0;right:0">
...overlay html...
</div>
```
The iframe:
```
<style>
iframe {
position: absolute;
border: none;
box-sizing: border-box;
width: 100%;
height: 100%;
}
</style>
<div>
<iframe src="http://..."> </iframe>
</div>
``` |
614,986 | I'm attempting to use Postfix (version 2.6.6 on RHEL6) to connect to and send mail via a mail relay on our internal network. I want to connect with STARTTLS on port 25 (port 465 is not available on this server). The mail relay uses a self-signed SSL/TLS certificate so I needed to skip certificate verification using a certificate authority. I discovered the [`smtp_tls_security_level = fingerprint`](http://www.postfix.org/TLS_README.html#client_tls_fprint) which does not check the trust chain, expiration date, etc. Instead it verifies using the certificate fingerprint.
I figured this was the perfect solution, but when I attempt to send an email, I still get errors in `/var/log/maillog` that say `postfix/smtp[15182]: certificate verification failed for xxxxxxxxxxxx[zz.zz.zz.zz]:25: untrusted issuer`.
**I thought the whole point of the `fingerprint` security level was to skip certificate verification. Am I misunderstanding the point of this option? Is there something else I need to configure?**
Here are the relevant lines from `main.cf`:
```
relayhost = [xxx.xxx.xxx]
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl-passwords
smtp_sasl_security_options=
smtp_generic_maps = hash:/etc/postfix/generic
smtp_use_tls = yes
smtp_tls_security_level = fingerprint
smtp_tls_fingerprint_digest = sha1
# fingerprint changed for ServerFault. just an example.
smtp_tls_fingerprint_cert_match = c1:d3:54:12:00:r0:ef:fa:42:48:10:ff:ac:1e:75:13:dd:ad:af:3e
smtp_tls_note_starttls_offer = yes
```
Edit: added bold | 2014/07/23 | [
"https://serverfault.com/questions/614986",
"https://serverfault.com",
"https://serverfault.com/users/103657/"
] | Gonna answer my own question here. I did not manage to get `fingerprint` verification working, but I did discover how to get TLS without certificate verification. From the [manual](http://www.postfix.org/TLS_README.html#client_tls_encrypt):
>
> Mandatory TLS encryption can be configured by setting "smtp\_tls\_security\_level = encrypt". Even though TLS encryption is always used, mail delivery continues even if the server certificate is untrusted or bears the wrong name.
>
>
>
I had tried this at one point but must not have had all the right options enabled. But using the settings above, I simply changed `smtp_tls_security_level` to `encrypt` and it works fine. | Since Postfix has enable chroot (by default in Debian) "/etc/postfix/master.cf":
```
# ==========================================================================
# service type private unpriv chroot wakeup maxproc command + args
# (yes) (yes) (yes) (never) (100)
# ==========================================================================
smtp unix - - - - - smtp
```
and the default value for the variable **[smtp\_tls\_CAfile](http://www.postfix.org/postconf.5.html#smtp_tls_CAfile)** is empty, the solution pass for setting it with the location of the certificates file inside de chroot:
In "/etc/postfix/main.cf":
```
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
``` |
5,215 | This is more like an academic question. Although, common perception is that dynamic analysis is testing itself, most of advanced sources (but AFAIK also the ISTQB) distinct between:
* **dynamic testing** (excercising the program) and
* **dynamic analysis** (analysis of memory leaks, pointer exceptions etc. during runtime) by special tools.
Of course it is not perfect classification because:
* ISTQB, having adapted IEEE, says **analysis** = **testing**
* but on the other hand it distincts between **dynamic analysis** and **dynamic testing**.
Needless to say, ISTQB uses a **static testing** term which is not used by most of the other authoritative resources, they call it **static analysis**.
Well, the question would be: How should I classify dynamic analysis and dynamic testing relation in terms of taxonomy in my thesis?
If DA is not testing, I cannot simply call it dynamic testing technique. So how should I resolve it?
A Quote from **Advanced Software Testing - Vol. 2: Guide to the ISTQB Advanced** ...:
>
> ***Dynamic analysis tools** provide runtime information of the state of the executing software. They can be used to pinpoint a number of
> problems that are hard to find in static analysis and **dynamic
> testing.***
>
>
>
So it is clear that this is correctly saying DA is not
dynamic testing (Wikipedia does not agree but that is not trusted
source).
Another source: **Guide to Advanced Software Testing**:
>
> ***Dynamic analysis** cannot be done without tool support.... provides information as a by-product of dynamic testing (...) **Dynamic testing** can be
> used when the test object is executable. We can also use **dynamic analysis**, especially during component
> testing.*
>
>
> | 2012/11/15 | [
"https://sqa.stackexchange.com/questions/5215",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/2740/"
] | My thoughts are that this is more about the differences between static and dynamic than analysis and testing.
My own personal definitions are:
**Static testing** = Testing of requirements, designs, specifications, log files, configuration files etc.
**Dynamic testing** = Testing of the application whilst it is running.
Likewise,
**Static analysis** = Analysis of application source code to find errors, inconsistencies and areas of high complexity, etc.
**Dynamic analysis** = Analysis of the application whilst it is running, to find memory leaks, performance issues etc.
So back to your original question, my personal view, would be that you could have analysis as part of your testing, however testing != analysis. | To perform dynamic analysis (memory leaks...) you have to execute the program, so I should try to provide a clear description when defining "dynamic testing" as a different aspect than "dynamic analysis" (and not just in a way of "exercising the program").
Usually, the test cases executions (from unit testing to regression system/function test) are used in order to produce the dynamic analysis reports. Not necessary, but let's say a "real world" relationship between them.
Maybe you should try to find a definition that focus on the objetives (results). "Static/dynamic code analysis" are mainly focused on the code violations/pitfalls no matter what functionality is implemented. "Dynamic testing" take care of how functionality (requirements) are implemented. |
51,656 | I have been having a problem with my wife's 2008 Toyota Highlander Hybrid.
It is blowing headlamps every 3 or 4 months. Usually one at a time, so it is probably really 6 months of life per lamp before it blows. I have made sure not to touch the bulb glass, but that doesn't seem to affect the time to failure on the bulb. I have not been using electrical grease.
I guess I should go measure the lamp voltage. Has anyone heard of such a high failure rate on headlights before? Other than high voltage, are there any suggestions of things I should look at? | 2018/02/09 | [
"https://mechanics.stackexchange.com/questions/51656",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/35467/"
] | I have the answer AND it certainly has to do with the age of the car.
So, the 2008 Toyota highlander lens are made of plastic and they develop a white film over time that is a product of UV damage and the elements.
At some point, that film begins to contribute significantly a reduction in visible brightness, but it also means that a significant portion of the light is being reflected back into the lamp housing, thus making it much hotter than it was when the lens was new and more clear. The increase in temp cause the life of the bulb to be significantly reduced.
The solution is to clean the lenses. The cheapest way is to use a headlight lens restoration box kit, which can be obtained from Amazon or your local auto store. Just requires some elbow grease to clean it up.
Alternately, and this is what I did, I took it to my auto shop and they used a fine sand blaster and polisher. The lenses look new and no more blown bulbs. | Had similar problem with 2010 Toyota [another model]. Recently Toyota admitted there is a problem (years around 2010) and dealership made some fix.
Another problem could be water in a headlight. |
51,656 | I have been having a problem with my wife's 2008 Toyota Highlander Hybrid.
It is blowing headlamps every 3 or 4 months. Usually one at a time, so it is probably really 6 months of life per lamp before it blows. I have made sure not to touch the bulb glass, but that doesn't seem to affect the time to failure on the bulb. I have not been using electrical grease.
I guess I should go measure the lamp voltage. Has anyone heard of such a high failure rate on headlights before? Other than high voltage, are there any suggestions of things I should look at? | 2018/02/09 | [
"https://mechanics.stackexchange.com/questions/51656",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/35467/"
] | I have the answer AND it certainly has to do with the age of the car.
So, the 2008 Toyota highlander lens are made of plastic and they develop a white film over time that is a product of UV damage and the elements.
At some point, that film begins to contribute significantly a reduction in visible brightness, but it also means that a significant portion of the light is being reflected back into the lamp housing, thus making it much hotter than it was when the lens was new and more clear. The increase in temp cause the life of the bulb to be significantly reduced.
The solution is to clean the lenses. The cheapest way is to use a headlight lens restoration box kit, which can be obtained from Amazon or your local auto store. Just requires some elbow grease to clean it up.
Alternately, and this is what I did, I took it to my auto shop and they used a fine sand blaster and polisher. The lenses look new and no more blown bulbs. | Look for long-life bulbs. There is a tradeoff between light output and bulb lifetime if you keep the wattage of the bulb constant. Some vehicles (which probably includes Toyota according to my experiences with a 2011 Toyota Yaris) might have slightly higher charging system voltage than others, and therefore, the bulb lifetime is reduced due to a high voltage, but the light output is increased. If you choose a high-output bulb to such a car, the lifetime will be very short indeed.
The solution of using long-life bulbs means the inherent low light output of the long-life bulb is compensated by the slightly higher charging system voltage, and thus, in a car with slightly higher voltage you get about the same light output and lifetime you would get from a regular high-output bulb in a car with normal charging system voltage.
In a car with normal charging system voltage, the long-life bulbs would last very long indeed, but the light output would suck. |
51,656 | I have been having a problem with my wife's 2008 Toyota Highlander Hybrid.
It is blowing headlamps every 3 or 4 months. Usually one at a time, so it is probably really 6 months of life per lamp before it blows. I have made sure not to touch the bulb glass, but that doesn't seem to affect the time to failure on the bulb. I have not been using electrical grease.
I guess I should go measure the lamp voltage. Has anyone heard of such a high failure rate on headlights before? Other than high voltage, are there any suggestions of things I should look at? | 2018/02/09 | [
"https://mechanics.stackexchange.com/questions/51656",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/35467/"
] | I have the answer AND it certainly has to do with the age of the car.
So, the 2008 Toyota highlander lens are made of plastic and they develop a white film over time that is a product of UV damage and the elements.
At some point, that film begins to contribute significantly a reduction in visible brightness, but it also means that a significant portion of the light is being reflected back into the lamp housing, thus making it much hotter than it was when the lens was new and more clear. The increase in temp cause the life of the bulb to be significantly reduced.
The solution is to clean the lenses. The cheapest way is to use a headlight lens restoration box kit, which can be obtained from Amazon or your local auto store. Just requires some elbow grease to clean it up.
Alternately, and this is what I did, I took it to my auto shop and they used a fine sand blaster and polisher. The lenses look new and no more blown bulbs. | Switch to LED head lights. I had this problem with a blinker and now it is fixed. You could install a dimmer switch, dim your head lights a touch and they may last longer. |
24,069,473 | In the Swift programming language I see an example
```
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
```
It appears that `T.GeneratorType.Element == U.GeneratorType.Element` means that the elements generated when the sequences are decomposed share the same underlying type. So I can do
```
anyCommonElements("123", "1234")
anyCommonElements([1, 2, 3], [1])
```
but not
```
anyCommonElements("123", [1, 2])
```
But `T: Sequence, U: Sequence` means that the parameters T and U have to be sequences, such as a String or an Array.
What is the proper way to write a function that takes two parameters T and U which are required to be the same type using the where clause? Omitting the `T: Sequence, U: Sequence` requirement results in the error "GeneratorType is not a member of type T" | 2014/06/05 | [
"https://Stackoverflow.com/questions/24069473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370927/"
] | As @conner noted but you would never specify it that way as there is only one type. This is better:
```
func functionName<T> (lhs: T, rhs: T) -> Bool { ... }
``` | If you want both of your parameters to be the same type, you can just use the same generic for both of them. Something like:
```
func functionName <T, T> (lhs: T, rhs: T) -> Bool {
return false
}
``` |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | Use this
```
dataStore.edit {
it.clear()
}
```
Method description states
>
> Removes all preferences from this MutablePreferences.
>
>
>
For proto datastore (Thanks to Amir Raza for comment)
```
datastore.updateData {
it.toBuilder().clear().build()
}
``` | For Proto DataStore you can do:
dataStore.updateData { it.getDefaultInstance() }
It doesn't delete the file, but it's effectively the same. |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | Use this
```
dataStore.edit {
it.clear()
}
```
Method description states
>
> Removes all preferences from this MutablePreferences.
>
>
>
For proto datastore (Thanks to Amir Raza for comment)
```
datastore.updateData {
it.toBuilder().clear().build()
}
``` | Try this (for Proto DataStore):
```
dataStore.updateData { obj ->
obj.toBuilder()
.clear()
.build()
}
``` |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | Use this
```
dataStore.edit {
it.clear()
}
```
Method description states
>
> Removes all preferences from this MutablePreferences.
>
>
>
For proto datastore (Thanks to Amir Raza for comment)
```
datastore.updateData {
it.toBuilder().clear().build()
}
``` | If you want to delete a specific key then try this
```
dataStore.edit {
if (it.contains(key)) {
it.remove(key)
}
}
``` |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | Use this
```
dataStore.edit {
it.clear()
}
```
Method description states
>
> Removes all preferences from this MutablePreferences.
>
>
>
For proto datastore (Thanks to Amir Raza for comment)
```
datastore.updateData {
it.toBuilder().clear().build()
}
``` | In case anyone wants to know how to remove a specific preference
```
context.dataStore.edit {
it.remove(key)
}
``` |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | Try this (for Proto DataStore):
```
dataStore.updateData { obj ->
obj.toBuilder()
.clear()
.build()
}
``` | For Proto DataStore you can do:
dataStore.updateData { it.getDefaultInstance() }
It doesn't delete the file, but it's effectively the same. |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | If you want to delete a specific key then try this
```
dataStore.edit {
if (it.contains(key)) {
it.remove(key)
}
}
``` | For Proto DataStore you can do:
dataStore.updateData { it.getDefaultInstance() }
It doesn't delete the file, but it's effectively the same. |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | In case anyone wants to know how to remove a specific preference
```
context.dataStore.edit {
it.remove(key)
}
``` | For Proto DataStore you can do:
dataStore.updateData { it.getDefaultInstance() }
It doesn't delete the file, but it's effectively the same. |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | Try this (for Proto DataStore):
```
dataStore.updateData { obj ->
obj.toBuilder()
.clear()
.build()
}
``` | If you want to delete a specific key then try this
```
dataStore.edit {
if (it.contains(key)) {
it.remove(key)
}
}
``` |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | In case anyone wants to know how to remove a specific preference
```
context.dataStore.edit {
it.remove(key)
}
``` | Try this (for Proto DataStore):
```
dataStore.updateData { obj ->
obj.toBuilder()
.clear()
.build()
}
``` |
64,851,765 | i've been using jetpack datastore for a while, but then i got a problem.
I want to clear data in datastore when the app is destroyed.
Im using jetpack datastore to persist data only in form
i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?
i found clear function in
[datastore documentation](https://developer.android.com/reference/kotlin/androidx/datastore/preferences/package-summary#clear) but there is no explanation on how to use it | 2020/11/16 | [
"https://Stackoverflow.com/questions/64851765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11230663/"
] | In case anyone wants to know how to remove a specific preference
```
context.dataStore.edit {
it.remove(key)
}
``` | If you want to delete a specific key then try this
```
dataStore.edit {
if (it.contains(key)) {
it.remove(key)
}
}
``` |
46,448,046 | I would like to inject data to `DeviceMarkerComponent` before running this:
```
let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
...
fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
```
`DeviceMarkerComponent` uses variables in `ngOnInit` and I can't create the component without initializing the variables. `NgOnInit` is firing when `TestBed.CreateComponent` is called and it causes error, so I have to set these variables or modify a code which I'm testing :(
[](https://i.stack.imgur.com/TNv7I.png) | 2017/09/27 | [
"https://Stackoverflow.com/questions/46448046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6212581/"
] | There are a number of ways you "might" do this, you could
* Create a factory method to apply the properties and listeners you need to mimic the functionality
* Create a new class which extends from `JButton` or `AbstractButton` and provide core functionality/properties you need in a self contained package
* You could provide you own UI delegate, and customise the look and feel of the button at the core
Each method has it's pros and cons and you need to decide which better meets you overall needs.
For example, it's much easier to supply a customised look and feel delegate into an existing code base, as you don't need to change the code, other then to install the look and feel when you want to use it
The following is an example of using a look and feel delegate, this is just a proof of concept and there are probably a lot of additional functionality/work that needs to be done - for example, I'd like to supply more hints about the colors to use and the thickness of the roll over border, for example
[](https://i.stack.imgur.com/zKnBm.png)[](https://i.stack.imgur.com/7B0tL.png)
```
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javaapplication24.Test.MetroLookAndFeel;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicButtonUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
JButton fancyPB = new JButton("Restart Now");
fancyPB.setUI(new MetroLookAndFeel());
JButton normalPB = new JButton("Restart Now");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
add(fancyPB, gbc);
add(normalPB, gbc);
}
}
public class MetroLookAndFeel extends BasicButtonUI {
// This could be computed properties, where the border color
// is determined based on other properties
private Border focusBorder = new CompoundBorder(new LineBorder(Color.DARK_GRAY, 3), new EmptyBorder(7, 13, 7, 14));
private Border unfocusedBorder = new EmptyBorder(10, 14, 10, 14);
@Override
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
Font f = new Font("Segoe UI", Font.PLAIN, 20);
Color gray = new Color(204, 204, 204);
b.setFont(f);
b.setBackground(gray);
b.setContentAreaFilled(false);
b.setFocusPainted(false);
// This seems like an oddity...
b.setFocusable(false);
b.setForeground(Color.BLACK);
// b.setBorder(BorderFactory.createEmptyBorder(10, 14, 10, 14));
b.setBorder(unfocusedBorder);
}
@Override
protected void installListeners(AbstractButton b) {
super.installListeners(b);
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
((JButton)e.getSource()).setBorder(focusBorder);
}
@Override
public void mouseExited(MouseEvent e) {
((JButton)e.getSource()).setBorder(unfocusedBorder);
}
});
}
}
}
``` | Here is an example
```
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
public class WinButton {
public static void main(String[] args) {
final JButton button = createWinButton("Restart now");
JFrame frm = new JFrame("Test");
JPanel layoutPanel = new JPanel();
layoutPanel.add(button);
frm.add(layoutPanel);
frm.setSize(200, 200);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
private static JButton createWinButton(String text) {
final JButton button = new JButton(text);
Font f = new Font("Segoe UI", Font.PLAIN, 20);
Color gray = new Color(204, 204, 204);
button.setFont(f);
button.setBackground(gray);
button.setContentAreaFilled(false);
button.setFocusPainted(false);
button.setFocusable(false);
button.setForeground(Color.BLACK);
button.setOpaque(true);
button.setBorder(BorderFactory.createEmptyBorder(10, 14, 10, 14));
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Color borderColor = new Color(100, 100, 100);
button.setBorder(new CompoundBorder(new LineBorder(borderColor, 3), BorderFactory.createEmptyBorder(7, 11, 7, 11)));
}
@Override
public void mouseExited(MouseEvent e) {
button.setBorder(BorderFactory.createEmptyBorder(10, 14, 10, 14));
}
});
return button;
}
}
``` |
46,448,046 | I would like to inject data to `DeviceMarkerComponent` before running this:
```
let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
...
fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
```
`DeviceMarkerComponent` uses variables in `ngOnInit` and I can't create the component without initializing the variables. `NgOnInit` is firing when `TestBed.CreateComponent` is called and it causes error, so I have to set these variables or modify a code which I'm testing :(
[](https://i.stack.imgur.com/TNv7I.png) | 2017/09/27 | [
"https://Stackoverflow.com/questions/46448046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6212581/"
] | There are a number of ways you "might" do this, you could
* Create a factory method to apply the properties and listeners you need to mimic the functionality
* Create a new class which extends from `JButton` or `AbstractButton` and provide core functionality/properties you need in a self contained package
* You could provide you own UI delegate, and customise the look and feel of the button at the core
Each method has it's pros and cons and you need to decide which better meets you overall needs.
For example, it's much easier to supply a customised look and feel delegate into an existing code base, as you don't need to change the code, other then to install the look and feel when you want to use it
The following is an example of using a look and feel delegate, this is just a proof of concept and there are probably a lot of additional functionality/work that needs to be done - for example, I'd like to supply more hints about the colors to use and the thickness of the roll over border, for example
[](https://i.stack.imgur.com/zKnBm.png)[](https://i.stack.imgur.com/7B0tL.png)
```
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javaapplication24.Test.MetroLookAndFeel;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicButtonUI;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
JButton fancyPB = new JButton("Restart Now");
fancyPB.setUI(new MetroLookAndFeel());
JButton normalPB = new JButton("Restart Now");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4, 4, 4, 4);
add(fancyPB, gbc);
add(normalPB, gbc);
}
}
public class MetroLookAndFeel extends BasicButtonUI {
// This could be computed properties, where the border color
// is determined based on other properties
private Border focusBorder = new CompoundBorder(new LineBorder(Color.DARK_GRAY, 3), new EmptyBorder(7, 13, 7, 14));
private Border unfocusedBorder = new EmptyBorder(10, 14, 10, 14);
@Override
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
Font f = new Font("Segoe UI", Font.PLAIN, 20);
Color gray = new Color(204, 204, 204);
b.setFont(f);
b.setBackground(gray);
b.setContentAreaFilled(false);
b.setFocusPainted(false);
// This seems like an oddity...
b.setFocusable(false);
b.setForeground(Color.BLACK);
// b.setBorder(BorderFactory.createEmptyBorder(10, 14, 10, 14));
b.setBorder(unfocusedBorder);
}
@Override
protected void installListeners(AbstractButton b) {
super.installListeners(b);
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
((JButton)e.getSource()).setBorder(focusBorder);
}
@Override
public void mouseExited(MouseEvent e) {
((JButton)e.getSource()).setBorder(unfocusedBorder);
}
});
}
}
}
``` | In order to manipulate mouse events, such as hovering, you'll have to treat these events yourself, one of the ways to do is to create your own button.
---
**Edit**
Adding a mouse listener to your button, as answered by Sergiy Medvynskyy, would be a better practice since there is no need to tinker with the button class itself.
---
You may also have to play with the LaF (UIManager Look and Feel) since it can add undesired effects to UI components.
**note that this can affect all of the interface components.**
Following is a basic example.
Button:
```
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.border.Border;
public class UWPButton extends JButton{
private final Border regularBorder;
private final Border hoverBorder;
private final Color bgColor = new Color(204, 204, 204);
private final Color transparent;
private final Font metroFont = new Font("Segoe UI", Font.PLAIN, 20);
public UWPButton() {
super();
// thickness of the button's borders
int thickness = 4;
// Create a transparent color, to use for the regular border
// could also be the bgColor (204 204 204)
Color c = new Color(1f, 0f, 0f, 0f);
transparent = c;
// Creates a compound border to be present on the button majority of the time.
// uses an invisible line border on the outside in order to change border smoothly
// the inside border is just an empty border for insets.
regularBorder = BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(transparent, thickness), //outside
BorderFactory.createEmptyBorder(10, 14, 10, 14)); //inside
// Creates a compound border which will be used when the mouse hovers the button.
// the outside border has a darker colour than the background
// the inside border is just an empty border for insets.
hoverBorder = BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(bgColor.darker(), thickness), //outside
BorderFactory.createEmptyBorder(10, 14, 10, 14)); //inside
// configures the button
initButton();
}
// Here is where the mouse events are treated.
@Override
protected void processMouseEvent(MouseEvent e) {
// Gets the ID of the event,
// if it is a mouse entering the button, sets the new border
// if it is the mouse exiting the button, resets the border to the default.
switch(e.getID()){
case MouseEvent.MOUSE_ENTERED:
this.setBorder(hoverBorder);
break;
case MouseEvent.MOUSE_EXITED:
this.setBorder(regularBorder);
break;
}
// the parent then does all the other handling.
super.processMouseEvent(e);
}
// Configures the button.
private void initButton(){
setFont(metroFont);
setBorder(regularBorder);
setBackground(bgColor);
setFocusPainted(false);
}
}
```
Changing the LaF: If you created your frame through an IDE drag and drop, you should have something like this inside your main (this is from netbeans):
CHANGE "Nimbus" to "Metro"(or remove the LaF setting) so the interface manager won't render all the Nimbus stuff.
**Note:** there is no "Metro" LaF, this is just to disable the applied LaF.
```
// other stuff above
//
// change "Nimbus" for something else or just remove this try-catch block
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// other stuff bellow
```
More on the LaF (Look and Feel):
<https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html> |
35,196,469 | I'm using the following code taken from [this tutorial](http://www.codeproject.com/Articles/236394/Bi-Cubic-and-Bi-Linear-Interpolation-with-GLSL) to perform linear filtering on a floating point texture in my fragment shader in WebGL:
```
float fHeight = 512.0;
float fWidth = 1024.0;
float texelSizeX = 1.0/fWidth;
float texelSizeY = 1.0/fHeight;
float tex2DBiLinear( sampler2D textureSampler_i, vec2 texCoord_i )
{
float p0q0 = texture2D(textureSampler_i, texCoord_i)[0];
float p1q0 = texture2D(textureSampler_i, texCoord_i + vec2(texelSizeX, 0))[0];
float p0q1 = texture2D(textureSampler_i, texCoord_i + vec2(0, texelSizeY))[0];
float p1q1 = texture2D(textureSampler_i, texCoord_i + vec2(texelSizeX , texelSizeY))[0];
float a = fract( texCoord_i.x * fWidth ); // Get Interpolation factor for X direction.
// Fraction near to valid data.
float pInterp_q0 = mix( p0q0, p1q0, a ); // Interpolates top row in X direction.
float pInterp_q1 = mix( p0q1, p1q1, a ); // Interpolates bottom row in X direction.
float b = fract( texCoord_i.y * fHeight );// Get Interpolation factor for Y direction.
return mix( pInterp_q0, pInterp_q1, b ); // Interpolate in Y direction.
}
```
On an Nvidia GPU this looks fine, but on two other computers with an Intel integrated GPU it looks like this:
[](https://i.stack.imgur.com/Dxcet.png)
[](https://i.stack.imgur.com/faMpz.png)
[](https://i.stack.imgur.com/0aDgc.png)
[](https://i.stack.imgur.com/UUJr2.png)
There are lighter or darker lines appearing that shouldn't be there. They become visible if you zoom in, and tend to get more frequent the more you zoom. When zooming in very closely, they appear at the edge of every texel of the texture I'm filtering. I tried changing the precision statement in the fragment shader, but this didn't fix it.
The built-in linear filtering works on both GPUs, but I still need the manual filtering as a fallback for GPUs that don't support linear filtering on floating point textures with WebGL.
The Intel GPUs are from a desktop Core i5-4460 and a notebook with an Intel HD 5500 GPU. For all precisions of floating point values I get a rangeMin and rangeMax of 127 and a precision of 23 from `getShaderPrecisionFormat`.
Any idea on what causes these artifacts and how I can work around it?
**Edit:**
By experimenting a bit more I found that reducing the texel size variable in the fragment shader removes these artifacts:
```
float texelSizeX = 1.0/fWidth*0.998;
float texelSizeY = 1.0/fHeight*0.998;
```
Multiplying by 0.999 isn't enough, but multiplying the texel size by 0.998 removes the artifacts.
This is obviously not a satisfying fix, I still don't know what causes it and I probably caused artifacts on other GPUs or drivers now. So I'm still interested in figuring out what the actual issue is here. | 2016/02/04 | [
"https://Stackoverflow.com/questions/35196469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/347857/"
] | This is not impossible, but it is a bad idea - it's very tricky to get right.
Instead, you want to separate the business logic from the UI, so that you can do the logic in the background, while the UI is still on the UI thread. The key is that you must not modify the UI controls from the background thread - instead, you first load whatever data you need, and then either use `Invoke` or `ReportProgress` to marshal it back on the UI thread, where you can update the UI.
If creating the controls themselves is taking too long, you might want to look at some options at increasing the performance there. For example, using `BeginUpdate` and friends to avoid unnecessary redraws and layouting while you're still filling in the data, or creating the controls on demand (as they are about to be visible), rather than all upfront.
A simple example using `await` (using Windows Forms, but the basic idea works everywhere):
```
tabSlow.Enabled = false;
try
{
var data = await Database.LoadDataAsync();
dataGrid.DataSource = data;
}
finally
{
tabSlow.Enabled = true;
}
```
The database operation is done in the background, and when it's done, the UI update is performed back on the UI thread. If you need to do some expensive calculations, rather than I/O, you'd simply use `await Task.Run(...)` instead - just make sure that the task itself doesn't update any UI; it should just return the data you need to update the UI. | WPF does not allow you to change UI from the background thread. Only ONE SINGLE thread can handle UI thread. Instead, you should calculate your data in the background thread, and then call `Application.Current.Dispatcher.Invoke(...)` method to update the UI. For example:
```
Application.Current.Dispatcher.Invoke(() => textBoxTab2.Text = "changing UI from the background thread");
``` |
142,173 | I have read a lot of computer architecture textbooks, and I wonder why most of them (if not all) used MIPS as the architecture to teach. Why MIPS and not Intel or AMD or something else? What makes the architecture suitable for teaching? | 2012/03/29 | [
"https://softwareengineering.stackexchange.com/questions/142173",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/21461/"
] | The MIPS architecture is derived from an architecture specifically designed at Stanford for educational use and for research into CPU ISAs and architectural implementations. Early academic RISC architecture were designed such that they could be implemented (included layout) by small teams of graduate or upper-division students (not the cast of thousands involved in current Intel CPUs.) Thus MIPS may have basic features more compatible with textbook pedagogical explanations, and less legacy-derived "stuff" that isn't, compared with other commercial architectures.
MIPS may also have more available open source implementations very similar to it than other RISC or currently popular architectures. | Intel and AMD have a large share of the Desktop market. Other processor families are much more common in devices outside that fairly small area of influence. MIPS is also a RISC architecture which are generally thought of as being easier to learn. You learn a small number of commands that can be combined orthogonally a multitude of ways similar to UNIX style piping.
Computer Architecture books that are educational rather than specificational are generally geared toward concepts rather than specific implementation details and thus tend to be more likely to use RISC over CISC simply because there's less to teach in order to understand the instruction set.
I do expect a convergence with ARM though as it is an extremely widely used architecture that is also RISC so I'd think it will show up in architecture books soon enough. |
138,104 | I'm developing a sort of ’social mmmo’ where people build an avatar and chat with people around them, carryout tasks together, and play team games.
At the moment I have a product I want to release to beta testers but I only have 2 locations ready and they are quite far apart.
I have a fast travel system in place where people can pay to ride the bus making any journey take a short period of time.
If people run out of money they either have to earn more or make the walk themselves.
In the beta would it be better to make the bus free, or have people walk the empty land to get to the other town if they run out of money?
At the moment the land is just plain grass, hills, a river, and the odd tree with nothing of interest.
The journey currently takes around 10-15 minutes to walk if you know the way. | 2017/03/02 | [
"https://gamedev.stackexchange.com/questions/138104",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/82339/"
] | First: **Why should you have fast-travel in the first place?**
Because fast travel has an important function: It prevents boredom.
Traversing a well-designed area for the first time is interesting because there is lots of new stuff to discover for the player. The player is exploring, which is one of [the four major appeals of MMOs](https://en.wikipedia.org/wiki/Bartle_taxonomy_of_player_types). But when traversing it again, the novelty has worn off and it becomes boring. You don't want the players to experience boredom, so you shouldn't force them to make the same hike multiple times. That's why many games have fast-travel systems which get unlocked for each route after the player has traversed it manually for the first time.
So now **why make it cost money**? When fast-travel is costly, you encourage players to walk instead. That's a bad design decision! You should never encourage players to do boring stuff. Your encouragement should always be towards the most fun aspects of your game.
But then why do so many games still do it? Because it is a money sink. Typical MMO economies have a problem with inflation. Players constantly generate wealth in form of money and items when they play the game. To fight that inflation, you need to remove money from the economy. The best way to do that is through NPC services which cost money. Fast-travel services are a good opportunity for such a service.
But you need to balance the cost properly so that it is enough to remove a non-negligible amount of money from the game but not so high that any player thinks twice about spending their money on it. A good logic to come up with a good price is to consider how much money players make per minute traveling and how much when they are making while playing in the (for them) most lucrative location. When a player saves 10 minutes travel-time with fast-traveling, makes 100 gold per minute while walking and 1000 gold per minute while at their destination, it is economically better for players to pay up to `(1000 - 100) * 10 =` 900 gold for fast-traveling to their destination immediately.
But unless you are a very experienced game analyst who has figured out every progression curve just from the game formulas before even writing the first line of code, you likely don't have a good idea yet of how much money players will make in what location. But you can easily figure that out when you have actual data from test players. So my recommendation would be to keep fast-travel free for now and then add a cost after you figured out how much money exactly you should take for it.
For further watching I recommend the video [MMO Economies - How to Manage Inflation in Virtual Economies](https://www.youtube.com/watch?v=W39TtF14i8I) by our game design gurus [Extra Credits](https://www.youtube.com/channel/UCCODtTcd5M1JavPCOr_Uydg). | When you talk about beta testing, I don't know if you mean **closed beta**. If that is the case, you can focus testing on particular parts of the game, which also means you may ask the testers to do certain things (such as use the bus). In this enviroment it would be ok to give them the money for the bus.
Otherwise, we are talking about **open beta**, and people will do whatever. Including going to the empty land even when they have money for the bus.
---
If you are considering making the bus free to give a better experience to beta testers, you should also consider make the bus free in the final game. After all, the purpose of the test is to find ways to improve the final game. An improvement for the test should be an improvement for the final game.
Evidently, the game is subject to change. Consider if that if you are planning to make temporary changes to ease beta testers, perhaps the game is not ready for beta.
On the other hand, testing is useful at every stage of the game, you should not be ashamed※ of an incomplete game when evidently that is what beta tester have signed for.
※: It is impossible to fix everything; every video game company has released games with bugs. And testing can be ridiculous, even tedious... but without it, things would be worst.
**You know that this empty land is a problem**. It is a known issue. You will be fixing it before or after testing. Do not hide it. Think that even if you make the bus free, a good tester will try every option, and thus will wander into the empty land.
*Aside: I am guessing you have grand plans for the empty land. That sounds too ambitious! You could have created the game without the empty land, being the bus the only option... and then, when you have created whatever plans you have for the empty land (which would no longer be empty), you can introduce it to the game. Regardless, you have the empty land there. Let the feedback come.*
---
So, I suggest to not introducing temporary changes. That includes making the bus free or giving free money. Instead, be clear with the beta testers about what they are going into. That may include telling them what the route is in the long walk. In fact, it is a good idea to provide manuals for an open beta, where you explain the game.
As an alternative to beta testing, you can do blind alpha tests. In that case, you have people in a controlled environment where you can supervise them. The idea is to see how the player reacts to the situation first hand (that is much more reliable than their account of what happened). This kind of testing is great for discoverability. Consider that perhaps players will not know that they have to take the bus, or that the empty land only takes them to the same place the bus does.
As per beta testing. People will probably provide feedback about the empty land. Be ready to receive that feedback. The mitigation is including it in manuals as mentioned above. |
2,849,394 | I've learnt some ways of finding a point on a line which can minimize the sum of length to other points.
[](https://i.stack.imgur.com/PwOce.png)
I want to generalize this to three points using **geometric** methods.
>
> **Question:**
>
>
> There're three points $(A,B,C)$ on same side of a line, finding a point on that line to minimize $PA+PB+PC$.
>
>
>
I know that the Lagrange Multiplier Method can solve such problems, but I want to find some geometric meaning.
My Attempt
----------
Just like the two point case, let point $B$ go to another side.
$P$ maybe lies on the intersection of $BA, BC$ with the x-axis.
But I suddenly realized that the point of minimum total distance from the three vertices of the triangle is called Fermat–Torricelli Point ($F$ on picture).
But that point may not on the line. But we can get an intersection by connecting $BF$.
I can't prove which point is smaller, or there are other smaller points.
[](https://i.stack.imgur.com/SxK06.png) | 2018/07/13 | [
"https://math.stackexchange.com/questions/2849394",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/483338/"
] | This is not something you can solve with geometric constructions for more than two points.
Suppose the $n$ points are $(x\_i,y\_i)$ and the target point is constrained to the $x$-axis, then the problem is equivalent to minimising the following function:
$$\sum\_i\sqrt{(x-x\_i)^2+y\_i^2}$$
When considering the unconstrained problem, the set of points whose sum of distances to the $n$ points is constant is an [$n$-ellipse](https://en.wikipedia.org/wiki/N-ellipse), and the constrained problem is indirectly asking for that constant for which the $n$-ellipse is tangent to the $x$-axis. For two points, this shape is a normal ellipse, and the depicted reflection method works because the shortest distance between *two* points is a straight line (and the ellipse is of algebraic degree 2).
For three points, however, the 3-ellipse is of degree **8** – far too large to admit an exact solution in all cases.
I took your last diagram and assigned coordinates $(0,2),(2,-2),(3,3)$ to $A,B,C$ respectively. What is $P$ in your diagram – the $x$-intercept of the line between the Fermat point of $\triangle ABC$ and $B$ – lies at $(1.61509982\dots,0)$ where the sum of distances to $A,B,C$ is
$$7.911\mathbf64173\dots$$ This is quite good, but not optimal. The optimal point is $(1.59405306\dots,0)$ whose corresponding sum-distance is
$$7.911\mathbf42964\dots$$
That this differs only after the fourth decimal place shows how delicate this problem is, and the unchallenged superiority of numerical methods for tackling such problems. | For the special case of the three points $(0,0)$, $(1,1)$, $(2,2)$, I find that the minimal $x$ is a root (approximately $0.5473905291$) of the polynomial $$3 x^8-36 x^7+206 x^6-708 x^5+1567 x^4-2280 x^3+2128 x^2-1152 x+256$$
The Galois group of this polynomial, according to Maple, is $S\_8$, which is not solvable. This means that not only is there no "ruler and compasses" geometric construction of the root, there is no expression for it using radicals. |
4,841,775 | I've got an ItemsControl that has another ItemsControl in it.
which means, for each item in the parent list, i want to show all the items in the child list.
so the Xaml is something like this (I'm neglecting some of the DataTemplate)"
```
<ItemsControl x:Name="dayPanel" Grid.Column="1">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<ItemsControl x:Name="dayHours" Grid.Row="1" ItemsSource={Binding HourItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
```
Now in the Code behind i Make a Class that creates a list of days, and each day contains a list of hours.
so i get something like this:
```
public WeekPanel()
{
InitializeComponent();
dayPanel.ItemsSource = new Dayx().CreateDays();
}
```
So.. the first part, that i define in code, works fine.
but the child ItemsControl doesn't get populated.
I want to bind it to the property: HourItems
how do i do that?
**Edit:**
Okay, the problem was that HourItems property was defined as:
```
Public List<Hour> HourItem {get; set;}
```
but it worked when i changed it to:
```
public List<Hour> HourItems
{
get { return hourItems; }
set { hourItems = value; }
}
```
what's the difference that made it work? | 2011/01/30 | [
"https://Stackoverflow.com/questions/4841775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563297/"
] | ```
<ItemsControl x:Name="dayPanel" Grid.Column="1" ItemsSource={Binding}>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<ItemsControl x:Name="dayHours" Grid.Row="1" ItemsSource={Binding HourItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
```
```
public WeekPanel()
{
InitializeComponent();
dayPanel.DataContext = new Dayx().CreateDays();
}
```
Try that code above. Basically I've set the datacontext of your itemscontrol object to your datasource, the ItemsSource then takes the value from itself and the DataContext should pass itself down.
Failing that, have a look in the output window while debugging because that usually tells you if something fails to bind. | In your `ItemsControl`, try using a `RelativeSource`:
```
<ItemsControl x:Name="dayHours" Grid.Row="1" ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemsSource }">
```
Helpful links:
* MSDN [Binding.RelativeSource Property](http://msdn.microsoft.com/en-us/library/system.windows.data.binding.relativesource%28VS.96%29.aspx)
* Silverlight forums [Using property value of parent UserControl](http://forums.silverlight.net/forums/p/182892/418054.aspx) |
11,332,803 | I have a custom cell with a thumbnail image, which the user can select from their photo albums. I know that saving images to Core Data will result in poor performance, and I should use the file system.
Anyone recommend some good tutorials on this. What exactly should I store in core data, if I am not storing the image there.
I will be storing the larger image as well, not just the thumbnail. | 2012/07/04 | [
"https://Stackoverflow.com/questions/11332803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597775/"
] | You should have two fields in your core data db : `thumbnailPath` : `NSString` and `originalPath` : `NSString`
With the file manager you create your thumbnail and original image at a specific path. so you'll have : ..../thumbs/myPicture\_thumb.jpg AND ..../originals/myPicture.jpg
Then you just store this two path to your core data db.
When you wan to display one of them you juste use `UIImage` method : [imageWithContentsOfFile](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html)
That's all | You can store the Images in the `Application Documents Folder` and save the path of the Images in CoreData or sqlite. Refer the Images with their paths. |
11,332,803 | I have a custom cell with a thumbnail image, which the user can select from their photo albums. I know that saving images to Core Data will result in poor performance, and I should use the file system.
Anyone recommend some good tutorials on this. What exactly should I store in core data, if I am not storing the image there.
I will be storing the larger image as well, not just the thumbnail. | 2012/07/04 | [
"https://Stackoverflow.com/questions/11332803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597775/"
] | ```
UIImage*image = [UIImage imageNamed:@"the image you wish to save.jpg"];
//build the path for your image on the filesystem
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPath objectAtIndex:0];
NSString* photoName = @"imageName.jpg";
NSString *photoPath = [docsDir stringByAppendingPathComponent:photoName];
//get the imageData from your UIImage
float imageCompression = 0.5;
NSData *imageData = UIImageJPEGRepresentation(image, imageCompression);
//save the image
if(![imageData writeToFile:path atomically:YES]){
return FALSE;
}
//store the imagePath to your model
photoModal.filePathImage = photoPath;
```
TIPS:
* Avoid duplicate names so you don't override exisitng files (don't worry you'll get a warning)
* Remember to delete the photo when the model is being deleted
* Build a logical path and folder structure that matches your model, e.g - album.photo should have a folder named album and in it you should store the files, helps when you delete the album model | You can store the Images in the `Application Documents Folder` and save the path of the Images in CoreData or sqlite. Refer the Images with their paths. |
11,332,803 | I have a custom cell with a thumbnail image, which the user can select from their photo albums. I know that saving images to Core Data will result in poor performance, and I should use the file system.
Anyone recommend some good tutorials on this. What exactly should I store in core data, if I am not storing the image there.
I will be storing the larger image as well, not just the thumbnail. | 2012/07/04 | [
"https://Stackoverflow.com/questions/11332803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/597775/"
] | ```
UIImage*image = [UIImage imageNamed:@"the image you wish to save.jpg"];
//build the path for your image on the filesystem
NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPath objectAtIndex:0];
NSString* photoName = @"imageName.jpg";
NSString *photoPath = [docsDir stringByAppendingPathComponent:photoName];
//get the imageData from your UIImage
float imageCompression = 0.5;
NSData *imageData = UIImageJPEGRepresentation(image, imageCompression);
//save the image
if(![imageData writeToFile:path atomically:YES]){
return FALSE;
}
//store the imagePath to your model
photoModal.filePathImage = photoPath;
```
TIPS:
* Avoid duplicate names so you don't override exisitng files (don't worry you'll get a warning)
* Remember to delete the photo when the model is being deleted
* Build a logical path and folder structure that matches your model, e.g - album.photo should have a folder named album and in it you should store the files, helps when you delete the album model | You should have two fields in your core data db : `thumbnailPath` : `NSString` and `originalPath` : `NSString`
With the file manager you create your thumbnail and original image at a specific path. so you'll have : ..../thumbs/myPicture\_thumb.jpg AND ..../originals/myPicture.jpg
Then you just store this two path to your core data db.
When you wan to display one of them you juste use `UIImage` method : [imageWithContentsOfFile](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html)
That's all |
2,256,364 | Like most of the average PHP web developers I use MySql as a RDBMS. MySql (as other RDBMS also) offers SPATIAL INDEX features, but I'm don't get it very well. I have googled for it but didn't find clear real world examples to clarify my bad knowledge about it.
Could someone explain me a little bit what is a SPATIAL INDEX and when should I use it? | 2010/02/13 | [
"https://Stackoverflow.com/questions/2256364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272256/"
] | You can use a spatial index for indexing geo-objects - shapes. The spatial index makes it possible to efficiently search for objects that overlap in space | Spatial Index is like an ordinary index with this difference that Spatial objects are not 1D data points rather are in higher dimension space (e.g. 2D) and thus Ordinary indexes such as BTree are not appropriate for indexing such data. The well-known spatial Index technique is R-tree ( Google it on wikipedia ) |
2,256,364 | Like most of the average PHP web developers I use MySql as a RDBMS. MySql (as other RDBMS also) offers SPATIAL INDEX features, but I'm don't get it very well. I have googled for it but didn't find clear real world examples to clarify my bad knowledge about it.
Could someone explain me a little bit what is a SPATIAL INDEX and when should I use it? | 2010/02/13 | [
"https://Stackoverflow.com/questions/2256364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272256/"
] | You can use a spatial index for indexing geo-objects - shapes. The spatial index makes it possible to efficiently search for objects that overlap in space | The use of spacial index is best for searching exact matching value look-up,not for range scan.It is mainly supported in MyISAM tables but from MySQL 5.7.4 LAB release,it is also supported by Innodb.
References:-
<http://dev.mysql.com/doc/refman/5.5/en/creating-spatial-indexes.html>
<http://mysqlserverteam.com/innodb-spatial-indexes-in-5-7-4-lab-release/> |
2,256,364 | Like most of the average PHP web developers I use MySql as a RDBMS. MySql (as other RDBMS also) offers SPATIAL INDEX features, but I'm don't get it very well. I have googled for it but didn't find clear real world examples to clarify my bad knowledge about it.
Could someone explain me a little bit what is a SPATIAL INDEX and when should I use it? | 2010/02/13 | [
"https://Stackoverflow.com/questions/2256364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272256/"
] | You can use a spatial index for indexing geo-objects - shapes. The spatial index makes it possible to efficiently search for objects that overlap in space | When we need to store some geographic data for storing locations OR we need to store shape related data then we can use it.
For Instance, Imagine that you are trying to develop an application that helps people find restaurants, pubs, bars and other hangout places near them. In nutshell, this will be a location discovery platform.
Looking from a back-end perspective, we would be needing to store geographic data of these locations like Latitude and Longitude. Then we would need to write functions that calculate the distance between the user and the location (to show how far the location is from him/her). Using the same function, we can design an algorithm that finds closest places near to the user or within a given radius from him/her.
You may find the better idea with example over here :- <https://medium.com/sysf/playing-with-geometry-spatial-data-type-in-mysql-645b83880331> |
2,256,364 | Like most of the average PHP web developers I use MySql as a RDBMS. MySql (as other RDBMS also) offers SPATIAL INDEX features, but I'm don't get it very well. I have googled for it but didn't find clear real world examples to clarify my bad knowledge about it.
Could someone explain me a little bit what is a SPATIAL INDEX and when should I use it? | 2010/02/13 | [
"https://Stackoverflow.com/questions/2256364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272256/"
] | Spatial Index is like an ordinary index with this difference that Spatial objects are not 1D data points rather are in higher dimension space (e.g. 2D) and thus Ordinary indexes such as BTree are not appropriate for indexing such data. The well-known spatial Index technique is R-tree ( Google it on wikipedia ) | The use of spacial index is best for searching exact matching value look-up,not for range scan.It is mainly supported in MyISAM tables but from MySQL 5.7.4 LAB release,it is also supported by Innodb.
References:-
<http://dev.mysql.com/doc/refman/5.5/en/creating-spatial-indexes.html>
<http://mysqlserverteam.com/innodb-spatial-indexes-in-5-7-4-lab-release/> |
2,256,364 | Like most of the average PHP web developers I use MySql as a RDBMS. MySql (as other RDBMS also) offers SPATIAL INDEX features, but I'm don't get it very well. I have googled for it but didn't find clear real world examples to clarify my bad knowledge about it.
Could someone explain me a little bit what is a SPATIAL INDEX and when should I use it? | 2010/02/13 | [
"https://Stackoverflow.com/questions/2256364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/272256/"
] | When we need to store some geographic data for storing locations OR we need to store shape related data then we can use it.
For Instance, Imagine that you are trying to develop an application that helps people find restaurants, pubs, bars and other hangout places near them. In nutshell, this will be a location discovery platform.
Looking from a back-end perspective, we would be needing to store geographic data of these locations like Latitude and Longitude. Then we would need to write functions that calculate the distance between the user and the location (to show how far the location is from him/her). Using the same function, we can design an algorithm that finds closest places near to the user or within a given radius from him/her.
You may find the better idea with example over here :- <https://medium.com/sysf/playing-with-geometry-spatial-data-type-in-mysql-645b83880331> | The use of spacial index is best for searching exact matching value look-up,not for range scan.It is mainly supported in MyISAM tables but from MySQL 5.7.4 LAB release,it is also supported by Innodb.
References:-
<http://dev.mysql.com/doc/refman/5.5/en/creating-spatial-indexes.html>
<http://mysqlserverteam.com/innodb-spatial-indexes-in-5-7-4-lab-release/> |
63,084,330 | I have used below code to encrypt my value. However, I noticed that for the same value new encryption format is generated instead of same encryption value. Can anyone help me to solve this issue?
Example:
Value is HelloWorld123$
When I executed for the first time, I am getting this encryption - EAAAAE+WzLTCsNOJSQBuTwnRsfrRxqLa6WLVr0zWQ8eozkr1
When I executed for the second time, I am getting this encryption - EAAAAEJuBne0limVQ4aQij89v2SjU8eHasyDlnsGGQ1MD43V
**Question: How can I solve to get same encryption all time for same value?**
```
private static byte[] _salt = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Array of numbers
internal static byte[] key = { 0x0A, 01, 02, 0x48 };
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
private static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
//if (string.IsNullOrEmpty(sharedSecret))
// throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
private static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
//if (string.IsNullOrEmpty(sharedSecret))
// throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
```
User Case:
I have a form which insert form value into database. Including some valuable items which are encrypted.
I have another form which checks whether value exist in database, When I using some method for some lookup functions I need to compare many condition for the same value. So I am directly coparing encrypted values. But as new value is created. I am unable to compare those value
Hope I am able to explain mu Use Case | 2020/07/25 | [
"https://Stackoverflow.com/questions/63084330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3481508/"
] | Take a look at - <https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes?view=netcore-3.1>
This class uses a pseudorandom number generator in its work, which means that it is *supposed* to generate different data over time which means that your encrypted data is *supposed* to change. It always decrypts the same, but it isn't intended to be deterministic (producing same output for same inputs)
If you're doing something like storing a password you should use a hashing function (eg SHA256) rather than an encrypting function; they produce the same output for given inputs so you can compare the output today to the output yesterday and if they're the same you can decide that the user typed the same password today as he did yesterday
Ultimately you are probably in (or should want to be in) one of two places:
* you need to store some data securely and be able to retrieve it and turn it back into the data it was, maybe because you're the only person who knows it but it needs to be used or known elsewhere. You need to **encrypt** the data for storage, decrypt it, use it, if you update it you need to re-encrypt and store it again
* you need to be able to confirm some data that someone else knows; they will give you the data and you will check your record and decide whether they got it right or not. You need to **hash** the data then forget the original, the next time the person appears claiming they know the original data you hash what they claim it is and compare the hashes. If it's the same then their claim they know the data is correct
You might be wanting to have an encryption that is deterministic, but it's quite a rare thing to want and it feels more like you're misunderstanding some aspect of your use case. Go into more detail so we can better advise | If you encrypt the same value it will give you different result, it’s basically security and most of the encryptions work in this manner.
If it gives you same results on each encryption then it will be deterministic and should be avoided. |
56,806,407 | This is using bash 4.3.48.
```
$ ARR=(entry1 entry2 entry3)
$ echo "${ARR[*]}"
entry1 entry2 entry3
```
Things work as expected until here, but after
```
$ { IFS=: ; echo "${ARR[*]}" ;}
entry1:entry2:entry3
```
IFS is strangely changed half persistently after the change
```
$ echo "${ARR[*]}"
entry1:entry2:entry3
$ echo $IFS
$ echo "$IFS"
:
```
As I cannot get my head around this behaviour, I would assume this is a bug. There might be a connection to [IFS change with Bash 4.2](https://stackoverflow.com/questions/24929819/ifs-change-with-bash-4-2). | 2019/06/28 | [
"https://Stackoverflow.com/questions/56806407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485767/"
] | >
>
> ```
> $ echo $IFS
>
> $ echo "$IFS"
> :
>
> ```
>
>
Writing a variable expansion without double quotes makes it subject to word splitting (and globbing). Word splitting splits a string up by the characters in `$IFS`. When you write `$var` it's as if there's a hidden function call `split+glob($var)`.
If you think about it, writing `$IFS` without quotes is doomed to failure. It splits up `$IFS` by the characters inside `$IFS`. How meta. The result is an empty string, no matter what `$IFS` is set to:
```
$ (IFS='abc'; echo $IFS)
$ (IFS='<>'; echo $IFS)
$ (IFS='!@#$'; echo $IFS)
```
Lesson: Always quote variable expansions.
```
$ (IFS='abc'; echo "$IFS")
abc
$ (IFS='<>'; echo "$IFS")
<>
$ (IFS='!@#$'; echo "$IFS")
!@#$
``` | `{ ... ; }` runs the commands in the context of the current shell. $IFS (or any other variable) changed inside curly braces keeps its value even after the closing brace.
To localise a change of a variable, use a subshell (round parentheses):
```
(IFS=:; echo "${arr[*]}")
```
The reason why `echo $IFS` doesn't output a colon is different. In fact, after $IFS has been set to `:`, any variable containing `:` prints empty:
```
IFS=:
x=:
echo $x # Nothing!
```
That's because the variable without double quotes undergoes word splitting which uses $IFS to define the separator.
```
x=a:b:c
echo $x # a:b:c
IFS=:
echo $x # a b c
```
In the second case, echo has three parameters. When you `echo $IFS`, there's no parameter, regardless of what the current value of $IFS is. |
56,806,407 | This is using bash 4.3.48.
```
$ ARR=(entry1 entry2 entry3)
$ echo "${ARR[*]}"
entry1 entry2 entry3
```
Things work as expected until here, but after
```
$ { IFS=: ; echo "${ARR[*]}" ;}
entry1:entry2:entry3
```
IFS is strangely changed half persistently after the change
```
$ echo "${ARR[*]}"
entry1:entry2:entry3
$ echo $IFS
$ echo "$IFS"
:
```
As I cannot get my head around this behaviour, I would assume this is a bug. There might be a connection to [IFS change with Bash 4.2](https://stackoverflow.com/questions/24929819/ifs-change-with-bash-4-2). | 2019/06/28 | [
"https://Stackoverflow.com/questions/56806407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485767/"
] | >
>
> ```
> $ echo $IFS
>
> $ echo "$IFS"
> :
>
> ```
>
>
Writing a variable expansion without double quotes makes it subject to word splitting (and globbing). Word splitting splits a string up by the characters in `$IFS`. When you write `$var` it's as if there's a hidden function call `split+glob($var)`.
If you think about it, writing `$IFS` without quotes is doomed to failure. It splits up `$IFS` by the characters inside `$IFS`. How meta. The result is an empty string, no matter what `$IFS` is set to:
```
$ (IFS='abc'; echo $IFS)
$ (IFS='<>'; echo $IFS)
$ (IFS='!@#$'; echo $IFS)
```
Lesson: Always quote variable expansions.
```
$ (IFS='abc'; echo "$IFS")
abc
$ (IFS='<>'; echo "$IFS")
<>
$ (IFS='!@#$'; echo "$IFS")
!@#$
``` | The `{ ... }` does not run in a subshell. So all changes within `{ .. }` are visible in the *current* shell.
```
{ a=1; }; echo $a
```
That includes IFS. You have set `IFS=:` and the change stays after the braces.
```
{ IFS=:; }; echo "$IFS"
```
Now we come to expansion and [word splitting](https://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html). This is why no matter what the IFS is set to the following will always print an empty line:
```
echo $IFS
```
IFS is the delimiter itself. The above `echo` receives one argument that is empty. `echo $IFS` is equivalent to `echo ''`. Example: Try it out, what will the following print:
```
IFS=@; echo Hello${IFS}world
```
To print the IFS value, you have to quote it, otherwise it acts as word splitter.
The way to print array members separated by the first character inside IFS is to use a subshell `( .. )`:
```
( IFS=:; echo "${arr[*]}"; )
``` |
26,508,203 | I'm working on a custom password validation that will do a bunch of extra checks, ideally including that the password the user is trying to create doesn't contain any permutations of their username.
We're using the Identity Framework, and my original intent was to just extend IIdentityValidator like this:
```
public class StrongPasswordValidator : IIdentityValidator<string>
{
public int MinimumLength { get; set; }
public int MaximumLength { get; set; }
public void CustomPasswordValidator(int minimumLength, int maximumLength)
{
this.MinimumLength = minimumLength;
this.MaximumLength = maximumLength;
}
public Task<IdentityResult> ValidateAsync(string item)
{
if (item.Length < MinimumLength)
{
return Task.FromResult(IdentityResult.Failed("Password must be a minimum of " + MinimumLength + " characters."));
}
if (item.Length > MaximumLength)
{
return Task.FromResult(IdentityResult.Failed("Password must be a maximum of " + MaximumLength + " characters."));
}
return Task.FromResult(IdentityResult.Success);
}
}
```
But that can only take a string as an argument per the UserManager. Is there any way to pull in the username/a custom object here as well, or otherwise compare the password string to the username before persisting the information?
**EDIT**
For context, this is how the password validator is set and used.
UserManager:
```
public CustomUserManager(IUserStore<User> store,
IPasswordHasher passwordHasher,
IIdentityMessageService emailService)
: base(store)
{
//Other validators
PasswordValidator = new StrongPasswordValidator
{
MinimumLength = 8,
MaximumLength = 100
};
PasswordHasher = passwordHasher;
EmailService = emailService;
}
```
User creation:
```
var userManager = new CustomUserManager(userStore,
new BCryptHasher(), emailService.Object);
userManager.CreateAsync(user, Password);
``` | 2014/10/22 | [
"https://Stackoverflow.com/questions/26508203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/865773/"
] | Instead of using the `PasswordValidator` use the `UserValidator` which will allow you to use your user object as the argument. The type for `ValidateAsync` comes from the generic parameter.
```
public class MyUserValidator : IIdentityValidator<User>
{
public Task<IdentityResult> ValidateAsync(User item)
{
...
}
}
```
In your usermanager register it...
```
public ApplicationUserManager(IUserStore<User> store)
: base(store)
{
UserValidator = new MyUserValidator<User>(...);
}
``` | Just add one/many field(s) of the type you wish in `StrongPasswordValidator`, and inject the values in constructor
```
public class StrongPasswordValidator : IIdentityValidator<string>
{
public int MinimumLength { get; set; }
public int MaximumLength { get; set; }
private readonly MyCustomObjectType _myCustomObject;
public void CustomPasswordValidator(int minimumLength, int maximumLength,
MyCustomObjectType myCustomObject)
{
// guard clause
if(myCustomObject == null)
{
throw new ArgumentExpcetion("myCustomObject was not provided.");
}
_myCustomObject = myCustomObject;
this.MinimumLength = minimumLength;
this.MaximumLength = maximumLength;
}
public Task<IdentityResult> ValidateAsync(string item)
{
// use _myCustomObject here
if (item.Length < MinimumLength)
{
return Task.FromResult(IdentityResult.Failed("Password must be a minimum of " + MinimumLength + " characters."));
}
if (item.Length > MaximumLength)
{
return Task.FromResult(IdentityResult.Failed("Password must be a maximum of " + MaximumLength + " characters."));
}
return Task.FromResult(IdentityResult.Success);
}
}
```
Now, when you will create instance of `StrongPasswordValidator`, you can inject your custom object.
```
MyCustomObjectType myCustomObject = new MyCustomObjectType();
UserManager.PasswordValidator = new StrongPasswordValidator(6, 10, myCustomObject);
```
**EDIT**
Based on updated post, what stops you from newing up `StrongPasswordValidator` by passing to its constructor the object you need.
```
public CustomUserManager(IUserStore<User> store,
IPasswordHasher passwordHasher,
IIdentityMessageService emailService)
: base(store)
{
//Other validators
MyCustomObjectType myCustomObject = new MyCustomObjectType();
PasswordValidator = new StrongPasswordValidator(8, 100, myCustomObject);
PasswordHasher = passwordHasher;
EmailService = emailService;
}
```
And then create a user.
```
var userManager = new CustomUserManager(userStore,
new BCryptHasher(), emailService.Object);
userManager.CreateAsync(user, Password);
``` |
680,715 | Can you use C++.Net for writting a Silverlight application? Not use C# or VB.Net as the backend language but C++.Net | 2009/03/25 | [
"https://Stackoverflow.com/questions/680715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81948/"
] | You can use any language so long as it compiles to pure managed code. For example there are Silverlight applications using IronPython, IronRuby. The only restriction is you can't have any native code, or use parts of the FCL that are restricted by Silverlight (e.g. P/Invoke) | Check [this](http://silverlight.net/forums/p/5329/164934.aspx#164934). A google search would have answered your query.
Update: I was wrong. Apologies for that. Mark has answered it correctly.
Mark : You can use any language so long as it compiles to pure managed code. For example there are Silverlight applications using IronPython, IronRuby. The only restriction is you can't have any native code, or use parts of the FCL that are restricted by Silverlight (e.g. P/Invoke) |
78,539 | I've been working on a site for a new company that is in the tactical gear/survival gear niche and have ran into a hitch with the keywords that Google ranks for the site.
Namely 4 of the top 5 keywords aren't content related at all, and are elements/functions of the site. The top 5 are as follows:
1. Tactical
2. Cart
3. Compare
4. Wishlist
5. Quick (from a quick-view function on the site)
My question is how the heck can I avoid this issue? Or CAN I avoid this issue? | 2015/03/25 | [
"https://webmasters.stackexchange.com/questions/78539",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/50875/"
] | Just looking at your list, it looks like you need more content. If things like "cart, compare, and wishlist' are ranking because of some buttons on your site, you need more blogs or text related to your niche.
In other words, your descriptions and posts should outnumber and overwhelm your store keywords. | Use textalyser.net and run your pages through it. It will list you the top keywords as well as the top pairs of keywords and if you don't want google to rank for a keyword, then try to make the keyword density for it to under 1%. Just make sure at the same time you don't make any keyword density set to over 5%. |
78,539 | I've been working on a site for a new company that is in the tactical gear/survival gear niche and have ran into a hitch with the keywords that Google ranks for the site.
Namely 4 of the top 5 keywords aren't content related at all, and are elements/functions of the site. The top 5 are as follows:
1. Tactical
2. Cart
3. Compare
4. Wishlist
5. Quick (from a quick-view function on the site)
My question is how the heck can I avoid this issue? Or CAN I avoid this issue? | 2015/03/25 | [
"https://webmasters.stackexchange.com/questions/78539",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/50875/"
] | The content keyword list in Google Webmaster Tools measures which keywords are used on the most pages on your site compared to other sites. So if you have a shopping cart on every page of your site, you will have "cart" in your content keywords. Words like "the" don't show up in the list because most sites have them on every page.
As long as this list doesn't have spam words on it, it isn't hurting you. Google says that you should watch this list to see if your site is hacked. If you see "viagra" on this list, then you know there is a problem.
The words on this list **don't** indicate what you are likely to rank for. Google's relevance algorithms are much more sophisticated than "used on many pages of your site." The relevance algorithms take into account:
* If the word is used in the title
* If the word is used near the beginning of the title
* If the word appears in headings
* If the word appears multiple times on the page
* If the word is used in inbound anchor text
* If users click on your site Google puts it in the search results for that term
The "content keywords" don't appear to factor in any of these other relevancy factors, just how many pages on your site use the words.
I've tried adjusting the words on my site to make this content keywords list more accurately reflect the thing I would like the site to rank for. In my experience, doing so doesn't help. Using a word on more pages on my site doesn't seem to help my rank better for those keywords. Removing irrelevant keywords doesn't make the remaining keywords rank better.
Bottom line: don't worry about the content keywords unless there is spam listed. | Use textalyser.net and run your pages through it. It will list you the top keywords as well as the top pairs of keywords and if you don't want google to rank for a keyword, then try to make the keyword density for it to under 1%. Just make sure at the same time you don't make any keyword density set to over 5%. |
78,539 | I've been working on a site for a new company that is in the tactical gear/survival gear niche and have ran into a hitch with the keywords that Google ranks for the site.
Namely 4 of the top 5 keywords aren't content related at all, and are elements/functions of the site. The top 5 are as follows:
1. Tactical
2. Cart
3. Compare
4. Wishlist
5. Quick (from a quick-view function on the site)
My question is how the heck can I avoid this issue? Or CAN I avoid this issue? | 2015/03/25 | [
"https://webmasters.stackexchange.com/questions/78539",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/50875/"
] | The content keyword list in Google Webmaster Tools measures which keywords are used on the most pages on your site compared to other sites. So if you have a shopping cart on every page of your site, you will have "cart" in your content keywords. Words like "the" don't show up in the list because most sites have them on every page.
As long as this list doesn't have spam words on it, it isn't hurting you. Google says that you should watch this list to see if your site is hacked. If you see "viagra" on this list, then you know there is a problem.
The words on this list **don't** indicate what you are likely to rank for. Google's relevance algorithms are much more sophisticated than "used on many pages of your site." The relevance algorithms take into account:
* If the word is used in the title
* If the word is used near the beginning of the title
* If the word appears in headings
* If the word appears multiple times on the page
* If the word is used in inbound anchor text
* If users click on your site Google puts it in the search results for that term
The "content keywords" don't appear to factor in any of these other relevancy factors, just how many pages on your site use the words.
I've tried adjusting the words on my site to make this content keywords list more accurately reflect the thing I would like the site to rank for. In my experience, doing so doesn't help. Using a word on more pages on my site doesn't seem to help my rank better for those keywords. Removing irrelevant keywords doesn't make the remaining keywords rank better.
Bottom line: don't worry about the content keywords unless there is spam listed. | Just looking at your list, it looks like you need more content. If things like "cart, compare, and wishlist' are ranking because of some buttons on your site, you need more blogs or text related to your niche.
In other words, your descriptions and posts should outnumber and overwhelm your store keywords. |
201,855 | Using three parts name in SQL statements is a good practice it helps in object identification and performance improvement as well. It can also help for many other purposes like if you want to move SPs,View Functions to different database with same T-SQL statement..
So I wanted to create a policy which can enforce developers to use "Three Part Naming" when they'll create SPs, Views and functions.
Is there any inbuilt policy or way in SQL Server 2016 which can help me out?
Response will be appreciated.. :) | 2018/03/21 | [
"https://dba.stackexchange.com/questions/201855",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/91078/"
] | Using three-part names in queries that reference objects in the current database is a terrible practice and you should create a rule *against* it. The most frequent problem with it is that it prevents you from having two instances of your application database on a single server, and can lead to unintentional cross-database access.
Using two-part names in dynamic SQL has some, slight, performance benefit as the object name resolution doen't have to check the user's default schema and then the `dbo` schema. But in a view or stored procedure is not as helpful as object name resolution uses the object's schema. And in the paradigm case of a proc/view in `dbo` referencing a table in `dbo` it doesn't help at all. | Please follow this link. Might help you.
<https://www.mssqltips.com/sqlservertip/2298/enforce-sql-server-database-naming-conventions-using-policy-based-management/> |
56,538,388 | I tried to add product programmatically. and i use below code
```
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$paramater = array(
'product' => $product->getId(),
'related_product' => null,
'qty' => 1,
'form_key' => Mage::getSingleton('core/session')->getFormKey()
);
$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();
```
This code is working fine after login. but before login i am getting following error.
>
> a:5:{i:0;s:640:"SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db_magento_nua`.`sales_flat_quote_item`, CONSTRAINT `FK_SALES_FLAT_QUOTE_ITEM_QUOTE_ID_SALES_FLAT_QUOTE_ENTITY_ID` FOREIGN KEY (`quote_id`) REFERENCES `sales_flat_quote` (`entity_id`) ON DELE), query was: INSERT INTO `sales_flat_quote_item` (`created_at`, `updated_at`, `product_id`, `store_id`, `is_virtual`, `sku`, `name`, `is_qty_decimal`, `weight`, `qty`, `custom_price`, `product_type`, `original_custom_price`, `base_cost`) VALUES ('2019-06-11 12:17:58', '2019-06-11 12:17:58', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";i:1;s:2586:"#0 /var/www/html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend\_Db\_Statement\_Pdo->\_execute(Array)
>
>
>
Can some one help me to fix the issue. Thanks in advance. | 2019/06/11 | [
"https://Stackoverflow.com/questions/56538388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5336831/"
] | I found the solution to remove class placeholder
```
<div class="card-image placeholder">
<a [routerLink]="somelink">
<img src="{{url}}/someimage"
onError="this.src='image';"
onload="this.parentNode.parentNode.classList.remove('placeholder');">
</a>
</div>
``` | you can introduce boolean property isPlaceholder with default value 'true' in component class
and modify template like this:
```
<div class="card-image" [ngClass]="{'placeholder': isPlaceholder}">
<a [routerLink]="somelink">
<img src="{{url}}/someimage"
onError="this.src='image';"
(load)="isPlaceholder = false">
</a>
</div>
```
for adding animations, please refer to <https://angular.io/guide/animations>
**update**
here is the example on codepen <https://codepen.io/anon/pen/OeJxaX> |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | Probably you're using the Git Bash terminal, MinTTY, which doesn't have full support for TTY.
You have 4 options to fix the problem:
1. Use CMD terminal with the **Windows shell** (the default Windows console)
2. Use CMD terminal with the **Bash shell** (execute `"C:\Program Files\Git\bin\bash.exe" --login -i` in cmd terminal)
3. Use Powershell (an alternative terminal typically installed by default in Windows environments)
4. Use an alternative terminal (or develop a new one :stuck\_out\_tongue\_winking\_eye: )
If you just need execute isolated interactive commands like `karma init`, I recommend **option 1** for it and then come back to Git Bash. However I would give a try to Powershell. | In my case, the problem was that I was using the git bash terminal in windows. When I ran the command in a cmd window it worked fine. |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | The reason for the error with running npm in Cygwin seems to be a known issue with npm. You can use the work around mentioned here,
<https://stackoverflow.com/a/22436199/2390020> | In my case, the problem was that I was using the git bash terminal in windows. When I ran the command in a cmd window it worked fine. |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | The reason for the error with running npm in Cygwin seems to be a known issue with npm. You can use the work around mentioned here,
<https://stackoverflow.com/a/22436199/2390020> | If you open up the `karma` file it's just a node script, so an alternative way of executing it would be:
```
node karma init
```
This worked for me in the MINGW64/git bash shell |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | I got the same error with MINGW64.
Runs properly on default command prompt. | If you open up the `karma` file it's just a node script, so an alternative way of executing it would be:
```
node karma init
```
This worked for me in the MINGW64/git bash shell |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | The reason for the error with running npm in Cygwin seems to be a known issue with npm. You can use the work around mentioned here,
<https://stackoverflow.com/a/22436199/2390020> | Run the command in github shell command window. Worked for me. |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | I got the same error with MINGW64.
Runs properly on default command prompt. | In my case, the problem was that I was using the git bash terminal in windows. When I ran the command in a cmd window it worked fine. |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | Faced the same issue.try this
node node\_modules/karma/bin/karma init | If you open up the `karma` file it's just a node script, so an alternative way of executing it would be:
```
node karma init
```
This worked for me in the MINGW64/git bash shell |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | Faced the same issue.try this
node node\_modules/karma/bin/karma init | In my case, the problem was that I was using the git bash terminal in windows. When I ran the command in a cmd window it worked fine. |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | Faced the same issue.try this
node node\_modules/karma/bin/karma init | Run the command in github shell command window. Worked for me. |
19,070,777 | I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
```
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
```
Note that this error is virtually identical to the stack trace reported by [this person](https://stackoverflow.com/questions/18511860/getting-error-regarding-slice-during-karma-angularjs-unit-test-config) a month ago, but that report has received no response. | 2013/09/28 | [
"https://Stackoverflow.com/questions/19070777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10508/"
] | Faced the same issue.try this
node node\_modules/karma/bin/karma init | One other likely relevant point that I failed to mention is that I was running these commands from a Cygwin rxvt window.
I just tried completely uninstalling nodejs and reinstalling it.
When I brought up the rxvt window again and ran "npm install -g karma", it failed with the following:
```
/c/Program Files/nodejs/npm: line 2: $'\r': command not found
/c/Program Files/nodejs/npm: line 4: $'\r': command not found
/c/Program Files/nodejs/npm: line 5: syntax error near unexpected token `$'in\r''
'c/Program Files/nodejs/npm: line 5: `case `uname` in
```
That led me to search for that error on the web, and I found this [thread](https://github.com/isaacs/npm/issues/3710), which implies that it simply doesn't support Cygwin (unfortunate, but not a huge problem).
When I then brought up a plain, ugly, unfriendly "cmd" window, both the karma installation and "karma init" completed successfully (or at least it gave me the first question in the "init" process). |
74,476,789 | I have these two lists:
```cs
List<image> ImagesByPerimeterId
List<PerimeterTile> ImagesWithMorePerimeters
```
The context is the following:
I want to remove images that contain the id found in the `ImagesWithMorePerimeters` list from the `ImagesByPerimeterId` list. The `ImagesWithMorePerimeters` list has an `imageId` attribute to compare with the first one.
I have implemented this logic, and it works very well:
```cs
foreach(var i in ImagesByPerimeterId)
{
foreach(var j in ImagesWithMorePerimeters)
{
if (i.Id == j.ImageId)
{
ImagesByPerimeterId.Remove(i);
}
}
}
```
but I'm looking for a simpler way to compare these lists. Any suggestions?
I tried to use `list.Except()`, but as the lists are different objects, that did not make it | 2022/11/17 | [
"https://Stackoverflow.com/questions/74476789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19943087/"
] | **Revised answer**
Unfortunately, using `Get-ADGroupMember` together with switch `-Recursive` will **not** return members that are groups.
As [the docs](https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adgroupmember?view=windowsserver2022-ps#description) state:
>
> If the Recursive parameter is specified, the cmdlet gets all members
> in the hierarchy of the group that do not contain child objects.
>
>
>
To get an array of nested group objects within a certain parent group, you will need a recursive function like below (untested):
```
function Get-NestedADGroup {
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$Group,
# the other parameters are optional
[string]$Server = $null,
[string]$SearchBase = $null,
[ValidateSet('Base', 'OneLevel', 'Subtree')]
[string]$SearchScope = 'Subtree'
)
$params = @{
Identity = $Group
SearchScope = $SearchScope
Properties = 'Members'
ErrorAction = 'SilentlyContinue'
}
if (![string]::IsNullOrWhiteSpace($Server)) { $params['Server'] = $Server }
if (![string]::IsNullOrWhiteSpace($SearchBase)) { $params['SearchBase'] = $SearchBase }
$adGroup = Get-ADGroup @params
if ($adGroup) {
if (-not $script:groupsHash.ContainsKey($Group)) {
# output this group object
$adGroup
$script:groupsHash[$Group] = $true
# and recurse to get the nested groups
foreach ($group in ($adGroup.Members | Where-Object {$_.objectClass -eq 'group'})) {
Get-NestedADGroup -Group $group.DistinguishedName -Server $Server -SearchBase $SearchBase
}
}
}
else {
Write-Warning "Group '$($Group)' could not be found.."
}
}
# create a Hashtable to avoid circular nested groups
$groupsHash = @{}
# call the function
$result = Get-NestedADGroup -Group 'TheGroupToInspect'
# output just the names
$result.Name
``` | Another take to [Theo's helpful answer](https://stackoverflow.com/a/74478184/15339544) using a [`Stack<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1?view=net-7.0) instead of recursion.
**Note, this function will output unique objects, i.e.: if a user was a member of more than one nested group, said user will be only outputted once (same applies for any `ObjectClass`).**
```bash
function Get-ADGroupMemberRecursive {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[alias('DistinguishedName')]
[string] $Identity,
[Parameter()]
[string[]] $Properties,
[Parameter()]
[string] $Server
)
begin {
$adGroupParams = @{
Properties = 'member'
}
$adObjParams = @{ }
if($PSBoundParameters.ContainsKey('Properties')) {
$adObjParams['Properties'] = $Properties
}
if($PSBoundParameters.ContainsKey('Server')) {
$adObjParams['Server'] = $Server
$adGroupParams['Server'] = $Server
}
}
process {
$hash = [Collections.Generic.HashSet[guid]]::new()
$stack = [Collections.Generic.Stack[string]]::new()
$stack.Push($Identity)
while($stack.Count) {
$adGroupParams['Identity'] = $stack.Pop()
foreach($member in (Get-ADGroup @adGroupParams).member) {
$adObjParams['Identity'] = $member
foreach($item in Get-ADObject @adObjParams) {
if($hash.Add($item.ObjectGuid)) {
if($item.ObjectClass -eq 'group') {
$stack.Push($item.DistinguishedName)
}
$item
}
}
}
}
}
}
```
Usage is fairly straight forward:
```bash
# positional binding
Get-ADGroupMemberRecursive groupNameHere
# or through pipeline
Get-ADGroup groupNameHere | Get-ADGroupMemberRecursive
``` |
11,496 | I am running Hierarchical Dirichlet Process, HDP using gensim in Python but as my corpus is too large it is throwing me following error:
```
model = gensim.models.HdpModel(corpus, id2word=corpus.id2word, chunksize=50000)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 210, in __init__
self.update(corpus)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 245, in update
self.update_chunk(chunk)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 313, in update_chunk
self.update_lambda(ss, word_list, opt_o)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 415, in update_lambda
rhot * self.m_D * sstats.m_var_beta_ss / sstats.m_chunksize
MemoryError
```
I have loaded my corpus using following statement:
```
corpus = gensim.corpora.MalletCorpus('chunk5000K_records.mallet')
```
And the data which I used to load corpus has 5 million records. And this is working for me when I am loading only 50K records. So I have added chunksize option HdpModel but it is still giving me an error.
Please let me know how I can solve this issue. And I am running this on High Performance Computing so I think there should be a solution to resolve this issue as this cluster has really big size memory and disk capacity. | 2016/04/29 | [
"https://datascience.stackexchange.com/questions/11496",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/18275/"
] | This all depends on the needs and the budget for the models. The first cleaning steps usually bring a decent increase in performance. The more steps you take the slower the improvements will increase in general. If you are doing something for yourself, cut it off at a certain point, if you are doing it for somebody else, ask them what they want and how much they are willing to pay for it. It's comparable to the 80/20 rule where the first 20% of the total work will help with 80% of the performance.
On another note, your statement about robust algorithms should tolerate with data qualities, you have to be careful with this. If there are biases in your data (missing values are not random for example) they will not learn properly, no matter how robust your algorithm is. Spending time using domain knowledge to fix this properly will help a lot. | I would say do as much cleaning and possible. The phrase "Garbage in, garbage out" is here for a reason.
Missing values, different definitions, suspicious information...all must be cleaned before fetched into any model.
Sure, even without all of this, the model will produce something, but it most likely will be less than optimal. |
11,496 | I am running Hierarchical Dirichlet Process, HDP using gensim in Python but as my corpus is too large it is throwing me following error:
```
model = gensim.models.HdpModel(corpus, id2word=corpus.id2word, chunksize=50000)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 210, in __init__
self.update(corpus)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 245, in update
self.update_chunk(chunk)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 313, in update_chunk
self.update_lambda(ss, word_list, opt_o)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 415, in update_lambda
rhot * self.m_D * sstats.m_var_beta_ss / sstats.m_chunksize
MemoryError
```
I have loaded my corpus using following statement:
```
corpus = gensim.corpora.MalletCorpus('chunk5000K_records.mallet')
```
And the data which I used to load corpus has 5 million records. And this is working for me when I am loading only 50K records. So I have added chunksize option HdpModel but it is still giving me an error.
Please let me know how I can solve this issue. And I am running this on High Performance Computing so I think there should be a solution to resolve this issue as this cluster has really big size memory and disk capacity. | 2016/04/29 | [
"https://datascience.stackexchange.com/questions/11496",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/18275/"
] | This is a question that is very dependent upon the data in question. Assuming that you can train your models in a reasonable time, I would start by not cleaning the data at all, and seeing how well your model performs, and then cleaning it a bit and redoing the experiment and so on.
This is because it is possible to **overclean** your data, essentially removing variations in the data which are actually useful to your modelling.
The amount of cleaning that you apply is yet another meta-variable in your model. | This all depends on the needs and the budget for the models. The first cleaning steps usually bring a decent increase in performance. The more steps you take the slower the improvements will increase in general. If you are doing something for yourself, cut it off at a certain point, if you are doing it for somebody else, ask them what they want and how much they are willing to pay for it. It's comparable to the 80/20 rule where the first 20% of the total work will help with 80% of the performance.
On another note, your statement about robust algorithms should tolerate with data qualities, you have to be careful with this. If there are biases in your data (missing values are not random for example) they will not learn properly, no matter how robust your algorithm is. Spending time using domain knowledge to fix this properly will help a lot. |
11,496 | I am running Hierarchical Dirichlet Process, HDP using gensim in Python but as my corpus is too large it is throwing me following error:
```
model = gensim.models.HdpModel(corpus, id2word=corpus.id2word, chunksize=50000)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 210, in __init__
self.update(corpus)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 245, in update
self.update_chunk(chunk)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 313, in update_chunk
self.update_lambda(ss, word_list, opt_o)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 415, in update_lambda
rhot * self.m_D * sstats.m_var_beta_ss / sstats.m_chunksize
MemoryError
```
I have loaded my corpus using following statement:
```
corpus = gensim.corpora.MalletCorpus('chunk5000K_records.mallet')
```
And the data which I used to load corpus has 5 million records. And this is working for me when I am loading only 50K records. So I have added chunksize option HdpModel but it is still giving me an error.
Please let me know how I can solve this issue. And I am running this on High Performance Computing so I think there should be a solution to resolve this issue as this cluster has really big size memory and disk capacity. | 2016/04/29 | [
"https://datascience.stackexchange.com/questions/11496",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/18275/"
] | This all depends on the needs and the budget for the models. The first cleaning steps usually bring a decent increase in performance. The more steps you take the slower the improvements will increase in general. If you are doing something for yourself, cut it off at a certain point, if you are doing it for somebody else, ask them what they want and how much they are willing to pay for it. It's comparable to the 80/20 rule where the first 20% of the total work will help with 80% of the performance.
On another note, your statement about robust algorithms should tolerate with data qualities, you have to be careful with this. If there are biases in your data (missing values are not random for example) they will not learn properly, no matter how robust your algorithm is. Spending time using domain knowledge to fix this properly will help a lot. | Data cleaning can be a real pain and also can easily take you away from the core task. Nevertheless, it is one of the critical aspect and hence cannot be taken lightly.
I believe you have the right idea because you mentioned that you are seeking `balance`. I always think of data cleaning as a marginal transaction. Beyond a certain point, it is not worth the time.
As [Jan van](https://datascience.stackexchange.com/users/14904/jan-van-der-vegt) mentioned, it all depends on your needs. If your model could be very sensitive to certain features, its better to have them cleaned religiously. If what you are looking for are broader insights, even a general clean of important features can work. The trick is to really understand the tipping point which can come with experience and / or knowledge of the data set.
There is this approach that my team takes often and has worked so far.
```
1. Once you know what model fits your problem, throw in a feature with random values.
2. Model your data set with minimal / basic cleaning.
3. Plot or tabulate accuracy for all features.
4. Drop all features that perform equal or worse than the random feature.
5. Some times depending on the accuracy even drop features that perform slightly higher than random.
```
Using this, we are mostly able to get rid of unnecessary features that hog up tidying effort.
Wash Rinse Repeat. |
11,496 | I am running Hierarchical Dirichlet Process, HDP using gensim in Python but as my corpus is too large it is throwing me following error:
```
model = gensim.models.HdpModel(corpus, id2word=corpus.id2word, chunksize=50000)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 210, in __init__
self.update(corpus)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 245, in update
self.update_chunk(chunk)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 313, in update_chunk
self.update_lambda(ss, word_list, opt_o)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 415, in update_lambda
rhot * self.m_D * sstats.m_var_beta_ss / sstats.m_chunksize
MemoryError
```
I have loaded my corpus using following statement:
```
corpus = gensim.corpora.MalletCorpus('chunk5000K_records.mallet')
```
And the data which I used to load corpus has 5 million records. And this is working for me when I am loading only 50K records. So I have added chunksize option HdpModel but it is still giving me an error.
Please let me know how I can solve this issue. And I am running this on High Performance Computing so I think there should be a solution to resolve this issue as this cluster has really big size memory and disk capacity. | 2016/04/29 | [
"https://datascience.stackexchange.com/questions/11496",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/18275/"
] | This is a question that is very dependent upon the data in question. Assuming that you can train your models in a reasonable time, I would start by not cleaning the data at all, and seeing how well your model performs, and then cleaning it a bit and redoing the experiment and so on.
This is because it is possible to **overclean** your data, essentially removing variations in the data which are actually useful to your modelling.
The amount of cleaning that you apply is yet another meta-variable in your model. | I would say do as much cleaning and possible. The phrase "Garbage in, garbage out" is here for a reason.
Missing values, different definitions, suspicious information...all must be cleaned before fetched into any model.
Sure, even without all of this, the model will produce something, but it most likely will be less than optimal. |
11,496 | I am running Hierarchical Dirichlet Process, HDP using gensim in Python but as my corpus is too large it is throwing me following error:
```
model = gensim.models.HdpModel(corpus, id2word=corpus.id2word, chunksize=50000)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 210, in __init__
self.update(corpus)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 245, in update
self.update_chunk(chunk)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 313, in update_chunk
self.update_lambda(ss, word_list, opt_o)
File "/usr/cluster/contrib/Enthought/Canopy_64/User/lib/python2.7/site-packages/gensim/models/hdpmodel.py", line 415, in update_lambda
rhot * self.m_D * sstats.m_var_beta_ss / sstats.m_chunksize
MemoryError
```
I have loaded my corpus using following statement:
```
corpus = gensim.corpora.MalletCorpus('chunk5000K_records.mallet')
```
And the data which I used to load corpus has 5 million records. And this is working for me when I am loading only 50K records. So I have added chunksize option HdpModel but it is still giving me an error.
Please let me know how I can solve this issue. And I am running this on High Performance Computing so I think there should be a solution to resolve this issue as this cluster has really big size memory and disk capacity. | 2016/04/29 | [
"https://datascience.stackexchange.com/questions/11496",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/18275/"
] | This is a question that is very dependent upon the data in question. Assuming that you can train your models in a reasonable time, I would start by not cleaning the data at all, and seeing how well your model performs, and then cleaning it a bit and redoing the experiment and so on.
This is because it is possible to **overclean** your data, essentially removing variations in the data which are actually useful to your modelling.
The amount of cleaning that you apply is yet another meta-variable in your model. | Data cleaning can be a real pain and also can easily take you away from the core task. Nevertheless, it is one of the critical aspect and hence cannot be taken lightly.
I believe you have the right idea because you mentioned that you are seeking `balance`. I always think of data cleaning as a marginal transaction. Beyond a certain point, it is not worth the time.
As [Jan van](https://datascience.stackexchange.com/users/14904/jan-van-der-vegt) mentioned, it all depends on your needs. If your model could be very sensitive to certain features, its better to have them cleaned religiously. If what you are looking for are broader insights, even a general clean of important features can work. The trick is to really understand the tipping point which can come with experience and / or knowledge of the data set.
There is this approach that my team takes often and has worked so far.
```
1. Once you know what model fits your problem, throw in a feature with random values.
2. Model your data set with minimal / basic cleaning.
3. Plot or tabulate accuracy for all features.
4. Drop all features that perform equal or worse than the random feature.
5. Some times depending on the accuracy even drop features that perform slightly higher than random.
```
Using this, we are mostly able to get rid of unnecessary features that hog up tidying effort.
Wash Rinse Repeat. |
23,204 | I am using Bernoulli's equation in order to calculate a relative area between two points in a pipe. Problem is, based on the solution I have obtained, I end up with imaginary numbers and not sure what to make of this practically. Here is my math:
$$\begin{gather}
P\_1 + \dfrac{1}{2}\rho v\_1^2 + \rho gh\_1 = P\_2 + \dfrac{1}{2}\rho v\_2^2 + \rho gh\_2 \\
v\_1 A\_1 = v\_2 A\_2 \\
\dfrac{A\_1}{A\_2} = \sqrt{\dfrac{v\_2^2}{v\_2^2+\dfrac{2}{\rho}\left(P\_2-P\_1\right)}}
\end{gather}$$
I know my velocity at location 2, density, and pressures. I have no change in height so I got rid of third element in Bernoulli's equation. I am trying to obtain an area ratio between both points.
It is very possible in my model that I will have a low P2 and high P1 leading to a negative denominator and an imaginary solution. I feel like I am missing something practical or mathematical here that is simple but my mind has drawn a blank.
As a side note, I am assuming non-compressible airflow. Cannot assume laminar flow. | 2018/08/12 | [
"https://engineering.stackexchange.com/questions/23204",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/17123/"
] | Unless you are putting "randomly chosen numbers" into your equation, or you have measured the numbers but your assumptions about Bernoulli and compressibility don't apply to your real-world flow situation, you shouldn't have a problem.
Look at it this way: for given values of $P\_2$ and $v\_2$, physically $P\_1$ must always be less than some maximum value - namely, the value when $v\_1 = 0$.
That follows directly from your first equation (your statement of Bernoulli's principle).
That maximum value of $P\_1$ that is physically possible will make the denominator of your square-root equal to zero, or in other words, $A\_1$ will be "infinite" - which of course is correct, if $v\_1$ is zero! | Adding to alephzero,
Imagine you are getting a negative denominator,
$v\_{2}^2 + \frac{2}{\rho}(P\_2 - P\_1) < 0 $,
$\Rightarrow \frac{1}{2}{\rho}v\_{2}^2 +(P\_2 - P\_1) < 0 $ ,
$\Rightarrow \frac{1}{2}{\rho}v\_{2}^2 +P\_2 < P\_1 $ ,
$\Rightarrow P\_{02} < P\_1 $ , This violates the Bernoulli's principle. So you will never get an imaginary velocity value.
As alephzero clearly mentioned, $P\_1 \rightarrow P\_0$ when $v\_1 \rightarrow 0$.
Note: $P\_0$ is the total pressure and it will be constant along the streamline on wihch you apply the Bernoulli's equation. |
23,204 | I am using Bernoulli's equation in order to calculate a relative area between two points in a pipe. Problem is, based on the solution I have obtained, I end up with imaginary numbers and not sure what to make of this practically. Here is my math:
$$\begin{gather}
P\_1 + \dfrac{1}{2}\rho v\_1^2 + \rho gh\_1 = P\_2 + \dfrac{1}{2}\rho v\_2^2 + \rho gh\_2 \\
v\_1 A\_1 = v\_2 A\_2 \\
\dfrac{A\_1}{A\_2} = \sqrt{\dfrac{v\_2^2}{v\_2^2+\dfrac{2}{\rho}\left(P\_2-P\_1\right)}}
\end{gather}$$
I know my velocity at location 2, density, and pressures. I have no change in height so I got rid of third element in Bernoulli's equation. I am trying to obtain an area ratio between both points.
It is very possible in my model that I will have a low P2 and high P1 leading to a negative denominator and an imaginary solution. I feel like I am missing something practical or mathematical here that is simple but my mind has drawn a blank.
As a side note, I am assuming non-compressible airflow. Cannot assume laminar flow. | 2018/08/12 | [
"https://engineering.stackexchange.com/questions/23204",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/17123/"
] | Unless you are putting "randomly chosen numbers" into your equation, or you have measured the numbers but your assumptions about Bernoulli and compressibility don't apply to your real-world flow situation, you shouldn't have a problem.
Look at it this way: for given values of $P\_2$ and $v\_2$, physically $P\_1$ must always be less than some maximum value - namely, the value when $v\_1 = 0$.
That follows directly from your first equation (your statement of Bernoulli's principle).
That maximum value of $P\_1$ that is physically possible will make the denominator of your square-root equal to zero, or in other words, $A\_1$ will be "infinite" - which of course is correct, if $v\_1$ is zero! | >
> As a side note, I am assuming non-compressible airflow. Cannot assume laminar flow.
>
>
>
The assumptions that $\dot{V}\_1 = v\_1 A\_1 = v\_2 A\_2 = \dot{V}\_2$ and that $\rho =$ constant are only valid for incompressible flow. Air is compressible, not incompressible. Use the ideal gas law with $\rho = M\_{air}(p/RT)$ and $v = \dot{V}/A = \dot{n}RT/pA$. This gives
$$\dot{n}\_1 = \dot{n}\_2 = \dot{n}$$
$$\frac{RT\_1}{M\_{air}} + \frac{1}{2}\left(\frac{\dot{n}RT\_1}{p\_1 A\_1}\right)^2 = \frac{RT\_2}{M\_{air}} + \frac{1}{2}\left(\frac{\dot{n}RT\_2}{p\_2 A\_2}\right)^2$$
The proper analysis for a compressible (ideal) gas must consider pressure and *temperature* not pressure and *velocity*. Corrections for non-ideality may be applied depending on how drastically the gas is compressed and/or how accurate the answer really must be.
The ratio of areas as a function of velocities for ideal gas flow is expressed as
$$ \frac{A\_1}{A\_2} = \frac{\dot{V}\_1 v\_2}{\dot{V}\_2 v\_1} = \frac{T\_1 v\_2 p\_2}{T\_2 v\_1 p\_1}$$ |
2,913,160 | Is there a way I can count the size of an associated collection without initializing?
e.g.
```
Select count(p.children) from Parent p
```
(there is a good reason why I cant do this any other way as my where clause is more complicated and my from clause is a polymorphic query)
Thanks. | 2010/05/26 | [
"https://Stackoverflow.com/questions/2913160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249571/"
] | A possible solution other than queries might be mapping `children` with `lazy="extra"` (in XML notation). This way, you can fetch the Parent with whatever query you need, then call `parent.getChildren().size()` without loading the whole collection (only a `SELECT COUNT` type query is executed).
With annotations, it would be
```
@OneToMany
@org.hibernate.annotations.LazyCollection(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
private Set<Child> children = new HashSet<Child>();
```
**Update:** Quote from [Java Persistence with Hibernate](http://www.manning.com/bauer2/), ch. 13.1.3:
>
> A proxy is initialized if you call any method that is not the identifier getter
> method, a collection is initialized if you start iterating through its elements or if
> you call any of the collection-management operations, such as `size()` and `contains()`.
> Hibernate provides an additional setting that is mostly useful for large collections; they can be mapped as *extra lazy*. [...]
>
>
> [Mapped as above,] the collection is no longer initialized if you call `size()`, `contains()`, or `isEmpty()` — the database is queried to retrieve the necessary information. If it’s a `Map` or a `List`, the operations `containsKey()`
> and `get()` also query the database directly.
>
>
>
So with an entity mapped as above, you can then do
```
Parent p = // execute query to load desired parent
// due to lazy loading, at this point p.children is a proxy object
int count = p.getChildren().size(); // the collection is not loaded, only its size
``` | You can use Session#createFilter which is a form of HQL which explicitly operates on collections. For example, you mention Parent and Children so if you have a Person p the most basic form would be:
```
session.createFilter( p.getChildren(), "" ).list()
```
This simply returns you a list of the children. It is important to note that the returned collection is not "live", it is not in any way associated with p.
The interesting part comes from the second argument. This is an HQL fragment. Here for example, you might want:
```
session.createFilter( p.getChildren(), "select count(*)" ).uniqueResult();
```
You mentioned you have a where clause, so you also might want:
```
session.createFilter( p.getChildren(), "select count(*) where this.age > 18" ).uniqueResult();
```
Notice there is no from clause. That is to say that the from clause is implied from the association. The elements of the collection are given the alias 'this' so you can refer to it from other parts of the HQL fragment. |
2,913,160 | Is there a way I can count the size of an associated collection without initializing?
e.g.
```
Select count(p.children) from Parent p
```
(there is a good reason why I cant do this any other way as my where clause is more complicated and my from clause is a polymorphic query)
Thanks. | 2010/05/26 | [
"https://Stackoverflow.com/questions/2913160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249571/"
] | A possible solution other than queries might be mapping `children` with `lazy="extra"` (in XML notation). This way, you can fetch the Parent with whatever query you need, then call `parent.getChildren().size()` without loading the whole collection (only a `SELECT COUNT` type query is executed).
With annotations, it would be
```
@OneToMany
@org.hibernate.annotations.LazyCollection(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
private Set<Child> children = new HashSet<Child>();
```
**Update:** Quote from [Java Persistence with Hibernate](http://www.manning.com/bauer2/), ch. 13.1.3:
>
> A proxy is initialized if you call any method that is not the identifier getter
> method, a collection is initialized if you start iterating through its elements or if
> you call any of the collection-management operations, such as `size()` and `contains()`.
> Hibernate provides an additional setting that is mostly useful for large collections; they can be mapped as *extra lazy*. [...]
>
>
> [Mapped as above,] the collection is no longer initialized if you call `size()`, `contains()`, or `isEmpty()` — the database is queried to retrieve the necessary information. If it’s a `Map` or a `List`, the operations `containsKey()`
> and `get()` also query the database directly.
>
>
>
So with an entity mapped as above, you can then do
```
Parent p = // execute query to load desired parent
// due to lazy loading, at this point p.children is a proxy object
int count = p.getChildren().size(); // the collection is not loaded, only its size
``` | You can do the same like this:
```
@Override
public FaqQuestions getFaqQuestionById(Long questionId) {
session = sessionFactory.openSession();
tx = session.beginTransaction();
FaqQuestions faqQuestions = null;
try {
faqQuestions = (FaqQuestions) session.get(FaqQuestions.class,
questionId);
Hibernate.initialize(faqQuestions.getFaqAnswers());
tx.commit();
faqQuestions.getFaqAnswers().size();
} finally {
session.close();
}
return faqQuestions;
}
```
Just use faqQuestions.getFaqAnswers().size()nin your controller and you will get the size if lazily intialised list, without fetching the list itself. |
2,913,160 | Is there a way I can count the size of an associated collection without initializing?
e.g.
```
Select count(p.children) from Parent p
```
(there is a good reason why I cant do this any other way as my where clause is more complicated and my from clause is a polymorphic query)
Thanks. | 2010/05/26 | [
"https://Stackoverflow.com/questions/2913160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249571/"
] | You can use Session#createFilter which is a form of HQL which explicitly operates on collections. For example, you mention Parent and Children so if you have a Person p the most basic form would be:
```
session.createFilter( p.getChildren(), "" ).list()
```
This simply returns you a list of the children. It is important to note that the returned collection is not "live", it is not in any way associated with p.
The interesting part comes from the second argument. This is an HQL fragment. Here for example, you might want:
```
session.createFilter( p.getChildren(), "select count(*)" ).uniqueResult();
```
You mentioned you have a where clause, so you also might want:
```
session.createFilter( p.getChildren(), "select count(*) where this.age > 18" ).uniqueResult();
```
Notice there is no from clause. That is to say that the from clause is implied from the association. The elements of the collection are given the alias 'this' so you can refer to it from other parts of the HQL fragment. | You can do the same like this:
```
@Override
public FaqQuestions getFaqQuestionById(Long questionId) {
session = sessionFactory.openSession();
tx = session.beginTransaction();
FaqQuestions faqQuestions = null;
try {
faqQuestions = (FaqQuestions) session.get(FaqQuestions.class,
questionId);
Hibernate.initialize(faqQuestions.getFaqAnswers());
tx.commit();
faqQuestions.getFaqAnswers().size();
} finally {
session.close();
}
return faqQuestions;
}
```
Just use faqQuestions.getFaqAnswers().size()nin your controller and you will get the size if lazily intialised list, without fetching the list itself. |
68,870,250 | For example, I have this string array
```
const groceries = [
'milk',
'coriander',
'cucumber',
'eggplant',
'carrot',
'brinjal',
'onions',
'tomatoes',
'soap',
'bag',
'pepper',
'salt',
'fruits',
'bread',
'pasta',
'oil',
'butter',
'honey',
'sugar'
];
```
I need to pick a random of three elements from the above groceries list with no-repeat and along with their indexes. | 2021/08/21 | [
"https://Stackoverflow.com/questions/68870250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804085/"
] | Several points to cover here. First, a binary search needs *sorted* data in order to work. As your list is *not* sorted, weirdness and hilarity may ensue :-)
Consider, for example, the unsorted `[27 , 39 , 56, 73, 3, 43, 15, 98, 21]` when you're looking for `39`.
The first midpoint is at value `3` so a binary search will discard the left half entirely (including the 3`) since it expects` 39`to be to the right of that`3`. Hence it will never find` 39`, despite the fact it's in the list.
If your list is unsorted, you're basically stuck with a sequential search.
---
Second, you should be changing `first` *or* `last` depending on the comparison. You change `last` in both cases, which won't end well.
---
Third, it's not usually a good idea to use standard data type names or functions as variable names. Because Python treats classes and functions as first-class objects, you can get into a situation where your bindings break things:
```py
>>> a_tuple = (1, 2) ; a_tuple
(1, 2)
>>> list(a_tuple) # Works.
[1, 2]
>>> list = list(a_tuple) ; list # Works, unintended consequences.
[1, 2]
>>> another_list = list(a_tuple) # No longer works.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
```
---
Covering those issues, your code would look something like this (slightly reorganised in the process):
```py
my_list = [3, 15, 21, 27, 39, 43, 56, 73, 84, 98]
found = False
first, last = 0, len(my_list) - 1
searchValue = int(input("Which number are you looking for? "))
while not found:
if first > last:
break
mid = (first + last) // 2
if my_list[mid] == searchValue:
found = True
else:
if my_list[mid] > searchValue:
last = mid - 1
else:
first = mid + 1
if found:
print("Your number was found at location", mid)
else:
print("The number does not exist within the list")
```
---
That works, according to the following transcript:
```sh
pax> for i in {1..6}; do echo; python prog.py; done
Which number are you looking for? 3
Your number was found at location 0
Which number are you looking for? 39
Your number was found at location 4
Which number are you looking for? 98
Your number was found at location 9
Which number are you looking for? 1
The number does not exist within the list
Which number are you looking for? 40
The number does not exist within the list
Which number are you looking for? 99
The number does not exist within the list
``` | First of all, do not use any reserved word (here `list`) to name your variables. Secondly, you have a logical error in the following lines:
```
if list[mid] > searchValue:
last = mid - 1
else:
last = mid + 1
```
In the last line of the above snippet, it should be `first = mid + 1` |
68,870,250 | For example, I have this string array
```
const groceries = [
'milk',
'coriander',
'cucumber',
'eggplant',
'carrot',
'brinjal',
'onions',
'tomatoes',
'soap',
'bag',
'pepper',
'salt',
'fruits',
'bread',
'pasta',
'oil',
'butter',
'honey',
'sugar'
];
```
I need to pick a random of three elements from the above groceries list with no-repeat and along with their indexes. | 2021/08/21 | [
"https://Stackoverflow.com/questions/68870250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804085/"
] | First of all, do not use any reserved word (here `list`) to name your variables. Secondly, you have a logical error in the following lines:
```
if list[mid] > searchValue:
last = mid - 1
else:
last = mid + 1
```
In the last line of the above snippet, it should be `first = mid + 1` | There are very good answers to this question, also you can consider this simpler version adapted to your case:
```py
my_list = [3, 15, 21, 27, 39, 43, 56, 73, 84, 98] # sorted!
left, right = 0, len(my_list) # [left, right)
search_value = int(input("Which number are you looking for? "))
while left + 1 < right:
mid = (left + right) // 2
if my_list[mid] <= search_value:
left = mid
else:
right = mid
if my_list[left] == search_value: # found!
print("Your number was found at location", left)
else:
print("The number does not exist within the list")
``` |
68,870,250 | For example, I have this string array
```
const groceries = [
'milk',
'coriander',
'cucumber',
'eggplant',
'carrot',
'brinjal',
'onions',
'tomatoes',
'soap',
'bag',
'pepper',
'salt',
'fruits',
'bread',
'pasta',
'oil',
'butter',
'honey',
'sugar'
];
```
I need to pick a random of three elements from the above groceries list with no-repeat and along with their indexes. | 2021/08/21 | [
"https://Stackoverflow.com/questions/68870250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804085/"
] | First of all, do not use any reserved word (here `list`) to name your variables. Secondly, you have a logical error in the following lines:
```
if list[mid] > searchValue:
last = mid - 1
else:
last = mid + 1
```
In the last line of the above snippet, it should be `first = mid + 1` | The problem with your function is that in Binary Search the array or the list needs to be **SORTED** because it's one of the most important principal of binary search, i made same function working correctly for you
```
#low is the first index and high is the last index, val is the value to find, list_ is the list, you can leave low as it is
def binary_search(list_: list, val,high: int, low: int = 0):
mid = (low+high)//2
if list_[mid] == val:
return mid
elif list_[mid] <= val:
return binary_search(list_, val, high+1)
elif list_[mid] >= val:
return binary_search(list_, val, high, low-1)
```
and now here's the output
```
>>> binary_search(list_, 21, len(list_)-1)
>>> 2
```
what will happen here is that first it will calculate the middle index of the list, which i think of your list is 5, then it will check whether the middle value is equal to the value given to search, and then return the mid index, and if the mid index is smaller than the value, then we will tell it to add one to high index, and we did the comparison with index and value because as i told you, list needs to be sorted and this means if index is greater or equal to the mid index then the value is also surely greater than the middle value, so now what we will do is that we will call the same function again but this time with a higher `high` which will increase the mid point and if this time middle index is equal to value, then its gonna return the value and going to do this untill mid is equal to value, and in the last elif it says if middle value is greater than value, we will call same function again but lower the low i.e which is 0 and now -1, which will reduce the mid point and this whole process will continue untill mid is equal to value |
68,870,250 | For example, I have this string array
```
const groceries = [
'milk',
'coriander',
'cucumber',
'eggplant',
'carrot',
'brinjal',
'onions',
'tomatoes',
'soap',
'bag',
'pepper',
'salt',
'fruits',
'bread',
'pasta',
'oil',
'butter',
'honey',
'sugar'
];
```
I need to pick a random of three elements from the above groceries list with no-repeat and along with their indexes. | 2021/08/21 | [
"https://Stackoverflow.com/questions/68870250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804085/"
] | Several points to cover here. First, a binary search needs *sorted* data in order to work. As your list is *not* sorted, weirdness and hilarity may ensue :-)
Consider, for example, the unsorted `[27 , 39 , 56, 73, 3, 43, 15, 98, 21]` when you're looking for `39`.
The first midpoint is at value `3` so a binary search will discard the left half entirely (including the 3`) since it expects` 39`to be to the right of that`3`. Hence it will never find` 39`, despite the fact it's in the list.
If your list is unsorted, you're basically stuck with a sequential search.
---
Second, you should be changing `first` *or* `last` depending on the comparison. You change `last` in both cases, which won't end well.
---
Third, it's not usually a good idea to use standard data type names or functions as variable names. Because Python treats classes and functions as first-class objects, you can get into a situation where your bindings break things:
```py
>>> a_tuple = (1, 2) ; a_tuple
(1, 2)
>>> list(a_tuple) # Works.
[1, 2]
>>> list = list(a_tuple) ; list # Works, unintended consequences.
[1, 2]
>>> another_list = list(a_tuple) # No longer works.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
```
---
Covering those issues, your code would look something like this (slightly reorganised in the process):
```py
my_list = [3, 15, 21, 27, 39, 43, 56, 73, 84, 98]
found = False
first, last = 0, len(my_list) - 1
searchValue = int(input("Which number are you looking for? "))
while not found:
if first > last:
break
mid = (first + last) // 2
if my_list[mid] == searchValue:
found = True
else:
if my_list[mid] > searchValue:
last = mid - 1
else:
first = mid + 1
if found:
print("Your number was found at location", mid)
else:
print("The number does not exist within the list")
```
---
That works, according to the following transcript:
```sh
pax> for i in {1..6}; do echo; python prog.py; done
Which number are you looking for? 3
Your number was found at location 0
Which number are you looking for? 39
Your number was found at location 4
Which number are you looking for? 98
Your number was found at location 9
Which number are you looking for? 1
The number does not exist within the list
Which number are you looking for? 40
The number does not exist within the list
Which number are you looking for? 99
The number does not exist within the list
``` | There are very good answers to this question, also you can consider this simpler version adapted to your case:
```py
my_list = [3, 15, 21, 27, 39, 43, 56, 73, 84, 98] # sorted!
left, right = 0, len(my_list) # [left, right)
search_value = int(input("Which number are you looking for? "))
while left + 1 < right:
mid = (left + right) // 2
if my_list[mid] <= search_value:
left = mid
else:
right = mid
if my_list[left] == search_value: # found!
print("Your number was found at location", left)
else:
print("The number does not exist within the list")
``` |
68,870,250 | For example, I have this string array
```
const groceries = [
'milk',
'coriander',
'cucumber',
'eggplant',
'carrot',
'brinjal',
'onions',
'tomatoes',
'soap',
'bag',
'pepper',
'salt',
'fruits',
'bread',
'pasta',
'oil',
'butter',
'honey',
'sugar'
];
```
I need to pick a random of three elements from the above groceries list with no-repeat and along with their indexes. | 2021/08/21 | [
"https://Stackoverflow.com/questions/68870250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804085/"
] | Several points to cover here. First, a binary search needs *sorted* data in order to work. As your list is *not* sorted, weirdness and hilarity may ensue :-)
Consider, for example, the unsorted `[27 , 39 , 56, 73, 3, 43, 15, 98, 21]` when you're looking for `39`.
The first midpoint is at value `3` so a binary search will discard the left half entirely (including the 3`) since it expects` 39`to be to the right of that`3`. Hence it will never find` 39`, despite the fact it's in the list.
If your list is unsorted, you're basically stuck with a sequential search.
---
Second, you should be changing `first` *or* `last` depending on the comparison. You change `last` in both cases, which won't end well.
---
Third, it's not usually a good idea to use standard data type names or functions as variable names. Because Python treats classes and functions as first-class objects, you can get into a situation where your bindings break things:
```py
>>> a_tuple = (1, 2) ; a_tuple
(1, 2)
>>> list(a_tuple) # Works.
[1, 2]
>>> list = list(a_tuple) ; list # Works, unintended consequences.
[1, 2]
>>> another_list = list(a_tuple) # No longer works.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
```
---
Covering those issues, your code would look something like this (slightly reorganised in the process):
```py
my_list = [3, 15, 21, 27, 39, 43, 56, 73, 84, 98]
found = False
first, last = 0, len(my_list) - 1
searchValue = int(input("Which number are you looking for? "))
while not found:
if first > last:
break
mid = (first + last) // 2
if my_list[mid] == searchValue:
found = True
else:
if my_list[mid] > searchValue:
last = mid - 1
else:
first = mid + 1
if found:
print("Your number was found at location", mid)
else:
print("The number does not exist within the list")
```
---
That works, according to the following transcript:
```sh
pax> for i in {1..6}; do echo; python prog.py; done
Which number are you looking for? 3
Your number was found at location 0
Which number are you looking for? 39
Your number was found at location 4
Which number are you looking for? 98
Your number was found at location 9
Which number are you looking for? 1
The number does not exist within the list
Which number are you looking for? 40
The number does not exist within the list
Which number are you looking for? 99
The number does not exist within the list
``` | The problem with your function is that in Binary Search the array or the list needs to be **SORTED** because it's one of the most important principal of binary search, i made same function working correctly for you
```
#low is the first index and high is the last index, val is the value to find, list_ is the list, you can leave low as it is
def binary_search(list_: list, val,high: int, low: int = 0):
mid = (low+high)//2
if list_[mid] == val:
return mid
elif list_[mid] <= val:
return binary_search(list_, val, high+1)
elif list_[mid] >= val:
return binary_search(list_, val, high, low-1)
```
and now here's the output
```
>>> binary_search(list_, 21, len(list_)-1)
>>> 2
```
what will happen here is that first it will calculate the middle index of the list, which i think of your list is 5, then it will check whether the middle value is equal to the value given to search, and then return the mid index, and if the mid index is smaller than the value, then we will tell it to add one to high index, and we did the comparison with index and value because as i told you, list needs to be sorted and this means if index is greater or equal to the mid index then the value is also surely greater than the middle value, so now what we will do is that we will call the same function again but this time with a higher `high` which will increase the mid point and if this time middle index is equal to value, then its gonna return the value and going to do this untill mid is equal to value, and in the last elif it says if middle value is greater than value, we will call same function again but lower the low i.e which is 0 and now -1, which will reduce the mid point and this whole process will continue untill mid is equal to value |
68,870,250 | For example, I have this string array
```
const groceries = [
'milk',
'coriander',
'cucumber',
'eggplant',
'carrot',
'brinjal',
'onions',
'tomatoes',
'soap',
'bag',
'pepper',
'salt',
'fruits',
'bread',
'pasta',
'oil',
'butter',
'honey',
'sugar'
];
```
I need to pick a random of three elements from the above groceries list with no-repeat and along with their indexes. | 2021/08/21 | [
"https://Stackoverflow.com/questions/68870250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11804085/"
] | There are very good answers to this question, also you can consider this simpler version adapted to your case:
```py
my_list = [3, 15, 21, 27, 39, 43, 56, 73, 84, 98] # sorted!
left, right = 0, len(my_list) # [left, right)
search_value = int(input("Which number are you looking for? "))
while left + 1 < right:
mid = (left + right) // 2
if my_list[mid] <= search_value:
left = mid
else:
right = mid
if my_list[left] == search_value: # found!
print("Your number was found at location", left)
else:
print("The number does not exist within the list")
``` | The problem with your function is that in Binary Search the array or the list needs to be **SORTED** because it's one of the most important principal of binary search, i made same function working correctly for you
```
#low is the first index and high is the last index, val is the value to find, list_ is the list, you can leave low as it is
def binary_search(list_: list, val,high: int, low: int = 0):
mid = (low+high)//2
if list_[mid] == val:
return mid
elif list_[mid] <= val:
return binary_search(list_, val, high+1)
elif list_[mid] >= val:
return binary_search(list_, val, high, low-1)
```
and now here's the output
```
>>> binary_search(list_, 21, len(list_)-1)
>>> 2
```
what will happen here is that first it will calculate the middle index of the list, which i think of your list is 5, then it will check whether the middle value is equal to the value given to search, and then return the mid index, and if the mid index is smaller than the value, then we will tell it to add one to high index, and we did the comparison with index and value because as i told you, list needs to be sorted and this means if index is greater or equal to the mid index then the value is also surely greater than the middle value, so now what we will do is that we will call the same function again but this time with a higher `high` which will increase the mid point and if this time middle index is equal to value, then its gonna return the value and going to do this untill mid is equal to value, and in the last elif it says if middle value is greater than value, we will call same function again but lower the low i.e which is 0 and now -1, which will reduce the mid point and this whole process will continue untill mid is equal to value |
47,037,067 | I am unable to find the location where images and containers are stored in my machine, i checked [this](https://stackoverflow.com/questions/42250222/what-is-docker-image-location-on-windows-10) and with 'docker info' in *Docker Root Dir* i have `/var/lib/docker` , but i'm unable to find this anywhere, | 2017/10/31 | [
"https://Stackoverflow.com/questions/47037067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7660161/"
] | **you need to import from main.js**
`import {HTTP} from './main';` | Try changing
`import {HTTP} from './http-common';` to
`import {HTTP} from '../http-common';`
Hope this helps in some cases. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | Do you really need to log in using Safari?
Otherwise you go to 'System Preferences' > 'Wi-Fi' > Select the appropriate network > Log in > Deselect 'Ask To Join Networks'
This way, your iPhone remembers this Wi-Fi network and your iPhone will automatically connect to this network when you're within the range of the academy Wi-Fi. | It's not a matter of Safari not remembering the password, its a matter of the network requiring login based on the browser. Most captive walled gardens require it with every disconnect for security purposes. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | check out this link <http://www.ausbt.com.au/how-to-save-passwords-in-safari-on-the-ipad-iphone> to setup autofill name and passwords for safari on IOS.
And it totally is a matter of safari not remembering username/password.
It's a little hidden, but it's there, and thanks for asking a good question. The other answerers here must never have logged into a captive portal before or something. | Do you really need to log in using Safari?
Otherwise you go to 'System Preferences' > 'Wi-Fi' > Select the appropriate network > Log in > Deselect 'Ask To Join Networks'
This way, your iPhone remembers this Wi-Fi network and your iPhone will automatically connect to this network when you're within the range of the academy Wi-Fi. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | Do you really need to log in using Safari?
Otherwise you go to 'System Preferences' > 'Wi-Fi' > Select the appropriate network > Log in > Deselect 'Ask To Join Networks'
This way, your iPhone remembers this Wi-Fi network and your iPhone will automatically connect to this network when you're within the range of the academy Wi-Fi. | I had this problem. Turns out I was in Private Browsing mode. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | If this is a "captive portal" - a wifi network where you need to input your password into a form on a web page, or check a box agreeing to terms of use, then in my experience the iPhone will not remember the password. | It's not a matter of Safari not remembering the password, its a matter of the network requiring login based on the browser. Most captive walled gardens require it with every disconnect for security purposes. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | check out this link <http://www.ausbt.com.au/how-to-save-passwords-in-safari-on-the-ipad-iphone> to setup autofill name and passwords for safari on IOS.
And it totally is a matter of safari not remembering username/password.
It's a little hidden, but it's there, and thanks for asking a good question. The other answerers here must never have logged into a captive portal before or something. | If this is a "captive portal" - a wifi network where you need to input your password into a form on a web page, or check a box agreeing to terms of use, then in my experience the iPhone will not remember the password. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | If this is a "captive portal" - a wifi network where you need to input your password into a form on a web page, or check a box agreeing to terms of use, then in my experience the iPhone will not remember the password. | I had this problem. Turns out I was in Private Browsing mode. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | check out this link <http://www.ausbt.com.au/how-to-save-passwords-in-safari-on-the-ipad-iphone> to setup autofill name and passwords for safari on IOS.
And it totally is a matter of safari not remembering username/password.
It's a little hidden, but it's there, and thanks for asking a good question. The other answerers here must never have logged into a captive portal before or something. | It's not a matter of Safari not remembering the password, its a matter of the network requiring login based on the browser. Most captive walled gardens require it with every disconnect for security purposes. |
67,246 | My Academy's wi-fi requires me to log in via a web-browser portal page before I have access to the internet. Safari on my iPhone doesn't save my username and password for it. Is there a way to manually force it to save them? | 2012/10/13 | [
"https://apple.stackexchange.com/questions/67246",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/31797/"
] | check out this link <http://www.ausbt.com.au/how-to-save-passwords-in-safari-on-the-ipad-iphone> to setup autofill name and passwords for safari on IOS.
And it totally is a matter of safari not remembering username/password.
It's a little hidden, but it's there, and thanks for asking a good question. The other answerers here must never have logged into a captive portal before or something. | I had this problem. Turns out I was in Private Browsing mode. |
42,553,224 | I am new to Sql query if I had a table called Employee:
```
Id, Name, Department
1 tim sales
2 tom sales
3 jay HR
4 ben design
5 lin design
```
I am trying to write a query that returns the number of employees in each department.
```
SELECT COUNT(Department) FROM Employee
```
Does anyone have any advise on how I can improve this query?
\*\*\*\*Edit
What about if I wanted to return the number of employees in the same department | 2017/03/02 | [
"https://Stackoverflow.com/questions/42553224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259826/"
] | ```
SELECT COUNT(id), department FROM Employee GROUP BY department;
``` | ```
SELECT COUNT([id]), [department] FROM [Employee], GROUP BY [department].
``` |
42,553,224 | I am new to Sql query if I had a table called Employee:
```
Id, Name, Department
1 tim sales
2 tom sales
3 jay HR
4 ben design
5 lin design
```
I am trying to write a query that returns the number of employees in each department.
```
SELECT COUNT(Department) FROM Employee
```
Does anyone have any advise on how I can improve this query?
\*\*\*\*Edit
What about if I wanted to return the number of employees in the same department | 2017/03/02 | [
"https://Stackoverflow.com/questions/42553224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259826/"
] | **Using group by**
`SELECT COUNT(id), department FROM Employee GROUP BY department`
OR
**By WHERE condition**`SELECT COUNT(id),Department FROM Employee WHERE Department='HR'` | ```
SELECT COUNT([id]), [department] FROM [Employee], GROUP BY [department].
``` |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Playing devils advocate, it's almost always pointless to waste your time reporting these machines. Most attacks come from zombies machines that the user has no idea is even occurring. So even if you report them to their ISP and their ISP cuts their connection until they have their machine cleaned they will most likely just end up infected again later or even if they don't the fact you removed 1 zombie machine from the internet is a meaningless achievement.
The only time I would say it's worth reporting these attempts is if the machine is part of a hosted network like ThePlanet. Taking a compromised server off the internet is a big deal especially since the owner of the server might not even realize it's compromised. The other difference is the scale of attacks the server is capable of versus the home pc. | afrinic.net, apnic.net, arin.net, jpnic.net, krnic.net, lacnic.net, ripe.net or twnic.net all have web-sites that you can perform a whois lookup. I normally start with the American (arin) NIC.
You can also download a whois client. I use the GNU ***JWHOIS***. It's OK. Additionally one can also get some information by using a ***PING -a -n 1*** command. For example: 6.127.6.109.rev.sfr.net |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Most ISPs have an abuse@ispname.com email address for reporting such things.. If you can revers lookup the ISP name from the IP I would send the info there. | By SQL injection from sites, I take it: (a) you have some web forms, (b) there's a SQL back-end, (c) you use methods which prevent user input from being mis-interpreted as SQL (parameterized queries, etc.)
But still you would like to detect attempts at SQL injection. Ok.
One of the standard ways to attempt SQL injection is to probe around seeking an input field which is incorporated to a SQL query by using string insertion. For example:
>
> snprintf(buf, dimensionof(buf), "SELECT calory\_limit FROM user\_diets WHERE user\_firstname='%s' AND user\_surname='%s'", firstname, surname);
>
>
>
Where *surname* and *firstname* are unfiltered inputs from a web form. In this example, a user could provide the name *firstname*=`Johnny'`, *surname*=`'-';DROP DATABASE;--`
The sprintf would result in:
>
> SELECT calory\_limit FROM user\_diets WHERE user\_firstname='Johnny'' AND user\_surname=''-';DROP DATABASE;--'
>
>
>
Because '' (two single quotes) in SQL is interpreted as an escaped ' which is part of the string, we have "broken open" the string delimiter in the intended original statement. This lets us convert what later should have been string, *surname*, into commmand.
In short, look for people entering fields which:
* End in a single quote mark
* Begin with a single quote mark
* Contain a "--" at or near the end (The purpose of wrapping the attack payloads up with a SQL comment delimiter is that without that, the attacker's distortion of the intended query could leave some unparsable command bits at the end. These could generate an error message to a log and alert you.)
Also, you might consider the same heuristics after, e.g., UTF-8 decoding the input. Or UTF-8 decoding it twice over. The penetration tester will be thinking about bugs that might be in your code, so they will try inputs which seem not to make sense -- such as twice-UTF-8-encoded single quote marks.
Also, look for `"` and other HTML entity sequences.
You can search arxiv.org and find some papers which detail certain specific attack flavors: cross-site scripting, SQL injection, URL modification. Reading some papers there will lead you to more. |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Donate your logs to [SANS](http://isc.sans.org/howto.html)! They have a client for most firewalls that will pull the logs and send them to the DShield database. | Either everyone else understood something else or I did, but from what I can understand you are trying to report the people attempting SQL injections to their ISPs.
This will usually be a dead end, and you're better off just blocking the users attempting the attacks, as most machines performing attacks are not usually owned by the 'hacker', and instead they could be compromised machines, or someone abusing a website which offers free vulnerability scans or something similar. |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Donate your logs to [SANS](http://isc.sans.org/howto.html)! They have a client for most firewalls that will pull the logs and send them to the DShield database. | Playing devils advocate, it's almost always pointless to waste your time reporting these machines. Most attacks come from zombies machines that the user has no idea is even occurring. So even if you report them to their ISP and their ISP cuts their connection until they have their machine cleaned they will most likely just end up infected again later or even if they don't the fact you removed 1 zombie machine from the internet is a meaningless achievement.
The only time I would say it's worth reporting these attempts is if the machine is part of a hosted network like ThePlanet. Taking a compromised server off the internet is a big deal especially since the owner of the server might not even realize it's compromised. The other difference is the scale of attacks the server is capable of versus the home pc. |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | By SQL injection from sites, I take it: (a) you have some web forms, (b) there's a SQL back-end, (c) you use methods which prevent user input from being mis-interpreted as SQL (parameterized queries, etc.)
But still you would like to detect attempts at SQL injection. Ok.
One of the standard ways to attempt SQL injection is to probe around seeking an input field which is incorporated to a SQL query by using string insertion. For example:
>
> snprintf(buf, dimensionof(buf), "SELECT calory\_limit FROM user\_diets WHERE user\_firstname='%s' AND user\_surname='%s'", firstname, surname);
>
>
>
Where *surname* and *firstname* are unfiltered inputs from a web form. In this example, a user could provide the name *firstname*=`Johnny'`, *surname*=`'-';DROP DATABASE;--`
The sprintf would result in:
>
> SELECT calory\_limit FROM user\_diets WHERE user\_firstname='Johnny'' AND user\_surname=''-';DROP DATABASE;--'
>
>
>
Because '' (two single quotes) in SQL is interpreted as an escaped ' which is part of the string, we have "broken open" the string delimiter in the intended original statement. This lets us convert what later should have been string, *surname*, into commmand.
In short, look for people entering fields which:
* End in a single quote mark
* Begin with a single quote mark
* Contain a "--" at or near the end (The purpose of wrapping the attack payloads up with a SQL comment delimiter is that without that, the attacker's distortion of the intended query could leave some unparsable command bits at the end. These could generate an error message to a log and alert you.)
Also, you might consider the same heuristics after, e.g., UTF-8 decoding the input. Or UTF-8 decoding it twice over. The penetration tester will be thinking about bugs that might be in your code, so they will try inputs which seem not to make sense -- such as twice-UTF-8-encoded single quote marks.
Also, look for `"` and other HTML entity sequences.
You can search arxiv.org and find some papers which detail certain specific attack flavors: cross-site scripting, SQL injection, URL modification. Reading some papers there will lead you to more. | afrinic.net, apnic.net, arin.net, jpnic.net, krnic.net, lacnic.net, ripe.net or twnic.net all have web-sites that you can perform a whois lookup. I normally start with the American (arin) NIC.
You can also download a whois client. I use the GNU ***JWHOIS***. It's OK. Additionally one can also get some information by using a ***PING -a -n 1*** command. For example: 6.127.6.109.rev.sfr.net |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Either everyone else understood something else or I did, but from what I can understand you are trying to report the people attempting SQL injections to their ISPs.
This will usually be a dead end, and you're better off just blocking the users attempting the attacks, as most machines performing attacks are not usually owned by the 'hacker', and instead they could be compromised machines, or someone abusing a website which offers free vulnerability scans or something similar. | Playing devils advocate, it's almost always pointless to waste your time reporting these machines. Most attacks come from zombies machines that the user has no idea is even occurring. So even if you report them to their ISP and their ISP cuts their connection until they have their machine cleaned they will most likely just end up infected again later or even if they don't the fact you removed 1 zombie machine from the internet is a meaningless achievement.
The only time I would say it's worth reporting these attempts is if the machine is part of a hosted network like ThePlanet. Taking a compromised server off the internet is a big deal especially since the owner of the server might not even realize it's compromised. The other difference is the scale of attacks the server is capable of versus the home pc. |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Either everyone else understood something else or I did, but from what I can understand you are trying to report the people attempting SQL injections to their ISPs.
This will usually be a dead end, and you're better off just blocking the users attempting the attacks, as most machines performing attacks are not usually owned by the 'hacker', and instead they could be compromised machines, or someone abusing a website which offers free vulnerability scans or something similar. | afrinic.net, apnic.net, arin.net, jpnic.net, krnic.net, lacnic.net, ripe.net or twnic.net all have web-sites that you can perform a whois lookup. I normally start with the American (arin) NIC.
You can also download a whois client. I use the GNU ***JWHOIS***. It's OK. Additionally one can also get some information by using a ***PING -a -n 1*** command. For example: 6.127.6.109.rev.sfr.net |
75,078 | EDIT : Sorry, my question clearly wasn't clear. I don't want to report attempted server attacks internally; we already have systems that log. record and report that activity.
What I was keen to do was to report the attacks to the perpetrator's ISP or somesuch.
Original question:
Our sites are immune to SQL Injection (AFAIK!), but of course we still get targeted regularly.
Is there some way I could automate reporting of attempted attacks - reverse DNS lookup etc.?
Although I guess its only worthwhile if, overall, it would be doing the community a favour.
Ditto I suppose for all the other attacks we see - probing for wide-open BBS, MySQL, PHPAdmin, etc. | 2009/10/16 | [
"https://serverfault.com/questions/75078",
"https://serverfault.com",
"https://serverfault.com/users/23154/"
] | Donate your logs to [SANS](http://isc.sans.org/howto.html)! They have a client for most firewalls that will pull the logs and send them to the DShield database. | afrinic.net, apnic.net, arin.net, jpnic.net, krnic.net, lacnic.net, ripe.net or twnic.net all have web-sites that you can perform a whois lookup. I normally start with the American (arin) NIC.
You can also download a whois client. I use the GNU ***JWHOIS***. It's OK. Additionally one can also get some information by using a ***PING -a -n 1*** command. For example: 6.127.6.109.rev.sfr.net |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.