qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
178,546 | So far any search for Pogoplug security risk does not bring up anything alarming. Just wondering if anyone else has run across any mention of security issues with this device. | 2010/08/21 | [
"https://superuser.com/questions/178546",
"https://superuser.com",
"https://superuser.com/users/46807/"
] | Let's go down the stack and look at every aspect of its security.
* **Remote Computer**: very easily compromised on an untrustworthy computer via a keylogger, so if you either a) only access your Pogoplug from your (trustworthy) computers, b) change your password often (i.e., at least once every 6 weeks), or c) use the very awesome [Keepass](http://keepass.info) 2.x that has a feature that scrambles then descrambles the password through simulated keystrokes, the clipboard and the arrow keys.
* **Remote Computer's Internet-Your Pogoplug**: not as easily compromised because Pogoplug (if the reviews are correct) operates entirely under Secure Sockets (SSL), meaning any data between the remote computer and the pogoplug is encrypted with encryptions algorithms that only quantum computers can crack before the universe explodes.
* **The Pogoplug**: There aren't any insomnia-worthy viruses or threats out there, since it runs ARM (only common in phones) and Linux. Unless somebody launches a DDoS attack on it (which, assuming your son isn't Osama bin Laden or targeted by 4chan) means that nobody will a) be able to get into it without the codes, or b) care.
* **Your Son and His Friends**: This is the most important part because most modern schemes involve exploiting human psychology and inability to think reasonably when in immense stress. The worst thing that can feasibly happen is that your son accidentally changes the Pogoplug's privacy settings without knowing or forgetting to log out of a borrowed or public computer.
**In Summary**: The Pogoplug itself isn't a security problem, the people who use it are. And for the same reason phishing schemes are so widespread nowadays.
**Edit**: I should mention that when I was analyzing the security weakpoints, I was assuming that there's some superpowerful group of people after your son (e.g. the NSA, Al Qaeda). Otherwise the chances of people even trying the worst-case attacks I show here are nigh unlikely. | It's basically a linux server with a custom web interface, so whatever vulnerabilities exist with linux in general are also shared by the pogoplug, as well as the specific installed applications, which I don't know because I don't have one. More of a risk is not changing default passwords, and the general privacy issues with having something that's designed for sharing files. |
178,546 | So far any search for Pogoplug security risk does not bring up anything alarming. Just wondering if anyone else has run across any mention of security issues with this device. | 2010/08/21 | [
"https://superuser.com/questions/178546",
"https://superuser.com",
"https://superuser.com/users/46807/"
] | The pogoplug essentially makes a connection to the manufacturer's server and provides content through it, at least in part. In my book that is a security concern, but for most people it is no more a threat than posting your pictures on facebook and only letting your friends see them is.
You're trusting the manufacturer to actively protect your data though, rather than passively protect it by designing a good password authentication scheme (for example).
This is based on what I've read about pogoplug which is very little recently, and a bit more, but a lot longer ago. | It's basically a linux server with a custom web interface, so whatever vulnerabilities exist with linux in general are also shared by the pogoplug, as well as the specific installed applications, which I don't know because I don't have one. More of a risk is not changing default passwords, and the general privacy issues with having something that's designed for sharing files. |
178,546 | So far any search for Pogoplug security risk does not bring up anything alarming. Just wondering if anyone else has run across any mention of security issues with this device. | 2010/08/21 | [
"https://superuser.com/questions/178546",
"https://superuser.com",
"https://superuser.com/users/46807/"
] | Let's go down the stack and look at every aspect of its security.
* **Remote Computer**: very easily compromised on an untrustworthy computer via a keylogger, so if you either a) only access your Pogoplug from your (trustworthy) computers, b) change your password often (i.e., at least once every 6 weeks), or c) use the very awesome [Keepass](http://keepass.info) 2.x that has a feature that scrambles then descrambles the password through simulated keystrokes, the clipboard and the arrow keys.
* **Remote Computer's Internet-Your Pogoplug**: not as easily compromised because Pogoplug (if the reviews are correct) operates entirely under Secure Sockets (SSL), meaning any data between the remote computer and the pogoplug is encrypted with encryptions algorithms that only quantum computers can crack before the universe explodes.
* **The Pogoplug**: There aren't any insomnia-worthy viruses or threats out there, since it runs ARM (only common in phones) and Linux. Unless somebody launches a DDoS attack on it (which, assuming your son isn't Osama bin Laden or targeted by 4chan) means that nobody will a) be able to get into it without the codes, or b) care.
* **Your Son and His Friends**: This is the most important part because most modern schemes involve exploiting human psychology and inability to think reasonably when in immense stress. The worst thing that can feasibly happen is that your son accidentally changes the Pogoplug's privacy settings without knowing or forgetting to log out of a borrowed or public computer.
**In Summary**: The Pogoplug itself isn't a security problem, the people who use it are. And for the same reason phishing schemes are so widespread nowadays.
**Edit**: I should mention that when I was analyzing the security weakpoints, I was assuming that there's some superpowerful group of people after your son (e.g. the NSA, Al Qaeda). Otherwise the chances of people even trying the worst-case attacks I show here are nigh unlikely. | The pogoplug essentially makes a connection to the manufacturer's server and provides content through it, at least in part. In my book that is a security concern, but for most people it is no more a threat than posting your pictures on facebook and only letting your friends see them is.
You're trusting the manufacturer to actively protect your data though, rather than passively protect it by designing a good password authentication scheme (for example).
This is based on what I've read about pogoplug which is very little recently, and a bit more, but a lot longer ago. |
65,475 | Find Familiar lets you cast touch spells through your familiar. Warding Bond is a Touch spell, that creates a connection between "you and the target". I can't find anything against it, but would it be possible to have my Wizard make his familiar cast Warding Bond on the Wizard himself, so that the Wizard gets the +1 to AC and saving throws and resistance to damage?
I realized after I wrote this much that Wizards don't get Warding Bond, but I think the question is still valid for multiclassers. | 2015/07/30 | [
"https://rpg.stackexchange.com/questions/65475",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/17884/"
] | So to start with, it's worth pointing out that you can cast *Warding Bond* on yourself. Touch range spells are described as:
>
> Some spells can target only a creature (including you) that you touch.
>
>
>
Further, under the Targeting Yourself section, it says:
>
> If a spell targets a creature of your choice, you can choose yourself, unless the creature must be hostile or specifically a creature other than you.
>
>
>
You can cast touch spells on yourself unless they specifically say you can't, and *Warding Bond* doesn't specify that. This is actually not a bad idea - you'll get the +1 to AC and saving throws, and the double damage you'll take will be canceled out by the resistance to damage.
*Find Familiar* says that:
>
> when you cast a spell with a range of touch, your familiar can deliver the spell as if it had cast the spell.
>
>
>
Your familiar can **deliver** the spell as if it had cast the spell. This is the only way in which the familiar acts as the caster of the spell. It can certainly deliver *Warding Bond* for you, but you will still be the caster of the spell, and the "you" in *Warding Bond* will still be you, not your familiar. This is effectively equivalent to casting it on yourself directly, except that it took your familiar's reaction. | Short Answer
============
* **If** you can cast Warding Bond on yourself, via touch, then **Yes**, your familiar can do it.
* **If** you can't cast Warding Bond on yourself, via touch, then **No**, your familiar cannot do it.
The embedded question required to answer the question posed is:
===============================================================
**"Can you cast Warding Bond on yourself?"**
1. Miniman's answer suggests that you can.
2. The following RAW-based analysis suggests **"No, You Can't"** based on the specifics in the spell description rather than the general rules cited in the "Yes" answer. The spell relies on there being **two creatures** (plural) for this magical bond to form and protect one of them. From the spell description:
>
> The spell ends if you drop to 0 hit points or if you and the target become separated by more than 60 feet. It also ends if the spell is cast again on **either of the connected creatures.**
>
>
>
3. [A tweet by Jeremy Crawford suggests that you can't](http://www.sageadvice.eu/2016/11/19/can-you-cast-warding-bond-on-yourself/):
>
> **Sean** @Lord\_Sicarious · [6 Oct 2016](https://twitter.com/Lord_Sicarious/status/784019326311407625)
>
> @JeremyECrawford can you cast Warding Bond on yourself? Its rules seem to assume two people, but no explicit limitation.
>
>
> **Jeremy Crawford** @JeremyECrawford · [6 Oct 2016](https://twitter.com/JeremyECrawford/status/784078660034703360)
>
> Warding bond—you can't target yourself with it. #DnD
>
>
>
4. "Specific over General" supports **No** over **Yes**.
Each DM will rule on what makes most sense to that DM. Since the impact isn't game breaking, it probably doesn't matter. A "Yes" ruling provides a one-hour period where a cleric gets +1 AC and +1 to saves for the price of a level 2 spell after touching him / her self while wearing two platinum rings. A "No" ruling means the cleric uses the 2d level slot on something else.
---
Analysis of the Spell to Support the No Answer (Specific over General)
======================================================================
>
> Casting Time: 1 action
>
> Range: Touch
>
> Components: V, S, M (a pairof platinum rings worth at least 50 gp each, **which *you and the target must wear* for the duration**)
>
>
>
The italicized text implies two creatures -- a caster and a target -- each wearing a platinum ring, but it does not state that explicitly in this part of the spell description.
>
> This spell wards a willing creature you touch and creates a mystic connection between you and the target until the spell ends.
>
>
>
"A willing creature" isn't necessarily only "another willing creature," so one can argue that the caster is "a willing creature" who can touch his/her self. That said, the second half of the sentence implies two parties being involved: the caster and a target. this spell
>
> ... creates a mystic connection between you and the target until the spell ends.
>
>
>
* "You create a mystic connection with yourself"
is not the same statement as
* "you create a mystic connection between you and (any other different creature than you.)"
The "general rule" arguments about spell targets, self spells, and touch spells seems to have raised its head again. (See a [previous discussion on Paladin Smite spells](https://rpg.stackexchange.com/questions/62330/paladin-smite-spells-and-the-steed-can-either-or-both-trigger-the-damage?s=2%7C1.2883)).
Two parties being involved is the common sense / common usage reading of this spell description.
>
> While **the target is within 60 feet of you,** it gains a +1 bonus to AC and saving throws, and it has resistance to all damage.
>
>
>
We see a second and a third person usage, implying the presence of another creature other than the caster.
>
> Also, each time **it** takes damage, **you** take the same amount of damage.
>
>
>
"You take damage" and "it" takes damage: second person and third person references. Two different persons, to different creatures are damaged.
>
> The spell ends if you drop to 0 hit points or **if you and the target become separated** by more than 60 feet.
>
>
>
The caster reaching a zero-hit-point condition ending a spell is common result. Neither a pro nor con element for this question. Outside edge case magical effects, you can't be separated from yourself so this makes no sense in a case other than two creatures being involved.
>
> It also ends if the spell is cast again on ***either of the connected creatures***. You can also dismiss the spell as an action.
>
>
>
**Creatures**, plural. Two creatures, a caster and a target who needs to be touched while wearing the appropriate platinum ring.
What was **implied** in previous language is **specified** at the end of the spell description. "Either" obviously refers to more than one party/creature.
Conclusion:
===========
By reading the specifics of the spell description, the spell requires two creatures, each wearing the appropriate platinum ring, one touching the other, and both staying within 60' of each other for up to an hour for the spell to provide the damage reduction to recipient of this spell, as well as the AC and Saving throw bonuses.
**No, you can't cast this spell on yourself because it requires two creatures, each wearing that platinum ring, to create the spell effect.** |
28,358,916 | Getting below exception while reading a PDF. It opens well in Acrobat reader. I read in another question that though its opened in acrobat its not necessary to open via iText because PDF contains an error and he recommends to fix the PDF. But the file is coming from the client and they are able to open Acrobat, so either I have to fix it or show the error or warning in Acrobat.
```
com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed: Error reading string at file pointer 10891; Original message: Error reading string at file pointer 10891
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:655)
```
Excerpt of PDF file
```
%PDF-1.1
1 0 obj
<<
/Creator (Developer 2000)
/CreatorDate (
/Author (Oracle Reports)
/Producer (Oracle PDF driver)
/Title (con5010I412014141258.pdf)
>>
endobj
3 0 obj
<<
/Type /Pages
/Kids 4 0 R
/Count 5 0 R
>>
endobj
7 0 obj
<</Length 8 0 R>>
stream
BT
```
1. Is there any way I can show the client that the PDF has error? either via Acrobat or some other software rather Java exception.
2. Is there way to go around this error and proceed? We faced similar issues for secured PDF and we did unlock. Please suggest | 2015/02/06 | [
"https://Stackoverflow.com/questions/28358916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006944/"
] | It is actually a Invalid PDF. When I open the PDF in text editor I noticed that header has CreatorDate with out close bracket. I just added the close bracket with valid date like this CreatorDate (05 November 2014 17:50:24) then It works. I asked client to correct on their side | Edit the PDF in a text editor (notepad, notepad++, etc.) and simply add a closing parenthesis.
So the following line:
/CreatorDate (
Changes to:
/CreatorDate () |
28,358,916 | Getting below exception while reading a PDF. It opens well in Acrobat reader. I read in another question that though its opened in acrobat its not necessary to open via iText because PDF contains an error and he recommends to fix the PDF. But the file is coming from the client and they are able to open Acrobat, so either I have to fix it or show the error or warning in Acrobat.
```
com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed: Error reading string at file pointer 10891; Original message: Error reading string at file pointer 10891
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:655)
```
Excerpt of PDF file
```
%PDF-1.1
1 0 obj
<<
/Creator (Developer 2000)
/CreatorDate (
/Author (Oracle Reports)
/Producer (Oracle PDF driver)
/Title (con5010I412014141258.pdf)
>>
endobj
3 0 obj
<<
/Type /Pages
/Kids 4 0 R
/Count 5 0 R
>>
endobj
7 0 obj
<</Length 8 0 R>>
stream
BT
```
1. Is there any way I can show the client that the PDF has error? either via Acrobat or some other software rather Java exception.
2. Is there way to go around this error and proceed? We faced similar issues for secured PDF and we did unlock. Please suggest | 2015/02/06 | [
"https://Stackoverflow.com/questions/28358916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006944/"
] | It is actually a Invalid PDF. When I open the PDF in text editor I noticed that header has CreatorDate with out close bracket. I just added the close bracket with valid date like this CreatorDate (05 November 2014 17:50:24) then It works. I asked client to correct on their side | In my case, it allows me to use printing to fix the file.
(The printed file is basically a binary/image of the file, lots of info/metadata is lost)
[](https://i.stack.imgur.com/XJrd7.png) |
28,358,916 | Getting below exception while reading a PDF. It opens well in Acrobat reader. I read in another question that though its opened in acrobat its not necessary to open via iText because PDF contains an error and he recommends to fix the PDF. But the file is coming from the client and they are able to open Acrobat, so either I have to fix it or show the error or warning in Acrobat.
```
com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed: Error reading string at file pointer 10891; Original message: Error reading string at file pointer 10891
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:655)
```
Excerpt of PDF file
```
%PDF-1.1
1 0 obj
<<
/Creator (Developer 2000)
/CreatorDate (
/Author (Oracle Reports)
/Producer (Oracle PDF driver)
/Title (con5010I412014141258.pdf)
>>
endobj
3 0 obj
<<
/Type /Pages
/Kids 4 0 R
/Count 5 0 R
>>
endobj
7 0 obj
<</Length 8 0 R>>
stream
BT
```
1. Is there any way I can show the client that the PDF has error? either via Acrobat or some other software rather Java exception.
2. Is there way to go around this error and proceed? We faced similar issues for secured PDF and we did unlock. Please suggest | 2015/02/06 | [
"https://Stackoverflow.com/questions/28358916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006944/"
] | Edit the PDF in a text editor (notepad, notepad++, etc.) and simply add a closing parenthesis.
So the following line:
/CreatorDate (
Changes to:
/CreatorDate () | In my case, it allows me to use printing to fix the file.
(The printed file is basically a binary/image of the file, lots of info/metadata is lost)
[](https://i.stack.imgur.com/XJrd7.png) |
13,137,439 | I have a method that I call multiple times, but each time a different method with a different signature is called from inside.
```
public void MethodOne()
{
//some stuff
*MethodCall();
//some stuff
}
```
So `MethodOne` is called multiple times, each time with a different `*MethodCall()`. What I'm trying to do is something like this :
```
public void MethodOne(Func<> MethodCall)
{
//some stuff
*MethodCall;
//some stuff
}
```
but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?
Thank you! | 2012/10/30 | [
"https://Stackoverflow.com/questions/13137439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733379/"
] | You best bet would be to use the non-generic `Action` type (or `MethodInvoker` would be the same), i.e.
```
public void MethodOne(Action callback)
{
//some stuff
if(callback != null) callback();
//some stuff
}
```
From this you can call any method by wrapping it at the caller, i.e.
```
MethodOne(SimpleMethod); // SimpleMethod has no parameters and returns void
MethodOne(() => MoreComplexMethod(1, "abc")); // this one returns void
MethodOne(() => { MethodThatReturnsSomething(12); }); // anything you like
```
etc | You cannot call a function which requires parameters without supplying them, so the answer is "no, not possible"
Also, maybe you want the following:
```
void MethodOne(Action a)
{
// some stuff
a();
// some stuff
}
... // somewhere in the code
MethodOne((Action)(() => { DoSomethingOther(1, 2, 3); }));
MethodOne((Action)(() => { DoSomethingEvenDifferent(1, 2, 3, 4, 5); }));
``` |
13,137,439 | I have a method that I call multiple times, but each time a different method with a different signature is called from inside.
```
public void MethodOne()
{
//some stuff
*MethodCall();
//some stuff
}
```
So `MethodOne` is called multiple times, each time with a different `*MethodCall()`. What I'm trying to do is something like this :
```
public void MethodOne(Func<> MethodCall)
{
//some stuff
*MethodCall;
//some stuff
}
```
but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?
Thank you! | 2012/10/30 | [
"https://Stackoverflow.com/questions/13137439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733379/"
] | You best bet would be to use the non-generic `Action` type (or `MethodInvoker` would be the same), i.e.
```
public void MethodOne(Action callback)
{
//some stuff
if(callback != null) callback();
//some stuff
}
```
From this you can call any method by wrapping it at the caller, i.e.
```
MethodOne(SimpleMethod); // SimpleMethod has no parameters and returns void
MethodOne(() => MoreComplexMethod(1, "abc")); // this one returns void
MethodOne(() => { MethodThatReturnsSomething(12); }); // anything you like
```
etc | This is basically not possible. You could make `MethodOne` generic for the return type, and use a lambda that closes over its outside block instead of parameters:
```
static void Main(string[] args)
{
int parameterSubst = 1;
int result = MethodOne<int>(() => parameterSubst);
string result2 = MethodOne<string>(() =>
{
string s = parameterSubst.ToString();
s += "foo";
return s;
});
}
static T MethodOne<T>(Func<T> function)
{
return function();
}
```
As you can see, `parameterSubst` is used in the passed `Func<T>`s, but not as a parameter. |
13,137,439 | I have a method that I call multiple times, but each time a different method with a different signature is called from inside.
```
public void MethodOne()
{
//some stuff
*MethodCall();
//some stuff
}
```
So `MethodOne` is called multiple times, each time with a different `*MethodCall()`. What I'm trying to do is something like this :
```
public void MethodOne(Func<> MethodCall)
{
//some stuff
*MethodCall;
//some stuff
}
```
but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?
Thank you! | 2012/10/30 | [
"https://Stackoverflow.com/questions/13137439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733379/"
] | You best bet would be to use the non-generic `Action` type (or `MethodInvoker` would be the same), i.e.
```
public void MethodOne(Action callback)
{
//some stuff
if(callback != null) callback();
//some stuff
}
```
From this you can call any method by wrapping it at the caller, i.e.
```
MethodOne(SimpleMethod); // SimpleMethod has no parameters and returns void
MethodOne(() => MoreComplexMethod(1, "abc")); // this one returns void
MethodOne(() => { MethodThatReturnsSomething(12); }); // anything you like
```
etc | Every delegate in .Net is an instance of a class derived from [Delegate](http://msdn.microsoft.com/en-us/library/y22acf51.aspx). So if you really wish to pass 'any' delegate to a method, you can pass it as `Delegate`
To invoke it, you need to use its [DynamicInvoke](http://msdn.microsoft.com/en-us/library/system.delegate.dynamicinvoke.aspx) method.
```
public void MethodOne(Delegate MethodCall)
{
//some stuff
//Assuming you now have the required parameters
//or add params object[] args to the signature of this method
object res = MethodCall.DynamicInvoke(args); //args is object[] representing the parameters
//some stuff
}
```
But this is not recommended as `DynamicInvoke` is slow and it does not offer any compile time safety. Probably you should revisit your design. |
13,137,439 | I have a method that I call multiple times, but each time a different method with a different signature is called from inside.
```
public void MethodOne()
{
//some stuff
*MethodCall();
//some stuff
}
```
So `MethodOne` is called multiple times, each time with a different `*MethodCall()`. What I'm trying to do is something like this :
```
public void MethodOne(Func<> MethodCall)
{
//some stuff
*MethodCall;
//some stuff
}
```
but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?
Thank you! | 2012/10/30 | [
"https://Stackoverflow.com/questions/13137439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733379/"
] | You cannot call a function which requires parameters without supplying them, so the answer is "no, not possible"
Also, maybe you want the following:
```
void MethodOne(Action a)
{
// some stuff
a();
// some stuff
}
... // somewhere in the code
MethodOne((Action)(() => { DoSomethingOther(1, 2, 3); }));
MethodOne((Action)(() => { DoSomethingEvenDifferent(1, 2, 3, 4, 5); }));
``` | This is basically not possible. You could make `MethodOne` generic for the return type, and use a lambda that closes over its outside block instead of parameters:
```
static void Main(string[] args)
{
int parameterSubst = 1;
int result = MethodOne<int>(() => parameterSubst);
string result2 = MethodOne<string>(() =>
{
string s = parameterSubst.ToString();
s += "foo";
return s;
});
}
static T MethodOne<T>(Func<T> function)
{
return function();
}
```
As you can see, `parameterSubst` is used in the passed `Func<T>`s, but not as a parameter. |
13,137,439 | I have a method that I call multiple times, but each time a different method with a different signature is called from inside.
```
public void MethodOne()
{
//some stuff
*MethodCall();
//some stuff
}
```
So `MethodOne` is called multiple times, each time with a different `*MethodCall()`. What I'm trying to do is something like this :
```
public void MethodOne(Func<> MethodCall)
{
//some stuff
*MethodCall;
//some stuff
}
```
but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?
Thank you! | 2012/10/30 | [
"https://Stackoverflow.com/questions/13137439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733379/"
] | Every delegate in .Net is an instance of a class derived from [Delegate](http://msdn.microsoft.com/en-us/library/y22acf51.aspx). So if you really wish to pass 'any' delegate to a method, you can pass it as `Delegate`
To invoke it, you need to use its [DynamicInvoke](http://msdn.microsoft.com/en-us/library/system.delegate.dynamicinvoke.aspx) method.
```
public void MethodOne(Delegate MethodCall)
{
//some stuff
//Assuming you now have the required parameters
//or add params object[] args to the signature of this method
object res = MethodCall.DynamicInvoke(args); //args is object[] representing the parameters
//some stuff
}
```
But this is not recommended as `DynamicInvoke` is slow and it does not offer any compile time safety. Probably you should revisit your design. | This is basically not possible. You could make `MethodOne` generic for the return type, and use a lambda that closes over its outside block instead of parameters:
```
static void Main(string[] args)
{
int parameterSubst = 1;
int result = MethodOne<int>(() => parameterSubst);
string result2 = MethodOne<string>(() =>
{
string s = parameterSubst.ToString();
s += "foo";
return s;
});
}
static T MethodOne<T>(Func<T> function)
{
return function();
}
```
As you can see, `parameterSubst` is used in the passed `Func<T>`s, but not as a parameter. |
52,333,702 | I have minimum to none knowledge of powershell :(
Hi I have two possible options to replace text from an .ini file, one is a menu-style batch, where choosing an option will execute a command.
My problem is: if I use the batch code I can only change a known resolution, because I don't know how to add multiple replace actions so they work if one fails.
The Powershell code does executes MULTIPLE replace commands, but I don't know how to edit it to use it as a batch command (`powershell -command` etc.)
Thank you in advance :)
Batch script:
```
@echo off
set ffile='resolutions.ini'
set HDReady='/resolution:1280,720'
set FullHD='/resolution:1920,1080'
set QuadHD='/resolution:2560,1440'
set UltraHD='/resolution:3840,2160'
powershell -Command "(gc %ffile%) -replace %hdready%, %fullhd% | Out-File %ffile% -encoding utf8"
```
Powershell script:
```
$original_file = 'path\resolutions.ini'
$destination_file = 'path\resolutions.ini'
(Get-Content $original_file) | Foreach-Object {
$_ -replace '/resolution:1280,720', '/resolution:1920,1080' `
-replace '/resolution:2560,1440', '/resolution:1920,1080' `
-replace '/resolution:3840,2160', '/resolution:1920,1080'
} | Set-Content $destination_file
``` | 2018/09/14 | [
"https://Stackoverflow.com/questions/52333702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10153742/"
] | Your solution above would also return documents where the field is null, which you don't want I guess. So the correct solution would be this one:
```
GET memoire/_search/?
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "test"
}
},
"must_not": {
"term": {
"test.keyword": ""
}
}
}
}
}
``` | Here is a solution. Use `must_not` with `term` query. This should work:
```
GET memoire/_search/?
{
"query": {
"bool": {
"must_not": {
"term": {"IMG.keyword": ""}
}
}
}
}
``` |
32,396 | Say I have a 1D (spatial) signal (resolution = $1000$) which is zero everywhere except from $x = 250$ to $750$, where it equals one.
[](https://i.stack.imgur.com/wSVrp.png)
I ultimately want to calculate the spatial width of this signal using FFTs. Of course we know the width here to be $500$; in actuality, I am dealing with a signal that evolves with time and wish to calculate the average "pulse" width over all the time frames, so I do not know the widths. I have opted to use FFTs in this pursuit, so I must conduct a "sanity check" to make sure the method works. This method was suggested to me by a colleague whose intuition is many leagues farther than my own, so if someone could explain the intuition to me, I would appreciate it a lot.
* Step 1: Subtract the DC background (subtract the mean from every point of the signal).
* Step 2: Take the FFT of the signal, then the power (the Fourier transform times the complex conjugate of it). Normalize the power spectrum.
* Step 3: Calculate the half-width at half-maximum (HWHM); here half-width is the half-width of the peak in k-space, of course.
* Step 4: Convert this k-space HWHM back to real-space: real-space width = 1 / (HWHM / resolution).
[](https://i.stack.imgur.com/dcf5M.png)
When I do these steps for the signal above, I calculate a real-space width of $1189427$, laughably off from $500$. Where does the method go wrong? | 2016/07/30 | [
"https://dsp.stackexchange.com/questions/32396",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/23123/"
] | >
> Say I have a 1D (spatial) signal (resolution = $1000$) which is zero everywhere except from $x=250$ to $750$, where it equals one.
>
>
>
This is not "resolution". Resolution is 300 **Dots Per Inch**. In which case, we could say that the total **physical** length of your pulse is $\frac{500}{300} \approx 1.666$ **inches** (or any other **unit of length**).
>
> I ultimately want to calculate the spatial width of this signal using FFTs.
>
>
>
Why?
>
> I am dealing with a signal that evolves with time and wish to calculate the average "pulse" width over all the time frames, so I do not know the widths.
>
>
>
If there will be multiple pulses of different widths on the same signal, then by opting to detect them with the FFT you are setting yourself a very big challenge because the FFT would return to you information about the signal as a whole. So you could, for example, derive an average rate of pulses (even using the algorithm that is presented here) but not the widths of individual pulses.
If it is somehow guaranteed that within a window of 1000 **samples**, there will be a pulse whose length is guaranteed to be staying well below 1000 samples and all we have to do now is detect where the pulse is and how long it is, then opting for the FFT is an overkill.
The usual way to detect pulse widths is via the simple use of a threshold and a counter. Once the signal's amplitude goes above the threshold, the counter starts counting and it stops once the signal's amplitude goes below the threshold. If you are going to operate in a noisy environment, then there are a number of improvements to that such as adding [hysterisis](https://en.wikipedia.org/wiki/Discrete_wavelet_transform) to the threshold, so that it doesn't respond to very short "bounces" of the waveform and adaptive thresholding where the threshold limit would be derived from the given window of observation (here, from the 1000 **samples**).
If you absolutely have to work in the frequency domain, it might be better to look into the [discrete wavelet transform](https://en.wikipedia.org/wiki/Discrete_wavelet_transform) (DWT), whose output is a time/scale(frequency) representation. But the actual detection of the pulse width is likely to be happening (again) using some form of threhsolding on the output of the DWT. (So, again, huge overkill). | Step 1 already solves your problem: If your only states are 0 and 1, and you get a mean of $0\le a\le 1$, then $a$ is the fraction of time your pulse was "on". You can very often reduce more complex problems to a threshholding problem that is exactly this one.
>
> Step 2: Take the FFT of the signal, then the power (the Fourier transform times the complex conjugate of it).
>
>
>
Redundant; when calculating the Mean in the first step, you could have already summed up the sample sqaures and thus gotten the power; and Parsevals theorem states that power in time and frequency domain are equivalent.
>
> Step 3: Calculate the half-width at half-maximum (HWHM); here half-width is the half-width of the peak in k-space, of course.
>
>
>
which is the same operation, but on a less "clearly" bounded waveform, as "counting" the width of your pulse in the original time signal.
---
so all in all, you're really not after spectral properties of your signal; I don't see how applying the DFT helps here.
If you want so, first consider the square wave, of which we know the spectrum very well. Now apply the theorem of time-scaling to the Fourier transform, and you'll get a function describing non-unit-periodic square waves. Multiply with a rectangular window (convolve with a sinc in frequency domain), and you'll see that no matter what you're doing, you're not making the original problem easier to distinguish; you'd still be down to counting the zero-passes or edges of the spectrum, and that's not easier or more accurate than doing that in the time domain.
What one could argue is that you inherently, and unknowingly, while simply claiming you'd get the "half-width half-maximum" "just by looking at it" built a specific filter. And in fact, as hinted at in the very beginning, that's your easiest solution:
A "mean value" will give you the percentage of time your signal was 1; also, an average is nothing but a long FIR with constant taps.
So, yeah, build a very low-pass filter, and you shall be done.
You're not really telling us how your overall waveform looks like, but it's thoroughly possible the opposite of the low-pass approach would be a good thing, too: Just use a very high-pass filter to only see the rising/falling edge of your pulse, and simple count the length between these two. |
13,864 | I always hear a lot about The Rule of Thirds. I'd like to know more about other 'tried-and-true' composition techniques (not special effects) that can make a photo more interesting.
In particular, I'd especially like to know:
* The name of the technique
* Any particular types of settings the technique is particulary useful
* Interesting ways to 'break' the rule | 2011/07/09 | [
"https://photo.stackexchange.com/questions/13864",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/5867/"
] | While this isn't a duplicate, this can essentially be answered by linking to a few questions we've collected regarding other composition techniques (thanks largely to @JayLancePhotography!):
* [Bakker's Saddle](https://photo.stackexchange.com/questions/11450/what-is-bakkers-saddle)
* [Rule of Odds](https://photo.stackexchange.com/questions/11475/what-is-the-rule-of-odds)
* [Diagonal Method](https://photo.stackexchange.com/questions/11060/what-is-the-diagonal-method-and-should-i-use-it-instead-of-the-rule-of-thirds)
* [Golden Ratio](https://photo.stackexchange.com/questions/8965/what-is-the-golden-ratio-and-why-is-it-better-than-the-rule-of-thirds)
Searching the [composition](https://photo.stackexchange.com/questions/tagged/composition) and [composition-basics](https://photo.stackexchange.com/questions/tagged/composition-basics) tag provides a wealth of knowledge. | Apart from rules of thumb like the rule of thirds, there are mand general compositional principles which are generally the same in all art forms, things such as balance, space, pattern, texture, lines and shapes, light and shadow.
Very common compositional techniques in photography that I can think of
* leading lines - leading the viewer's eye through the image
* patterns, and I think even more importantly broken/interrupted patterns
* selective focus or color (attracting attention to the subject by blurring/desaturating the background, I guess vignettes fall into this category
* negative space
* unusual perspectives - images of objects from a viewpoint not usually seen (ant's eye view of a flower or pet), extreme wide angle or tele shots
* framing - leaving space in front of the subject if moving, or looking out of the picture
* with wide angle images, having strong foreground interest
* use of strong contrast, bright objects or bright colors to draw the viewer's eye
* lines - diagonal lines and curves are more "dynamic", while vertical ines imply strenght and horizontal lines are more static and calming
* horizon - generally should not be placed in the center of the image, either the foreground or sky should be given more space - one exception would be water reflections where dead center often works
* in general the main subject should be off centre (rule of thirds or otherwise) but usually needs balancing by other objects
* triangles generally make for strong compositions
I think the best images are ones the attract the eye even when looking at a small thumbnail, and you're not sure what the subject is, but the eye is attracted by a strong pattern, shape or color.
The article below is worth a read. It covers a lot of the above, and more.
[Wikepedia article Composition](http://en.wikipedia.org/wiki/Composition_%28visual_arts%29)
Also, you might want to look into Gestalt Theory, very relevant to photographic composition. For example here: [PDF](http://www.imageinnside.com/wp-content/uploads/2010/09/Gestalt-Theory-and-Photographic-Composition..pdf) |
13,864 | I always hear a lot about The Rule of Thirds. I'd like to know more about other 'tried-and-true' composition techniques (not special effects) that can make a photo more interesting.
In particular, I'd especially like to know:
* The name of the technique
* Any particular types of settings the technique is particulary useful
* Interesting ways to 'break' the rule | 2011/07/09 | [
"https://photo.stackexchange.com/questions/13864",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/5867/"
] | While this isn't a duplicate, this can essentially be answered by linking to a few questions we've collected regarding other composition techniques (thanks largely to @JayLancePhotography!):
* [Bakker's Saddle](https://photo.stackexchange.com/questions/11450/what-is-bakkers-saddle)
* [Rule of Odds](https://photo.stackexchange.com/questions/11475/what-is-the-rule-of-odds)
* [Diagonal Method](https://photo.stackexchange.com/questions/11060/what-is-the-diagonal-method-and-should-i-use-it-instead-of-the-rule-of-thirds)
* [Golden Ratio](https://photo.stackexchange.com/questions/8965/what-is-the-golden-ratio-and-why-is-it-better-than-the-rule-of-thirds)
Searching the [composition](https://photo.stackexchange.com/questions/tagged/composition) and [composition-basics](https://photo.stackexchange.com/questions/tagged/composition-basics) tag provides a wealth of knowledge. | For interesting ways to break a rule, learn why the rule works and break it when you want to achieve opposite effect. For example, break the [rule of odds](https://photo.stackexchange.com/q/11475/4390) when you want to stress symmetry and dullness of a scene. |
13,864 | I always hear a lot about The Rule of Thirds. I'd like to know more about other 'tried-and-true' composition techniques (not special effects) that can make a photo more interesting.
In particular, I'd especially like to know:
* The name of the technique
* Any particular types of settings the technique is particulary useful
* Interesting ways to 'break' the rule | 2011/07/09 | [
"https://photo.stackexchange.com/questions/13864",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/5867/"
] | Apart from rules of thumb like the rule of thirds, there are mand general compositional principles which are generally the same in all art forms, things such as balance, space, pattern, texture, lines and shapes, light and shadow.
Very common compositional techniques in photography that I can think of
* leading lines - leading the viewer's eye through the image
* patterns, and I think even more importantly broken/interrupted patterns
* selective focus or color (attracting attention to the subject by blurring/desaturating the background, I guess vignettes fall into this category
* negative space
* unusual perspectives - images of objects from a viewpoint not usually seen (ant's eye view of a flower or pet), extreme wide angle or tele shots
* framing - leaving space in front of the subject if moving, or looking out of the picture
* with wide angle images, having strong foreground interest
* use of strong contrast, bright objects or bright colors to draw the viewer's eye
* lines - diagonal lines and curves are more "dynamic", while vertical ines imply strenght and horizontal lines are more static and calming
* horizon - generally should not be placed in the center of the image, either the foreground or sky should be given more space - one exception would be water reflections where dead center often works
* in general the main subject should be off centre (rule of thirds or otherwise) but usually needs balancing by other objects
* triangles generally make for strong compositions
I think the best images are ones the attract the eye even when looking at a small thumbnail, and you're not sure what the subject is, but the eye is attracted by a strong pattern, shape or color.
The article below is worth a read. It covers a lot of the above, and more.
[Wikepedia article Composition](http://en.wikipedia.org/wiki/Composition_%28visual_arts%29)
Also, you might want to look into Gestalt Theory, very relevant to photographic composition. For example here: [PDF](http://www.imageinnside.com/wp-content/uploads/2010/09/Gestalt-Theory-and-Photographic-Composition..pdf) | For interesting ways to break a rule, learn why the rule works and break it when you want to achieve opposite effect. For example, break the [rule of odds](https://photo.stackexchange.com/q/11475/4390) when you want to stress symmetry and dullness of a scene. |
70,876,660 | I have an object of data and I want to split it array of objects
```
let data = {
"education_center-266": "Software House x",
"education_center-267": "Learning Academy xyz",
"end_date-266": "2022-01-26",
"end_date-267": "2021-01-22",
"start_date-266": "2021-01-26",
"start_date-267": "1998-11-26",
"title-266": "Web Developer",
"title-267": "Teacher",
}
```
I tried differents ways but couldn't reach the result I want..
the result should be
```
[
{
id: "266",
education_center: "Software House x",
title: "Web Developer",
start_date: "2021-01-26",
end_date: "2022-01-26",
},
{
id: "267",
education_center: "Learning Academy xyz",
title: "Teacher",
start_date: "1998-11-26",
end_date: "2021-01-22",
},
]
``` | 2022/01/27 | [
"https://Stackoverflow.com/questions/70876660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17363169/"
] | ```
const myObjects = {};
Object.keys(data).map((key) => {
const splitKey = key.split('-');
const elemId = splitKey[1];
const realKey = splitKey[0];
if (!myObjects[ elemId ]) {
myObjects[ elemId ] = { id: elemId }; // Create entry
}
myObjects[ elemId ][ realKey ] = data[ key ];
});
// Turn into array
const myObjectsToArray = Object.values(myObjects);
// Or use the myObjects as a key/value store with ID as index
const selectedElement = myObjects[ myID ];
``` | ```
const data = {
"education_center-266": "Software House x",
"education_center-267": "Learning Academy xyz",
"end_date-266": "2022-01-26",
"end_date-267": "2021-01-22",
"start_date-266": "2021-01-26",
"start_date-267": "1998-11-26",
"title-266": "Web Developer",
"title-267": "Teacher"
};
const results = [];
function splitKey(key) {
const indexOfDelimiter = key.lastIndexOf("-");
return {
id: key.substring(indexOfDelimiter + 1),
key: key.substring(0, indexOfDelimiter)
};
}
function getItemFromResults(id) {
return results.find((r) => r.id === id);
}
function processKeyValuePair(id, key, value) {
const item = getItemFromResults(id);
if (!item) {
results.push({ id, [key]: value });
return;
}
item[key] = value;
}
for (const k in data) {
const { id, key } = splitKey(k);
const value = data[k];
processKeyValuePair(id, key, value);
}
``` |
70,876,660 | I have an object of data and I want to split it array of objects
```
let data = {
"education_center-266": "Software House x",
"education_center-267": "Learning Academy xyz",
"end_date-266": "2022-01-26",
"end_date-267": "2021-01-22",
"start_date-266": "2021-01-26",
"start_date-267": "1998-11-26",
"title-266": "Web Developer",
"title-267": "Teacher",
}
```
I tried differents ways but couldn't reach the result I want..
the result should be
```
[
{
id: "266",
education_center: "Software House x",
title: "Web Developer",
start_date: "2021-01-26",
end_date: "2022-01-26",
},
{
id: "267",
education_center: "Learning Academy xyz",
title: "Teacher",
start_date: "1998-11-26",
end_date: "2021-01-22",
},
]
``` | 2022/01/27 | [
"https://Stackoverflow.com/questions/70876660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17363169/"
] | ```
const myObjects = {};
Object.keys(data).map((key) => {
const splitKey = key.split('-');
const elemId = splitKey[1];
const realKey = splitKey[0];
if (!myObjects[ elemId ]) {
myObjects[ elemId ] = { id: elemId }; // Create entry
}
myObjects[ elemId ][ realKey ] = data[ key ];
});
// Turn into array
const myObjectsToArray = Object.values(myObjects);
// Or use the myObjects as a key/value store with ID as index
const selectedElement = myObjects[ myID ];
``` | Here a slightly different solution, first getting all **unique** `id's`, then builiding the `result` array with looping over `Object.entries`.
```js
let data = { "education_center-266": "Software House x", "education_center-267": "Learning Academy xyz", "end_date-266": "2022-01-26", "end_date-267": "2021-01-22", "start_date-266": "2021-01-26", "start_date-267": "1998-11-26", "title-266": "Web Developer", "title-267": "Teacher", }
const ids= [...new Set(Object.keys(data).map((el)=>{
return el.split('-')[1]
}))];
console.log(ids) //unique id's
let result = [];
ids.forEach((i)=>{
let obj={id: i}
Object.entries(data).forEach((el)=>{
if(el[0].includes(i)) obj[el[0].split('-')[0]]=el[1];
})
result.push(obj)
})
console.log(result);
``` |
39,397,702 | Here is my Perl code
```
use POSIX;
my @arr = split(/\\n\\n/, $content);
my $len = length @arr;
$len = $len / 2;
my $b = round($len) - 1;
```
At the top of my script I have `use POSIX`. I once had `use Math::Round` but that didn't work.
I'm trying to use the `round` function but the page keeps breaking when I call it. | 2016/09/08 | [
"https://Stackoverflow.com/questions/39397702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135605/"
] | You are not calling `changeToFahrenheit()` method from `main()` method, so it will do nothing and exit | * As the method is static method you could call the method with out creating an object.
* reader.nextInt(); // This returns integer .. so store it in integer.
* you don't have to return value unless you have other methods which reuses this value returned. |
39,397,702 | Here is my Perl code
```
use POSIX;
my @arr = split(/\\n\\n/, $content);
my $len = length @arr;
$len = $len / 2;
my $b = round($len) - 1;
```
At the top of my script I have `use POSIX`. I once had `use Math::Round` but that didn't work.
I'm trying to use the `round` function but the page keeps breaking when I call it. | 2016/09/08 | [
"https://Stackoverflow.com/questions/39397702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135605/"
] | You have to actually call `changeToFahrenheit` from your main method, so your code is:
```
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
changeToFahrenheit();
}
public static double changeToFahrenheit(){
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number between 0-20: ");
double celsius = reader.nextInt();
double fahrenheit = (9/5) * celsius +32;
System.out.println(fahrenheit);
return fahrenheit;
}
}
```
To use a function, you must call a function (This is like the equivalent of the `Main` function in C#). By the way, you cannot do `9/5`, since integer division will result in an integer, `1`. Try `9.0/5.0` for the computation. | You are not calling `changeToFahrenheit()` method from `main()` method, so it will do nothing and exit |
39,397,702 | Here is my Perl code
```
use POSIX;
my @arr = split(/\\n\\n/, $content);
my $len = length @arr;
$len = $len / 2;
my $b = round($len) - 1;
```
At the top of my script I have `use POSIX`. I once had `use Math::Round` but that didn't work.
I'm trying to use the `round` function but the page keeps breaking when I call it. | 2016/09/08 | [
"https://Stackoverflow.com/questions/39397702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135605/"
] | You have to actually call `changeToFahrenheit` from your main method, so your code is:
```
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
changeToFahrenheit();
}
public static double changeToFahrenheit(){
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number between 0-20: ");
double celsius = reader.nextInt();
double fahrenheit = (9/5) * celsius +32;
System.out.println(fahrenheit);
return fahrenheit;
}
}
```
To use a function, you must call a function (This is like the equivalent of the `Main` function in C#). By the way, you cannot do `9/5`, since integer division will result in an integer, `1`. Try `9.0/5.0` for the computation. | * As the method is static method you could call the method with out creating an object.
* reader.nextInt(); // This returns integer .. so store it in integer.
* you don't have to return value unless you have other methods which reuses this value returned. |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | Try this:
```
$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
$product = $this->db->query($sql)->result_array();
``` | You can try this solution for your problem :
```
$query = $this->db->query('select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc');
$row_array = $query->result_array();
```
I Hop it will help you. |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | It's better to use built-in Codeigniter Query-builder:
```
$this->db->select('*');
$this->db->where([
'status' => 1,
'country' => 5,
'product_price >' => 50,
'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();
``` | You can try this solution for your problem :
```
$query = $this->db->query('select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc');
$row_array = $query->result_array();
```
I Hop it will help you. |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | Try this:
```
$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
$product = $this->db->query($sql)->result_array();
``` | Try this
```
$this->db->from('products');
$this->db->where("status='1' AND country='5' AND product_price > '50' AND product_price <= '100'", null, false);
$this->db->order_by("product_id", "desc");
$query = $this->db->get();
return $query->result_array();
``` |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | It's better to use built-in Codeigniter Query-builder:
```
$this->db->select('*');
$this->db->where([
'status' => 1,
'country' => 5,
'product_price >' => 50,
'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();
``` | Try this
```
$this->db->from('products');
$this->db->where("status='1' AND country='5' AND product_price > '50' AND product_price <= '100'", null, false);
$this->db->order_by("product_id", "desc");
$query = $this->db->get();
return $query->result_array();
``` |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | Try this:
```
$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
$product = $this->db->query($sql)->result_array();
``` | Please try below code:
```
$this->db->select('products.*');
$this->db->from('products');
$sql="status='1' AND country='5' AND (product_price > '50' AND product_price <= '100')";
$this->db->where($sql, NULL, FALSE)->order_by("product_id", "DESC");
$products_query = $this->db->get();
$products_info_array = array();
$products_info_array = $products_query->result_array();
return $products_info_array;
``` |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | Try this:
```
$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
$product = $this->db->query($sql)->result_array();
``` | It's better to use built-in Codeigniter Query-builder:
```
$this->db->select('*');
$this->db->where([
'status' => 1,
'country' => 5,
'product_price >' => 50,
'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();
``` |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | Try this:
```
$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
$product = $this->db->query($sql)->result_array();
``` | Can you "describe" type the table? If the field "product\_id" is text (Example: **VARCHAR**), then it will never follow the order asc/desc..
Sorry My English.. **Good work**! |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | It's better to use built-in Codeigniter Query-builder:
```
$this->db->select('*');
$this->db->where([
'status' => 1,
'country' => 5,
'product_price >' => 50,
'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();
``` | Please try below code:
```
$this->db->select('products.*');
$this->db->from('products');
$sql="status='1' AND country='5' AND (product_price > '50' AND product_price <= '100')";
$this->db->where($sql, NULL, FALSE)->order_by("product_id", "DESC");
$products_query = $this->db->get();
$products_info_array = array();
$products_info_array = $products_query->result_array();
return $products_info_array;
``` |
47,688,879 | I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ? | 2017/12/07 | [
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] | It's better to use built-in Codeigniter Query-builder:
```
$this->db->select('*');
$this->db->where([
'status' => 1,
'country' => 5,
'product_price >' => 50,
'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();
``` | Can you "describe" type the table? If the field "product\_id" is text (Example: **VARCHAR**), then it will never follow the order asc/desc..
Sorry My English.. **Good work**! |
11,231,418 | assume a text file with about 40k lines of
```
Color LaserJet 8500, Color Laserjet 8550, Color Laserjet 8500N, Color Laserjet 8500DN, Color Laserjet 8500GN, Color Laserjet 8550N, Color Laserjet 8550DN, Color Laserjet 8550GN, Color Laserjet 8550 MFP,
```
as an example
any1 able to help me with a reg-ex that can trim out all data after the numbers, but before the comma? so that 8500N becomes just 8500
end result would be
```
Color Laserjet 8500, Color Laserjet 8550, Color Laserjet 8500, Color Laserjet 8500, Color Laserjet 8500, Color Laserjet 8550, Color Laserjet 8550, Color Laserjet 8550, Color Laserjet 8550,
```
amazing bonus kudos to anybody that can then somehow suggest the best way to remove duplicates in notepad++ (or other easily available program) | 2012/06/27 | [
"https://Stackoverflow.com/questions/11231418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1298883/"
] | You should replace each match of `(?<=\d)[^\d,]+(?=,)` with empty string.
The above regex reads: *"Any one or more non-digit and non-comma character(s) between digit and comma"*.
In case you may experience such number with trailing letter(s) at then end of string (or line) and you want that trim as well, even there is no comma behind, then use `(?<=\d)[^\d,]+(?:(?=,)|$)`
That reads similar, it just adds *"or end of string"* behind the first meaning.
---
***Update:***
Because it seems that Notepad++ does not support regex lookaround, then the solution is to replace `(\d)([^\d,]+)(,)` with `\1\3` or `(\d)[^\d,]+(,)` with `\1\2`. | How about this:
```
(.*?\d+)\D*(,)
```
It will match the entire thing, but you can just grab group 1 and 2. That will leave out the non-digits between the digits and commas.
The replace would be:
```
\1\2
```
[Here is a SO that elaborates that this is the only way to do this.](https://stackoverflow.com/questions/277547/regular-expression-to-skip-character-in-capture-group)
Or, as Arithmomaniac suggests, you could do this with one group, adding the comma back in after each match
```
(.*?\d+)\D*,
```
The replace would be
```
\1,
``` |
11,231,418 | assume a text file with about 40k lines of
```
Color LaserJet 8500, Color Laserjet 8550, Color Laserjet 8500N, Color Laserjet 8500DN, Color Laserjet 8500GN, Color Laserjet 8550N, Color Laserjet 8550DN, Color Laserjet 8550GN, Color Laserjet 8550 MFP,
```
as an example
any1 able to help me with a reg-ex that can trim out all data after the numbers, but before the comma? so that 8500N becomes just 8500
end result would be
```
Color Laserjet 8500, Color Laserjet 8550, Color Laserjet 8500, Color Laserjet 8500, Color Laserjet 8500, Color Laserjet 8550, Color Laserjet 8550, Color Laserjet 8550, Color Laserjet 8550,
```
amazing bonus kudos to anybody that can then somehow suggest the best way to remove duplicates in notepad++ (or other easily available program) | 2012/06/27 | [
"https://Stackoverflow.com/questions/11231418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1298883/"
] | You should replace each match of `(?<=\d)[^\d,]+(?=,)` with empty string.
The above regex reads: *"Any one or more non-digit and non-comma character(s) between digit and comma"*.
In case you may experience such number with trailing letter(s) at then end of string (or line) and you want that trim as well, even there is no comma behind, then use `(?<=\d)[^\d,]+(?:(?=,)|$)`
That reads similar, it just adds *"or end of string"* behind the first meaning.
---
***Update:***
Because it seems that Notepad++ does not support regex lookaround, then the solution is to replace `(\d)([^\d,]+)(,)` with `\1\3` or `(\d)[^\d,]+(,)` with `\1\2`. | Screenshot of regex in notepad++...
 |
46,659 | [This question](https://meta.stackexchange.com/questions/49550/why-am-i-getting-welcome-to-stack-overflow-visit-your-user-page-to-set-your-nam) was just migrated from SO, and it brought the restricted `[faq]` tag with it. Now no one but a moderator can remove this tag.
Restricted tags\* should be stripped from the question when it is migrated.
\*And blacklisted tags, when [this feature](https://meta.stackexchange.com/questions/19018/implement-a-tag-black-list) is implemented in 6 to 8 weeks | 2010/04/14 | [
"https://meta.stackexchange.com/questions/46659",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/132636/"
] | Great suggestion - no need to overwhelm the mods :)
This will be deployed either tonight or in tomorrow's push. | How about letting Community user drop all the moderator-only tags and add `support` tag as new revision, once a question is migrated to meta. |
48,128,912 | While writing a c program I encountered a puzzling behavior with printf and write. It appears that write is in some cases called before printf even though it is after it in the code (is printf asynchronous?). Also if there are two lines in the printf, output after that appears to be inserted between them. My question is what causes this behavior and how can I know what will happen when? What about other output functions (ex. puts) - can I look out for something in the documentation to know how they will behave with others. Example code:
```
#include <unistd.h>
#include <stdio.h>
int main(void)
{
write(STDOUT_FILENO, "1.", 2);
printf("2.");
write(STDOUT_FILENO, "3.", 2);
printf("4.\n5.");
printf("6.");
write(STDOUT_FILENO, "7.", 2);
return 0;
}
```
Output:
```
1.3.2.4.
7.5.6.
``` | 2018/01/06 | [
"https://Stackoverflow.com/questions/48128912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9156061/"
] | `write` is not buffered `printf` is. Whenever you use `write` it gets to the console - but `printf` is outputted when it gets `\n` here, because then the buffer is flushed.
That's why after `1.3.` you see `2.4.`
You can flush the output by using `fflush(stdout)` right after the `printf` calls. (`Steve Summit` commented this)
You may wonder there is no other `\n` after that `printf` so why do those characters are flushed?
On program termination the output buffer is also flushed. That is what causes the rest of the `printf` outputs to appear. The `setvbuf()` function may only be used after opening a stream and before any other operations have been performed on it.
---
Also as `zwol` mentioned you can turn of line bufferng of `stdout` using this before making any other call to standard I/O functions.
```
setvbuf(stdout, 0, _IONBF, 0)
^^^
causes input/output to be unbuffered
``` | In addition to the mentioned use of `fflush()` after each output operation, you could also make `stdout` *unbuffered* with
```
setvbuf(stdout, NULL, _IONBF, 0);
```
This way, all output by `printf`, `puts`, `putchar`, ... would appear in order with `write` output (without the need to sprinkle a lot of fflush()s around). |
34,881,724 | My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*". | 2016/01/19 | [
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] | Based on the comments provided here - <https://azure.microsoft.com/en-in/documentation/articles/cloud-services-dotnet-install-dotnet/>, there's no way to suppress this warning.
[](https://i.stack.imgur.com/Mnr6a.png)
>
> Is .Net 4.5.2 actually available on Azure?
>
>
>
As of today, yes. .Net 4.5.2 is available on Azure. In fact, we ported our solution from .Net 4.5 to .Net 4.5.2 just a few days ago.
In order to make use of .Net 4.5.2, you can't use "\*" for osVersion. You would need to target a specific OS version. Please see the Guest OS/Target Framework version matrix here: <https://azure.microsoft.com/en-in/documentation/articles/cloud-services-guestos-update-matrix/>.
Our solution makes use of osFamily 4 and based on this matrix, we ended up using `WA-GUEST-OS-4.26_201511-02` osVersion. Here's how our service configuration file looks like:
```
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="ServiceName" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="4" osVersion="WA-GUEST-OS-4.26_201511-02" schemaVersion="2015-04.2.6">
<Role name="RoleName">
</Role>
</ServiceConfiguration>
``` | You should to install .net 4.5.2 on webrole virtual machine.
Download the the web installer for the .NET framework you want to install
[.NET 4.5.2 Web Installer](http://go.microsoft.com/fwlink/p/?linkid=397703&clcid=0x409)
**For a Web Role**
1. In Solution Explorer, under In Roles in the cloud service project right click on your role and select Add>New Folder.
2. Create a folder named bin
Right click on the bin folder and select Add>Existing Item. Select the .NET installer and add it to the bin folder.
3. Define startup task for your role
**ServiceDefinition.csdef**
`<LocalResources>
<LocalStorage name="NETFXInstall" sizeInMB="1024" cleanOnRoleRecycle="false" />
</LocalResources>
<Startup>
<Task commandLine="install.cmd" executionContext="elevated" taskType="simple">
<Environment>
<Variable name="PathToNETFXInstall">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/LocalResources/LocalResource[@name='NETFXInstall']/@path" />
</Variable>
</Environment>
</Task>
</Startup>`
4. Create a file install.cmd and add it to role by right click on the role and selecting Add>Existing Item.
**install.cmd**
```
```
REM Set the value of netfx to install appropriate .NET Framework.
REM ***** To install .NET 4.5.2 set the variable netfx to "NDP452" *****
REM ***** To install .NET 4.6 set the variable netfx to "NDP46" *****
REM ***** To install .NET 4.6.1 set the variable netfx to "NDP461" *****
set netfx="NDP46"
REM ***** Needed to correctly install .NET 4.6.1, otherwise you may see an out of disk space error *****
set TMP=%PathToNETFXInstall%
set TEMP=%PathToNETFXInstall%
REM ***** Setup .NET filenames and registry keys *****
if %netfx%=="NDP461" goto NDP461
if %netfx%=="NDP46" goto NDP46
set netfxinstallfile="NDP452-KB2901954-Web.exe"
set netfxregkey="0x5cbf5"
goto logtimestamp
:NDP46
set netfxinstallfile="NDP46-KB3045560-Web.exe"
set netfxregkey="0x60051"
goto logtimestamp
:NDP461
set netfxinstallfile="NDP461-KB3102438-Web.exe"
set netfxregkey="0x6041f"
:logtimestamp
REM ***** Setup LogFile with timestamp *****
set timehour=%time:~0,2%
set timestamp=%date:~-4,4%%date:~-10,2%%date:~-7,2%-%timehour: =0%%time:~3,2%
md "%PathToNETFXInstall%\log"
set startuptasklog="%PathToNETFXInstall%log\startuptasklog-%timestamp%.txt"
set netfxinstallerlog="%PathToNETFXInstall%log\NetFXInstallerLog-%timestamp%"
echo Logfile generated at: %startuptasklog% >> %startuptasklog%
echo TMP set to: %TMP% >> %startuptasklog%
echo TEMP set to: %TEMP% >> %startuptasklog%
REM ***** Check if .NET is installed *****
echo Checking if .NET (%netfx%) is installed >> %startuptasklog%
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v Release | Find %netfxregkey%
if %ERRORLEVEL%== 0 goto end
REM ***** Installing .NET *****
echo Installing .NET: start /wait %~dp0%netfxinstallfile% /q /serialdownload /log %netfxinstallerlog% >> %startuptasklog%
start /wait %~dp0%netfxinstallfile% /q /serialdownload /log %netfxinstallerlog% >> %startuptasklog% 2>>&1
:end
echo install.cmd completed: %date:~-4,4%%date:~-10,2%%date:~-7,2%-%timehour: =0%%time:~3,2% >> %startuptasklog%
```
```
You can get the full detailed procedures here:
[Install .NET on a Cloud Service Role](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-install-dotnet/)
--------------------------------------------------------------------------------------------------------------------------------------
I think you should implement this workaround until Azure full support .net 4.5.2 may be is not yet supported in your region.Try creating a new cloud instance in EastUS to test if net fx 4.5.2 is already supported. |
34,881,724 | My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*". | 2016/01/19 | [
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] | >
> Is .Net 4.5.2 actually available on Azure?
>
>
>
[Yes](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-guestos-update-matrix/). .NET 4.5.2 is available in the current `osVersion` \* of `osFamily` 2, 3 and 4.
>
> Is there a way to suppress warnings that don't have codes?
>
>
>
Cloud service projects upgraded to Azure SDK 2.9 no longer generate this warning. Projects using a prior version of the SDK (even if version 2.9 is installed) still generate this warning. To suppress this warning without upgrading the project to SDK 2.9 you can add the following snippet to your .ccproj file.
`<ItemGroup>
<WindowsAzureFrameworkMoniker Include=".NETFramework,Version=v4.5.2" />
</ItemGroup>` | You should to install .net 4.5.2 on webrole virtual machine.
Download the the web installer for the .NET framework you want to install
[.NET 4.5.2 Web Installer](http://go.microsoft.com/fwlink/p/?linkid=397703&clcid=0x409)
**For a Web Role**
1. In Solution Explorer, under In Roles in the cloud service project right click on your role and select Add>New Folder.
2. Create a folder named bin
Right click on the bin folder and select Add>Existing Item. Select the .NET installer and add it to the bin folder.
3. Define startup task for your role
**ServiceDefinition.csdef**
`<LocalResources>
<LocalStorage name="NETFXInstall" sizeInMB="1024" cleanOnRoleRecycle="false" />
</LocalResources>
<Startup>
<Task commandLine="install.cmd" executionContext="elevated" taskType="simple">
<Environment>
<Variable name="PathToNETFXInstall">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/LocalResources/LocalResource[@name='NETFXInstall']/@path" />
</Variable>
</Environment>
</Task>
</Startup>`
4. Create a file install.cmd and add it to role by right click on the role and selecting Add>Existing Item.
**install.cmd**
```
```
REM Set the value of netfx to install appropriate .NET Framework.
REM ***** To install .NET 4.5.2 set the variable netfx to "NDP452" *****
REM ***** To install .NET 4.6 set the variable netfx to "NDP46" *****
REM ***** To install .NET 4.6.1 set the variable netfx to "NDP461" *****
set netfx="NDP46"
REM ***** Needed to correctly install .NET 4.6.1, otherwise you may see an out of disk space error *****
set TMP=%PathToNETFXInstall%
set TEMP=%PathToNETFXInstall%
REM ***** Setup .NET filenames and registry keys *****
if %netfx%=="NDP461" goto NDP461
if %netfx%=="NDP46" goto NDP46
set netfxinstallfile="NDP452-KB2901954-Web.exe"
set netfxregkey="0x5cbf5"
goto logtimestamp
:NDP46
set netfxinstallfile="NDP46-KB3045560-Web.exe"
set netfxregkey="0x60051"
goto logtimestamp
:NDP461
set netfxinstallfile="NDP461-KB3102438-Web.exe"
set netfxregkey="0x6041f"
:logtimestamp
REM ***** Setup LogFile with timestamp *****
set timehour=%time:~0,2%
set timestamp=%date:~-4,4%%date:~-10,2%%date:~-7,2%-%timehour: =0%%time:~3,2%
md "%PathToNETFXInstall%\log"
set startuptasklog="%PathToNETFXInstall%log\startuptasklog-%timestamp%.txt"
set netfxinstallerlog="%PathToNETFXInstall%log\NetFXInstallerLog-%timestamp%"
echo Logfile generated at: %startuptasklog% >> %startuptasklog%
echo TMP set to: %TMP% >> %startuptasklog%
echo TEMP set to: %TEMP% >> %startuptasklog%
REM ***** Check if .NET is installed *****
echo Checking if .NET (%netfx%) is installed >> %startuptasklog%
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v Release | Find %netfxregkey%
if %ERRORLEVEL%== 0 goto end
REM ***** Installing .NET *****
echo Installing .NET: start /wait %~dp0%netfxinstallfile% /q /serialdownload /log %netfxinstallerlog% >> %startuptasklog%
start /wait %~dp0%netfxinstallfile% /q /serialdownload /log %netfxinstallerlog% >> %startuptasklog% 2>>&1
:end
echo install.cmd completed: %date:~-4,4%%date:~-10,2%%date:~-7,2%-%timehour: =0%%time:~3,2% >> %startuptasklog%
```
```
You can get the full detailed procedures here:
[Install .NET on a Cloud Service Role](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-install-dotnet/)
--------------------------------------------------------------------------------------------------------------------------------------
I think you should implement this workaround until Azure full support .net 4.5.2 may be is not yet supported in your region.Try creating a new cloud instance in EastUS to test if net fx 4.5.2 is already supported. |
34,881,724 | My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*". | 2016/01/19 | [
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] | I'm getting a similar version of this error, essentially, the new version of it:
>
> Microsoft Azure Cloud Service projects only support roles that run on
> .NET Framework versions 4.0,
> 4.5 and 4.6. Please set the Target Framework property in the project settings for project 'MyWorkerRole' to .NET Framework 4.0, .NET
> Framework 4.5 or .NET Framework 4.6.
>
>
>
And
>
> The project 'MyWorkerRole' targets .NET Framework 4.7.2. To make sure
> that the role starts, this version of the .NET Framework must be
> installed on the virtual machine for this role. You can use a startup
> task to install the required version, if it is not already installed
> as part of the Microsoft Azure guest OS. For more details, see
> <https://go.microsoft.com/fwlink/?LinkId=309796>.
>
>
>
Even after following the directions located at the link in the message (which were helpful in creating the installer scripts, etc.), the warning message did not go away. I tried all sorts of stuff including the framework moniker item groups, all kinds of properties, etc.
Ultimately, I ended up turning my build on `Detailed` output, figured out the .targets file this was coming from and inspected it. -- I found that there is just no built-in way to suppress it.
HOWEVER, there is a hack you can do -- I basically copied that block from the .targets file into my .ccproj file, and removed the part about the warning. Basically I added the following to the end of my .ccproj file, and ***BADAO!***, just like that **NO MORE WARNINGS!**:
```
<Target Name="ValidateRoleTargetFramework"
Outputs="%(RoleReference.Identity)"
Condition="'@(RoleReference)' != ''">
<PropertyGroup>
<_RoleTargetFramework>%(RoleReference.RoleTargetFramework)</_RoleTargetFramework>
<_IsValidRoleTargetFramework>False</_IsValidRoleTargetFramework>
<_IsValidRoleTargetFramework
Condition="$(_RoleTargetFramework.StartsWith('v4.0')) Or $(_RoleTargetFramework.StartsWith('v4.5')) Or $(_RoleTargetFramework.StartsWith('v4.6'))">True</_IsValidRoleTargetFramework>
</PropertyGroup>
</Target>
```
(Obviously, you should put that INSIDE your `<Project />` tag, of course.) | You should to install .net 4.5.2 on webrole virtual machine.
Download the the web installer for the .NET framework you want to install
[.NET 4.5.2 Web Installer](http://go.microsoft.com/fwlink/p/?linkid=397703&clcid=0x409)
**For a Web Role**
1. In Solution Explorer, under In Roles in the cloud service project right click on your role and select Add>New Folder.
2. Create a folder named bin
Right click on the bin folder and select Add>Existing Item. Select the .NET installer and add it to the bin folder.
3. Define startup task for your role
**ServiceDefinition.csdef**
`<LocalResources>
<LocalStorage name="NETFXInstall" sizeInMB="1024" cleanOnRoleRecycle="false" />
</LocalResources>
<Startup>
<Task commandLine="install.cmd" executionContext="elevated" taskType="simple">
<Environment>
<Variable name="PathToNETFXInstall">
<RoleInstanceValue xpath="/RoleEnvironment/CurrentInstance/LocalResources/LocalResource[@name='NETFXInstall']/@path" />
</Variable>
</Environment>
</Task>
</Startup>`
4. Create a file install.cmd and add it to role by right click on the role and selecting Add>Existing Item.
**install.cmd**
```
```
REM Set the value of netfx to install appropriate .NET Framework.
REM ***** To install .NET 4.5.2 set the variable netfx to "NDP452" *****
REM ***** To install .NET 4.6 set the variable netfx to "NDP46" *****
REM ***** To install .NET 4.6.1 set the variable netfx to "NDP461" *****
set netfx="NDP46"
REM ***** Needed to correctly install .NET 4.6.1, otherwise you may see an out of disk space error *****
set TMP=%PathToNETFXInstall%
set TEMP=%PathToNETFXInstall%
REM ***** Setup .NET filenames and registry keys *****
if %netfx%=="NDP461" goto NDP461
if %netfx%=="NDP46" goto NDP46
set netfxinstallfile="NDP452-KB2901954-Web.exe"
set netfxregkey="0x5cbf5"
goto logtimestamp
:NDP46
set netfxinstallfile="NDP46-KB3045560-Web.exe"
set netfxregkey="0x60051"
goto logtimestamp
:NDP461
set netfxinstallfile="NDP461-KB3102438-Web.exe"
set netfxregkey="0x6041f"
:logtimestamp
REM ***** Setup LogFile with timestamp *****
set timehour=%time:~0,2%
set timestamp=%date:~-4,4%%date:~-10,2%%date:~-7,2%-%timehour: =0%%time:~3,2%
md "%PathToNETFXInstall%\log"
set startuptasklog="%PathToNETFXInstall%log\startuptasklog-%timestamp%.txt"
set netfxinstallerlog="%PathToNETFXInstall%log\NetFXInstallerLog-%timestamp%"
echo Logfile generated at: %startuptasklog% >> %startuptasklog%
echo TMP set to: %TMP% >> %startuptasklog%
echo TEMP set to: %TEMP% >> %startuptasklog%
REM ***** Check if .NET is installed *****
echo Checking if .NET (%netfx%) is installed >> %startuptasklog%
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v Release | Find %netfxregkey%
if %ERRORLEVEL%== 0 goto end
REM ***** Installing .NET *****
echo Installing .NET: start /wait %~dp0%netfxinstallfile% /q /serialdownload /log %netfxinstallerlog% >> %startuptasklog%
start /wait %~dp0%netfxinstallfile% /q /serialdownload /log %netfxinstallerlog% >> %startuptasklog% 2>>&1
:end
echo install.cmd completed: %date:~-4,4%%date:~-10,2%%date:~-7,2%-%timehour: =0%%time:~3,2% >> %startuptasklog%
```
```
You can get the full detailed procedures here:
[Install .NET on a Cloud Service Role](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-dotnet-install-dotnet/)
--------------------------------------------------------------------------------------------------------------------------------------
I think you should implement this workaround until Azure full support .net 4.5.2 may be is not yet supported in your region.Try creating a new cloud instance in EastUS to test if net fx 4.5.2 is already supported. |
34,881,724 | My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*". | 2016/01/19 | [
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] | >
> Is .Net 4.5.2 actually available on Azure?
>
>
>
[Yes](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-guestos-update-matrix/). .NET 4.5.2 is available in the current `osVersion` \* of `osFamily` 2, 3 and 4.
>
> Is there a way to suppress warnings that don't have codes?
>
>
>
Cloud service projects upgraded to Azure SDK 2.9 no longer generate this warning. Projects using a prior version of the SDK (even if version 2.9 is installed) still generate this warning. To suppress this warning without upgrading the project to SDK 2.9 you can add the following snippet to your .ccproj file.
`<ItemGroup>
<WindowsAzureFrameworkMoniker Include=".NETFramework,Version=v4.5.2" />
</ItemGroup>` | Based on the comments provided here - <https://azure.microsoft.com/en-in/documentation/articles/cloud-services-dotnet-install-dotnet/>, there's no way to suppress this warning.
[](https://i.stack.imgur.com/Mnr6a.png)
>
> Is .Net 4.5.2 actually available on Azure?
>
>
>
As of today, yes. .Net 4.5.2 is available on Azure. In fact, we ported our solution from .Net 4.5 to .Net 4.5.2 just a few days ago.
In order to make use of .Net 4.5.2, you can't use "\*" for osVersion. You would need to target a specific OS version. Please see the Guest OS/Target Framework version matrix here: <https://azure.microsoft.com/en-in/documentation/articles/cloud-services-guestos-update-matrix/>.
Our solution makes use of osFamily 4 and based on this matrix, we ended up using `WA-GUEST-OS-4.26_201511-02` osVersion. Here's how our service configuration file looks like:
```
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="ServiceName" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="4" osVersion="WA-GUEST-OS-4.26_201511-02" schemaVersion="2015-04.2.6">
<Role name="RoleName">
</Role>
</ServiceConfiguration>
``` |
34,881,724 | My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*". | 2016/01/19 | [
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] | Based on the comments provided here - <https://azure.microsoft.com/en-in/documentation/articles/cloud-services-dotnet-install-dotnet/>, there's no way to suppress this warning.
[](https://i.stack.imgur.com/Mnr6a.png)
>
> Is .Net 4.5.2 actually available on Azure?
>
>
>
As of today, yes. .Net 4.5.2 is available on Azure. In fact, we ported our solution from .Net 4.5 to .Net 4.5.2 just a few days ago.
In order to make use of .Net 4.5.2, you can't use "\*" for osVersion. You would need to target a specific OS version. Please see the Guest OS/Target Framework version matrix here: <https://azure.microsoft.com/en-in/documentation/articles/cloud-services-guestos-update-matrix/>.
Our solution makes use of osFamily 4 and based on this matrix, we ended up using `WA-GUEST-OS-4.26_201511-02` osVersion. Here's how our service configuration file looks like:
```
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="ServiceName" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="4" osVersion="WA-GUEST-OS-4.26_201511-02" schemaVersion="2015-04.2.6">
<Role name="RoleName">
</Role>
</ServiceConfiguration>
``` | I'm getting a similar version of this error, essentially, the new version of it:
>
> Microsoft Azure Cloud Service projects only support roles that run on
> .NET Framework versions 4.0,
> 4.5 and 4.6. Please set the Target Framework property in the project settings for project 'MyWorkerRole' to .NET Framework 4.0, .NET
> Framework 4.5 or .NET Framework 4.6.
>
>
>
And
>
> The project 'MyWorkerRole' targets .NET Framework 4.7.2. To make sure
> that the role starts, this version of the .NET Framework must be
> installed on the virtual machine for this role. You can use a startup
> task to install the required version, if it is not already installed
> as part of the Microsoft Azure guest OS. For more details, see
> <https://go.microsoft.com/fwlink/?LinkId=309796>.
>
>
>
Even after following the directions located at the link in the message (which were helpful in creating the installer scripts, etc.), the warning message did not go away. I tried all sorts of stuff including the framework moniker item groups, all kinds of properties, etc.
Ultimately, I ended up turning my build on `Detailed` output, figured out the .targets file this was coming from and inspected it. -- I found that there is just no built-in way to suppress it.
HOWEVER, there is a hack you can do -- I basically copied that block from the .targets file into my .ccproj file, and removed the part about the warning. Basically I added the following to the end of my .ccproj file, and ***BADAO!***, just like that **NO MORE WARNINGS!**:
```
<Target Name="ValidateRoleTargetFramework"
Outputs="%(RoleReference.Identity)"
Condition="'@(RoleReference)' != ''">
<PropertyGroup>
<_RoleTargetFramework>%(RoleReference.RoleTargetFramework)</_RoleTargetFramework>
<_IsValidRoleTargetFramework>False</_IsValidRoleTargetFramework>
<_IsValidRoleTargetFramework
Condition="$(_RoleTargetFramework.StartsWith('v4.0')) Or $(_RoleTargetFramework.StartsWith('v4.5')) Or $(_RoleTargetFramework.StartsWith('v4.6'))">True</_IsValidRoleTargetFramework>
</PropertyGroup>
</Target>
```
(Obviously, you should put that INSIDE your `<Project />` tag, of course.) |
34,881,724 | My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*". | 2016/01/19 | [
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] | >
> Is .Net 4.5.2 actually available on Azure?
>
>
>
[Yes](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-guestos-update-matrix/). .NET 4.5.2 is available in the current `osVersion` \* of `osFamily` 2, 3 and 4.
>
> Is there a way to suppress warnings that don't have codes?
>
>
>
Cloud service projects upgraded to Azure SDK 2.9 no longer generate this warning. Projects using a prior version of the SDK (even if version 2.9 is installed) still generate this warning. To suppress this warning without upgrading the project to SDK 2.9 you can add the following snippet to your .ccproj file.
`<ItemGroup>
<WindowsAzureFrameworkMoniker Include=".NETFramework,Version=v4.5.2" />
</ItemGroup>` | I'm getting a similar version of this error, essentially, the new version of it:
>
> Microsoft Azure Cloud Service projects only support roles that run on
> .NET Framework versions 4.0,
> 4.5 and 4.6. Please set the Target Framework property in the project settings for project 'MyWorkerRole' to .NET Framework 4.0, .NET
> Framework 4.5 or .NET Framework 4.6.
>
>
>
And
>
> The project 'MyWorkerRole' targets .NET Framework 4.7.2. To make sure
> that the role starts, this version of the .NET Framework must be
> installed on the virtual machine for this role. You can use a startup
> task to install the required version, if it is not already installed
> as part of the Microsoft Azure guest OS. For more details, see
> <https://go.microsoft.com/fwlink/?LinkId=309796>.
>
>
>
Even after following the directions located at the link in the message (which were helpful in creating the installer scripts, etc.), the warning message did not go away. I tried all sorts of stuff including the framework moniker item groups, all kinds of properties, etc.
Ultimately, I ended up turning my build on `Detailed` output, figured out the .targets file this was coming from and inspected it. -- I found that there is just no built-in way to suppress it.
HOWEVER, there is a hack you can do -- I basically copied that block from the .targets file into my .ccproj file, and removed the part about the warning. Basically I added the following to the end of my .ccproj file, and ***BADAO!***, just like that **NO MORE WARNINGS!**:
```
<Target Name="ValidateRoleTargetFramework"
Outputs="%(RoleReference.Identity)"
Condition="'@(RoleReference)' != ''">
<PropertyGroup>
<_RoleTargetFramework>%(RoleReference.RoleTargetFramework)</_RoleTargetFramework>
<_IsValidRoleTargetFramework>False</_IsValidRoleTargetFramework>
<_IsValidRoleTargetFramework
Condition="$(_RoleTargetFramework.StartsWith('v4.0')) Or $(_RoleTargetFramework.StartsWith('v4.5')) Or $(_RoleTargetFramework.StartsWith('v4.6'))">True</_IsValidRoleTargetFramework>
</PropertyGroup>
</Target>
```
(Obviously, you should put that INSIDE your `<Project />` tag, of course.) |
89,359 | I've managed to get a Wubi installation onto my USB flash drive, which works on *both* VirtualBox and on a native computer. (The data is on the `root.disk` file.)
It works *completely fine*, except for one little caveat: the files I create or modify don't actually persist on the drive!
My grub.cfg:
```
menuentry "Ubuntu, Linux 2.6.38-13-generic" {
insmod part_msdos
insmod ntfs
set root='(/dev/sdb,msdos1)'
search --no-floppy --fs-uuid --set=root 02E8D1D3E8D1C4D7
loopback loop0 /ubuntu/disks/root.disk
set root=(loop0)
linux /boot/vmlinuz-2.6.38-13-generic root=UUID=02E8D1D3E8D1C4D7 loop=/ubuntu/disks/root.disk ro acpi_sleep=nonvs acpi_osi=Linux acpi_backlight=vendor splash
initrd /boot/initrd.img-2.6.38-13-generic
}
```
My fstab:
```
# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc nodev,noexec,nosuid 0 0
/host/ubuntu/disks/root.disk / ext2 loop,errors=remount-ro 0 1
```
Ideas on why this is happening? | 2011/12/21 | [
"https://askubuntu.com/questions/89359",
"https://askubuntu.com",
"https://askubuntu.com/users/8678/"
] | I feel so silly.
VirtualBox was never writing the changes to the file; it was discarding them after each boot.
It was fine on the native machine. | I see a read-only flag on the following line:
`linux /boot/vmlinuz-2.6.38-13-generic root=UUID=02E8D1D3E8D1C4D7 loop=/ubuntu/disks/root.disk ro`
on your grub.cfg. Have you tried removing this flag? |
364,052 | I'm using Minecraft Education Edition. I want to summon 3 to 5 fish whenever a player comes closer to a location in the sea and I want it to put some delay for summoning too, for example: 3 seconds.
Can I achieve this with command blocks or with other methods? | 2020/02/16 | [
"https://gaming.stackexchange.com/questions/364052",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/244115/"
] | **Try resolving the problem using a 'Cure All' batch file.**
These files list all known active effects from the base game and DLC (and the Wet & Cold and Skyrim Immersive Creatures mods), preceded by the `player.sme` command (which stands for 'Stop Magic Effect' on 'player'), and can be executed using the in-game console.
You can find an archive file with these batch files under *Solution 4* on [this page](https://forums.nexusmods.com/index.php?/topic/872861-tutorial-removing-unwanted-magic-effects-from-the-player/). [Here](http://forums.nexusmods.com/index.php?app=core&module=attach§ion=attach&attach_id=40779) is a direct link (you need a (free) account in order to download). The file was created by NexusForums user *LubitelSofta*.
Be sure to take off all your (enchanted) gear beforehand.
Instructions as per the Nexus forum thread:
>
> * Extract the files to your Skyrim root folder (not the data subfolder).
> * Edit the Dawnguard, Dragonborn, or WC or SIC batch files (if necessary) so that every shader or effect ID matches your load order (see above).
> * Start the game.
> * In the console type `bat <filename>` (without quotes), e.g. `bat DBMGEF`.
>
>
> | You can remove all applied spells by using player.DispelAllSpells, I believe. Note that this will also remove blessings and apparel effects, so you will need to unequip and re-equip armor to re-apply the effects from armor. |
64,731 | I'm looking add-in a bit more speficity to the WP Cron intervals. To add a "weekly" interval, I've done the following:
```
function re_not_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('weekly')
);
return $schedules;
}
add_filter('cron_schedules', 're_not_add_weekly');
```
Which works great, but - the extra sauce here is getting that cron to run on a specific day:
```
if( !wp_next_scheduled( 're_not_mail' ) ) {
wp_schedule_event( time(), 'weekly', 're_not_mail' );
}
```
Anyone have any thoughts on the best way to accomplish this using WP Cron (assuming this isn't per a specific site that we'll have control over their cPanel/CRON area). Thanks!
Update
======
Going at this full-force and found [an article](http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/?search_index=1) that may have clarified things a bit more, but doesn't exactly answer my question. The basic gist of that article states that the WP Cron isn't as flexible (past the "hourly, daily, weekly" params), so extending it to something like *weekly on a certain day* seems a bit farfetched.
The issue (calling it an issue out of confusion/frustration) I have with that is -> sure, I could disable WP CRON and have WP CRON run once a week using the server CRON, BUT, that also means that the items that are normally run, like plugin/theme updates, post deletions/publishes based on CRON are put on a backlog for an entire week (if I wanted CRON to run once a week every Monday for example).
I'd have to assume others have come across this, so anymore insight on this would be a huge help. Thanks! | 2012/09/10 | [
"https://wordpress.stackexchange.com/questions/64731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9605/"
] | WP-Cron is not intended to be that precise, and should not be used if you have to have things scheduled at specific times. WP-Cron is a "best effort" scheduling mechanism, and it cannot guarantee run timing like a real cron system can.
If you need precision of this nature, the only real answer is to not use WP-Cron for it. It's not designed for that, and it cannot do it. Any hacky code you attempt to add to it to make it capable of this won't fix that underlying problem.
Use a real cron system. | According to [Codex you can use wp\_get\_schedules](http://codex.wordpress.org/Function_Reference/wp_get_schedules) to add in an option like Weekly (which you've already done).
WP-Cron was not intended to have all the Cron functions so why not just login to the server and create a cron job to call your PHP file only on Monday and add something like this to your crontab
`* 07 * * Mon root cmd` |
64,731 | I'm looking add-in a bit more speficity to the WP Cron intervals. To add a "weekly" interval, I've done the following:
```
function re_not_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('weekly')
);
return $schedules;
}
add_filter('cron_schedules', 're_not_add_weekly');
```
Which works great, but - the extra sauce here is getting that cron to run on a specific day:
```
if( !wp_next_scheduled( 're_not_mail' ) ) {
wp_schedule_event( time(), 'weekly', 're_not_mail' );
}
```
Anyone have any thoughts on the best way to accomplish this using WP Cron (assuming this isn't per a specific site that we'll have control over their cPanel/CRON area). Thanks!
Update
======
Going at this full-force and found [an article](http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/?search_index=1) that may have clarified things a bit more, but doesn't exactly answer my question. The basic gist of that article states that the WP Cron isn't as flexible (past the "hourly, daily, weekly" params), so extending it to something like *weekly on a certain day* seems a bit farfetched.
The issue (calling it an issue out of confusion/frustration) I have with that is -> sure, I could disable WP CRON and have WP CRON run once a week using the server CRON, BUT, that also means that the items that are normally run, like plugin/theme updates, post deletions/publishes based on CRON are put on a backlog for an entire week (if I wanted CRON to run once a week every Monday for example).
I'd have to assume others have come across this, so anymore insight on this would be a huge help. Thanks! | 2012/09/10 | [
"https://wordpress.stackexchange.com/questions/64731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9605/"
] | If you have important WP cron jobs on a schedule you should of course have a system cron job running that regularly calls WP cron to make things are always fired when you need them.
If you need a specific time/date for your WP cron runs you can always schedule a single event and have the called method schedule the next event.
Simple example:
```
function some_awesome_hook() {
// Do stuff here
// Run next Monday
$next_run = strtotime('next monday');
// Clear hook, just in case
wp_clear_scheduled_hook('some_awesome_hook');
// Add our event
wp_schedule_single_event($next_run, 'some_awesome_hook');
}
// Run next Monday
$first_run = strtotime('next monday');
// Add our event
wp_schedule_single_event($first_run, 'some_awesome_hook');
```
OOP style:
```
class My_Sweet_Plugin {
public $cron_hook;
public function __construct() {
// Store our cron hook name
$this->cron_hook = 'my_awesome_cron_hook';
// Install cron!
$this->setup_cron();
// Add action that points to class method
add_action($this->cron_hook, array($this, 'my_awesome_function'));
}
public function setup_cron() {
// Clear existing hooks
wp_clear_scheduled_hook($this->cron_hook);
// Next run time
$next_run = strtotime('next monday');
// Add single event
wp_schedule_single_event($first_run, $this->cron_hook);
}
public function my_awesome_function() {
// Do stuff!
// Setup our next run
$this->setup_cron();
}
}
``` | According to [Codex you can use wp\_get\_schedules](http://codex.wordpress.org/Function_Reference/wp_get_schedules) to add in an option like Weekly (which you've already done).
WP-Cron was not intended to have all the Cron functions so why not just login to the server and create a cron job to call your PHP file only on Monday and add something like this to your crontab
`* 07 * * Mon root cmd` |
64,731 | I'm looking add-in a bit more speficity to the WP Cron intervals. To add a "weekly" interval, I've done the following:
```
function re_not_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('weekly')
);
return $schedules;
}
add_filter('cron_schedules', 're_not_add_weekly');
```
Which works great, but - the extra sauce here is getting that cron to run on a specific day:
```
if( !wp_next_scheduled( 're_not_mail' ) ) {
wp_schedule_event( time(), 'weekly', 're_not_mail' );
}
```
Anyone have any thoughts on the best way to accomplish this using WP Cron (assuming this isn't per a specific site that we'll have control over their cPanel/CRON area). Thanks!
Update
======
Going at this full-force and found [an article](http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/?search_index=1) that may have clarified things a bit more, but doesn't exactly answer my question. The basic gist of that article states that the WP Cron isn't as flexible (past the "hourly, daily, weekly" params), so extending it to something like *weekly on a certain day* seems a bit farfetched.
The issue (calling it an issue out of confusion/frustration) I have with that is -> sure, I could disable WP CRON and have WP CRON run once a week using the server CRON, BUT, that also means that the items that are normally run, like plugin/theme updates, post deletions/publishes based on CRON are put on a backlog for an entire week (if I wanted CRON to run once a week every Monday for example).
I'd have to assume others have come across this, so anymore insight on this would be a huge help. Thanks! | 2012/09/10 | [
"https://wordpress.stackexchange.com/questions/64731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9605/"
] | WP-Cron is not intended to be that precise, and should not be used if you have to have things scheduled at specific times. WP-Cron is a "best effort" scheduling mechanism, and it cannot guarantee run timing like a real cron system can.
If you need precision of this nature, the only real answer is to not use WP-Cron for it. It's not designed for that, and it cannot do it. Any hacky code you attempt to add to it to make it capable of this won't fix that underlying problem.
Use a real cron system. | If you have important WP cron jobs on a schedule you should of course have a system cron job running that regularly calls WP cron to make things are always fired when you need them.
If you need a specific time/date for your WP cron runs you can always schedule a single event and have the called method schedule the next event.
Simple example:
```
function some_awesome_hook() {
// Do stuff here
// Run next Monday
$next_run = strtotime('next monday');
// Clear hook, just in case
wp_clear_scheduled_hook('some_awesome_hook');
// Add our event
wp_schedule_single_event($next_run, 'some_awesome_hook');
}
// Run next Monday
$first_run = strtotime('next monday');
// Add our event
wp_schedule_single_event($first_run, 'some_awesome_hook');
```
OOP style:
```
class My_Sweet_Plugin {
public $cron_hook;
public function __construct() {
// Store our cron hook name
$this->cron_hook = 'my_awesome_cron_hook';
// Install cron!
$this->setup_cron();
// Add action that points to class method
add_action($this->cron_hook, array($this, 'my_awesome_function'));
}
public function setup_cron() {
// Clear existing hooks
wp_clear_scheduled_hook($this->cron_hook);
// Next run time
$next_run = strtotime('next monday');
// Add single event
wp_schedule_single_event($first_run, $this->cron_hook);
}
public function my_awesome_function() {
// Do stuff!
// Setup our next run
$this->setup_cron();
}
}
``` |
64,731 | I'm looking add-in a bit more speficity to the WP Cron intervals. To add a "weekly" interval, I've done the following:
```
function re_not_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('weekly')
);
return $schedules;
}
add_filter('cron_schedules', 're_not_add_weekly');
```
Which works great, but - the extra sauce here is getting that cron to run on a specific day:
```
if( !wp_next_scheduled( 're_not_mail' ) ) {
wp_schedule_event( time(), 'weekly', 're_not_mail' );
}
```
Anyone have any thoughts on the best way to accomplish this using WP Cron (assuming this isn't per a specific site that we'll have control over their cPanel/CRON area). Thanks!
Update
======
Going at this full-force and found [an article](http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/?search_index=1) that may have clarified things a bit more, but doesn't exactly answer my question. The basic gist of that article states that the WP Cron isn't as flexible (past the "hourly, daily, weekly" params), so extending it to something like *weekly on a certain day* seems a bit farfetched.
The issue (calling it an issue out of confusion/frustration) I have with that is -> sure, I could disable WP CRON and have WP CRON run once a week using the server CRON, BUT, that also means that the items that are normally run, like plugin/theme updates, post deletions/publishes based on CRON are put on a backlog for an entire week (if I wanted CRON to run once a week every Monday for example).
I'd have to assume others have come across this, so anymore insight on this would be a huge help. Thanks! | 2012/09/10 | [
"https://wordpress.stackexchange.com/questions/64731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9605/"
] | WP-Cron is not intended to be that precise, and should not be used if you have to have things scheduled at specific times. WP-Cron is a "best effort" scheduling mechanism, and it cannot guarantee run timing like a real cron system can.
If you need precision of this nature, the only real answer is to not use WP-Cron for it. It's not designed for that, and it cannot do it. Any hacky code you attempt to add to it to make it capable of this won't fix that underlying problem.
Use a real cron system. | You can use this approach
```
//Your cron function which you want to execute any specific day, e.g. Monday
function daily_cron_callback() {
$timestamp = time();
if(date('D', $timestamp) !== 'Mon') { //do nothing, if not Monday
return;
}
//Process your logic here
}
``` |
64,731 | I'm looking add-in a bit more speficity to the WP Cron intervals. To add a "weekly" interval, I've done the following:
```
function re_not_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('weekly')
);
return $schedules;
}
add_filter('cron_schedules', 're_not_add_weekly');
```
Which works great, but - the extra sauce here is getting that cron to run on a specific day:
```
if( !wp_next_scheduled( 're_not_mail' ) ) {
wp_schedule_event( time(), 'weekly', 're_not_mail' );
}
```
Anyone have any thoughts on the best way to accomplish this using WP Cron (assuming this isn't per a specific site that we'll have control over their cPanel/CRON area). Thanks!
Update
======
Going at this full-force and found [an article](http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/?search_index=1) that may have clarified things a bit more, but doesn't exactly answer my question. The basic gist of that article states that the WP Cron isn't as flexible (past the "hourly, daily, weekly" params), so extending it to something like *weekly on a certain day* seems a bit farfetched.
The issue (calling it an issue out of confusion/frustration) I have with that is -> sure, I could disable WP CRON and have WP CRON run once a week using the server CRON, BUT, that also means that the items that are normally run, like plugin/theme updates, post deletions/publishes based on CRON are put on a backlog for an entire week (if I wanted CRON to run once a week every Monday for example).
I'd have to assume others have come across this, so anymore insight on this would be a huge help. Thanks! | 2012/09/10 | [
"https://wordpress.stackexchange.com/questions/64731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9605/"
] | If you have important WP cron jobs on a schedule you should of course have a system cron job running that regularly calls WP cron to make things are always fired when you need them.
If you need a specific time/date for your WP cron runs you can always schedule a single event and have the called method schedule the next event.
Simple example:
```
function some_awesome_hook() {
// Do stuff here
// Run next Monday
$next_run = strtotime('next monday');
// Clear hook, just in case
wp_clear_scheduled_hook('some_awesome_hook');
// Add our event
wp_schedule_single_event($next_run, 'some_awesome_hook');
}
// Run next Monday
$first_run = strtotime('next monday');
// Add our event
wp_schedule_single_event($first_run, 'some_awesome_hook');
```
OOP style:
```
class My_Sweet_Plugin {
public $cron_hook;
public function __construct() {
// Store our cron hook name
$this->cron_hook = 'my_awesome_cron_hook';
// Install cron!
$this->setup_cron();
// Add action that points to class method
add_action($this->cron_hook, array($this, 'my_awesome_function'));
}
public function setup_cron() {
// Clear existing hooks
wp_clear_scheduled_hook($this->cron_hook);
// Next run time
$next_run = strtotime('next monday');
// Add single event
wp_schedule_single_event($first_run, $this->cron_hook);
}
public function my_awesome_function() {
// Do stuff!
// Setup our next run
$this->setup_cron();
}
}
``` | You can use this approach
```
//Your cron function which you want to execute any specific day, e.g. Monday
function daily_cron_callback() {
$timestamp = time();
if(date('D', $timestamp) !== 'Mon') { //do nothing, if not Monday
return;
}
//Process your logic here
}
``` |
3,274,167 | Let's consider the following problem. Imagine there is a tank filled up water (it's volume is equal to $V$). We connect two pumps to out tank. The first one pumps into the tank a mixture of 10% alcohol and water ($s\_1$ liter per minute). The second one pumps out of the tank what's inside (with the speed equal to $s\_2$ liters per minute).
I am to find the function $x(t)$ which describes the concentration of alkohol in a tank at any given time $t$. Of course $x(0) = 0$.
I am a bit stuck here. How should the equation look like? How can I derive it? | 2019/06/25 | [
"https://math.stackexchange.com/questions/3274167",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403569/"
] | $\{1,i\}$ is a basis for complex numbers $\Bbb C$ as a vector space over real numbers $\Bbb R$; the dimension is $2$.
A basis for $\Bbb C^2$ as a vector space over $\Bbb R$ is $\{(1,0), (i,0), (0, 1), (0,i)\};$ the dimension is $4$.
In general, a complex vector space of dimension $n$ is a real vector space of dimension $2n$. | Since C² = C x C = R² x R² = R x R x R x R
=> C² has 4 unit vectors
=> Base has 4 Elements
=> dimension of the R-vector space of (C²) = 4. |
3,274,167 | Let's consider the following problem. Imagine there is a tank filled up water (it's volume is equal to $V$). We connect two pumps to out tank. The first one pumps into the tank a mixture of 10% alcohol and water ($s\_1$ liter per minute). The second one pumps out of the tank what's inside (with the speed equal to $s\_2$ liters per minute).
I am to find the function $x(t)$ which describes the concentration of alkohol in a tank at any given time $t$. Of course $x(0) = 0$.
I am a bit stuck here. How should the equation look like? How can I derive it? | 2019/06/25 | [
"https://math.stackexchange.com/questions/3274167",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403569/"
] | In general you can prove the following:
Let $V$ be a vector space over $\mathbb{C}$ of dimension $\text{dim}\_{\mathbb{C}}(V) = n$. If you choose a basis $v\_1,\dots, v\_n \in V$ of $V$ as a $\mathbb{C}$-vector space, then $v\_1,\dots, v\_n,iv\_1,\dots, iv\_n \in V$ is a basis of $V$ as a $\mathbb{R}$-vector space. That means we have $\text{dim}\_{\mathbb{R}}(V) = 2n$. You can apply that to your situation. | Since C² = C x C = R² x R² = R x R x R x R
=> C² has 4 unit vectors
=> Base has 4 Elements
=> dimension of the R-vector space of (C²) = 4. |
3,274,167 | Let's consider the following problem. Imagine there is a tank filled up water (it's volume is equal to $V$). We connect two pumps to out tank. The first one pumps into the tank a mixture of 10% alcohol and water ($s\_1$ liter per minute). The second one pumps out of the tank what's inside (with the speed equal to $s\_2$ liters per minute).
I am to find the function $x(t)$ which describes the concentration of alkohol in a tank at any given time $t$. Of course $x(0) = 0$.
I am a bit stuck here. How should the equation look like? How can I derive it? | 2019/06/25 | [
"https://math.stackexchange.com/questions/3274167",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403569/"
] | $\{1,i\}$ is a basis for complex numbers $\Bbb C$ as a vector space over real numbers $\Bbb R$; the dimension is $2$.
A basis for $\Bbb C^2$ as a vector space over $\Bbb R$ is $\{(1,0), (i,0), (0, 1), (0,i)\};$ the dimension is $4$.
In general, a complex vector space of dimension $n$ is a real vector space of dimension $2n$. | In general you can prove the following:
Let $V$ be a vector space over $\mathbb{C}$ of dimension $\text{dim}\_{\mathbb{C}}(V) = n$. If you choose a basis $v\_1,\dots, v\_n \in V$ of $V$ as a $\mathbb{C}$-vector space, then $v\_1,\dots, v\_n,iv\_1,\dots, iv\_n \in V$ is a basis of $V$ as a $\mathbb{R}$-vector space. That means we have $\text{dim}\_{\mathbb{R}}(V) = 2n$. You can apply that to your situation. |
31,165,342 | Let's consider the following simple program:
```
int main()
{
int *a = new int;
}
```
Is it reliable that the value of `*a` is `0`. I'm **not** sure about that because primitives don't have default-initialization:
>
> To default-initialize an object of type T means:
>
>
> (7.1) — If T is a (possibly cv-qualified) class type (Clause 9),
> constructors are considered. The applicable constructors are
> enumerated (13.3.1.3), and the best one for the initializer () is
> chosen through overload resolution (13.3). The constructor thus
> selected is called, with an empty argument list, to initialize the
> object.
>
>
> (7.2) — If T is an array type, each element is default-initialized.
>
>
> (7.3) — **Otherwise, no initialization is performed**.
>
>
>
I'd say that `*a` is not initializaed so accessing it would lead to UB. Is that correct? | 2015/07/01 | [
"https://Stackoverflow.com/questions/31165342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] | To be absolutely clear, consider
```
int *a = new int;
int *b = new int();
```
`*a` is **not initialised**, `*b` is initialised to 0.
Use of `*a` prior to initialisation is undefined behaviour. | Yes.
You can value-initialize it (i.e set it to zero for an `int`) by using `new int()`. |
3,770,970 | In Example 2.39 in Hatcher, he used cellular homology to compute the homology groups of the 3-torus. I am studying for my exam and we did not cover the cellular homology. So I am thinking of using Mayer-Vietoris sequence. So we are considering the standard representation of the 3-torus X as a quotient space of the cube.
I am going take A=small ball inside the cube. $B=X\setminus A'$ (A' small neighborhood of A) so that
$A \cap B $ deformation retracts onto the sphere $S^2$. I know the homology groups of $A$ and of $A \cap B$. I also know that $B$ deformation retracts to the quotient space of the union of all square faces of the cube.
My problem is this: How can I determine the homology groups of B?
And once I do that how can I see the map from $H\_2(S^2)$ to $H\_2(B)$?
PS: One of the answer suggested a really nice other decomposition. However, I might want to need to compute the homology of B first as the problem recommended! | 2020/07/27 | [
"https://math.stackexchange.com/questions/3770970",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/752801/"
] | First, I think Matteo Tesla proposed a great decomposition that simplifies the problem.
Since OP requested to keep the original MV argument, I decided to complete it.
Let $A=D^3,B$ be as what OP stated in the question.
>
> Determine $H\_\*(B)$.
>
>
>
$B$ deformation retracts onto the surface of the cube, which consists of six squares with opposite edges identified, i.e., it consists of six $T^2$, whose homology groups are known. Thus, $H\_2(B)=\bigoplus\_{i=1}^3{H\_2(T^2)}=\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}$ because opposite faces are identified on the edges, which are also generators of the $2$nd homology group of each $T^2$. Similarly, $H\_1(B)=\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}$. You can work out these expressions by drawing a flat diagram of the surface of the cube and labelling all equivalence classes. (I can also edit the post to include my drawing if you want...)
[](https://i.stack.imgur.com/vd8gE.png)
Although all of the six faces are tori, their generators of $H\_1,H\_2$ are identified. A brief way to determine the homology group is just observing this graph, but you can also regard them as different tori and apply MV sequence multiple times, then mod out those identified images, which is more convincing but also more complicated.
>
> Compute $H\_\*(T^3)$:
>
>
>
We compute $H\_3(T^3)$ by a part of MV sequence:
$$0\to H\_3(T^3)\overset{\phi\_3}{\to}\mathbb{Z}\overset{\psi\_3}{\to}\bigoplus\_{i=1}^3\mathbb{Z}\to...$$
Your question specifically asks for how to determine $\psi$, so let's focus on that.
Consider the following commutative diagram similar to that of Seifer-Van Kampen Thm
$$
\require{AMScd}
\begin{CD}
H\_2(S^2)@>i>>H\_2(A)\\
@Vj=\psi VV @VlVV\\
H\_2(B)@>k>>H\_2(T^3)
\end{CD}
$$
We can ignore $H(A)$ because $A\simeq\{\*\}$. And, Let $\alpha,\beta,\gamma$ be the three generators of $H\_2(B)$ that are oriented counterclockwise and $\delta$ the generator of $H\_2(S^2)$.
Then, $\psi(\delta)=\alpha+\beta+\gamma-\alpha-\beta-\gamma=0$ (use the diagram of the flat surface to help you). **Geometrically, the diagram is induced by the chain complex, so $\psi$ actually sends cycles to cycles. $\delta$, as a generator of $H\_2(S^2)$ is mapped into $B$ (observing $\delta$ in $B$) it deformation retracts onto the surface. The surface consists of three pairs of faces with opposite orientation when it is identified (you can try to make one, even though they're all oriented counterclockwise in the diagram), so we get the expression as desired because all groups are abelian.** Thus $\text{im}(\psi)=0,\text{ker}(\psi)=\Bbb{Z}$, which implies $H\_3(T^3)\cong\mathbb{Z}$.
For $H\_2(T^3)$, we already know that the map $\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}\overset{}{\to} H\_2(T^3)$ is surjective because we have $H\_2(T^3)\to H\_1(S^2)=0$. Now because $\text{im}(\psi)=0$, the map $\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}\overset{}{\to} H\_2(T^3)$ is also injective. Hence, $H\_2(T^3)\cong\bigoplus\_{i=1}^3\mathbb{Z}$.
I guess I can stop here to make this post focus on the main problem on that map. | I assume that by 3-torus you mean $S^1 \times S^1 \times S^1$. You can decompose the first component, $S^1=A \cup B$ $A\times S^1\times S^1$ is homotopic to a 2-torus, also the other part. The intersection is homotopic to 2 disconnected 2-tori, so you have to know the homology of $S^1 \times S^1$ first. To do computation you have to consider also the maps involved.
For the 2-torus you obtain
$$ 0\to H\_2(T) \to H\_1(S^1\times (S^1\setminus\{-1,1\})) \to H\_1(S^1\times (S^1\setminus \{-1\}))\oplus H\_1(S^1\times (S^1\setminus \{1\})) \to H\_1(T) \to \dots $$
To study the map $d:H\_1(S^1\times (S^1\setminus\{-1,1\})) \to H\_1(S^1\times S^1\setminus \{-1\})\oplus H\_1(S^1\times S^1\setminus \{1\})$, you consider the generator of the domain which are, $[\gamma,P],[\gamma,Q]$ ($P, Q$ in different connected component of $S^1 \setminus \{-1,1\}$). This generator are mapped by $d$ to $([\gamma,P],-[\gamma,P])$ and $([\gamma,Q],-[\gamma,Q])$ respectively (this are the same because $S^1 \times (S^1 \setminus P)$ is connected).
So $d$ has non trivial kernel $[\gamma,P]-[\gamma,Q]$, so $H\_2(T)\cong \mathbb{Z}$.
Let's do the hard part and compute $H\_1(S^1 \times S^1)\cong \mathbb{Z}^2$.
We can splite the sequence at the level of $H\_1(S^1\times S^1)$:
$$0\to\text{Coker} (\phi)\to H\_1(T)\to \text{Im}(\delta)\to 0$$
is exaxt. Where $\phi: H\_1(S^1\times (S^1\setminus\{-1,1\})) \to H\_1(S^1\times (S^1\setminus \{-1\}))\oplus H\_1(S^1\times (S^1\setminus \{1\}))$,
$\delta:H\_1(T) \to H\_0(S^1\times (S^1\setminus\{-1,1\}))$.
It remain to prove that $\text{Im}(\delta)\cong \mathbb{Z}$, so that the sequence split. Also $\text{Coker}(\phi)\cong \mathbb{Z}$, so $H\_1(T)\cong \mathbb{Z}\oplus \mathbb{Z}$.
For the 3-torus you can proceed in the same way.
The decomposition you are taking I don't think it is useful but I might be wrong. In dimension two your $B$ is $S^1 \times S^1\setminus D$ where $D$ is a small disc which is homotopic to a bucket of two circumference. You have to use again MV. |
2,282,020 | $f$ is a function from $\Bbb R$ to $(0,2)$ defined as
$$f(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}+1.$$
The function $f$ is invertible and I want to find its inverse.
I tried using methods like taking $\ln$ on both sides but they don't seem to work. | 2017/05/15 | [
"https://math.stackexchange.com/questions/2282020",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/255512/"
] | Here is my go at it. First, observe that we have the two hyperbolic trig functions
$$ \mathrm{sinh}(x)=\dfrac{e^{x}-e^{-x}}{2}, \qquad \mathrm{cosh}(x)=\dfrac{e^{x}+e^{-x}}{2}$$
which defines $\mathrm{tanh}(x):=\mathrm{sinh}(x)/\mathrm{cosh}(x)$. It follows form this that your function $f$ may be written as $f(x)=\mathrm{tanh}(x)+1$. From this, one knows that the inverse function of the hyperbolic tangent is well defined and equal to
$$\mathrm{artanh}(x)=\frac{1}{2}\ln \left(\frac{1+x}{1-x}\right)$$
with domain $(-1,1)$. Thus,
$$\mathrm{tanh}(x)=f(x)-1\qquad\Rightarrow\qquad f^{-1}(x)=\frac{1}{2}\ln \left(\frac{x}{2-x}\right).$$
If your are not satisfied with my use of hyperbolic trig functions, you can always "reverse engineer" the inverse.
I hope this helps! | $$y=f(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}+1$$
$$y-1=\frac{e^x-e^{-x}}{e^x+e^{-x}}$$
$$y-1=\frac{e^{2x}-1}{e^{2x}+1}$$
$$ye^{2x} +y -e^{2x}-1=e^{2x}-1$$
$$e^{2x}(y-2)=-y$$
$$e^{2x}=\frac{y}{2-y}$$
Taking log
$$2x=\log\left(\frac{y}{2-y}\right)$$
$$x=\frac12\log\left(\frac{y}{2-y}\right)$$
Now$$ f^{-1}(x)=\frac12\log\left(\frac{x}{2-x}\right)$$ |
73,175 | There are two different stories of how King Arthur received his sword, Excalibur. The first is that he pulled it out of an anvil or stone slab (and by doing so confirmed that he was the rightful king of the land). The second is that he received it from the Lady of the Lake (and that he had to return it to her before he died).
Which one of these stories is correct? Or did King Arthur have two different swords that he got different ways? | 2014/11/21 | [
"https://scifi.stackexchange.com/questions/73175",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/-1/"
] | The Excalibur problem is that, over time, people have combined two different Arthurian swords into a single blade. This is a serious pet-peeve of mine.
* **Sword # 1:** "Clarent", the sword in the stone. It was used in Ceremonies (e.g. the dubbing of knights). This sword designates Arthur as being rightful heir of Uthur.
* **Sword # 2:** "Excalibur/Caliburn", given to Arthur by the Lady of the Lake, and Arthur's sword for battle. This sword grants the divine right to rule England.
Most popular depictions (especially in recent years) tend just to use one sword or the other and call it Excalibur. However, some find a way of placing the sword in the position of both: e.g. the Lady of the Lake puts it into the stone, or something to that effect.
Older texts, however, *do* make the distinction clear even if it's a "blink and you miss it" moment. For example, a sentence saying that the sword in the stone was fragile, and couldn't be used for combat, so Arthur went to the Lady of the Lake for a new one.
In the medieval "Alliterative Morte d'Arthur" the roles of Arthur having the two swords is actually really important: Part of Mordred's coup involves stealing Clarent (establishing that he has the mortal right to rule by laws of men) in addition to kidnapping/"marrying" the queen. The final battle involves Arthur, wielding Excalibur (divine right to rule), versus Mordred, wielding Clarent. The two then destroy each other.
I really hope this helped clear things up for you. I'd recommend starting with Geoffrey of Monmouth and working your way through medieval texts to see the evolution of the depiction of Arthur's swords. | The short version is that both of those swords are Excalibur. *Le Morte D'Artur* is, to be blunt, incredibly self-contradictory in places. Malory took a number of existing stories and collected them without always concerning himself with conflicts between them.
[From Wikipedia](http://en.wikipedia.org/wiki/Excalibur)
>
> In Robert de Boron's Merlin, Arthur obtained the throne by pulling a sword from a stone. In this account, the act could not be performed except by "the true king," meaning the divinely appointed king or true heir of Uther Pendragon. This sword is thought by many to be the famous Excalibur, and its identity is made explicit in the later so-called Vulgate Merlin Continuation, part of the Lancelot-Grail cycle. However, in what is sometimes called the Post-Vulgate Merlin, Excalibur was given to Arthur by the Lady of the Lake sometime after he began to reign. She calls the sword "Excalibur, that is as to say as Cut-steel." In the Vulgate Mort Artu, Arthur orders Griflet to throw the sword into the enchanted lake.
>
>
> |
73,175 | There are two different stories of how King Arthur received his sword, Excalibur. The first is that he pulled it out of an anvil or stone slab (and by doing so confirmed that he was the rightful king of the land). The second is that he received it from the Lady of the Lake (and that he had to return it to her before he died).
Which one of these stories is correct? Or did King Arthur have two different swords that he got different ways? | 2014/11/21 | [
"https://scifi.stackexchange.com/questions/73175",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/-1/"
] | The short version is that both of those swords are Excalibur. *Le Morte D'Artur* is, to be blunt, incredibly self-contradictory in places. Malory took a number of existing stories and collected them without always concerning himself with conflicts between them.
[From Wikipedia](http://en.wikipedia.org/wiki/Excalibur)
>
> In Robert de Boron's Merlin, Arthur obtained the throne by pulling a sword from a stone. In this account, the act could not be performed except by "the true king," meaning the divinely appointed king or true heir of Uther Pendragon. This sword is thought by many to be the famous Excalibur, and its identity is made explicit in the later so-called Vulgate Merlin Continuation, part of the Lancelot-Grail cycle. However, in what is sometimes called the Post-Vulgate Merlin, Excalibur was given to Arthur by the Lady of the Lake sometime after he began to reign. She calls the sword "Excalibur, that is as to say as Cut-steel." In the Vulgate Mort Artu, Arthur orders Griflet to throw the sword into the enchanted lake.
>
>
> | Caliburn was the sword in the stone, but was broken by Clarent during the battle between Arthur and his illegitimate son Mordred. Excalibur was given to Arthur by the Lady of the Lake in order to defeat Mordred, and it became Arthur's second sword while Caliburn was said to not only declare the one true king of England but was supposedly unbeatable as long as the wielder's heart was pure.
Arthur's heart grew dark from his hatred towards his step-sister, Morgan le Fay, and that's why the sword broke. Excalibur was made to be the opposite to Clarent, therefore becoming the sword of ice while Clarent was the sword of fire.
These are the major differences between the three swords |
73,175 | There are two different stories of how King Arthur received his sword, Excalibur. The first is that he pulled it out of an anvil or stone slab (and by doing so confirmed that he was the rightful king of the land). The second is that he received it from the Lady of the Lake (and that he had to return it to her before he died).
Which one of these stories is correct? Or did King Arthur have two different swords that he got different ways? | 2014/11/21 | [
"https://scifi.stackexchange.com/questions/73175",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/-1/"
] | The Excalibur problem is that, over time, people have combined two different Arthurian swords into a single blade. This is a serious pet-peeve of mine.
* **Sword # 1:** "Clarent", the sword in the stone. It was used in Ceremonies (e.g. the dubbing of knights). This sword designates Arthur as being rightful heir of Uthur.
* **Sword # 2:** "Excalibur/Caliburn", given to Arthur by the Lady of the Lake, and Arthur's sword for battle. This sword grants the divine right to rule England.
Most popular depictions (especially in recent years) tend just to use one sword or the other and call it Excalibur. However, some find a way of placing the sword in the position of both: e.g. the Lady of the Lake puts it into the stone, or something to that effect.
Older texts, however, *do* make the distinction clear even if it's a "blink and you miss it" moment. For example, a sentence saying that the sword in the stone was fragile, and couldn't be used for combat, so Arthur went to the Lady of the Lake for a new one.
In the medieval "Alliterative Morte d'Arthur" the roles of Arthur having the two swords is actually really important: Part of Mordred's coup involves stealing Clarent (establishing that he has the mortal right to rule by laws of men) in addition to kidnapping/"marrying" the queen. The final battle involves Arthur, wielding Excalibur (divine right to rule), versus Mordred, wielding Clarent. The two then destroy each other.
I really hope this helped clear things up for you. I'd recommend starting with Geoffrey of Monmouth and working your way through medieval texts to see the evolution of the depiction of Arthur's swords. | Caliburn was the sword in the stone, but was broken by Clarent during the battle between Arthur and his illegitimate son Mordred. Excalibur was given to Arthur by the Lady of the Lake in order to defeat Mordred, and it became Arthur's second sword while Caliburn was said to not only declare the one true king of England but was supposedly unbeatable as long as the wielder's heart was pure.
Arthur's heart grew dark from his hatred towards his step-sister, Morgan le Fay, and that's why the sword broke. Excalibur was made to be the opposite to Clarent, therefore becoming the sword of ice while Clarent was the sword of fire.
These are the major differences between the three swords |
55,757,089 | I was playing with below javascript code. Understanding of `Object.defineProperty()` and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the `name & age` property in the object
But at the time of output, it only shows the `name` property
```js
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
```
Now expected output here should be
```
{name: "Barry Allen", age: 23}
23
```
but I get the output as.
Note that I am able to access the `age` property defined afterwards.
I am not sure why the `console.log()` is behaving this way.
```
{name: "Barry Allen"}
23
``` | 2019/04/19 | [
"https://Stackoverflow.com/questions/55757089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6531794/"
] | You should set `enumerable` to `true`. In `Object.defineProperty` its `false` by default. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description).
>
> **enumerable**
>
>
> `true` if and only if this property shows up during enumeration of the properties on the corresponding object.
>
>
> **Defaults to false.**
>
>
>
Non-enumerable means that property will not be shown in `Object.keys()` or `for..in` loop neither in console
```js
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
```
All the properties and methods on `prototype` object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.
To get all properties(including non-enumerable)[`Object.getOwnPropertyNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames).
```js
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too
``` | By default, properties you define with `defineProperty` are not *enumerable* - this means that they will not show up when you iterate over their `Object.keys` (which is what the snippet console does). (Similarly, the `length` property of an array does not get displayed, because it's non-enumerable.)
See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty):
>
> **enumerable**
>
>
> true if and only if this property shows up during enumeration of the properties on the corresponding object.
>
>
> **Defaults to false.**
>
>
>
Make it enumerable instead:
```js
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
```
The reason you can see the property in the [logged image](https://pasteboard.co/IaOxMqB.png) is that Chrome's console will show you non-enumerable properties as well - **but the non-enumerable properties will be slightly greyed-out**:
[](https://i.stack.imgur.com/1k4zA.png)
See how `age` is grey-ish, while `name` is not - this indicates that `name` is enumerable, and `age` is not. |
55,757,089 | I was playing with below javascript code. Understanding of `Object.defineProperty()` and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the `name & age` property in the object
But at the time of output, it only shows the `name` property
```js
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
```
Now expected output here should be
```
{name: "Barry Allen", age: 23}
23
```
but I get the output as.
Note that I am able to access the `age` property defined afterwards.
I am not sure why the `console.log()` is behaving this way.
```
{name: "Barry Allen"}
23
``` | 2019/04/19 | [
"https://Stackoverflow.com/questions/55757089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6531794/"
] | You should set `enumerable` to `true`. In `Object.defineProperty` its `false` by default. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description).
>
> **enumerable**
>
>
> `true` if and only if this property shows up during enumeration of the properties on the corresponding object.
>
>
> **Defaults to false.**
>
>
>
Non-enumerable means that property will not be shown in `Object.keys()` or `for..in` loop neither in console
```js
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
```
All the properties and methods on `prototype` object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.
To get all properties(including non-enumerable)[`Object.getOwnPropertyNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames).
```js
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too
``` | Whenever you use".defineProperty" method of object. You should better define all the properties of the descriptor. Because if you don't define other property descriptor then it assumes default values for all of them which is false. So your console.log checks for all the enumerable : true properties and logs them.
```
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable : true,
configurable : true
})
console.log(profile)
console.log(profile.age)
``` |
55,757,089 | I was playing with below javascript code. Understanding of `Object.defineProperty()` and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the `name & age` property in the object
But at the time of output, it only shows the `name` property
```js
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
```
Now expected output here should be
```
{name: "Barry Allen", age: 23}
23
```
but I get the output as.
Note that I am able to access the `age` property defined afterwards.
I am not sure why the `console.log()` is behaving this way.
```
{name: "Barry Allen"}
23
``` | 2019/04/19 | [
"https://Stackoverflow.com/questions/55757089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6531794/"
] | By default, properties you define with `defineProperty` are not *enumerable* - this means that they will not show up when you iterate over their `Object.keys` (which is what the snippet console does). (Similarly, the `length` property of an array does not get displayed, because it's non-enumerable.)
See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty):
>
> **enumerable**
>
>
> true if and only if this property shows up during enumeration of the properties on the corresponding object.
>
>
> **Defaults to false.**
>
>
>
Make it enumerable instead:
```js
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
```
The reason you can see the property in the [logged image](https://pasteboard.co/IaOxMqB.png) is that Chrome's console will show you non-enumerable properties as well - **but the non-enumerable properties will be slightly greyed-out**:
[](https://i.stack.imgur.com/1k4zA.png)
See how `age` is grey-ish, while `name` is not - this indicates that `name` is enumerable, and `age` is not. | Whenever you use".defineProperty" method of object. You should better define all the properties of the descriptor. Because if you don't define other property descriptor then it assumes default values for all of them which is false. So your console.log checks for all the enumerable : true properties and logs them.
```
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true,
enumerable : true,
configurable : true
})
console.log(profile)
console.log(profile.age)
``` |
40,612,700 | I have a remote api that gives this data
```
{ "images" :
[
{ "image_link" : "http://example.com/image1.png"},
{ "image_link" : "http://example.com/image2.png"},
]
}
```
I have a class with the functions. I have not included constructor here.
```
componentWillMount() {
var url = 'https://naren.com/images.json';
var that = this;
fetch( url )
.then((response) => response.json())
.then((responseJson) => { that.setState({ images : responseJson.images }); })
.catch((error) => { console.error(error); });
}
render() {
return ( <View>
this.state.images.map(( image, key ) => {
console.log(image);
return (
<View key={key}>
<Image source={{ uri : image.image_link }} />
</View>
);
});
</View>);
}
```
I cannot seem to get the images fetched from the api to loop through the view. If I use a static array without the remote source i.e. `fetch`. THis seems to work perfectly.But when I use the fetch and get data from the api this does not work. I can confirm that I am getting the data because the `console.log(image)` inside the `return` statements consoles the expected data. | 2016/11/15 | [
"https://Stackoverflow.com/questions/40612700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2159370/"
] | I quickly Simulated this, and it does not seem to have an issue to loop over the Image array and Render each Image.
```
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class ImageLoop extends Component {
constructor(props){
super(props)
this.state = {
images : []
}
}
componentWillMount() {
var url = 'https://api.myjson.com/bins/2xu3k';
{/*
or any API that can return the following JSON
{"images":[{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"}]}
*/}
var that = this;
fetch( url )
.then((response) => response.json())
.then((responseJson) => {
console.log('responseJson.images',responseJson.images);
that.setState({ images : responseJson.images });
})
.catch((error) => { console.error(error); });
}
render() {
return (
<View style={{height:100,width:100}}>
{this.state.images.map((eachImage)=>{
console.log('Each Image', eachImage);
return (
<Image key = {Math.random()} style={{height:100,width:100}} source ={{uri:eachImage.image_link}}/>
);
})}
</View>
);
}
}
AppRegistry.registerComponent('ImageLoop', () => ImageLoop);
```
Please see the output Here: <https://rnplay.org/apps/bJcPhQ> | Try setting a `width` and a `height` on the `Image` style. Because the images come from a remote url, react-native does not know what size it is going to be.
```
render() {
return ( <View>
this.state.images.map(( image, key ) => {
console.log(image);
return (
<View key={key}>
<Image
source={{ uri : image.image_link }}
style={{ width: 120, height: 120 }}
/>
</View>
);
});
</View>);
}
``` |
10,067 | For bikes like [these](http://www.herocycles.com/images/octane-recra.jpg), why aren't the rear shocks (the shocks are directly above the pedal) vertical like those of a motorcycle? I don't see how the bike can take shocks when the shock absorber is at such a low angle.
A friend said the mud-guard is so high because there's no other way to attach it to the cycle at a lower height. Is that really the reason why the mud-guard is so high? | 2012/06/26 | [
"https://bicycles.stackexchange.com/questions/10067",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4393/"
] | From my understanding, one of the major features for bicycle suspension is vertical travel. This is to increase pedal efficiency and rear wheel feel. This is why you see engineers jump through hoops when designing rear suspension for bicycles. For example, take a look at the [Pivot Mach 429](http://www.29eronline.com/wp-content/uploads/2009/01/side-view-pivot-convert.jpg). If I count correctly, this bike has 5 points of rotation to accomplish beter pedal efficiency as well as offering more rear-wheel travel. Some motorcycles do have non-vertical mounted suspension as well; the first to come to mind is the [Kawasaki Ninja 650](http://www.motosavvy.com/_ImageAreas/Kawasaki650R-3.jpg).
As for the "mud-guard", that is often referred to as a [filth prophylactic](http://bikesnobnyc.blogspot.com/search?q=filth%20prophylactic). This isn't intended to do much more than keep mud off your shirt and backside. [Full fenders](http://cdn1.media.cyclingnews.futurecdn.net/2011/02/26/2/cielo_sportif_full_view_600.jpg) can be quite difficult to mount to a full-suspension bike (everything keeps moving, man!) so filth prophylactics are common "good enough" equipment. They also tend to have very little in frame requirements (full fenders require braze-ons for mounting them), so they fit on most any bike. | What's above the rear wheel for vertical shocks to mount to?
It's pretty clear from the provided picture that the fulcrum for the rear wheel is near the bottom bracket. An upward force against the rear wheel will cause it to lift, reducing the distance between it and the mount point of the shock, allowing the shock to resist that movement. |
10,067 | For bikes like [these](http://www.herocycles.com/images/octane-recra.jpg), why aren't the rear shocks (the shocks are directly above the pedal) vertical like those of a motorcycle? I don't see how the bike can take shocks when the shock absorber is at such a low angle.
A friend said the mud-guard is so high because there's no other way to attach it to the cycle at a lower height. Is that really the reason why the mud-guard is so high? | 2012/06/26 | [
"https://bicycles.stackexchange.com/questions/10067",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4393/"
] | What's above the rear wheel for vertical shocks to mount to?
It's pretty clear from the provided picture that the fulcrum for the rear wheel is near the bottom bracket. An upward force against the rear wheel will cause it to lift, reducing the distance between it and the mount point of the shock, allowing the shock to resist that movement. | The rear wheel is attached to stays that connect to a pivot point. As long as when the rear wheel moves upwards, the wheel and stays all rotate around the pivot to compress (or stretch, depending on shock type) the shock, then the rear suspension should work fine.
Take a look at this bike, the shock is vertical. But, unlike the picture you showed, there are a number of pivot points. The bike you showed has a single pivot near the crank and pedal area. <http://www.dirtragmag.com/sites/default/files/blogarific/wp-content/uploads/2007/06/trek-fuel-ex-full.jpg>
The mudguard is high so that the wheel doesn't hit it and to ensure there is plenty of mud clearance. Most mountain bikers I know don't bother with mudguards, because the faff of them is annoying (it's not because of lack of mud, I'm in the UK and it can get pretty muddy at times). So, they're usually not fitted to mountain bikes as standards. That means, this one has to be fitted to the seat tube, and it doesn't move with the wheel as it takes up shocks. |
10,067 | For bikes like [these](http://www.herocycles.com/images/octane-recra.jpg), why aren't the rear shocks (the shocks are directly above the pedal) vertical like those of a motorcycle? I don't see how the bike can take shocks when the shock absorber is at such a low angle.
A friend said the mud-guard is so high because there's no other way to attach it to the cycle at a lower height. Is that really the reason why the mud-guard is so high? | 2012/06/26 | [
"https://bicycles.stackexchange.com/questions/10067",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4393/"
] | From my understanding, one of the major features for bicycle suspension is vertical travel. This is to increase pedal efficiency and rear wheel feel. This is why you see engineers jump through hoops when designing rear suspension for bicycles. For example, take a look at the [Pivot Mach 429](http://www.29eronline.com/wp-content/uploads/2009/01/side-view-pivot-convert.jpg). If I count correctly, this bike has 5 points of rotation to accomplish beter pedal efficiency as well as offering more rear-wheel travel. Some motorcycles do have non-vertical mounted suspension as well; the first to come to mind is the [Kawasaki Ninja 650](http://www.motosavvy.com/_ImageAreas/Kawasaki650R-3.jpg).
As for the "mud-guard", that is often referred to as a [filth prophylactic](http://bikesnobnyc.blogspot.com/search?q=filth%20prophylactic). This isn't intended to do much more than keep mud off your shirt and backside. [Full fenders](http://cdn1.media.cyclingnews.futurecdn.net/2011/02/26/2/cielo_sportif_full_view_600.jpg) can be quite difficult to mount to a full-suspension bike (everything keeps moving, man!) so filth prophylactics are common "good enough" equipment. They also tend to have very little in frame requirements (full fenders require braze-ons for mounting them), so they fit on most any bike. | The fender or "mud guard" is so high because if it was much lower the tire would be banging into it whenever the shock compressed. |
10,067 | For bikes like [these](http://www.herocycles.com/images/octane-recra.jpg), why aren't the rear shocks (the shocks are directly above the pedal) vertical like those of a motorcycle? I don't see how the bike can take shocks when the shock absorber is at such a low angle.
A friend said the mud-guard is so high because there's no other way to attach it to the cycle at a lower height. Is that really the reason why the mud-guard is so high? | 2012/06/26 | [
"https://bicycles.stackexchange.com/questions/10067",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4393/"
] | From my understanding, one of the major features for bicycle suspension is vertical travel. This is to increase pedal efficiency and rear wheel feel. This is why you see engineers jump through hoops when designing rear suspension for bicycles. For example, take a look at the [Pivot Mach 429](http://www.29eronline.com/wp-content/uploads/2009/01/side-view-pivot-convert.jpg). If I count correctly, this bike has 5 points of rotation to accomplish beter pedal efficiency as well as offering more rear-wheel travel. Some motorcycles do have non-vertical mounted suspension as well; the first to come to mind is the [Kawasaki Ninja 650](http://www.motosavvy.com/_ImageAreas/Kawasaki650R-3.jpg).
As for the "mud-guard", that is often referred to as a [filth prophylactic](http://bikesnobnyc.blogspot.com/search?q=filth%20prophylactic). This isn't intended to do much more than keep mud off your shirt and backside. [Full fenders](http://cdn1.media.cyclingnews.futurecdn.net/2011/02/26/2/cielo_sportif_full_view_600.jpg) can be quite difficult to mount to a full-suspension bike (everything keeps moving, man!) so filth prophylactics are common "good enough" equipment. They also tend to have very little in frame requirements (full fenders require braze-ons for mounting them), so they fit on most any bike. | The rear wheel is attached to stays that connect to a pivot point. As long as when the rear wheel moves upwards, the wheel and stays all rotate around the pivot to compress (or stretch, depending on shock type) the shock, then the rear suspension should work fine.
Take a look at this bike, the shock is vertical. But, unlike the picture you showed, there are a number of pivot points. The bike you showed has a single pivot near the crank and pedal area. <http://www.dirtragmag.com/sites/default/files/blogarific/wp-content/uploads/2007/06/trek-fuel-ex-full.jpg>
The mudguard is high so that the wheel doesn't hit it and to ensure there is plenty of mud clearance. Most mountain bikers I know don't bother with mudguards, because the faff of them is annoying (it's not because of lack of mud, I'm in the UK and it can get pretty muddy at times). So, they're usually not fitted to mountain bikes as standards. That means, this one has to be fitted to the seat tube, and it doesn't move with the wheel as it takes up shocks. |
10,067 | For bikes like [these](http://www.herocycles.com/images/octane-recra.jpg), why aren't the rear shocks (the shocks are directly above the pedal) vertical like those of a motorcycle? I don't see how the bike can take shocks when the shock absorber is at such a low angle.
A friend said the mud-guard is so high because there's no other way to attach it to the cycle at a lower height. Is that really the reason why the mud-guard is so high? | 2012/06/26 | [
"https://bicycles.stackexchange.com/questions/10067",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4393/"
] | The fender or "mud guard" is so high because if it was much lower the tire would be banging into it whenever the shock compressed. | The rear wheel is attached to stays that connect to a pivot point. As long as when the rear wheel moves upwards, the wheel and stays all rotate around the pivot to compress (or stretch, depending on shock type) the shock, then the rear suspension should work fine.
Take a look at this bike, the shock is vertical. But, unlike the picture you showed, there are a number of pivot points. The bike you showed has a single pivot near the crank and pedal area. <http://www.dirtragmag.com/sites/default/files/blogarific/wp-content/uploads/2007/06/trek-fuel-ex-full.jpg>
The mudguard is high so that the wheel doesn't hit it and to ensure there is plenty of mud clearance. Most mountain bikers I know don't bother with mudguards, because the faff of them is annoying (it's not because of lack of mud, I'm in the UK and it can get pretty muddy at times). So, they're usually not fitted to mountain bikes as standards. That means, this one has to be fitted to the seat tube, and it doesn't move with the wheel as it takes up shocks. |
64,367,207 | I use an app called PDF Lightweight to compress my PDFs (since I have made very good experiences) and Thunderbird to send emails.
I want to write an AppleScript that compresses PDFs before attaching them to an email:
```
set attachment1 to "/Users/username/Desktop/Test.pdf"
do shell script "open -a " & quoted form of ("/Applications/Lightweight PDF.app") & " " & quoted form of attachment1
set email_attachment to "attachment=" & "'file://" & attachment1 & "'"
set thunderbird_bin to "/Applications/Thunderbird.app/Contents/MacOS/thunderbird-bin -compose "
set arguments to email_attachment
do shell script thunderbird_bin & quoted form of arguments & ">/dev/null 2>&1 &"
```
The problem is that the original PDF will be attached before the compression finishes. I tried to work with something like [this](https://stackoverflow.com/questions/20146093/waiting-for-do-shell-script-to-finish) but it does not work either. I suppose because I start PDF Lightweight with an "open" command which is -technically- complete even when the app is still compressing.
Any ideas how get the script waiting for the PDF compression?
Thank you! | 2020/10/15 | [
"https://Stackoverflow.com/questions/64367207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2408764/"
] | You could rewrite your hook to set the [fetch policy](https://www.apollographql.com/docs/react/data/queries/#configuring-fetch-logic) to 'no-cache' or 'network-only'
```
const [getResetLink, { loading, data }] = useLazyQuery(FORGOT_PASSWORD, {fetchPolicy: 'no-cache'})
```
On another note, you should consider using Mutation instead of Query for this operation, as probably there is some change in data. For example, you store the unique hash or link for resetting a password or something similar. | Alternatively you could use useQuery with skip option and the refetch result function. Refetch will always update the cache by default.
Something along these lines:
```
const { refetch: getResetLink, loading, data } = useQuery(FORGOT_PASSWORD, { skip: true } )
```
then in onSubmit `getResetLink({ email })`
<https://www.apollographql.com/docs/react/data/queries/#refetching>
>
> A function that enables you to re-execute the query, optionally passing in new variables. To guarantee that the refetch performs a network request, its fetchPolicy is set to network-only (unless the original query's fetchPolicy is no-cache or cache-and-network, which also guarantee a network request)
>
>
> |
29,584,909 | now with swift 2.0, IOS 8.3 this code doesn't work anymore.
'Set' does not have a member named 'allObjects'
```
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch: UITouch = event.allTouches()?.allObjects.last as UITouch!
}
```
I tried a lot of stuffs but nothing seems to work, any idea ?
Thanks | 2015/04/12 | [
"https://Stackoverflow.com/questions/29584909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4544794/"
] | Swift 1.2 has introduced a native `Set` type, but unlike `NSSet` it doesn't have the `anyObject` method. You have a couple of options. You can use the `first()` method or you can take advantage of the ability to bridge a Swift Set to NSSet -
```
let touch = touches.first() as? UITouch
```
or
```
let touchesSet=touches as NSSet
let touch=touchesSet.anyObject() as? UITouch
``` | I've noticed that, too. I'm not sure if this is the actual alternation for the original code these days... I'm sure it isn't. But I've simply changed that code to this:
```
(touches: NSObject, withEvent event: UIEvent)
```
Sorry if that doesn't work for you. It's been working for me perfectly fine. |
44,760,033 | I'm just starting out learning Python/Spyder. I have completed a few classes in R for data science.
Below is failing with the error: IOError: File APPL.csv does not exist
However, my script and .csv file are in the same folder. Any thoughts on what I'm doing wrong? Thanks
```
import pandas as pd
def test_run():
df = pd.read_csv("APPL.csv")
print df
if __name__ == "__main__":
test_run()
``` | 2017/06/26 | [
"https://Stackoverflow.com/questions/44760033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270921/"
] | I implemented my own version of k-means on top of spark which uses standard TF-IDF vector representation and (-ve) cosine similarity as the distance metric [code snippet for reference](https://gist.github.com/rajanim/e01d1af591d697202c75ee0a785fa94f). The results from this k-means look right, not as skewed as spark k-means. [figure 1 and 2](https://i.stack.imgur.com/CkcIZ.png)
Additionally, I experimented by plugging in Euclidean distance as a similarity metric (into my own version of k-mean) and results continue to look right, not at all as skewed as spark k-means. Results indicate that its not issue with distance measure but some other case with spark's k-means implementation(scala mllib) | The KMeans algorithm is based on Euclidean distance, and can not directly use cosine distance. [Here](https://stats.stackexchange.com/questions/81481/why-does-k-means-clustering-algorithm-use-only-euclidean-distance-metric) is a good explanation of this fact:
>
> K-Means is implicitly based on pairwise Euclidean distances b/w data points, because the sum of squared deviations from centroid is equal to the sum of pairwise squared Euclidean distances divided by the number of points.
>
>
>
If you wish to use cosine distance (or any other metric), [KMedoids](https://en.wikipedia.org/wiki/K-medoids) might be a good option. It is similar to KMeans, but uses the median, instead of the mean, in it's update step. This allows the use of arbitrary distance metrics. |
44,760,033 | I'm just starting out learning Python/Spyder. I have completed a few classes in R for data science.
Below is failing with the error: IOError: File APPL.csv does not exist
However, my script and .csv file are in the same folder. Any thoughts on what I'm doing wrong? Thanks
```
import pandas as pd
def test_run():
df = pd.read_csv("APPL.csv")
print df
if __name__ == "__main__":
test_run()
``` | 2017/06/26 | [
"https://Stackoverflow.com/questions/44760033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270921/"
] | You can normalize your vectors and then cosine similarity or Euclidean distance will give same results. Mathematically it is easy to see that the Euclidean distance = 2 (1 - Cosine Similarity) for normalized vectors. | The KMeans algorithm is based on Euclidean distance, and can not directly use cosine distance. [Here](https://stats.stackexchange.com/questions/81481/why-does-k-means-clustering-algorithm-use-only-euclidean-distance-metric) is a good explanation of this fact:
>
> K-Means is implicitly based on pairwise Euclidean distances b/w data points, because the sum of squared deviations from centroid is equal to the sum of pairwise squared Euclidean distances divided by the number of points.
>
>
>
If you wish to use cosine distance (or any other metric), [KMedoids](https://en.wikipedia.org/wiki/K-medoids) might be a good option. It is similar to KMeans, but uses the median, instead of the mean, in it's update step. This allows the use of arbitrary distance metrics. |
44,760,033 | I'm just starting out learning Python/Spyder. I have completed a few classes in R for data science.
Below is failing with the error: IOError: File APPL.csv does not exist
However, my script and .csv file are in the same folder. Any thoughts on what I'm doing wrong? Thanks
```
import pandas as pd
def test_run():
df = pd.read_csv("APPL.csv")
print df
if __name__ == "__main__":
test_run()
``` | 2017/06/26 | [
"https://Stackoverflow.com/questions/44760033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270921/"
] | I implemented my own version of k-means on top of spark which uses standard TF-IDF vector representation and (-ve) cosine similarity as the distance metric [code snippet for reference](https://gist.github.com/rajanim/e01d1af591d697202c75ee0a785fa94f). The results from this k-means look right, not as skewed as spark k-means. [figure 1 and 2](https://i.stack.imgur.com/CkcIZ.png)
Additionally, I experimented by plugging in Euclidean distance as a similarity metric (into my own version of k-mean) and results continue to look right, not at all as skewed as spark k-means. Results indicate that its not issue with distance measure but some other case with spark's k-means implementation(scala mllib) | A late update incase anyone runs into this. Current versions of spark kmeans do implement cosine distance function, but the default is *euclidean*. For pyspark, this can be set in the constructor:
```py
from pyspark.ml.clustering import KMeans
km = KMeans(distanceMeasure='cosine', k=2, seed=1.0)
# or via setter
km.setDistanceMeasure('cosine')
```
[pyspark docs](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.clustering.KMeans.html#pyspark.ml.clustering.KMeans.distanceMeasure)
---
For Scala use the setter:
```scala
import org.apache.spark.ml.clustering.KMeans
val km = new KMeans()
km.setDistanceMeasure("cosine")
```
[Scala docs](https://spark.apache.org/docs/latest/api/scala/org/apache/spark/ml/clustering/KMeans.html#distanceMeasure:org.apache.spark.ml.param.Param%5BString%5D)
Note that an exception will be thrown if there are any zero vectors in the feature vector. |
44,760,033 | I'm just starting out learning Python/Spyder. I have completed a few classes in R for data science.
Below is failing with the error: IOError: File APPL.csv does not exist
However, my script and .csv file are in the same folder. Any thoughts on what I'm doing wrong? Thanks
```
import pandas as pd
def test_run():
df = pd.read_csv("APPL.csv")
print df
if __name__ == "__main__":
test_run()
``` | 2017/06/26 | [
"https://Stackoverflow.com/questions/44760033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270921/"
] | I implemented my own version of k-means on top of spark which uses standard TF-IDF vector representation and (-ve) cosine similarity as the distance metric [code snippet for reference](https://gist.github.com/rajanim/e01d1af591d697202c75ee0a785fa94f). The results from this k-means look right, not as skewed as spark k-means. [figure 1 and 2](https://i.stack.imgur.com/CkcIZ.png)
Additionally, I experimented by plugging in Euclidean distance as a similarity metric (into my own version of k-mean) and results continue to look right, not at all as skewed as spark k-means. Results indicate that its not issue with distance measure but some other case with spark's k-means implementation(scala mllib) | You can normalize your vectors and then cosine similarity or Euclidean distance will give same results. Mathematically it is easy to see that the Euclidean distance = 2 (1 - Cosine Similarity) for normalized vectors. |
44,760,033 | I'm just starting out learning Python/Spyder. I have completed a few classes in R for data science.
Below is failing with the error: IOError: File APPL.csv does not exist
However, my script and .csv file are in the same folder. Any thoughts on what I'm doing wrong? Thanks
```
import pandas as pd
def test_run():
df = pd.read_csv("APPL.csv")
print df
if __name__ == "__main__":
test_run()
``` | 2017/06/26 | [
"https://Stackoverflow.com/questions/44760033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270921/"
] | You can normalize your vectors and then cosine similarity or Euclidean distance will give same results. Mathematically it is easy to see that the Euclidean distance = 2 (1 - Cosine Similarity) for normalized vectors. | A late update incase anyone runs into this. Current versions of spark kmeans do implement cosine distance function, but the default is *euclidean*. For pyspark, this can be set in the constructor:
```py
from pyspark.ml.clustering import KMeans
km = KMeans(distanceMeasure='cosine', k=2, seed=1.0)
# or via setter
km.setDistanceMeasure('cosine')
```
[pyspark docs](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.clustering.KMeans.html#pyspark.ml.clustering.KMeans.distanceMeasure)
---
For Scala use the setter:
```scala
import org.apache.spark.ml.clustering.KMeans
val km = new KMeans()
km.setDistanceMeasure("cosine")
```
[Scala docs](https://spark.apache.org/docs/latest/api/scala/org/apache/spark/ml/clustering/KMeans.html#distanceMeasure:org.apache.spark.ml.param.Param%5BString%5D)
Note that an exception will be thrown if there are any zero vectors in the feature vector. |
20,765,066 | I have table in which only one td will be empty . Here user can drag and drop the td elements .I am trying to write condition so that empty td accept only its neighbor td elements.
Can you please suggest me the accept condition so that ui.droppable or empty td accept its neighbor td .
Code:
```
$("#dropdiv #c tr td").draggable({
appendTo: "body",
helper: 'clone',
cursor: "move",
revert: "invalid"
});
$('#c tr td').droppable({
accept: function(event, ui) {
return ($(this).html().trim().length == 0)
},
drop:function (event, ui ) {
$(this).append(ui.draggable.text());
$(ui.draggable).empty();
}
});
```
From above code if the td is empty then only the td accept ui.draggable .
Please find the demo here:<http://jsfiddle.net/ggbhat/6JKWp/2/>
In demo the middle(5) td is empty , i want only 2,4,6,8 are accepted by 5 . | 2013/12/24 | [
"https://Stackoverflow.com/questions/20765066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2110123/"
] | You can use something like,
```
$('#c tr td').droppable({
accept: function(ui, item) {
if($(this).html().trim().length != 0)
return false;
if($(ui).index()==$(this).index())
return true;
var next=$(this).next().get(0);
var prev=$(this).prev().get(0);
var me=ui.get(0);
if(me==next||me==prev)
return true;
return false;
},
drop:function (event, ui ) {
$(this).append(ui.draggable.text());
$(ui.draggable).empty();
}
});
``` | If you want to selectively accept or reject elements, assign your neighbouring `td` elements some class or id, then do something like this:
```
$("#c tr td").droppable({
accept: function(d) {
if(d.hasClass("neighbouring_table_element")){
return true;
}
}
});
``` |
19,347,441 | i've coded a simple map plotting program but there some error which i can't identify.
1. The bug only occur when X coordinate is positive, its ok when its a negative value.
2. Why is there a last column of dots printed when my range is 11 only?
Here's the code:
```
int xRange = 11;
int yRange = 11;
string _space = " ";
string _star = " * ";
for( int x = xRange; x > 0; x-- )
{
for( int y = 0; y < yRange; y++ )
{
int currentX = x - 6;
int currentY = y - 5;
//demo input
int testX = 2; //<----------ERROR for +ve int, correct for -ve
int testY = -4; //<-------- Y is working ok for +ve and -ve int
//Print x-axis
if( currentY == 0 )
{
if( currentX < 0 )
cout << currentX << " ";
else
cout << " " << currentX << " ";
}
//Print y-axis
if( currentX == 0 )
{
if( currentY < 0 )
cout << currentY << " ";
else
//0 printed in x axis already
if( currentY != 0 )
cout << " " << currentY << " ";
}
else if( currentY == testX and currentX == testY )
cout << _star;
else
cout << " . ";
}
//print new line every completed row print
cout << endl;
}
```
The ouput for demo input (x: 2, y: -4): ( it shows x at 3 which is wrong )
```
. . . . . 5 . . . . . .
. . . . . 4 . . . . . .
. . . . . 3 . . . . . .
. . . . . 2 . . . . . .
. . . . . 1 . . . . . .
-5 -4 -3 -2 -1 0 1 2 3 4 5
. . . . . -1 . . . . . .
. . . . . -2 . . . . . .
. . . . . -3 . . . . . .
. . . . . -4 . . * . . .
. . . . . -5 . . . . . .
```
The output for demo input (x: -2, y: 4):
```
. . . . . 5 . . . . . .
. . . * . 4 . . . . . .
. . . . . 3 . . . . . .
. . . . . 2 . . . . . .
. . . . . 1 . . . . . .
-5 -4 -3 -2 -1 0 1 2 3 4 5
. . . . . -1 . . . . . .
. . . . . -2 . . . . . .
. . . . . -3 . . . . . .
. . . . . -4 . . . . . .
. . . . . -5 . . . . . .
```
Can anyone help to identify the two problem in my code? thanks. | 2013/10/13 | [
"https://Stackoverflow.com/questions/19347441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545530/"
] | `if( currentY == testX and currentX == testY )`
That doesn't look right. Shouldn't you be comparing X to X and Y to Y?
Upon closer look, it's all even stranger. Your outer loop generates rows, but you index them with `x`. Inner loop generates columns for each row, and you index it with `y`. There's general confusion over which axis is the X one and which is the Y one.
**EDIT**: Ah, I see the problem now. When `currentY == 0`, you print the numbers for the axis, and **also** print the dot. | The problem is that when you print the Y axis, you still print a dot, so everything to the right of the y axis is shifted over by 1. You should have another `else` in there:
```
if( currentY == 0 )
{
....
}
else if (currentX == 0) // <--- add an else there
{
....
}
else if ...
``` |
40,070,992 | I keep getting this error in my code, uninitialized local variable "name" used. I set a variable like this
>
> int name = 0;
>
>
>
then later on in the code,
>
> int name = name + 1;
>
>
>
I am trying to set name to 0 then later on add 1 to it then go back to the beginning and still have it equaling name + 1. the problem is it keeps putting it back to 0.
To make it easier here is the part I am talking about.
```
int main()
{
int w = 0;
int choice;
cout << "1: Register\n2: Login\nYour Choice:"; cin >> choice;
if (choice == 1)
{
string username, password;
cout << "Select A Username: "; cin >> username;
cout << "Select A Password: "; cin >> password;
ofstream file;
file.open("data\\" + username + ".txt");
file << username << endl << password;
file.close();
main();
}
else if (choice == 2)
{
bool status = IsLoggedIn();
if (!status)
{
int w = w + 1;
cout << "Unsuccesfull Login!" << endl;
system("PAUSE");
if (w == 3)
{
return 0;
}
else if (w == 2)
{
main();
}
else if (w == 1)
{
main();
}
else if (w == 0)
{
main();
}
}
else
{
cout << "Succesfully Logged In!" << endl;
system("PAUSE");
return true;
}
}
}`
``` | 2016/10/16 | [
"https://Stackoverflow.com/questions/40070992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7026833/"
] | C++ complains when you try to declare two variables with the same name in the same scope.
Basically `int name;` creates the variable name. You can then address it by `name` without `int`.
You probably mean `int name = 0; [...] name = name + 1;`. | You are declaring the variable twice. I'd suggest:
```
int name = 0;
```
then later on in the code,
```
name++;
```
You can use also: `++name;` or `name += 1` |
40,070,992 | I keep getting this error in my code, uninitialized local variable "name" used. I set a variable like this
>
> int name = 0;
>
>
>
then later on in the code,
>
> int name = name + 1;
>
>
>
I am trying to set name to 0 then later on add 1 to it then go back to the beginning and still have it equaling name + 1. the problem is it keeps putting it back to 0.
To make it easier here is the part I am talking about.
```
int main()
{
int w = 0;
int choice;
cout << "1: Register\n2: Login\nYour Choice:"; cin >> choice;
if (choice == 1)
{
string username, password;
cout << "Select A Username: "; cin >> username;
cout << "Select A Password: "; cin >> password;
ofstream file;
file.open("data\\" + username + ".txt");
file << username << endl << password;
file.close();
main();
}
else if (choice == 2)
{
bool status = IsLoggedIn();
if (!status)
{
int w = w + 1;
cout << "Unsuccesfull Login!" << endl;
system("PAUSE");
if (w == 3)
{
return 0;
}
else if (w == 2)
{
main();
}
else if (w == 1)
{
main();
}
else if (w == 0)
{
main();
}
}
else
{
cout << "Succesfully Logged In!" << endl;
system("PAUSE");
return true;
}
}
}`
``` | 2016/10/16 | [
"https://Stackoverflow.com/questions/40070992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7026833/"
] | As you do not receive an error of redeclaring the variable `name` it seems like you use your `int name = name + 1;` somewhere in the code when it not see the first declaration. Here the problem is that `int name = name + 1;` second "name" is not declared before and you try to initialize your first "name" with it.
From start is a a bad approach but here the problem is that when you declare `int name = name + 1;` it is not in the scope of `int name = 0`.
So first be sure you are incrementing your `name` in a place where the compiler "sees" the declaration of `int name = 0` and get rid of the type in `int name = name + 1;` | You are declaring the variable twice. I'd suggest:
```
int name = 0;
```
then later on in the code,
```
name++;
```
You can use also: `++name;` or `name += 1` |
40,070,992 | I keep getting this error in my code, uninitialized local variable "name" used. I set a variable like this
>
> int name = 0;
>
>
>
then later on in the code,
>
> int name = name + 1;
>
>
>
I am trying to set name to 0 then later on add 1 to it then go back to the beginning and still have it equaling name + 1. the problem is it keeps putting it back to 0.
To make it easier here is the part I am talking about.
```
int main()
{
int w = 0;
int choice;
cout << "1: Register\n2: Login\nYour Choice:"; cin >> choice;
if (choice == 1)
{
string username, password;
cout << "Select A Username: "; cin >> username;
cout << "Select A Password: "; cin >> password;
ofstream file;
file.open("data\\" + username + ".txt");
file << username << endl << password;
file.close();
main();
}
else if (choice == 2)
{
bool status = IsLoggedIn();
if (!status)
{
int w = w + 1;
cout << "Unsuccesfull Login!" << endl;
system("PAUSE");
if (w == 3)
{
return 0;
}
else if (w == 2)
{
main();
}
else if (w == 1)
{
main();
}
else if (w == 0)
{
main();
}
}
else
{
cout << "Succesfully Logged In!" << endl;
system("PAUSE");
return true;
}
}
}`
``` | 2016/10/16 | [
"https://Stackoverflow.com/questions/40070992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7026833/"
] | As you do not receive an error of redeclaring the variable `name` it seems like you use your `int name = name + 1;` somewhere in the code when it not see the first declaration. Here the problem is that `int name = name + 1;` second "name" is not declared before and you try to initialize your first "name" with it.
From start is a a bad approach but here the problem is that when you declare `int name = name + 1;` it is not in the scope of `int name = 0`.
So first be sure you are incrementing your `name` in a place where the compiler "sees" the declaration of `int name = 0` and get rid of the type in `int name = name + 1;` | C++ complains when you try to declare two variables with the same name in the same scope.
Basically `int name;` creates the variable name. You can then address it by `name` without `int`.
You probably mean `int name = 0; [...] name = name + 1;`. |
40,070,992 | I keep getting this error in my code, uninitialized local variable "name" used. I set a variable like this
>
> int name = 0;
>
>
>
then later on in the code,
>
> int name = name + 1;
>
>
>
I am trying to set name to 0 then later on add 1 to it then go back to the beginning and still have it equaling name + 1. the problem is it keeps putting it back to 0.
To make it easier here is the part I am talking about.
```
int main()
{
int w = 0;
int choice;
cout << "1: Register\n2: Login\nYour Choice:"; cin >> choice;
if (choice == 1)
{
string username, password;
cout << "Select A Username: "; cin >> username;
cout << "Select A Password: "; cin >> password;
ofstream file;
file.open("data\\" + username + ".txt");
file << username << endl << password;
file.close();
main();
}
else if (choice == 2)
{
bool status = IsLoggedIn();
if (!status)
{
int w = w + 1;
cout << "Unsuccesfull Login!" << endl;
system("PAUSE");
if (w == 3)
{
return 0;
}
else if (w == 2)
{
main();
}
else if (w == 1)
{
main();
}
else if (w == 0)
{
main();
}
}
else
{
cout << "Succesfully Logged In!" << endl;
system("PAUSE");
return true;
}
}
}`
``` | 2016/10/16 | [
"https://Stackoverflow.com/questions/40070992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7026833/"
] | C++ complains when you try to declare two variables with the same name in the same scope.
Basically `int name;` creates the variable name. You can then address it by `name` without `int`.
You probably mean `int name = 0; [...] name = name + 1;`. | The error you get looks more like a warning.
Still it seems that you declared the same variable twice in the same scope and usualy in this case the error would be something like this: redeclaration of variable "name" of type int.
Maybe you declared "name" again in another scope and are trying to get the first one from another scope,which is impossible without pointers or refrences. This is just me guessing because you didn't post the whole code. |
40,070,992 | I keep getting this error in my code, uninitialized local variable "name" used. I set a variable like this
>
> int name = 0;
>
>
>
then later on in the code,
>
> int name = name + 1;
>
>
>
I am trying to set name to 0 then later on add 1 to it then go back to the beginning and still have it equaling name + 1. the problem is it keeps putting it back to 0.
To make it easier here is the part I am talking about.
```
int main()
{
int w = 0;
int choice;
cout << "1: Register\n2: Login\nYour Choice:"; cin >> choice;
if (choice == 1)
{
string username, password;
cout << "Select A Username: "; cin >> username;
cout << "Select A Password: "; cin >> password;
ofstream file;
file.open("data\\" + username + ".txt");
file << username << endl << password;
file.close();
main();
}
else if (choice == 2)
{
bool status = IsLoggedIn();
if (!status)
{
int w = w + 1;
cout << "Unsuccesfull Login!" << endl;
system("PAUSE");
if (w == 3)
{
return 0;
}
else if (w == 2)
{
main();
}
else if (w == 1)
{
main();
}
else if (w == 0)
{
main();
}
}
else
{
cout << "Succesfully Logged In!" << endl;
system("PAUSE");
return true;
}
}
}`
``` | 2016/10/16 | [
"https://Stackoverflow.com/questions/40070992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7026833/"
] | As you do not receive an error of redeclaring the variable `name` it seems like you use your `int name = name + 1;` somewhere in the code when it not see the first declaration. Here the problem is that `int name = name + 1;` second "name" is not declared before and you try to initialize your first "name" with it.
From start is a a bad approach but here the problem is that when you declare `int name = name + 1;` it is not in the scope of `int name = 0`.
So first be sure you are incrementing your `name` in a place where the compiler "sees" the declaration of `int name = 0` and get rid of the type in `int name = name + 1;` | The error you get looks more like a warning.
Still it seems that you declared the same variable twice in the same scope and usualy in this case the error would be something like this: redeclaration of variable "name" of type int.
Maybe you declared "name" again in another scope and are trying to get the first one from another scope,which is impossible without pointers or refrences. This is just me guessing because you didn't post the whole code. |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | Index array defines a permutation. Each permutation consists of cycles. We could rearrange given array by following each cycle and replacing the array elements along the way.
The only problem here is to follow each cycle exactly once. One possible way to do this is to process the array elements in order and for each of them inspect the cycle going through this element. If such cycle touches at least one element with lesser index, elements along this cycle are already permuted. Otherwise we follow this cycle and reorder the elements.
```js
function rearrange(values, indexes) {
main_loop:
for (var start = 0, len = indexes.length; start < len; start++) {
var next = indexes[start];
for (; next != start; next = indexes[next])
if (next < start) continue main_loop;
next = start;
var tmp = values[start];
do {
next = indexes[next];
tmp = [values[next], values[next] = tmp][0]; // swap
} while (next != start);
}
return values;
}
```
This algorithm overwrites each element of given array exactly once, does not mutate the index array (even temporarily). Its worst-case complexity is O(n2). But for random permutations its expected complexity is O(n log n) (as noted in comments for [related answer](https://stackoverflow.com/a/31773540/1009831)).
---
This algorithm could be optimized a little bit. Most obvious optimization is to use a short bitset to keep information about several indexes ahead of current position (whether they are already processed or not). Using a single 32-or-64-bit word to implement this bitset should not violate O(1) space requirement. Such optimization would give small but noticeable speed improvement. Though it does not change worst case and expected asymptotic complexities.
To optimize more, we could temporarily use the index array. If elements of this array have at least one spare bit, we could use it to maintain a bitset allowing us to keep track of all processed elements, which results in a simple linear-time algorithm. But I don't think this could be considered as O(1) space algorithm. So I would assume that index array has no spare bits.
Still the index array could give us some space (much larger then a single word) for look-ahead bitset. Because this array defines a permutation, it contains much less information than arbitrary array of the same size. Stirling approximation for `ln(n!)` gives `n ln n` bits of information while the array could store `n log n` bits. Difference between natural and binary logarithms gives us to about 30% of potential free space. Also we could extract up to 1/64 = 1.5% or 1/32 = 3% free space if size of the array is not exactly a power-of-two, or in other words, if high-order bit is only partially used. (And these 1.5% could be much more valuable than guaranteed 30%).
The idea is to compress all indexes to the left of current position (because they are never used by the algorithm), use part of free space between compressed data and current position to store a look-ahead bitset (to boost performance of the main algorithm), use other part of free space to boost performance of the compression algorithm itself (otherwise we'll need quadratic time for compression only), and finally uncompress all the indexes back to original form.
To compress the indexes we could use factorial number system: scan the array of indexes to find how many of them are less than current index, put the result to compressed stream, and use available free space to process several values at once.
The downside of this method is that most of free space is produced when algorithm comes to the array's end while this space is mostly needed when we are at the beginning. As a result, worst-case complexity is likely to be only slightly less than O(n2). This could also increase expected complexity if not this simple trick: use original algorithm (without compression) while it is cheap enough, then switch to the "compressed" variant.
If length of the array is not a power of 2 (and we have partially unused high-order bit) we could just ignore the fact that index array contains a permutation, and pack all indexes as if in base-`n` numeric system. This allows to greatly reduce worst-case asymptotic complexity as well as speed up the algorithm in "average case". | I'm not sure on the time, but the map function does appear to do what was requested. It's an option, but since I don't know the inner workings of .map then I can't say for sure this is what you're looking for.
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
arr = ind.map(function(value)
{ return arr[value]; });
```
Another solution that doesn't use the map function could look something like this:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
var temp = [];
for (var i = 0, ind_length = ind.length; i < ind_length; i++)
{
var set_index = ind[i];
temp.push(arr[set_index]);
delete arr[set_index];
}
arr = temp;
```
This makes good use of space by using the delete option which also keeps the indexes from shifting. Since it's only doing one loop I imagine the execution is rather fast. Since the commands are very basic and simple this should be a viable solution. It's not quite what was asked which was a swap with no extra space used, but it comes pretty close. I'm new to answering questions like this one so please... constructive criticism. |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | Index array defines a permutation. Each permutation consists of cycles. We could rearrange given array by following each cycle and replacing the array elements along the way.
The only problem here is to follow each cycle exactly once. One possible way to do this is to process the array elements in order and for each of them inspect the cycle going through this element. If such cycle touches at least one element with lesser index, elements along this cycle are already permuted. Otherwise we follow this cycle and reorder the elements.
```js
function rearrange(values, indexes) {
main_loop:
for (var start = 0, len = indexes.length; start < len; start++) {
var next = indexes[start];
for (; next != start; next = indexes[next])
if (next < start) continue main_loop;
next = start;
var tmp = values[start];
do {
next = indexes[next];
tmp = [values[next], values[next] = tmp][0]; // swap
} while (next != start);
}
return values;
}
```
This algorithm overwrites each element of given array exactly once, does not mutate the index array (even temporarily). Its worst-case complexity is O(n2). But for random permutations its expected complexity is O(n log n) (as noted in comments for [related answer](https://stackoverflow.com/a/31773540/1009831)).
---
This algorithm could be optimized a little bit. Most obvious optimization is to use a short bitset to keep information about several indexes ahead of current position (whether they are already processed or not). Using a single 32-or-64-bit word to implement this bitset should not violate O(1) space requirement. Such optimization would give small but noticeable speed improvement. Though it does not change worst case and expected asymptotic complexities.
To optimize more, we could temporarily use the index array. If elements of this array have at least one spare bit, we could use it to maintain a bitset allowing us to keep track of all processed elements, which results in a simple linear-time algorithm. But I don't think this could be considered as O(1) space algorithm. So I would assume that index array has no spare bits.
Still the index array could give us some space (much larger then a single word) for look-ahead bitset. Because this array defines a permutation, it contains much less information than arbitrary array of the same size. Stirling approximation for `ln(n!)` gives `n ln n` bits of information while the array could store `n log n` bits. Difference between natural and binary logarithms gives us to about 30% of potential free space. Also we could extract up to 1/64 = 1.5% or 1/32 = 3% free space if size of the array is not exactly a power-of-two, or in other words, if high-order bit is only partially used. (And these 1.5% could be much more valuable than guaranteed 30%).
The idea is to compress all indexes to the left of current position (because they are never used by the algorithm), use part of free space between compressed data and current position to store a look-ahead bitset (to boost performance of the main algorithm), use other part of free space to boost performance of the compression algorithm itself (otherwise we'll need quadratic time for compression only), and finally uncompress all the indexes back to original form.
To compress the indexes we could use factorial number system: scan the array of indexes to find how many of them are less than current index, put the result to compressed stream, and use available free space to process several values at once.
The downside of this method is that most of free space is produced when algorithm comes to the array's end while this space is mostly needed when we are at the beginning. As a result, worst-case complexity is likely to be only slightly less than O(n2). This could also increase expected complexity if not this simple trick: use original algorithm (without compression) while it is cheap enough, then switch to the "compressed" variant.
If length of the array is not a power of 2 (and we have partially unused high-order bit) we could just ignore the fact that index array contains a permutation, and pack all indexes as if in base-`n` numeric system. This allows to greatly reduce worst-case asymptotic complexity as well as speed up the algorithm in "average case". | Below, one may find a PARTIAL solution for a case when we have only ONE cycle, i.e.
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 2, 5, 0, 1, 3];
function rearrange( i, arr, ind, temp ){
if( temp ){
if( arr[ind[i]] ){
var temp2 = arr[ind[i]];
arr[ind[i]] = temp;
rearrange( ind[i], arr, ind, temp2 );
}
else{ // cycle
arr[ind[i]] = temp;
// var unvisited_index = ...;
// if( unvisited_index ) rearrange( unvisited_index, arr, ind, "" );
}
}
else{
if( i == ind[i] ){
if( i < arr.length ) rearrange( i + 1, arr, ind, temp );
}
else{
temp = arr[ind[i]];
arr[ind[i]]=arr[i];
arr[i] = "";
i = ind[i];
rearrange(i, arr, ind, temp );
}
}
}
rearrange( 0, arr, ind, "" );
```
To make this solution to work for a general case, we need to find total numbers of unique cycles and one index from each of them.
For the `OP` example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
```
There are 2 unique cycles:
```
4 -> 1 -> 0 -> 4
5 -> 3 -> 2 -> 5
```
If one runs
```
rearrange( 0, arr, ind, "" );
rearrange( 5, arr, ind, "" );
```
S(he) will get desirable output for the `OP` problem. |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | This is the "sign bit" solution.
Given that this is a JavaScript question and the numerical literals specified in the *ind* array are therefore stored as signed floats, there is a sign bit available in the space used by the input.
This algorithm cycles through the elements according to the *ind* array and shifts the elements into place until it arrives back to the first element of that cycle. It then finds the next cycle and repeats the same mechanism.
The *ind* array is modified during execution, but will be restored to its original at the completion of the algorithm. In one of the comments you mentioned that this is acceptable.
The *ind* array consists of signed floats, even though they are all non-negative (integers). The sign-bit is used as an indicator for whether the value was already processed or not. In general, this could be considered extra storage (*n* bits, i.e. *O(n)*), but as the storage is already taken by the input, it is not additional acquired space. The sign bits of the *ind* values which represent the left-most member of a cycle are not altered.
**Edit:** I replaced the use of the `~` operator, as it does not produce the desired results for numbers equal or greater than *231*, while JavaScript should support numbers to be used as array indices up to at least *232 - 1*. So instead I now use *k = -k-1*, which is the same, but works for the whole range of floats that is safe for use as integers. Note that as alternative one could use a bit of the float's fractional part (+/- 0.5).
Here is the code:
```js
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log('arr: ' + arr);
console.log('ind: ' + ind);
function rearrange(arr, ind) {
var i, j, buf, temp;
for (j = 0; j < ind.length; j++) {
if (ind[j] >= 0) { // Found a cycle to resolve
i = ind[j];
buf = arr[j];
while (i !== j) { // Not yet back at start of cycle
// Swap buffer with element content
temp = buf;
buf = arr[i];
arr[i] = temp;
// Invert bits, making it negative, to mark as visited
ind[i] = -ind[i]-1;
// Visit next element in cycle
i = -ind[i]-1;
}
// dump buffer into final (=first) element of cycle
arr[j] = buf;
} else {
ind[j] = -ind[j]-1; // restore
}
}
}
```
Although the algorithm has a nested loop, it still runs in *O(n)* time: the swap happens only once per element, and also the outer loop visits every element only once.
The variable declarations show that the memory usage is constant, but with the remark that the sign bits of the *ind* array elements -- in space already allocated by the input -- are used as well. | ```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
function rearrange(arr, ind){
var map = [];
for (var i = 0; i < arr.length; i++) map[ind[i]] = arr[i];
for (var i = 0; i < arr.length; i++) arr[i] = map[i];
}
rearrange(arr, ind);
console.log(arr);
```
That works but, because I'm not a smart developper, I assume it's probably not the fastest algorithm. |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | This proposal utilizes the [answer](https://stackoverflow.com/a/37510065/1447675) of Evgeny Kluev.
I made an extension for faster processing, if all elements are already treated, but the index has not reached zero. This is done with an additional variable `count`, which counts down for every replaced element. This is used for leaving the main loop if all elements are at right position (`count = 0`).
This is helpful for rings, like in the first example with
```
["A", "B", "C", "D", "E", "F"]
[ 4, 0, 5, 2, 1, 3 ]
index 5: 3 -> 2 -> 5 -> 3
index 4: 1 -> 0 -> 4 -> 1
```
Both rings are at first two loops rearranged and while each ring has 3 elements, the `count` is now zero. This leads to a short circuit for the outer while loop.
```js
function rearrange(values, indices) {
var count = indices.length, index = count, next;
main: while (count && index--) {
next = index;
do {
next = indices[next];
if (next > index) continue main;
} while (next !== index)
do {
next = indices[next];
count--;
values[index] = [values[next], values[next] = values[index]][0];
} while (next !== index)
}
}
function go(values, indices) {
rearrange(values, indices);
console.log(values);
}
go(["A", "B", "C", "D", "E", "F"], [4, 0, 5, 2, 1, 3]);
go(["A", "B", "C", "D", "E", "F"], [1, 2, 0, 4, 5, 3]);
go(["A", "B", "C", "D", "E", "F"], [5, 0, 1, 2, 3, 4]);
go(["A", "B", "C", "D", "E", "F"], [0, 1, 3, 2, 4, 5]);
``` | Try this:
```
var result = new Array(5);
for (int i = 0; i < result.length; i++) {
result[i] = arr[ind[i]];
}
console.log(arr);
``` |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | This proposal utilizes the [answer](https://stackoverflow.com/a/37510065/1447675) of Evgeny Kluev.
I made an extension for faster processing, if all elements are already treated, but the index has not reached zero. This is done with an additional variable `count`, which counts down for every replaced element. This is used for leaving the main loop if all elements are at right position (`count = 0`).
This is helpful for rings, like in the first example with
```
["A", "B", "C", "D", "E", "F"]
[ 4, 0, 5, 2, 1, 3 ]
index 5: 3 -> 2 -> 5 -> 3
index 4: 1 -> 0 -> 4 -> 1
```
Both rings are at first two loops rearranged and while each ring has 3 elements, the `count` is now zero. This leads to a short circuit for the outer while loop.
```js
function rearrange(values, indices) {
var count = indices.length, index = count, next;
main: while (count && index--) {
next = index;
do {
next = indices[next];
if (next > index) continue main;
} while (next !== index)
do {
next = indices[next];
count--;
values[index] = [values[next], values[next] = values[index]][0];
} while (next !== index)
}
}
function go(values, indices) {
rearrange(values, indices);
console.log(values);
}
go(["A", "B", "C", "D", "E", "F"], [4, 0, 5, 2, 1, 3]);
go(["A", "B", "C", "D", "E", "F"], [1, 2, 0, 4, 5, 3]);
go(["A", "B", "C", "D", "E", "F"], [5, 0, 1, 2, 3, 4]);
go(["A", "B", "C", "D", "E", "F"], [0, 1, 3, 2, 4, 5]);
``` | I'm not sure on the time, but the map function does appear to do what was requested. It's an option, but since I don't know the inner workings of .map then I can't say for sure this is what you're looking for.
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
arr = ind.map(function(value)
{ return arr[value]; });
```
Another solution that doesn't use the map function could look something like this:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
var temp = [];
for (var i = 0, ind_length = ind.length; i < ind_length; i++)
{
var set_index = ind[i];
temp.push(arr[set_index]);
delete arr[set_index];
}
arr = temp;
```
This makes good use of space by using the delete option which also keeps the indexes from shifting. Since it's only doing one loop I imagine the execution is rather fast. Since the commands are very basic and simple this should be a viable solution. It's not quite what was asked which was a swap with no extra space used, but it comes pretty close. I'm new to answering questions like this one so please... constructive criticism. |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | Index array defines a permutation. Each permutation consists of cycles. We could rearrange given array by following each cycle and replacing the array elements along the way.
The only problem here is to follow each cycle exactly once. One possible way to do this is to process the array elements in order and for each of them inspect the cycle going through this element. If such cycle touches at least one element with lesser index, elements along this cycle are already permuted. Otherwise we follow this cycle and reorder the elements.
```js
function rearrange(values, indexes) {
main_loop:
for (var start = 0, len = indexes.length; start < len; start++) {
var next = indexes[start];
for (; next != start; next = indexes[next])
if (next < start) continue main_loop;
next = start;
var tmp = values[start];
do {
next = indexes[next];
tmp = [values[next], values[next] = tmp][0]; // swap
} while (next != start);
}
return values;
}
```
This algorithm overwrites each element of given array exactly once, does not mutate the index array (even temporarily). Its worst-case complexity is O(n2). But for random permutations its expected complexity is O(n log n) (as noted in comments for [related answer](https://stackoverflow.com/a/31773540/1009831)).
---
This algorithm could be optimized a little bit. Most obvious optimization is to use a short bitset to keep information about several indexes ahead of current position (whether they are already processed or not). Using a single 32-or-64-bit word to implement this bitset should not violate O(1) space requirement. Such optimization would give small but noticeable speed improvement. Though it does not change worst case and expected asymptotic complexities.
To optimize more, we could temporarily use the index array. If elements of this array have at least one spare bit, we could use it to maintain a bitset allowing us to keep track of all processed elements, which results in a simple linear-time algorithm. But I don't think this could be considered as O(1) space algorithm. So I would assume that index array has no spare bits.
Still the index array could give us some space (much larger then a single word) for look-ahead bitset. Because this array defines a permutation, it contains much less information than arbitrary array of the same size. Stirling approximation for `ln(n!)` gives `n ln n` bits of information while the array could store `n log n` bits. Difference between natural and binary logarithms gives us to about 30% of potential free space. Also we could extract up to 1/64 = 1.5% or 1/32 = 3% free space if size of the array is not exactly a power-of-two, or in other words, if high-order bit is only partially used. (And these 1.5% could be much more valuable than guaranteed 30%).
The idea is to compress all indexes to the left of current position (because they are never used by the algorithm), use part of free space between compressed data and current position to store a look-ahead bitset (to boost performance of the main algorithm), use other part of free space to boost performance of the compression algorithm itself (otherwise we'll need quadratic time for compression only), and finally uncompress all the indexes back to original form.
To compress the indexes we could use factorial number system: scan the array of indexes to find how many of them are less than current index, put the result to compressed stream, and use available free space to process several values at once.
The downside of this method is that most of free space is produced when algorithm comes to the array's end while this space is mostly needed when we are at the beginning. As a result, worst-case complexity is likely to be only slightly less than O(n2). This could also increase expected complexity if not this simple trick: use original algorithm (without compression) while it is cheap enough, then switch to the "compressed" variant.
If length of the array is not a power of 2 (and we have partially unused high-order bit) we could just ignore the fact that index array contains a permutation, and pack all indexes as if in base-`n` numeric system. This allows to greatly reduce worst-case asymptotic complexity as well as speed up the algorithm in "average case". | This proposal utilizes the [answer](https://stackoverflow.com/a/37510065/1447675) of Evgeny Kluev.
I made an extension for faster processing, if all elements are already treated, but the index has not reached zero. This is done with an additional variable `count`, which counts down for every replaced element. This is used for leaving the main loop if all elements are at right position (`count = 0`).
This is helpful for rings, like in the first example with
```
["A", "B", "C", "D", "E", "F"]
[ 4, 0, 5, 2, 1, 3 ]
index 5: 3 -> 2 -> 5 -> 3
index 4: 1 -> 0 -> 4 -> 1
```
Both rings are at first two loops rearranged and while each ring has 3 elements, the `count` is now zero. This leads to a short circuit for the outer while loop.
```js
function rearrange(values, indices) {
var count = indices.length, index = count, next;
main: while (count && index--) {
next = index;
do {
next = indices[next];
if (next > index) continue main;
} while (next !== index)
do {
next = indices[next];
count--;
values[index] = [values[next], values[next] = values[index]][0];
} while (next !== index)
}
}
function go(values, indices) {
rearrange(values, indices);
console.log(values);
}
go(["A", "B", "C", "D", "E", "F"], [4, 0, 5, 2, 1, 3]);
go(["A", "B", "C", "D", "E", "F"], [1, 2, 0, 4, 5, 3]);
go(["A", "B", "C", "D", "E", "F"], [5, 0, 1, 2, 3, 4]);
go(["A", "B", "C", "D", "E", "F"], [0, 1, 3, 2, 4, 5]);
``` |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | Index array defines a permutation. Each permutation consists of cycles. We could rearrange given array by following each cycle and replacing the array elements along the way.
The only problem here is to follow each cycle exactly once. One possible way to do this is to process the array elements in order and for each of them inspect the cycle going through this element. If such cycle touches at least one element with lesser index, elements along this cycle are already permuted. Otherwise we follow this cycle and reorder the elements.
```js
function rearrange(values, indexes) {
main_loop:
for (var start = 0, len = indexes.length; start < len; start++) {
var next = indexes[start];
for (; next != start; next = indexes[next])
if (next < start) continue main_loop;
next = start;
var tmp = values[start];
do {
next = indexes[next];
tmp = [values[next], values[next] = tmp][0]; // swap
} while (next != start);
}
return values;
}
```
This algorithm overwrites each element of given array exactly once, does not mutate the index array (even temporarily). Its worst-case complexity is O(n2). But for random permutations its expected complexity is O(n log n) (as noted in comments for [related answer](https://stackoverflow.com/a/31773540/1009831)).
---
This algorithm could be optimized a little bit. Most obvious optimization is to use a short bitset to keep information about several indexes ahead of current position (whether they are already processed or not). Using a single 32-or-64-bit word to implement this bitset should not violate O(1) space requirement. Such optimization would give small but noticeable speed improvement. Though it does not change worst case and expected asymptotic complexities.
To optimize more, we could temporarily use the index array. If elements of this array have at least one spare bit, we could use it to maintain a bitset allowing us to keep track of all processed elements, which results in a simple linear-time algorithm. But I don't think this could be considered as O(1) space algorithm. So I would assume that index array has no spare bits.
Still the index array could give us some space (much larger then a single word) for look-ahead bitset. Because this array defines a permutation, it contains much less information than arbitrary array of the same size. Stirling approximation for `ln(n!)` gives `n ln n` bits of information while the array could store `n log n` bits. Difference between natural and binary logarithms gives us to about 30% of potential free space. Also we could extract up to 1/64 = 1.5% or 1/32 = 3% free space if size of the array is not exactly a power-of-two, or in other words, if high-order bit is only partially used. (And these 1.5% could be much more valuable than guaranteed 30%).
The idea is to compress all indexes to the left of current position (because they are never used by the algorithm), use part of free space between compressed data and current position to store a look-ahead bitset (to boost performance of the main algorithm), use other part of free space to boost performance of the compression algorithm itself (otherwise we'll need quadratic time for compression only), and finally uncompress all the indexes back to original form.
To compress the indexes we could use factorial number system: scan the array of indexes to find how many of them are less than current index, put the result to compressed stream, and use available free space to process several values at once.
The downside of this method is that most of free space is produced when algorithm comes to the array's end while this space is mostly needed when we are at the beginning. As a result, worst-case complexity is likely to be only slightly less than O(n2). This could also increase expected complexity if not this simple trick: use original algorithm (without compression) while it is cheap enough, then switch to the "compressed" variant.
If length of the array is not a power of 2 (and we have partially unused high-order bit) we could just ignore the fact that index array contains a permutation, and pack all indexes as if in base-`n` numeric system. This allows to greatly reduce worst-case asymptotic complexity as well as speed up the algorithm in "average case". | Try this:
```
var result = new Array(5);
for (int i = 0; i < result.length; i++) {
result[i] = arr[ind[i]];
}
console.log(arr);
``` |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | ```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
function rearrange(arr, ind){
var map = [];
for (var i = 0; i < arr.length; i++) map[ind[i]] = arr[i];
for (var i = 0; i < arr.length; i++) arr[i] = map[i];
}
rearrange(arr, ind);
console.log(arr);
```
That works but, because I'm not a smart developper, I assume it's probably not the fastest algorithm. | I am using ind as indexes in it's own order
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
var obj = {}
for(var i=0;i<arr.length;i++)
obj[ind[i]]=arr[i];
console.log(obj);
```
**[Working Fiddle](https://jsfiddle.net/cfLd4w03/)** |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | This is the "sign bit" solution.
Given that this is a JavaScript question and the numerical literals specified in the *ind* array are therefore stored as signed floats, there is a sign bit available in the space used by the input.
This algorithm cycles through the elements according to the *ind* array and shifts the elements into place until it arrives back to the first element of that cycle. It then finds the next cycle and repeats the same mechanism.
The *ind* array is modified during execution, but will be restored to its original at the completion of the algorithm. In one of the comments you mentioned that this is acceptable.
The *ind* array consists of signed floats, even though they are all non-negative (integers). The sign-bit is used as an indicator for whether the value was already processed or not. In general, this could be considered extra storage (*n* bits, i.e. *O(n)*), but as the storage is already taken by the input, it is not additional acquired space. The sign bits of the *ind* values which represent the left-most member of a cycle are not altered.
**Edit:** I replaced the use of the `~` operator, as it does not produce the desired results for numbers equal or greater than *231*, while JavaScript should support numbers to be used as array indices up to at least *232 - 1*. So instead I now use *k = -k-1*, which is the same, but works for the whole range of floats that is safe for use as integers. Note that as alternative one could use a bit of the float's fractional part (+/- 0.5).
Here is the code:
```js
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log('arr: ' + arr);
console.log('ind: ' + ind);
function rearrange(arr, ind) {
var i, j, buf, temp;
for (j = 0; j < ind.length; j++) {
if (ind[j] >= 0) { // Found a cycle to resolve
i = ind[j];
buf = arr[j];
while (i !== j) { // Not yet back at start of cycle
// Swap buffer with element content
temp = buf;
buf = arr[i];
arr[i] = temp;
// Invert bits, making it negative, to mark as visited
ind[i] = -ind[i]-1;
// Visit next element in cycle
i = -ind[i]-1;
}
// dump buffer into final (=first) element of cycle
arr[j] = buf;
} else {
ind[j] = -ind[j]-1; // restore
}
}
}
```
Although the algorithm has a nested loop, it still runs in *O(n)* time: the swap happens only once per element, and also the outer loop visits every element only once.
The variable declarations show that the memory usage is constant, but with the remark that the sign bits of the *ind* array elements -- in space already allocated by the input -- are used as well. | I am using ind as indexes in it's own order
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
var obj = {}
for(var i=0;i<arr.length;i++)
obj[ind[i]]=arr[i];
console.log(obj);
```
**[Working Fiddle](https://jsfiddle.net/cfLd4w03/)** |
37,460,524 | Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243). | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] | This proposal utilizes the [answer](https://stackoverflow.com/a/37510065/1447675) of Evgeny Kluev.
I made an extension for faster processing, if all elements are already treated, but the index has not reached zero. This is done with an additional variable `count`, which counts down for every replaced element. This is used for leaving the main loop if all elements are at right position (`count = 0`).
This is helpful for rings, like in the first example with
```
["A", "B", "C", "D", "E", "F"]
[ 4, 0, 5, 2, 1, 3 ]
index 5: 3 -> 2 -> 5 -> 3
index 4: 1 -> 0 -> 4 -> 1
```
Both rings are at first two loops rearranged and while each ring has 3 elements, the `count` is now zero. This leads to a short circuit for the outer while loop.
```js
function rearrange(values, indices) {
var count = indices.length, index = count, next;
main: while (count && index--) {
next = index;
do {
next = indices[next];
if (next > index) continue main;
} while (next !== index)
do {
next = indices[next];
count--;
values[index] = [values[next], values[next] = values[index]][0];
} while (next !== index)
}
}
function go(values, indices) {
rearrange(values, indices);
console.log(values);
}
go(["A", "B", "C", "D", "E", "F"], [4, 0, 5, 2, 1, 3]);
go(["A", "B", "C", "D", "E", "F"], [1, 2, 0, 4, 5, 3]);
go(["A", "B", "C", "D", "E", "F"], [5, 0, 1, 2, 3, 4]);
go(["A", "B", "C", "D", "E", "F"], [0, 1, 3, 2, 4, 5]);
``` | I am using ind as indexes in it's own order
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
var obj = {}
for(var i=0;i<arr.length;i++)
obj[ind[i]]=arr[i];
console.log(obj);
```
**[Working Fiddle](https://jsfiddle.net/cfLd4w03/)** |
2,201,912 | Does the following series converge or diverge:
$$\sum\_{n=1}^\infty \frac{3^{1/\sqrt{n}}-1}{n}$$
Many thanks! | 2017/03/24 | [
"https://math.stackexchange.com/questions/2201912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428331/"
] | Since $a^{1/\sqrt{n}}-1$ is asymptotic to $ \frac{\log a}{ \sqrt{n}},$ the series converges. | Using [MVT](https://en.wikipedia.org/wiki/Mean_value_theorem) $3^x-1=3^{\epsilon}\ln{3}\cdot (x-0),\epsilon \in (0,x)$ or
$$0<\frac{3^{\frac{1}{\sqrt{n}}}-1}{n}=3^{\epsilon}\ln{3}\frac{1}{n\sqrt{n}}<3\ln{3}\frac{1}{n\sqrt{n}}$$
because $\epsilon \in (0,\frac{1}{\sqrt{n}})$ or $0<\epsilon<1$ and $f(x)=3^x$ is ascending. As a result:
$$\sum\_{n=1}^{\infty}\frac{3^{\frac{1}{\sqrt{n}}}-1}{n}<3\ln{3}\sum\_{n=1}^{\infty}\frac{1}{n^{1+\frac{1}{2}}}$$
which [converges](https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#p-series). |
2,201,912 | Does the following series converge or diverge:
$$\sum\_{n=1}^\infty \frac{3^{1/\sqrt{n}}-1}{n}$$
Many thanks! | 2017/03/24 | [
"https://math.stackexchange.com/questions/2201912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428331/"
] | Since $a^{1/\sqrt{n}}-1$ is asymptotic to $ \frac{\log a}{ \sqrt{n}},$ the series converges. | For any $a > 1$ and $b > 0$,
consider
$\sum\_{n=1}^\infty \frac{a^{1/n^b}-1}{n}
$.
I will show that this sum converges.
OP's problem is
$a=3$ and $b = \frac12$.
$a^{1/n^b}
=e^{\ln a/n^b}
$.
If $0 < x < \frac12$,
$\begin{array}\\
e^x
&=\sum\_{k=0}^{\infty} \frac{x^k}{k!}\\
&<\sum\_{k=0}^{\infty} x^k\\
&=\frac1{1-x}\\
&< 1+2x
\qquad\text{since } (1-x)(1+2x) = 1+x-2x^2
= 1+x(1-2x) > 1\\
\end{array}
$
Therefore,
for
$\ln a/n^b < \frac12$
(i.e.,
$n > (2\ln a)^{1/b}=N(a, b)$),
$e^{\ln a/n^b}
\lt 1+2\ln a/n^b
$
so that,
for $n > N(a, b)$,
$a^{1/n^b}-1
\lt \frac{2\ln a}{n^b}
$.
Therefore
$\frac{a^{1/n^b}-1}{n}
\lt \frac{2\ln a}{n^{b+1}}
$
and $\sum\_{n > N(a, b)} \frac{2\ln a}{n^{b+1}}
$
converges since $b > 0$. |
2,201,912 | Does the following series converge or diverge:
$$\sum\_{n=1}^\infty \frac{3^{1/\sqrt{n}}-1}{n}$$
Many thanks! | 2017/03/24 | [
"https://math.stackexchange.com/questions/2201912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428331/"
] | $$ 3^t = e^{t \log 3} = 1 + t \log 3 + O(t^2) $$
$$ 3^{1/\sqrt n} - 1 = \frac{ \log 3}{\sqrt n} + O(1/n) $$
$$ \frac{3^{1/\sqrt n} -1}{n} = \frac{ \log 3}{ n^{3/2}} + O(1/n^2) $$ | Using [MVT](https://en.wikipedia.org/wiki/Mean_value_theorem) $3^x-1=3^{\epsilon}\ln{3}\cdot (x-0),\epsilon \in (0,x)$ or
$$0<\frac{3^{\frac{1}{\sqrt{n}}}-1}{n}=3^{\epsilon}\ln{3}\frac{1}{n\sqrt{n}}<3\ln{3}\frac{1}{n\sqrt{n}}$$
because $\epsilon \in (0,\frac{1}{\sqrt{n}})$ or $0<\epsilon<1$ and $f(x)=3^x$ is ascending. As a result:
$$\sum\_{n=1}^{\infty}\frac{3^{\frac{1}{\sqrt{n}}}-1}{n}<3\ln{3}\sum\_{n=1}^{\infty}\frac{1}{n^{1+\frac{1}{2}}}$$
which [converges](https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#p-series). |
2,201,912 | Does the following series converge or diverge:
$$\sum\_{n=1}^\infty \frac{3^{1/\sqrt{n}}-1}{n}$$
Many thanks! | 2017/03/24 | [
"https://math.stackexchange.com/questions/2201912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428331/"
] | $$ 3^t = e^{t \log 3} = 1 + t \log 3 + O(t^2) $$
$$ 3^{1/\sqrt n} - 1 = \frac{ \log 3}{\sqrt n} + O(1/n) $$
$$ \frac{3^{1/\sqrt n} -1}{n} = \frac{ \log 3}{ n^{3/2}} + O(1/n^2) $$ | For any $a > 1$ and $b > 0$,
consider
$\sum\_{n=1}^\infty \frac{a^{1/n^b}-1}{n}
$.
I will show that this sum converges.
OP's problem is
$a=3$ and $b = \frac12$.
$a^{1/n^b}
=e^{\ln a/n^b}
$.
If $0 < x < \frac12$,
$\begin{array}\\
e^x
&=\sum\_{k=0}^{\infty} \frac{x^k}{k!}\\
&<\sum\_{k=0}^{\infty} x^k\\
&=\frac1{1-x}\\
&< 1+2x
\qquad\text{since } (1-x)(1+2x) = 1+x-2x^2
= 1+x(1-2x) > 1\\
\end{array}
$
Therefore,
for
$\ln a/n^b < \frac12$
(i.e.,
$n > (2\ln a)^{1/b}=N(a, b)$),
$e^{\ln a/n^b}
\lt 1+2\ln a/n^b
$
so that,
for $n > N(a, b)$,
$a^{1/n^b}-1
\lt \frac{2\ln a}{n^b}
$.
Therefore
$\frac{a^{1/n^b}-1}{n}
\lt \frac{2\ln a}{n^{b+1}}
$
and $\sum\_{n > N(a, b)} \frac{2\ln a}{n^{b+1}}
$
converges since $b > 0$. |
56,329,060 | I have a textbox `Job` in `Form2`, and I have multiple textboxes in `Form1`.
Lets say in `form1` I have `Textbox1` which is `RollFromInventory`, `Textbox2` is `RollFromMachine1`, `Texbox3` is `RollFromMachine2` and so on, assume there are 4 other machines, so four other Textboxes.
When I want to populate the textbox `Job` in `Form2`, I want to write an `If` loop which should look for the textbox which has value populated in it, in `form1` (there will be only one textbox which will have a value among all the available textboxes in `form1`), i.e. either `RollFromInventory` will have a value or `RollFromMachine1` will have a value or `RollFromMachine2`..
I am unsure of the looping logic, so I cant really figure out how to go about it.
Currently the code I have written is mainly for populating concatenated values (I am not providing that code, because it will make the objective seem complicated). | 2019/05/27 | [
"https://Stackoverflow.com/questions/56329060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11232616/"
] | This should work:
```
def validate(num):
try:
n = int(num)
return 2 <= n <= 4094
except:
return False
```
The above function returns `True` if the number is an integer in the specified range, `False` otherwise. | ```py
try:
val = int(user_input)
print("user input is an int")
except ValueError:
print("user_input is not an int")
``` |
56,329,060 | I have a textbox `Job` in `Form2`, and I have multiple textboxes in `Form1`.
Lets say in `form1` I have `Textbox1` which is `RollFromInventory`, `Textbox2` is `RollFromMachine1`, `Texbox3` is `RollFromMachine2` and so on, assume there are 4 other machines, so four other Textboxes.
When I want to populate the textbox `Job` in `Form2`, I want to write an `If` loop which should look for the textbox which has value populated in it, in `form1` (there will be only one textbox which will have a value among all the available textboxes in `form1`), i.e. either `RollFromInventory` will have a value or `RollFromMachine1` will have a value or `RollFromMachine2`..
I am unsure of the looping logic, so I cant really figure out how to go about it.
Currently the code I have written is mainly for populating concatenated values (I am not providing that code, because it will make the objective seem complicated). | 2019/05/27 | [
"https://Stackoverflow.com/questions/56329060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11232616/"
] | This should work:
```
def validate(num):
try:
n = int(num)
return 2 <= n <= 4094
except:
return False
```
The above function returns `True` if the number is an integer in the specified range, `False` otherwise. | You can use [`str.isdecimal()`](https://docs.python.org/3/library/stdtypes.html#str.isdecimal) to check if string contains only digits.
```
inp = input("Enter number: ")
if inp.isdecimal():
n = int(inp)
else:
print("Not a number")
```
If you need function:
```
def validate(inp):
return isinstance(inp, str) and inp.isdecimal()
inp = input("Enter number: ")
print(validate(inp))
``` |
56,329,060 | I have a textbox `Job` in `Form2`, and I have multiple textboxes in `Form1`.
Lets say in `form1` I have `Textbox1` which is `RollFromInventory`, `Textbox2` is `RollFromMachine1`, `Texbox3` is `RollFromMachine2` and so on, assume there are 4 other machines, so four other Textboxes.
When I want to populate the textbox `Job` in `Form2`, I want to write an `If` loop which should look for the textbox which has value populated in it, in `form1` (there will be only one textbox which will have a value among all the available textboxes in `form1`), i.e. either `RollFromInventory` will have a value or `RollFromMachine1` will have a value or `RollFromMachine2`..
I am unsure of the looping logic, so I cant really figure out how to go about it.
Currently the code I have written is mainly for populating concatenated values (I am not providing that code, because it will make the objective seem complicated). | 2019/05/27 | [
"https://Stackoverflow.com/questions/56329060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11232616/"
] | This should work:
```
def validate(num):
try:
n = int(num)
return 2 <= n <= 4094
except:
return False
```
The above function returns `True` if the number is an integer in the specified range, `False` otherwise. | When the function below return True, you can do the Math you need to do with the number.
```
def as_int_in_range(value,range):
try:
value = int(value)
if value >= range[0] and value <= range[1]:
return True,value
else:
return False,None
except ValueError:
return False,None
is_int,val = as_int_in_range('12',(10,100))
if is_int:
# do something with 'val' assuming it is int in the range
else:
# do something else
``` |
53,206,307 | I would like to change the legend style of the following picture generated in Matlab:
```
x1=-5;
x2=5;
y1=-5;
y2=5;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
fill(x,y,'b')
legend('A')
```
[](https://i.stack.imgur.com/nsQdo.jpg)
As you can see the legend displays a blue rectangle. What I would like is a **filled blue circle** in place of the rectangle **as if the picture was generated as a scatter plot**. How can I obtain that? | 2018/11/08 | [
"https://Stackoverflow.com/questions/53206307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9947624/"
] | Your idea with `when` is almost there. Read about <https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#register-variables>, then you can do:
```
tasks:
- name: npm config get strict-ssl
command: npm config get strict-ssl
register: npm_strict_ssl
changed_when: false
- name: Setting up NodeJS
command: npm config set strict-ssl false
when: "npm_strict_ssl['stdout'] == 'true'"
```
I will also add that the specific settings you want to disable, strict SSL, smells like a very bad idea. Please consider fixing the root cause of the problem instead of lowering down security. | You might want to use the construct
```
- command: npm config set strict-ssl false
args:
creates: "{{ lock_file }}"
```
If there is no *lock\_file* created by the *command* you might want to run the *command* in a *block* and create a *lock\_file* on your own.
As a *lock\_file* can be used any file that will be created by the *command*. |
976,665 | How can I prove that, for $a,b \in \mathbb{Z}$ we have $$ 0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor - 2 \left \lfloor{\frac{a}{b}}\right \rfloor \leq 1 \, ? $$ Here, $\left \lfloor\,\right \rfloor$ is the [floor](http://mathworld.wolfram.com/FloorFunction.html) function. I tried the following: say that $\frac{2a}{b} = x$, and $ \left \lfloor{\frac{2a}{b}}\right \rfloor = m$, with $0 \leq x - m \leq 1$. I tried the same for $ 2 \left \lfloor{\frac{2a}{b}}\right \rfloor $, and then combining the two inequalities. It did not seem to help, though. | 2014/10/16 | [
"https://math.stackexchange.com/questions/976665",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/53283/"
] | In general
$$
0\le \lfloor 2x\rfloor -2\lfloor x\rfloor\le 1.
$$
Proof. Either $x\in [k,k+1/2)$ or $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$.
If $x\in [k,k+1/2)$, then
$$
\lfloor 2x\rfloor=2k\quad\text{and}\quad 2\lfloor x\rfloor=2k,
$$
while $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$, then
$$
\lfloor 2x\rfloor=2k+1\quad\text{and}\quad 2\lfloor x\rfloor=2k.
$$
So the inequalities hold in both cases. | $0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor \leq \frac{2\*a}{b} < 2\*(\left \lfloor{\frac{a}{b}}\right \rfloor + 1)$ = $2\*\left \lfloor{\frac{a}{b}}\right \rfloor$ + 2
$\left \lfloor{\frac{2a}{b}}\right \rfloor$ is an integer, so being < than an other integer means being $\leq$ than this integer -1
=> $\left \lfloor{\frac{2a}{b}}\right \rfloor$ $\leq $ $2\*\left \lfloor{\frac{a}{b}}\right \rfloor$ + 1
**Edit:**
As for the other part of the inequality:
$$\frac{2a}{b}= 2\left \lfloor{\frac{a}{b}}\right \rfloor + 2(\frac{a}{b}) $$ with $(x)$ being the fractional part of $x$.
All that's left to consider is whether $2(\frac{a}{b})$ is smaller or greater than $1$ to conclude. |
976,665 | How can I prove that, for $a,b \in \mathbb{Z}$ we have $$ 0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor - 2 \left \lfloor{\frac{a}{b}}\right \rfloor \leq 1 \, ? $$ Here, $\left \lfloor\,\right \rfloor$ is the [floor](http://mathworld.wolfram.com/FloorFunction.html) function. I tried the following: say that $\frac{2a}{b} = x$, and $ \left \lfloor{\frac{2a}{b}}\right \rfloor = m$, with $0 \leq x - m \leq 1$. I tried the same for $ 2 \left \lfloor{\frac{2a}{b}}\right \rfloor $, and then combining the two inequalities. It did not seem to help, though. | 2014/10/16 | [
"https://math.stackexchange.com/questions/976665",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/53283/"
] | In general
$$
0\le \lfloor 2x\rfloor -2\lfloor x\rfloor\le 1.
$$
Proof. Either $x\in [k,k+1/2)$ or $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$.
If $x\in [k,k+1/2)$, then
$$
\lfloor 2x\rfloor=2k\quad\text{and}\quad 2\lfloor x\rfloor=2k,
$$
while $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$, then
$$
\lfloor 2x\rfloor=2k+1\quad\text{and}\quad 2\lfloor x\rfloor=2k.
$$
So the inequalities hold in both cases. | Hint: let $a=pb+q$ where $p, q \in \mathbb Z$ and $0\le q<b$. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.