qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
Line 141 of the code you page linked to is this:
```
141 - done
```
You are not going anything with that variable and you do not end with a semi-colon.
*(Since you are not using a Visual Studio editor, i suspect the program was working, then you introduced a compile time error. Now each time you run the program, you are possibly running an older version.
Hopefully, you can download and use Visual Studio Express which will increase learning time and decrease confusion time. Good luck)*
|
My suggestion: use Nunit and write an unit test for it. Nunit will give expected and actual value and you'll see why this isn't working.
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
First of all: You have error in line 141. Delete that `done` word. I suggest it was just copy paste mistake. Second of all: Here you say your code is:
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}
```
But in the solution you gave link to there is:
```
else if(type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
}
```
I suggest it is just inattention. Your code work fine, just replace
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
```
with
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
```
in your solution.
Talking about simplifying your code, and removing repeatings. Of course there is way to do that. That procedure is called code-refactoring. For example you wrote in your project:
```
...
else if(type == "grams")
{
amount = gramsToOunces(ozToGramsConverter, ref done);
}
...
```
Evaluation of `amount` you replaced to gramsToOunces() method. This is code refactoring too in some measure. You shoul take common parts of your code and look what they depending of. For example:
```
private static double MilesToFeet(UnitConverter milesToFeetConverter, ref int done)
{
double amount;
Console.WriteLine("Enter a number of miles to be converted to feet.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(milesToFeetConverter.Convert(amount) + " feet to said number of miles.");
return amount;
}
```
Every your convert method has such structure. In every method you do the same. You print the same instruction message... you declare the same amount variable and set it's value to console input... And you write almost the same information message after. All of this instead on N methods you have you can put in ONE method. First of all you should extend your converter class. Add two more string fields fields. `FromUnit` and `ToUnit`. Why??? Because you give converter instance as a parameter to your method. And you can use this instance for storing more information about this converter, and for creating information message after. For example:
```
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
```
Than, when you create instance of converter, set appropriate values for these properties.
```
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
```
Now let's write a method which will be represantation of all of your already created methods (gramsToOunces, kilometersToMiles and so on);
```
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
```
and now you can remove ALL of your methods and in if blocks you can call this one method, just with different parameters instead of calling different methods, which do the same.
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
After all these manipulation your solution will look like:
```
using System;
namespace ConsoleApplication2
{
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
class Test
{
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
public static void Main()
{
UnitConverter feetToInchesConverter = new UnitConverter(12) { From = "feet", To = "inches"};
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
UnitConverter kmsToMilesConverter = new UnitConverter(1.609) { From = "kilometers", To = "miles"};
UnitConverter centToInchesConverter = new UnitConverter(2.54) { From = "centimeters", To = "inches" };
UnitConverter ozToGramsConverter = new UnitConverter(28.349) { From = "ounces", To = "grams" };
UnitConverter cupsTolitConverter = new UnitConverter(4.226) { From = "cups", To = "litters" };
string type;
int done;
done = 0;
while(done == 0)
{
{
type = Console.ReadLine();
if(type == "centi")
{
MakeConversion(centToInchesConverter);
}
else if(type == "feet")
{
MakeConversion(feetToInchesConverter);
}
else if(type == "km")
{
MakeConversion(kmsToMilesConverter);
}
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
else if(type == "grams")
{
MakeConversion(ozToGramsConverter);
}
else if(type == "cups")
{
MakeConversion(cupsTolitConverter);
}
else if(type == "end")
{
done = 1;
}
}
}
}
}
}
```
Of curce you can do more a lot of things to make code easier and clearer. Replace if with cases, replace `MakeConversion` method directly to UnitConverter class, change architecture of your class. It is only my suggestions about what you can do. But first of all try to learn how to write your oun methods and classes, and don't use VisualStudio method generator, you should know how to write methods yourself. I somehow tried to explain that, hope it helped
|
My suggestion: use Nunit and write an unit test for it. Nunit will give expected and actual value and you'll see why this isn't working.
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
I ran your code and (after fixing a simple error) it correctly enters the *else if* that you reference.
You may want to echo back what you type in to make sure you are not mistyping your input.
The error was that you have
>
> done
>
>
>
on a line by itself. Presumably you meant to assign a value.
|
Line 141 of the code you page linked to is this:
```
141 - done
```
You are not going anything with that variable and you do not end with a semi-colon.
*(Since you are not using a Visual Studio editor, i suspect the program was working, then you introduced a compile time error. Now each time you run the program, you are possibly running an older version.
Hopefully, you can download and use Visual Studio Express which will increase learning time and decrease confusion time. Good luck)*
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
I ran your code and (after fixing a simple error) it correctly enters the *else if* that you reference.
You may want to echo back what you type in to make sure you are not mistyping your input.
The error was that you have
>
> done
>
>
>
on a line by itself. Presumably you meant to assign a value.
|
If the "If else" doesn't get hit, it means one of two things: Either a previous condition is true, or the condition is false.
The '==' operator is case sensitive when comparing [strings](http://msdn.microsoft.com/en-us/library/362314fe%28v=vs.71%29.aspx) So be sure to take that into account . It is a more complex topic that will make sense later on as you progress.
Good luck!
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
First of all: You have error in line 141. Delete that `done` word. I suggest it was just copy paste mistake. Second of all: Here you say your code is:
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}
```
But in the solution you gave link to there is:
```
else if(type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
}
```
I suggest it is just inattention. Your code work fine, just replace
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
```
with
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
```
in your solution.
Talking about simplifying your code, and removing repeatings. Of course there is way to do that. That procedure is called code-refactoring. For example you wrote in your project:
```
...
else if(type == "grams")
{
amount = gramsToOunces(ozToGramsConverter, ref done);
}
...
```
Evaluation of `amount` you replaced to gramsToOunces() method. This is code refactoring too in some measure. You shoul take common parts of your code and look what they depending of. For example:
```
private static double MilesToFeet(UnitConverter milesToFeetConverter, ref int done)
{
double amount;
Console.WriteLine("Enter a number of miles to be converted to feet.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(milesToFeetConverter.Convert(amount) + " feet to said number of miles.");
return amount;
}
```
Every your convert method has such structure. In every method you do the same. You print the same instruction message... you declare the same amount variable and set it's value to console input... And you write almost the same information message after. All of this instead on N methods you have you can put in ONE method. First of all you should extend your converter class. Add two more string fields fields. `FromUnit` and `ToUnit`. Why??? Because you give converter instance as a parameter to your method. And you can use this instance for storing more information about this converter, and for creating information message after. For example:
```
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
```
Than, when you create instance of converter, set appropriate values for these properties.
```
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
```
Now let's write a method which will be represantation of all of your already created methods (gramsToOunces, kilometersToMiles and so on);
```
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
```
and now you can remove ALL of your methods and in if blocks you can call this one method, just with different parameters instead of calling different methods, which do the same.
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
After all these manipulation your solution will look like:
```
using System;
namespace ConsoleApplication2
{
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
class Test
{
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
public static void Main()
{
UnitConverter feetToInchesConverter = new UnitConverter(12) { From = "feet", To = "inches"};
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
UnitConverter kmsToMilesConverter = new UnitConverter(1.609) { From = "kilometers", To = "miles"};
UnitConverter centToInchesConverter = new UnitConverter(2.54) { From = "centimeters", To = "inches" };
UnitConverter ozToGramsConverter = new UnitConverter(28.349) { From = "ounces", To = "grams" };
UnitConverter cupsTolitConverter = new UnitConverter(4.226) { From = "cups", To = "litters" };
string type;
int done;
done = 0;
while(done == 0)
{
{
type = Console.ReadLine();
if(type == "centi")
{
MakeConversion(centToInchesConverter);
}
else if(type == "feet")
{
MakeConversion(feetToInchesConverter);
}
else if(type == "km")
{
MakeConversion(kmsToMilesConverter);
}
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
else if(type == "grams")
{
MakeConversion(ozToGramsConverter);
}
else if(type == "cups")
{
MakeConversion(cupsTolitConverter);
}
else if(type == "end")
{
done = 1;
}
}
}
}
}
}
```
Of curce you can do more a lot of things to make code easier and clearer. Replace if with cases, replace `MakeConversion` method directly to UnitConverter class, change architecture of your class. It is only my suggestions about what you can do. But first of all try to learn how to write your oun methods and classes, and don't use VisualStudio method generator, you should know how to write methods yourself. I somehow tried to explain that, hope it helped
|
I ran your code and (after fixing a simple error) it correctly enters the *else if* that you reference.
You may want to echo back what you type in to make sure you are not mistyping your input.
The error was that you have
>
> done
>
>
>
on a line by itself. Presumably you meant to assign a value.
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
Line 141 of the code you page linked to is this:
```
141 - done
```
You are not going anything with that variable and you do not end with a semi-colon.
*(Since you are not using a Visual Studio editor, i suspect the program was working, then you introduced a compile time error. Now each time you run the program, you are possibly running an older version.
Hopefully, you can download and use Visual Studio Express which will increase learning time and decrease confusion time. Good luck)*
|
If the "If else" doesn't get hit, it means one of two things: Either a previous condition is true, or the condition is false.
The '==' operator is case sensitive when comparing [strings](http://msdn.microsoft.com/en-us/library/362314fe%28v=vs.71%29.aspx) So be sure to take that into account . It is a more complex topic that will make sense later on as you progress.
Good luck!
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
First of all: You have error in line 141. Delete that `done` word. I suggest it was just copy paste mistake. Second of all: Here you say your code is:
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}
```
But in the solution you gave link to there is:
```
else if(type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
}
```
I suggest it is just inattention. Your code work fine, just replace
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
```
with
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
```
in your solution.
Talking about simplifying your code, and removing repeatings. Of course there is way to do that. That procedure is called code-refactoring. For example you wrote in your project:
```
...
else if(type == "grams")
{
amount = gramsToOunces(ozToGramsConverter, ref done);
}
...
```
Evaluation of `amount` you replaced to gramsToOunces() method. This is code refactoring too in some measure. You shoul take common parts of your code and look what they depending of. For example:
```
private static double MilesToFeet(UnitConverter milesToFeetConverter, ref int done)
{
double amount;
Console.WriteLine("Enter a number of miles to be converted to feet.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(milesToFeetConverter.Convert(amount) + " feet to said number of miles.");
return amount;
}
```
Every your convert method has such structure. In every method you do the same. You print the same instruction message... you declare the same amount variable and set it's value to console input... And you write almost the same information message after. All of this instead on N methods you have you can put in ONE method. First of all you should extend your converter class. Add two more string fields fields. `FromUnit` and `ToUnit`. Why??? Because you give converter instance as a parameter to your method. And you can use this instance for storing more information about this converter, and for creating information message after. For example:
```
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
```
Than, when you create instance of converter, set appropriate values for these properties.
```
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
```
Now let's write a method which will be represantation of all of your already created methods (gramsToOunces, kilometersToMiles and so on);
```
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
```
and now you can remove ALL of your methods and in if blocks you can call this one method, just with different parameters instead of calling different methods, which do the same.
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
After all these manipulation your solution will look like:
```
using System;
namespace ConsoleApplication2
{
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
class Test
{
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
public static void Main()
{
UnitConverter feetToInchesConverter = new UnitConverter(12) { From = "feet", To = "inches"};
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
UnitConverter kmsToMilesConverter = new UnitConverter(1.609) { From = "kilometers", To = "miles"};
UnitConverter centToInchesConverter = new UnitConverter(2.54) { From = "centimeters", To = "inches" };
UnitConverter ozToGramsConverter = new UnitConverter(28.349) { From = "ounces", To = "grams" };
UnitConverter cupsTolitConverter = new UnitConverter(4.226) { From = "cups", To = "litters" };
string type;
int done;
done = 0;
while(done == 0)
{
{
type = Console.ReadLine();
if(type == "centi")
{
MakeConversion(centToInchesConverter);
}
else if(type == "feet")
{
MakeConversion(feetToInchesConverter);
}
else if(type == "km")
{
MakeConversion(kmsToMilesConverter);
}
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
else if(type == "grams")
{
MakeConversion(ozToGramsConverter);
}
else if(type == "cups")
{
MakeConversion(cupsTolitConverter);
}
else if(type == "end")
{
done = 1;
}
}
}
}
}
}
```
Of curce you can do more a lot of things to make code easier and clearer. Replace if with cases, replace `MakeConversion` method directly to UnitConverter class, change architecture of your class. It is only my suggestions about what you can do. But first of all try to learn how to write your oun methods and classes, and don't use VisualStudio method generator, you should know how to write methods yourself. I somehow tried to explain that, hope it helped
|
Line 141 of the code you page linked to is this:
```
141 - done
```
You are not going anything with that variable and you do not end with a semi-colon.
*(Since you are not using a Visual Studio editor, i suspect the program was working, then you introduced a compile time error. Now each time you run the program, you are possibly running an older version.
Hopefully, you can download and use Visual Studio Express which will increase learning time and decrease confusion time. Good luck)*
|
12,100,977 |
So I can't seem to get an else if to work right.
What I've been doing is writing a unit converter to try and teach myself the basics of programming, I'm kind of new to it. So new as to say this is actually my first working while loop. So I've been writing the code, and then doing as a friend who is somewhat more experienced at programming has told me to do. Which is separate said code out into methods. I used the VS2010 automatic method making thing for this, because I didn't know how to do it myself. The full source code in question is here <http://pastebin.com/9mZPPtWr> the problem bit is this one
`
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}`
```
I entered cups into the console, and despite every other entry/imput working fine and the loop looping back to the selection bit each time, I can't seem to get that section of code to work. It just won't display, I've been working on it for an hour now, and I starting to think I'm missing something incredibly obvious, or something incredibly arcane. Also I have a lot of repeated code and I was wondering if there was a way to simplify that down to less repeats.
Thanks, and I hope that was readable and understandable. Even if my code probably isn't. Also I got the starting code(the top bit) from Accelerated C#. Will elaborate more on my question if needed.
|
2012/08/23
|
['https://Stackoverflow.com/questions/12100977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620762/']
|
First of all: You have error in line 141. Delete that `done` word. I suggest it was just copy paste mistake. Second of all: Here you say your code is:
```
else if (type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
}
```
But in the solution you gave link to there is:
```
else if(type == "cups")
{
Console.WriteLine("Enter a number of liters to be converted into cups.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
}
```
I suggest it is just inattention. Your code work fine, just replace
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " centimeters to said number of inches.");
```
with
```
Console.WriteLine(cupsTolitConverter.Convert(amount) + " cups to said number of liters.");
```
in your solution.
Talking about simplifying your code, and removing repeatings. Of course there is way to do that. That procedure is called code-refactoring. For example you wrote in your project:
```
...
else if(type == "grams")
{
amount = gramsToOunces(ozToGramsConverter, ref done);
}
...
```
Evaluation of `amount` you replaced to gramsToOunces() method. This is code refactoring too in some measure. You shoul take common parts of your code and look what they depending of. For example:
```
private static double MilesToFeet(UnitConverter milesToFeetConverter, ref int done)
{
double amount;
Console.WriteLine("Enter a number of miles to be converted to feet.");
amount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(milesToFeetConverter.Convert(amount) + " feet to said number of miles.");
return amount;
}
```
Every your convert method has such structure. In every method you do the same. You print the same instruction message... you declare the same amount variable and set it's value to console input... And you write almost the same information message after. All of this instead on N methods you have you can put in ONE method. First of all you should extend your converter class. Add two more string fields fields. `FromUnit` and `ToUnit`. Why??? Because you give converter instance as a parameter to your method. And you can use this instance for storing more information about this converter, and for creating information message after. For example:
```
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
```
Than, when you create instance of converter, set appropriate values for these properties.
```
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
```
Now let's write a method which will be represantation of all of your already created methods (gramsToOunces, kilometersToMiles and so on);
```
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
```
and now you can remove ALL of your methods and in if blocks you can call this one method, just with different parameters instead of calling different methods, which do the same.
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
After all these manipulation your solution will look like:
```
using System;
namespace ConsoleApplication2
{
public class UnitConverter
{
double ratio;
public string From { get; set; }
public string To { get; set; }
public UnitConverter(double unitratio) { ratio = unitratio; }
public double Convert(double unit) { return unit * ratio; }
}
class Test
{
private static void MakeConversion(UnitConverter customConverter)
{
Console.WriteLine("Enter a number of {0} to be converted to {1}.",customConverter.From, customConverter.To);
double amount = Convert.ToDouble(Console.ReadLine());
string message = string.Format("{0} {1} to said number of {2}", amount, customConverter.To, customConverter.From);
Console.WriteLine(message);
}
public static void Main()
{
UnitConverter feetToInchesConverter = new UnitConverter(12) { From = "feet", To = "inches"};
UnitConverter milesToFeetConverter = new UnitConverter(5280) { From = "miles" , To = "feet"};
UnitConverter kmsToMilesConverter = new UnitConverter(1.609) { From = "kilometers", To = "miles"};
UnitConverter centToInchesConverter = new UnitConverter(2.54) { From = "centimeters", To = "inches" };
UnitConverter ozToGramsConverter = new UnitConverter(28.349) { From = "ounces", To = "grams" };
UnitConverter cupsTolitConverter = new UnitConverter(4.226) { From = "cups", To = "litters" };
string type;
int done;
done = 0;
while(done == 0)
{
{
type = Console.ReadLine();
if(type == "centi")
{
MakeConversion(centToInchesConverter);
}
else if(type == "feet")
{
MakeConversion(feetToInchesConverter);
}
else if(type == "km")
{
MakeConversion(kmsToMilesConverter);
}
else if(type == "miles")
{
MakeConversion(milesToFeetConverter);
}
else if(type == "grams")
{
MakeConversion(ozToGramsConverter);
}
else if(type == "cups")
{
MakeConversion(cupsTolitConverter);
}
else if(type == "end")
{
done = 1;
}
}
}
}
}
}
```
Of curce you can do more a lot of things to make code easier and clearer. Replace if with cases, replace `MakeConversion` method directly to UnitConverter class, change architecture of your class. It is only my suggestions about what you can do. But first of all try to learn how to write your oun methods and classes, and don't use VisualStudio method generator, you should know how to write methods yourself. I somehow tried to explain that, hope it helped
|
If the "If else" doesn't get hit, it means one of two things: Either a previous condition is true, or the condition is false.
The '==' operator is case sensitive when comparing [strings](http://msdn.microsoft.com/en-us/library/362314fe%28v=vs.71%29.aspx) So be sure to take that into account . It is a more complex topic that will make sense later on as you progress.
Good luck!
|
8,062,712 |
I am using VS2005 C# and SQL Server 2005. I am currently doing an import for a .CSV excel file data into my SQL Server database.
I am having some error, which I assume is related to my sql statement. Below is my code:
```
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv")
{
Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>");
return;
}
// Generate the file name to save.
string dir = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\";
string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileUpload1.SaveAs(dir+mycsv);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr))
{
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [TABLES] FROM" + mycsv, ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<UID>;Password=<PW>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "DEMUserRoles";
bulkCopy.WriteToServer(dr);
Response.Write("<script>alert('DEM User Data imported');</script>");
}
}
}
}
else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>");
}
```
I am getting the error
>
> "Syntax error (missing operator) in query expression '[Description] FROM20111109164041.csv'."
>
>
>
while executing using (DbDataReader dr = ExcelCommand.ExecuteReader()). Description is the last column in my database.
Anyone know what is wrong with my code? Thank You

|
2011/11/09
|
['https://Stackoverflow.com/questions/8062712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/872370/']
|
You need a space between FROM and the csv file! :)
```
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [TABLES] FROM " + mycsv, ExcelConnection);
```
That's why I always use the string.Format method, you see much better how the final string will look:
```
OleDbCommand ExcelCommand = new OleDbCommand(string.Format("SELECT [TABLES] FROM {0}",mycsv), ExcelConnection);
```
|
Seems like you need to place a blank between FROM and your CSV-File:
'[Description] FROM 20111109164041.csv'
|
8,062,712 |
I am using VS2005 C# and SQL Server 2005. I am currently doing an import for a .CSV excel file data into my SQL Server database.
I am having some error, which I assume is related to my sql statement. Below is my code:
```
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv")
{
Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>");
return;
}
// Generate the file name to save.
string dir = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\";
string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileUpload1.SaveAs(dir+mycsv);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr))
{
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [TABLES] FROM" + mycsv, ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<UID>;Password=<PW>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "DEMUserRoles";
bulkCopy.WriteToServer(dr);
Response.Write("<script>alert('DEM User Data imported');</script>");
}
}
}
}
else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>");
}
```
I am getting the error
>
> "Syntax error (missing operator) in query expression '[Description] FROM20111109164041.csv'."
>
>
>
while executing using (DbDataReader dr = ExcelCommand.ExecuteReader()). Description is the last column in my database.
Anyone know what is wrong with my code? Thank You

|
2011/11/09
|
['https://Stackoverflow.com/questions/8062712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/872370/']
|
You need a space between FROM and the csv file! :)
```
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [TABLES] FROM " + mycsv, ExcelConnection);
```
That's why I always use the string.Format method, you see much better how the final string will look:
```
OleDbCommand ExcelCommand = new OleDbCommand(string.Format("SELECT [TABLES] FROM {0}",mycsv), ExcelConnection);
```
|
If you are adding a string you should place it between single quotes
```
OleDbDataAdapter da = new OleDbDataAdapter("select * , '" + tempUid + "' as [UID] from [" + sheet1 + "]", conn);
```
|
8,062,712 |
I am using VS2005 C# and SQL Server 2005. I am currently doing an import for a .CSV excel file data into my SQL Server database.
I am having some error, which I assume is related to my sql statement. Below is my code:
```
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv")
{
Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>");
return;
}
// Generate the file name to save.
string dir = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\";
string mycsv = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileUpload1.SaveAs(dir+mycsv);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr))
{
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [TABLES] FROM" + mycsv, ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<UID>;Password=<PW>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "DEMUserRoles";
bulkCopy.WriteToServer(dr);
Response.Write("<script>alert('DEM User Data imported');</script>");
}
}
}
}
else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>");
}
```
I am getting the error
>
> "Syntax error (missing operator) in query expression '[Description] FROM20111109164041.csv'."
>
>
>
while executing using (DbDataReader dr = ExcelCommand.ExecuteReader()). Description is the last column in my database.
Anyone know what is wrong with my code? Thank You

|
2011/11/09
|
['https://Stackoverflow.com/questions/8062712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/872370/']
|
Seems like you need to place a blank between FROM and your CSV-File:
'[Description] FROM 20111109164041.csv'
|
If you are adding a string you should place it between single quotes
```
OleDbDataAdapter da = new OleDbDataAdapter("select * , '" + tempUid + "' as [UID] from [" + sheet1 + "]", conn);
```
|
62,770,330 |
I have a list of words that I want to search in a string of large text.I have defined a function that returns each individual word but I dont know how to pass the function to re.findall(). I want to get any sentense that contains any word that is in words list.
Can someone assist :)
here is what I got:
```
strings = ['some large text', 'some large text'...]
ad = []
words = ['ascertained','deep','detected','disclosed','disinterred','espied','explored','exposed','famous','happened upon','identified','invented','learned','observed','perceived','presented','revealed','searched out','shown','sighted','spotted','unveiled']
def word():
for i in words:
t = word[i]
return t
for i in range(len(strings)):
ad += re.findall(r"([^.]*?word()[^.]*\.)",strings[i])
sep = ''
adc = sep.join(ad)
```
|
2020/07/07
|
['https://Stackoverflow.com/questions/62770330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13863930/']
|
The problem was with the `transform.rotation` that was not able to change the rotation from -90/270 to new rotation. I instead had to use `transform.localRotation` and it worked perfectly.
```
using UnityEngine;
using System.Collections;
public class ScaleAndRotate : MonoBehaviour {
public int startSize = 3;
public int minSize = 1;
public int maxSize = 6;
public float speed = 2.0f;
private Vector3 targetScale;
private Vector3 baseScale;
private int currScale;
//ROT
public Quaternion targetRotation;
public Quaternion initialRotation;
public bool startRotation = false;
void Start() {
baseScale = transform.localScale;
transform.localScale = baseScale * startSize;
currScale = startSize;
targetScale = baseScale * startSize;
initialRotation = transform.localRotation;
}
void Update() {
transform.localScale = Vector3.Lerp (transform.localScale, targetScale, speed * Time.deltaTime);
if(startRotation == true)
{
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, Time.deltaTime * speed);
}
else
if(startRotation == false)
{
//Go Back To Initial Rotation
transform.localRotation = Quaternion.Slerp(transform.localRotation, initialRotation, Time.deltaTime * speed);
}
if (Input.GetKeyDown (KeyCode.UpArrow))
{
ChangeSize (true);
startRotation = false;
}
if (Input.GetKeyDown (KeyCode.DownArrow))
{
ChangeSize (false);
startRotation = true;
}
}
public void ChangeSize(bool bigger) {
if (bigger)
{
currScale++;
}
else
{
currScale--;
}
currScale = Mathf.Clamp (currScale, minSize, maxSize+1);
targetScale = baseScale * currScale;
}
}
```
|
I think the problem is that you miss brackets when you use `if` statements:
```
if (Input.GetKeyDown (KeyCode.UpArrow))
ChangeSize (true);
startRotation = true;
if (Input.GetKeyDown (KeyCode.DownArrow))
ChangeSize (false);
startRotation = false;
```
When you use something like that code above the `if` is used only to the first following line of code. Thus, add brackets to that code:
```
if (Input.GetKeyDown (KeyCode.UpArrow))
{
ChangeSize (true);
startRotation = true;
}
if (Input.GetKeyDown (KeyCode.DownArrow))
{
ChangeSize (false);
startRotation = false;
}
```
|
3,647,548 |
I want to manually update the `contentOffset` of an `UIScrollView` during rotation changes. The scroll view fills the screen and has flexible width and flexible height.
I'm currently trying to update the contentOffset in `willRotateToInterfaceOrientation`, like this:
```
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[Utils logPoint:myScrollView.contentOffset tag:@"initial"];
myScrollView.contentOffset = CGPointMake(modifiedX, modifiedY);
[Utils logPoint:myScrollView.contentOffset tag:@"modified"];
}
-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[Utils logPoint:myScrollView.contentOffset tag:@"final"];
}
```
However, the final value is not the modified value, and it kinda seems to be influenced by it, but it's not evident to me how.
These are some of the results that I get:
```
initial: (146.000000;-266.000000)
modified: (81.000000;-108.000000)
final: (59.000000;-0.000000)
initial: (146.000000;-266.000000)
modified: (500.000000;500.000000)
final: (59.000000;500.000000)
initial: (146.000000;-266.000000)
modified: (-500.000000;-500.000000)
final: (-0.000000;-0.000000)
```
How do I update the contentOffset of a scroll view during a rotation change?
|
2010/09/05
|
['https://Stackoverflow.com/questions/3647548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143378/']
|
Converting my comment to an answer :)
Try changing `contentOffset` from within `willAnimateRotationToInterfaceOrientation:duration:` instead. An animation block should be in place by then, and the OS regards your changes to contentOffset as belonging to the changes caused by the rotation.
If you change contentOffset before, it looks like the system doesn't respect these changes as belonging to the rotation, and still applies rotation-resizing, this time starting from your new dimensions.
|
Following snippets does the trick when paging is enabled on UIScrollView and page offset is to be maintained.
Declare a property which will calculate position of currentPage before rotation, and set it to -1 in `viewDidLoad`
```
@property (assign, nonatomic) NSInteger lastPageBeforeRotate;
```
Then override the `willRotateToInterfaceOrientation:toInterfaceOrientation:duration` method and assign calculated value to it.
```
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
int pageWidth = self.scrollView.contentSize.width / self.images.count;
int scrolledX = self.scrollView.contentOffset.x;
self.lastPageBeforeRotate = 0;
if (pageWidth > 0) {
self.lastPageBeforeRotate = scrolledX / pageWidth;
}
[self showBackButton:NO];
}
```
Then we ensure that before rotation is performed, we set our scrollview's content offset correctly, so as to focus it to our `lastPageBeforeRotate`
```
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
if (self.lastPageBeforeRotate != -1) {
self.scrollView.contentOffset = CGPointMake(self.scrollView.bounds.size.width * self.lastPageBeforeRotate, 0);
self.lastPageBeforeRotate = -1;
}
}
```
|
3,647,548 |
I want to manually update the `contentOffset` of an `UIScrollView` during rotation changes. The scroll view fills the screen and has flexible width and flexible height.
I'm currently trying to update the contentOffset in `willRotateToInterfaceOrientation`, like this:
```
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[Utils logPoint:myScrollView.contentOffset tag:@"initial"];
myScrollView.contentOffset = CGPointMake(modifiedX, modifiedY);
[Utils logPoint:myScrollView.contentOffset tag:@"modified"];
}
-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[Utils logPoint:myScrollView.contentOffset tag:@"final"];
}
```
However, the final value is not the modified value, and it kinda seems to be influenced by it, but it's not evident to me how.
These are some of the results that I get:
```
initial: (146.000000;-266.000000)
modified: (81.000000;-108.000000)
final: (59.000000;-0.000000)
initial: (146.000000;-266.000000)
modified: (500.000000;500.000000)
final: (59.000000;500.000000)
initial: (146.000000;-266.000000)
modified: (-500.000000;-500.000000)
final: (-0.000000;-0.000000)
```
How do I update the contentOffset of a scroll view during a rotation change?
|
2010/09/05
|
['https://Stackoverflow.com/questions/3647548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143378/']
|
Converting my comment to an answer :)
Try changing `contentOffset` from within `willAnimateRotationToInterfaceOrientation:duration:` instead. An animation block should be in place by then, and the OS regards your changes to contentOffset as belonging to the changes caused by the rotation.
If you change contentOffset before, it looks like the system doesn't respect these changes as belonging to the rotation, and still applies rotation-resizing, this time starting from your new dimensions.
|
Updated answer for iOS 8+
Implement viewWillTransitionToSize:withTransitionCoordinator: in your controller.
Example:
```
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
NSUInteger visiblePage = (NSInteger) self.scrollView.contentOffset.x / self.scrollView.bounds.size.width;
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
self.scrollView.contentOffset = CGPointMake(visiblePage * self.scrollView.bounds.size.width, self.scrollView.contentOffset.y);
} completion:nil];
}
```
|
23,089 |
I have a set of XML based services running on my network.
The data in these services needs to be mirrored into a Table on an SQL Server 2008 instance.
Getting the XML into a table is no problem I can already do that, but what I'm having to do at the moment is pass a huge long string of XML to a stored proc which then uses the OPENXML command to insert it into the table.
What I'm wanting to know, is instead of using a 3rd party program to get this data from the service then call the stored proc and insert it, is it in anyway possible for me to get SQL Server to just grab the XML directly from the service URL and process it like that.
All I can seem to find no matter how much I try is plenty of articles & posts on reading / writing files to / from the server file system and the several million or so on actually inserting the XML data, but I can't seem to find anything on getting the server to grab data directly from a URL.
Cheers
-----===== Update 25/8/2012 =====-----
After a little bit more research Iv'e found a third way to do this:
```
declare @xmlObject as int
declare @responseText as varchar(max)
declare @url as varchar(2048)
select @url = 'http://server/feed/data'
exec sp_OACreate 'MSXML2.XMLHTTP', @xmlObject OUT;
exec sp_OAMethod @xmlObject, 'open', NULL, 'get', @url, 'false'
exec sp_OAMethod @xmlObject, 'send'
exec sp_OAMethod @xmlObject, 'responsetext', @responseText OUTPUT
exec sp_OADestroy @xmlObject
select @responseText
exec sp_xml_preparedocument @idoc OUTPUT, @xmlData
```
Which seems to work, and work quite efficiently, however here's the weird thing.
If I use the full URL, which returns pure XML data with a mime type of 'text/xml' then response text contains nothing, it's null but if I strip it back to say 'http://server/feed/' or 'http://server/' so that the web server is just passing a 404 page or default html page, then I get the actual page content in.
At first I thought it might be the mime type, 'text/xml' vs 'text/html' but testing that made no difference, anything that returns valid XML seems to give null, but anything that returns broken XML seems to work!!
The code above however does work with correctly formatted XML from the internet, for example 'geonames' (which is what the original source of the above code was based on) works fine.
I suspect, that it's something to do with my feed server's config however, so need to do some work to resolve this, I thought I'd add the code here for others.
@Remus thank's for the suggestion, but that's how I currently do the task, I have a CLR binary that I wrote, that runs once a day to sync the feed to the DB, but it takes too long to sync the data. Using it to feed the XML is faster than doing a pure loop however, but the size of the XML can be quite variable (esp given that a binary would pass it to the stored proc using L2S) and Iv'e already overflowed the input to the SP a couple of times because there's been too much data, hence why I'm looking to get the SP to retrieve the data itself.
@Mr Browstone - SSIS seems to be the way to go, that's what other suggestions have been, I do however admit I don't know an awful lot about using SSIS other than to use the (Import / Export wizard - I'm more of a dev than a DBA :-) ) so any pointers on how I'd achieve this using SSIS would be helpful.
As for using CLR procs in the DB, I had thought of trying that, but Iv'e been bitten badly using these things before (And crashed a couple of servers too!!) so I'm a little wary of using them.
|
2012/08/24
|
['https://dba.stackexchange.com/questions/23089', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/8602/']
|
Use an external process that does the HTTP work and the inserts into the database. I explicitly advise against using SQLCLR for this. Hijacking precious SQL Server [workers](http://msdn.microsoft.com/en-us/library/ms187024%28v=sql.105%29.aspx) for the boring job of waiting for HTTP results will one day impact your server severely.
>
> but the size of the XML can be quite variable (esp given that a binary
> would pass it to the stored proc using L2S) and Iv'e already
> overflowed the input to the SP a couple of times because there's been
> too much data
>
>
>
Use the techniques from [DOWNLOAD AND UPLOAD IMAGES FROM SQL SERVER VIA ASP.NET MVC](http://rusanu.com/2010/12/28/download-and-upload-images-from-sql-server-with-asp-net-mvc/) to stream the HTTP response into the database.
|
There are a few ways to do this. You could use a custom driver and set up a web service as a linked server; you could use a CLR procedure to connect to the web service - or you could use SSIS which has the ability to do this built-in.
If you prefer to do less work then SSIS is the way to go; however if you wanted some fun and you wanted more flexibilty than SSIS can give: CLR is the way to go.
See the answer to the below question for more information on how to do this using CLR:
<https://stackoverflow.com/questions/8332298/connect-to-a-webservice-from-sql>
I hope this helps you.
|
23,089 |
I have a set of XML based services running on my network.
The data in these services needs to be mirrored into a Table on an SQL Server 2008 instance.
Getting the XML into a table is no problem I can already do that, but what I'm having to do at the moment is pass a huge long string of XML to a stored proc which then uses the OPENXML command to insert it into the table.
What I'm wanting to know, is instead of using a 3rd party program to get this data from the service then call the stored proc and insert it, is it in anyway possible for me to get SQL Server to just grab the XML directly from the service URL and process it like that.
All I can seem to find no matter how much I try is plenty of articles & posts on reading / writing files to / from the server file system and the several million or so on actually inserting the XML data, but I can't seem to find anything on getting the server to grab data directly from a URL.
Cheers
-----===== Update 25/8/2012 =====-----
After a little bit more research Iv'e found a third way to do this:
```
declare @xmlObject as int
declare @responseText as varchar(max)
declare @url as varchar(2048)
select @url = 'http://server/feed/data'
exec sp_OACreate 'MSXML2.XMLHTTP', @xmlObject OUT;
exec sp_OAMethod @xmlObject, 'open', NULL, 'get', @url, 'false'
exec sp_OAMethod @xmlObject, 'send'
exec sp_OAMethod @xmlObject, 'responsetext', @responseText OUTPUT
exec sp_OADestroy @xmlObject
select @responseText
exec sp_xml_preparedocument @idoc OUTPUT, @xmlData
```
Which seems to work, and work quite efficiently, however here's the weird thing.
If I use the full URL, which returns pure XML data with a mime type of 'text/xml' then response text contains nothing, it's null but if I strip it back to say 'http://server/feed/' or 'http://server/' so that the web server is just passing a 404 page or default html page, then I get the actual page content in.
At first I thought it might be the mime type, 'text/xml' vs 'text/html' but testing that made no difference, anything that returns valid XML seems to give null, but anything that returns broken XML seems to work!!
The code above however does work with correctly formatted XML from the internet, for example 'geonames' (which is what the original source of the above code was based on) works fine.
I suspect, that it's something to do with my feed server's config however, so need to do some work to resolve this, I thought I'd add the code here for others.
@Remus thank's for the suggestion, but that's how I currently do the task, I have a CLR binary that I wrote, that runs once a day to sync the feed to the DB, but it takes too long to sync the data. Using it to feed the XML is faster than doing a pure loop however, but the size of the XML can be quite variable (esp given that a binary would pass it to the stored proc using L2S) and Iv'e already overflowed the input to the SP a couple of times because there's been too much data, hence why I'm looking to get the SP to retrieve the data itself.
@Mr Browstone - SSIS seems to be the way to go, that's what other suggestions have been, I do however admit I don't know an awful lot about using SSIS other than to use the (Import / Export wizard - I'm more of a dev than a DBA :-) ) so any pointers on how I'd achieve this using SSIS would be helpful.
As for using CLR procs in the DB, I had thought of trying that, but Iv'e been bitten badly using these things before (And crashed a couple of servers too!!) so I'm a little wary of using them.
|
2012/08/24
|
['https://dba.stackexchange.com/questions/23089', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/8602/']
|
I use sp\_OACreate extensively to do the sort of thing you are doing. I suspect that your problem may be that the size of the XML data you are receiving exceeds 8000 characters. (i.e. SQL may not be returning any data when you exceed 8000 characters).
sp\_OAGetProperty and other extended stored procedures cannot pass varchar(MAX) parameters
As a work-around, you can INSERT the results into a table or table variable. In this way, you can successfully receive text (html or xml) of any size with sp\_OACreate.
Example:
```
INSERT INTO @tvResponse (Response)
EXEC @LastResultCode = sp_OAGetProperty @Obj, 'responseText' --, @Response OUT
--Note: sp_OAGetProperty (or any extended stored procedure parameter) does not support
--varchar(MAX), however returning as a resultset will return long results.
```
Also, I have released open source T-SQL code for retrieving and parsing HTML into SQL tables. Part of this is a procedure #sputilGetHTTP that provides a nice wrapper around the sp\_OAxxx procedures: it does error handling, makes it easy to specify various parameters, etc. You can [download](http://sf.net/p/sqldom) from SourceForge. and try accessing your XML results with this routine: you may find that it solves your problem with receiving XML.
(Note that #sputilGetHTTP and the other procedures are all implemented as temporary stored procedures--no changes are made to the database, so it is safe and easy to use this code in a production environment.)
Separately, I also do have a CLR stored procedure that can retrieve HTTP data. I am happy to share this if it is helpful, but the only time I have needed this is when I have to retrieve binary (non-text) data in excess of 8000 characters. When I am working with text I generally use the TSQL routine mentioned above.
|
There are a few ways to do this. You could use a custom driver and set up a web service as a linked server; you could use a CLR procedure to connect to the web service - or you could use SSIS which has the ability to do this built-in.
If you prefer to do less work then SSIS is the way to go; however if you wanted some fun and you wanted more flexibilty than SSIS can give: CLR is the way to go.
See the answer to the below question for more information on how to do this using CLR:
<https://stackoverflow.com/questions/8332298/connect-to-a-webservice-from-sql>
I hope this helps you.
|
23,089 |
I have a set of XML based services running on my network.
The data in these services needs to be mirrored into a Table on an SQL Server 2008 instance.
Getting the XML into a table is no problem I can already do that, but what I'm having to do at the moment is pass a huge long string of XML to a stored proc which then uses the OPENXML command to insert it into the table.
What I'm wanting to know, is instead of using a 3rd party program to get this data from the service then call the stored proc and insert it, is it in anyway possible for me to get SQL Server to just grab the XML directly from the service URL and process it like that.
All I can seem to find no matter how much I try is plenty of articles & posts on reading / writing files to / from the server file system and the several million or so on actually inserting the XML data, but I can't seem to find anything on getting the server to grab data directly from a URL.
Cheers
-----===== Update 25/8/2012 =====-----
After a little bit more research Iv'e found a third way to do this:
```
declare @xmlObject as int
declare @responseText as varchar(max)
declare @url as varchar(2048)
select @url = 'http://server/feed/data'
exec sp_OACreate 'MSXML2.XMLHTTP', @xmlObject OUT;
exec sp_OAMethod @xmlObject, 'open', NULL, 'get', @url, 'false'
exec sp_OAMethod @xmlObject, 'send'
exec sp_OAMethod @xmlObject, 'responsetext', @responseText OUTPUT
exec sp_OADestroy @xmlObject
select @responseText
exec sp_xml_preparedocument @idoc OUTPUT, @xmlData
```
Which seems to work, and work quite efficiently, however here's the weird thing.
If I use the full URL, which returns pure XML data with a mime type of 'text/xml' then response text contains nothing, it's null but if I strip it back to say 'http://server/feed/' or 'http://server/' so that the web server is just passing a 404 page or default html page, then I get the actual page content in.
At first I thought it might be the mime type, 'text/xml' vs 'text/html' but testing that made no difference, anything that returns valid XML seems to give null, but anything that returns broken XML seems to work!!
The code above however does work with correctly formatted XML from the internet, for example 'geonames' (which is what the original source of the above code was based on) works fine.
I suspect, that it's something to do with my feed server's config however, so need to do some work to resolve this, I thought I'd add the code here for others.
@Remus thank's for the suggestion, but that's how I currently do the task, I have a CLR binary that I wrote, that runs once a day to sync the feed to the DB, but it takes too long to sync the data. Using it to feed the XML is faster than doing a pure loop however, but the size of the XML can be quite variable (esp given that a binary would pass it to the stored proc using L2S) and Iv'e already overflowed the input to the SP a couple of times because there's been too much data, hence why I'm looking to get the SP to retrieve the data itself.
@Mr Browstone - SSIS seems to be the way to go, that's what other suggestions have been, I do however admit I don't know an awful lot about using SSIS other than to use the (Import / Export wizard - I'm more of a dev than a DBA :-) ) so any pointers on how I'd achieve this using SSIS would be helpful.
As for using CLR procs in the DB, I had thought of trying that, but Iv'e been bitten badly using these things before (And crashed a couple of servers too!!) so I'm a little wary of using them.
|
2012/08/24
|
['https://dba.stackexchange.com/questions/23089', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/8602/']
|
Use an external process that does the HTTP work and the inserts into the database. I explicitly advise against using SQLCLR for this. Hijacking precious SQL Server [workers](http://msdn.microsoft.com/en-us/library/ms187024%28v=sql.105%29.aspx) for the boring job of waiting for HTTP results will one day impact your server severely.
>
> but the size of the XML can be quite variable (esp given that a binary
> would pass it to the stored proc using L2S) and Iv'e already
> overflowed the input to the SP a couple of times because there's been
> too much data
>
>
>
Use the techniques from [DOWNLOAD AND UPLOAD IMAGES FROM SQL SERVER VIA ASP.NET MVC](http://rusanu.com/2010/12/28/download-and-upload-images-from-sql-server-with-asp-net-mvc/) to stream the HTTP response into the database.
|
Since you're a dev, you should have no trouble with SSIS.
Create a data flow task and use a script component as source. Choose your language of preference (VB.net or C#) for the script component. You can probably reuse most of your CLR code that downloads the file from the web site. Then follow the layout in the following tutorial to assign each node to it's position in the buffer: <http://beyondrelational.com/modules/2/blogs/106/posts/11130/ssis-read-xml-file-in-script-component-as-source.aspx>
From there, it should just be adding a sql or oledb destination and mapping column(s) for the insert.
|
23,089 |
I have a set of XML based services running on my network.
The data in these services needs to be mirrored into a Table on an SQL Server 2008 instance.
Getting the XML into a table is no problem I can already do that, but what I'm having to do at the moment is pass a huge long string of XML to a stored proc which then uses the OPENXML command to insert it into the table.
What I'm wanting to know, is instead of using a 3rd party program to get this data from the service then call the stored proc and insert it, is it in anyway possible for me to get SQL Server to just grab the XML directly from the service URL and process it like that.
All I can seem to find no matter how much I try is plenty of articles & posts on reading / writing files to / from the server file system and the several million or so on actually inserting the XML data, but I can't seem to find anything on getting the server to grab data directly from a URL.
Cheers
-----===== Update 25/8/2012 =====-----
After a little bit more research Iv'e found a third way to do this:
```
declare @xmlObject as int
declare @responseText as varchar(max)
declare @url as varchar(2048)
select @url = 'http://server/feed/data'
exec sp_OACreate 'MSXML2.XMLHTTP', @xmlObject OUT;
exec sp_OAMethod @xmlObject, 'open', NULL, 'get', @url, 'false'
exec sp_OAMethod @xmlObject, 'send'
exec sp_OAMethod @xmlObject, 'responsetext', @responseText OUTPUT
exec sp_OADestroy @xmlObject
select @responseText
exec sp_xml_preparedocument @idoc OUTPUT, @xmlData
```
Which seems to work, and work quite efficiently, however here's the weird thing.
If I use the full URL, which returns pure XML data with a mime type of 'text/xml' then response text contains nothing, it's null but if I strip it back to say 'http://server/feed/' or 'http://server/' so that the web server is just passing a 404 page or default html page, then I get the actual page content in.
At first I thought it might be the mime type, 'text/xml' vs 'text/html' but testing that made no difference, anything that returns valid XML seems to give null, but anything that returns broken XML seems to work!!
The code above however does work with correctly formatted XML from the internet, for example 'geonames' (which is what the original source of the above code was based on) works fine.
I suspect, that it's something to do with my feed server's config however, so need to do some work to resolve this, I thought I'd add the code here for others.
@Remus thank's for the suggestion, but that's how I currently do the task, I have a CLR binary that I wrote, that runs once a day to sync the feed to the DB, but it takes too long to sync the data. Using it to feed the XML is faster than doing a pure loop however, but the size of the XML can be quite variable (esp given that a binary would pass it to the stored proc using L2S) and Iv'e already overflowed the input to the SP a couple of times because there's been too much data, hence why I'm looking to get the SP to retrieve the data itself.
@Mr Browstone - SSIS seems to be the way to go, that's what other suggestions have been, I do however admit I don't know an awful lot about using SSIS other than to use the (Import / Export wizard - I'm more of a dev than a DBA :-) ) so any pointers on how I'd achieve this using SSIS would be helpful.
As for using CLR procs in the DB, I had thought of trying that, but Iv'e been bitten badly using these things before (And crashed a couple of servers too!!) so I'm a little wary of using them.
|
2012/08/24
|
['https://dba.stackexchange.com/questions/23089', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/8602/']
|
Use an external process that does the HTTP work and the inserts into the database. I explicitly advise against using SQLCLR for this. Hijacking precious SQL Server [workers](http://msdn.microsoft.com/en-us/library/ms187024%28v=sql.105%29.aspx) for the boring job of waiting for HTTP results will one day impact your server severely.
>
> but the size of the XML can be quite variable (esp given that a binary
> would pass it to the stored proc using L2S) and Iv'e already
> overflowed the input to the SP a couple of times because there's been
> too much data
>
>
>
Use the techniques from [DOWNLOAD AND UPLOAD IMAGES FROM SQL SERVER VIA ASP.NET MVC](http://rusanu.com/2010/12/28/download-and-upload-images-from-sql-server-with-asp-net-mvc/) to stream the HTTP response into the database.
|
I use sp\_OACreate extensively to do the sort of thing you are doing. I suspect that your problem may be that the size of the XML data you are receiving exceeds 8000 characters. (i.e. SQL may not be returning any data when you exceed 8000 characters).
sp\_OAGetProperty and other extended stored procedures cannot pass varchar(MAX) parameters
As a work-around, you can INSERT the results into a table or table variable. In this way, you can successfully receive text (html or xml) of any size with sp\_OACreate.
Example:
```
INSERT INTO @tvResponse (Response)
EXEC @LastResultCode = sp_OAGetProperty @Obj, 'responseText' --, @Response OUT
--Note: sp_OAGetProperty (or any extended stored procedure parameter) does not support
--varchar(MAX), however returning as a resultset will return long results.
```
Also, I have released open source T-SQL code for retrieving and parsing HTML into SQL tables. Part of this is a procedure #sputilGetHTTP that provides a nice wrapper around the sp\_OAxxx procedures: it does error handling, makes it easy to specify various parameters, etc. You can [download](http://sf.net/p/sqldom) from SourceForge. and try accessing your XML results with this routine: you may find that it solves your problem with receiving XML.
(Note that #sputilGetHTTP and the other procedures are all implemented as temporary stored procedures--no changes are made to the database, so it is safe and easy to use this code in a production environment.)
Separately, I also do have a CLR stored procedure that can retrieve HTTP data. I am happy to share this if it is helpful, but the only time I have needed this is when I have to retrieve binary (non-text) data in excess of 8000 characters. When I am working with text I generally use the TSQL routine mentioned above.
|
23,089 |
I have a set of XML based services running on my network.
The data in these services needs to be mirrored into a Table on an SQL Server 2008 instance.
Getting the XML into a table is no problem I can already do that, but what I'm having to do at the moment is pass a huge long string of XML to a stored proc which then uses the OPENXML command to insert it into the table.
What I'm wanting to know, is instead of using a 3rd party program to get this data from the service then call the stored proc and insert it, is it in anyway possible for me to get SQL Server to just grab the XML directly from the service URL and process it like that.
All I can seem to find no matter how much I try is plenty of articles & posts on reading / writing files to / from the server file system and the several million or so on actually inserting the XML data, but I can't seem to find anything on getting the server to grab data directly from a URL.
Cheers
-----===== Update 25/8/2012 =====-----
After a little bit more research Iv'e found a third way to do this:
```
declare @xmlObject as int
declare @responseText as varchar(max)
declare @url as varchar(2048)
select @url = 'http://server/feed/data'
exec sp_OACreate 'MSXML2.XMLHTTP', @xmlObject OUT;
exec sp_OAMethod @xmlObject, 'open', NULL, 'get', @url, 'false'
exec sp_OAMethod @xmlObject, 'send'
exec sp_OAMethod @xmlObject, 'responsetext', @responseText OUTPUT
exec sp_OADestroy @xmlObject
select @responseText
exec sp_xml_preparedocument @idoc OUTPUT, @xmlData
```
Which seems to work, and work quite efficiently, however here's the weird thing.
If I use the full URL, which returns pure XML data with a mime type of 'text/xml' then response text contains nothing, it's null but if I strip it back to say 'http://server/feed/' or 'http://server/' so that the web server is just passing a 404 page or default html page, then I get the actual page content in.
At first I thought it might be the mime type, 'text/xml' vs 'text/html' but testing that made no difference, anything that returns valid XML seems to give null, but anything that returns broken XML seems to work!!
The code above however does work with correctly formatted XML from the internet, for example 'geonames' (which is what the original source of the above code was based on) works fine.
I suspect, that it's something to do with my feed server's config however, so need to do some work to resolve this, I thought I'd add the code here for others.
@Remus thank's for the suggestion, but that's how I currently do the task, I have a CLR binary that I wrote, that runs once a day to sync the feed to the DB, but it takes too long to sync the data. Using it to feed the XML is faster than doing a pure loop however, but the size of the XML can be quite variable (esp given that a binary would pass it to the stored proc using L2S) and Iv'e already overflowed the input to the SP a couple of times because there's been too much data, hence why I'm looking to get the SP to retrieve the data itself.
@Mr Browstone - SSIS seems to be the way to go, that's what other suggestions have been, I do however admit I don't know an awful lot about using SSIS other than to use the (Import / Export wizard - I'm more of a dev than a DBA :-) ) so any pointers on how I'd achieve this using SSIS would be helpful.
As for using CLR procs in the DB, I had thought of trying that, but Iv'e been bitten badly using these things before (And crashed a couple of servers too!!) so I'm a little wary of using them.
|
2012/08/24
|
['https://dba.stackexchange.com/questions/23089', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/8602/']
|
I use sp\_OACreate extensively to do the sort of thing you are doing. I suspect that your problem may be that the size of the XML data you are receiving exceeds 8000 characters. (i.e. SQL may not be returning any data when you exceed 8000 characters).
sp\_OAGetProperty and other extended stored procedures cannot pass varchar(MAX) parameters
As a work-around, you can INSERT the results into a table or table variable. In this way, you can successfully receive text (html or xml) of any size with sp\_OACreate.
Example:
```
INSERT INTO @tvResponse (Response)
EXEC @LastResultCode = sp_OAGetProperty @Obj, 'responseText' --, @Response OUT
--Note: sp_OAGetProperty (or any extended stored procedure parameter) does not support
--varchar(MAX), however returning as a resultset will return long results.
```
Also, I have released open source T-SQL code for retrieving and parsing HTML into SQL tables. Part of this is a procedure #sputilGetHTTP that provides a nice wrapper around the sp\_OAxxx procedures: it does error handling, makes it easy to specify various parameters, etc. You can [download](http://sf.net/p/sqldom) from SourceForge. and try accessing your XML results with this routine: you may find that it solves your problem with receiving XML.
(Note that #sputilGetHTTP and the other procedures are all implemented as temporary stored procedures--no changes are made to the database, so it is safe and easy to use this code in a production environment.)
Separately, I also do have a CLR stored procedure that can retrieve HTTP data. I am happy to share this if it is helpful, but the only time I have needed this is when I have to retrieve binary (non-text) data in excess of 8000 characters. When I am working with text I generally use the TSQL routine mentioned above.
|
Since you're a dev, you should have no trouble with SSIS.
Create a data flow task and use a script component as source. Choose your language of preference (VB.net or C#) for the script component. You can probably reuse most of your CLR code that downloads the file from the web site. Then follow the layout in the following tutorial to assign each node to it's position in the buffer: <http://beyondrelational.com/modules/2/blogs/106/posts/11130/ssis-read-xml-file-in-script-component-as-source.aspx>
From there, it should just be adding a sql or oledb destination and mapping column(s) for the insert.
|
53,437,470 |
I have 3 UIStackViews laid as follows edge to edge:
```
SV1 ---- SV2 ---- SV3
```
SV1 sits at a fixed distance of 5 points to superview leading, SV2 center is aligned with center of superview, and SV3 is at a fixed distance of 5 points to views trailing. Problem is on iPhone SE, SV2 is too wide and too close to SV1 and SV3. How do I set autolayout constraints so that SV2 is at a minimum distance D to SV1 and SV3?
|
2018/11/22
|
['https://Stackoverflow.com/questions/53437470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/917521/']
|
Setting max unavailable to 0 is a way to go and also, using nodepools can be a good workaround.
```
gcloud container node-pools create <nodepool> --node-taints=app=dask-scheduler:NoSchedule
gcloud container node-pools create <nodepool> --node-labels app=dask-scheduler
```
This will create the nodepool with the label app=dask-scheduler, after in the pod spec, you can do this:
```
nodeSelector:
app: dask-scheduler
```
And put the dask scheduler on a node-pool that doesn't autoscale.
There's an object called PDB where in its spec you can set maxUnavailable
in the example of maxUnavailable=1, this means if you had 100 pods defined, always make sure there is only one removed/drained/re-scheduled at a time
in the case of maxUnavailable, if you have 2 pods, and you set maxUnavailable to 0, it will never remove your pods. It being the scheduler
```
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
name: zk-pdb
spec:
maxUnavailable: 1
selector:
matchLabels:
app: zookeeper
```
|
Are you specifying resource requests and limits?
|
1,623,321 |
I am trying to expand $\sqrt{x(1-x)}$ in order to find the order of it as $x\to0$.
Using Taylor expansion to find the derivative of the equation as $x\to0$ gives each item $0$.
Then how do we expand it? Thanks,
|
2016/01/23
|
['https://math.stackexchange.com/questions/1623321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206901/']
|
In general
$$\lim\_{x \to 0} (1+x)^{\alpha} = 1 + \binom{\alpha}{1} x + \binom{\alpha}{2} x^2 + \binom{\alpha}{3} x^3 + \ldots = \sum\_{i = 0}^{n} \binom{\alpha}{i} x^{i} + O(x^n)$$
thus as $x \to 0$
\begin{align}
\sqrt{x(1+x)}&=\sqrt{x} \cdot \sqrt{1+x} \\
&=x^{1/2} \cdot (1+x)^{1/2}\\
&=x^{1/2} \cdot \left( \sum\_{i = 0}^{n} \binom{\frac{1}{2}}{i} x^{i} + O(x^n) \right) \\
&=x^{1/2} \cdot \left( 1 + \frac{x}{2} - \frac{x^2}{8} + \ldots \right)
\end{align}
so, as $x \to 0$
\begin{align}
\sqrt{x(1-x)}&=\sqrt{x} \cdot \sqrt{1-x} \\
&=x^{1/2} \cdot (1-x)^{1/2}\\
&=x^{1/2} \cdot \left( \sum\_{i = 0}^{n} \binom{\frac{1}{2}}{i} (-x)^{i} + O(x^n) \right) \\
&=x^{1/2} \cdot \left( 1 - \frac{x}{2} + \frac{x^2}{8} + \ldots \right)
\end{align}
|
As Aditya Agarwal said:
$\sqrt{x(1+x)}=x^{1/2}(1-x/2+...)$
|
1,623,321 |
I am trying to expand $\sqrt{x(1-x)}$ in order to find the order of it as $x\to0$.
Using Taylor expansion to find the derivative of the equation as $x\to0$ gives each item $0$.
Then how do we expand it? Thanks,
|
2016/01/23
|
['https://math.stackexchange.com/questions/1623321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206901/']
|
my answer:
$\sqrt{x(1-x)}$
$=x^{1/2}(1-x)^{1/2}$
expand for $x\to 0$,
$=x^{1/2}(1+\frac 12(-x)+\frac{\frac12(1-\frac{1}{2})}{2!}(-x)^2+...........)$
$=x^{1/2}-\frac 12x^{3/2}-\frac{1}{8}x^{5/2}+...........$
|
As Aditya Agarwal said:
$\sqrt{x(1+x)}=x^{1/2}(1-x/2+...)$
|
1,623,321 |
I am trying to expand $\sqrt{x(1-x)}$ in order to find the order of it as $x\to0$.
Using Taylor expansion to find the derivative of the equation as $x\to0$ gives each item $0$.
Then how do we expand it? Thanks,
|
2016/01/23
|
['https://math.stackexchange.com/questions/1623321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206901/']
|
Find the derivatives of $$f(x)=\sqrt{1-x}$$
$$=\sqrt{1-0}+\frac{\frac{d}{dx}\left(\sqrt{1-x}\right)\left(0\right)}{1!}x+\frac{\frac{d^2}{dx^2}\left(\sqrt{1-x}\right)\left(0\right)}{2!}x^2+\frac{\frac{d^3}{dx^3}\left(\sqrt{1-x}\right)\left(0\right)}{3!}x^3+\ldots \:$$
Then
$\sqrt{1-0}\quad :\quad 1$
$\frac{d}{dx}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{1}{2}$
$\frac{d^2}{dx^2}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{1}{4}$
$\frac{d^3}{dx^3}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{3}{8}$
$\frac{d^4}{dx^4}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{15}{16}$
So
$$=1+\frac{-\frac{1}{2}}{1!}x+\frac{-\frac{1}{4}}{2!}x^2+\frac{-\frac{3}{8}}{3!}x^3+\frac{-\frac{15}{16}}{4!}x^4+\ldots $$
|
As Aditya Agarwal said:
$\sqrt{x(1+x)}=x^{1/2}(1-x/2+...)$
|
1,623,321 |
I am trying to expand $\sqrt{x(1-x)}$ in order to find the order of it as $x\to0$.
Using Taylor expansion to find the derivative of the equation as $x\to0$ gives each item $0$.
Then how do we expand it? Thanks,
|
2016/01/23
|
['https://math.stackexchange.com/questions/1623321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206901/']
|
In general
$$\lim\_{x \to 0} (1+x)^{\alpha} = 1 + \binom{\alpha}{1} x + \binom{\alpha}{2} x^2 + \binom{\alpha}{3} x^3 + \ldots = \sum\_{i = 0}^{n} \binom{\alpha}{i} x^{i} + O(x^n)$$
thus as $x \to 0$
\begin{align}
\sqrt{x(1+x)}&=\sqrt{x} \cdot \sqrt{1+x} \\
&=x^{1/2} \cdot (1+x)^{1/2}\\
&=x^{1/2} \cdot \left( \sum\_{i = 0}^{n} \binom{\frac{1}{2}}{i} x^{i} + O(x^n) \right) \\
&=x^{1/2} \cdot \left( 1 + \frac{x}{2} - \frac{x^2}{8} + \ldots \right)
\end{align}
so, as $x \to 0$
\begin{align}
\sqrt{x(1-x)}&=\sqrt{x} \cdot \sqrt{1-x} \\
&=x^{1/2} \cdot (1-x)^{1/2}\\
&=x^{1/2} \cdot \left( \sum\_{i = 0}^{n} \binom{\frac{1}{2}}{i} (-x)^{i} + O(x^n) \right) \\
&=x^{1/2} \cdot \left( 1 - \frac{x}{2} + \frac{x^2}{8} + \ldots \right)
\end{align}
|
my answer:
$\sqrt{x(1-x)}$
$=x^{1/2}(1-x)^{1/2}$
expand for $x\to 0$,
$=x^{1/2}(1+\frac 12(-x)+\frac{\frac12(1-\frac{1}{2})}{2!}(-x)^2+...........)$
$=x^{1/2}-\frac 12x^{3/2}-\frac{1}{8}x^{5/2}+...........$
|
1,623,321 |
I am trying to expand $\sqrt{x(1-x)}$ in order to find the order of it as $x\to0$.
Using Taylor expansion to find the derivative of the equation as $x\to0$ gives each item $0$.
Then how do we expand it? Thanks,
|
2016/01/23
|
['https://math.stackexchange.com/questions/1623321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206901/']
|
In general
$$\lim\_{x \to 0} (1+x)^{\alpha} = 1 + \binom{\alpha}{1} x + \binom{\alpha}{2} x^2 + \binom{\alpha}{3} x^3 + \ldots = \sum\_{i = 0}^{n} \binom{\alpha}{i} x^{i} + O(x^n)$$
thus as $x \to 0$
\begin{align}
\sqrt{x(1+x)}&=\sqrt{x} \cdot \sqrt{1+x} \\
&=x^{1/2} \cdot (1+x)^{1/2}\\
&=x^{1/2} \cdot \left( \sum\_{i = 0}^{n} \binom{\frac{1}{2}}{i} x^{i} + O(x^n) \right) \\
&=x^{1/2} \cdot \left( 1 + \frac{x}{2} - \frac{x^2}{8} + \ldots \right)
\end{align}
so, as $x \to 0$
\begin{align}
\sqrt{x(1-x)}&=\sqrt{x} \cdot \sqrt{1-x} \\
&=x^{1/2} \cdot (1-x)^{1/2}\\
&=x^{1/2} \cdot \left( \sum\_{i = 0}^{n} \binom{\frac{1}{2}}{i} (-x)^{i} + O(x^n) \right) \\
&=x^{1/2} \cdot \left( 1 - \frac{x}{2} + \frac{x^2}{8} + \ldots \right)
\end{align}
|
Find the derivatives of $$f(x)=\sqrt{1-x}$$
$$=\sqrt{1-0}+\frac{\frac{d}{dx}\left(\sqrt{1-x}\right)\left(0\right)}{1!}x+\frac{\frac{d^2}{dx^2}\left(\sqrt{1-x}\right)\left(0\right)}{2!}x^2+\frac{\frac{d^3}{dx^3}\left(\sqrt{1-x}\right)\left(0\right)}{3!}x^3+\ldots \:$$
Then
$\sqrt{1-0}\quad :\quad 1$
$\frac{d}{dx}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{1}{2}$
$\frac{d^2}{dx^2}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{1}{4}$
$\frac{d^3}{dx^3}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{3}{8}$
$\frac{d^4}{dx^4}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{15}{16}$
So
$$=1+\frac{-\frac{1}{2}}{1!}x+\frac{-\frac{1}{4}}{2!}x^2+\frac{-\frac{3}{8}}{3!}x^3+\frac{-\frac{15}{16}}{4!}x^4+\ldots $$
|
1,623,321 |
I am trying to expand $\sqrt{x(1-x)}$ in order to find the order of it as $x\to0$.
Using Taylor expansion to find the derivative of the equation as $x\to0$ gives each item $0$.
Then how do we expand it? Thanks,
|
2016/01/23
|
['https://math.stackexchange.com/questions/1623321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/206901/']
|
my answer:
$\sqrt{x(1-x)}$
$=x^{1/2}(1-x)^{1/2}$
expand for $x\to 0$,
$=x^{1/2}(1+\frac 12(-x)+\frac{\frac12(1-\frac{1}{2})}{2!}(-x)^2+...........)$
$=x^{1/2}-\frac 12x^{3/2}-\frac{1}{8}x^{5/2}+...........$
|
Find the derivatives of $$f(x)=\sqrt{1-x}$$
$$=\sqrt{1-0}+\frac{\frac{d}{dx}\left(\sqrt{1-x}\right)\left(0\right)}{1!}x+\frac{\frac{d^2}{dx^2}\left(\sqrt{1-x}\right)\left(0\right)}{2!}x^2+\frac{\frac{d^3}{dx^3}\left(\sqrt{1-x}\right)\left(0\right)}{3!}x^3+\ldots \:$$
Then
$\sqrt{1-0}\quad :\quad 1$
$\frac{d}{dx}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{1}{2}$
$\frac{d^2}{dx^2}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{1}{4}$
$\frac{d^3}{dx^3}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{3}{8}$
$\frac{d^4}{dx^4}\left(\sqrt{1-x}\right)\left(0\right)\quad :\quad -\frac{15}{16}$
So
$$=1+\frac{-\frac{1}{2}}{1!}x+\frac{-\frac{1}{4}}{2!}x^2+\frac{-\frac{3}{8}}{3!}x^3+\frac{-\frac{15}{16}}{4!}x^4+\ldots $$
|
24,642,453 |
I'm trying to get Google Places Autocomplete API working on WorkLight, but it looks like there is something wrong.
When using my computer's browser, once I start typing the name of a place, the Autocomplete suggestions works fine and I am able to pick one. But when running the app on a mobile device (either Android or iPhone), I am able to see the autocomplete results, but nothing happens when I tap them.
I found some js libraries that makes it easier to get GooglePlaces Autocomplete API working - I mean, except on mobile devices (WorkLight / Cordova App)
I Also found some people reporting that problem with cordova. Some were able to fix the problem by adding a "needclick" class to google's element, but that didn't work for me
Here is a JS Library for testing:
<http://ubilabs.github.io/geocomplete/>
StackOverflow link with related issue:
[can't tap on item in google autocomplete list on mobile](https://stackoverflow.com/questions/9972080/cant-tap-on-item-in-google-autocomplete-list-on-mobile)
Does anyone have any idea for a possible solution?
|
2014/07/08
|
['https://Stackoverflow.com/questions/24642453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1117919/']
|
I just tried it and it worked fine for me. This is what I did, let us know if you did anything different
1. Created a new Hybrid app
2. Added jquery.geocomplete.js to common/js folder
3. Updated the index.html code with the code sample provided by the api
documentation
4. Tested on common preview (works fine)
5. Created an android environment and executed it on a Nexus 7 device(android 4.4.2) -
Worked fine.
With "worked fine" I mean that I can see the list of options provided while I type in the text field and I can tap one of the options and it will fill the text field.
This is the code for index.html
```
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>googleplaces</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<style type="text/css" media="screen">
form {
background: url(https://developers.google.com/maps/documentation/places/images/powered-by-google-on-white.png) no-repeat center right;
}
</style>
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<form>
<input id="geocomplete" type="text" placeholder="Type in an address" size="90" />
<input id="find" type="button" value="find" />
</form>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/jquery.geocomplete.js"></script>
<script>
$(function(){
$("#geocomplete").geocomplete()
.bind("geocode:result", function(event, result){
$.log("Result: " + result.formatted_address);
})
.bind("geocode:error", function(event, status){
$.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
$.log("Multiple: " + results.length + " results found");
});
$("#find").click(function(){
$("#geocomplete").trigger("geocode");
});
});
</script>
</body>
</html>
```
|
Have you tried to stop propagating the click event?
>
> $( "p" ).click(function( event ) { event.stopPropagation(); // Do
> something });
>
>
>
|
24,642,453 |
I'm trying to get Google Places Autocomplete API working on WorkLight, but it looks like there is something wrong.
When using my computer's browser, once I start typing the name of a place, the Autocomplete suggestions works fine and I am able to pick one. But when running the app on a mobile device (either Android or iPhone), I am able to see the autocomplete results, but nothing happens when I tap them.
I found some js libraries that makes it easier to get GooglePlaces Autocomplete API working - I mean, except on mobile devices (WorkLight / Cordova App)
I Also found some people reporting that problem with cordova. Some were able to fix the problem by adding a "needclick" class to google's element, but that didn't work for me
Here is a JS Library for testing:
<http://ubilabs.github.io/geocomplete/>
StackOverflow link with related issue:
[can't tap on item in google autocomplete list on mobile](https://stackoverflow.com/questions/9972080/cant-tap-on-item-in-google-autocomplete-list-on-mobile)
Does anyone have any idea for a possible solution?
|
2014/07/08
|
['https://Stackoverflow.com/questions/24642453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1117919/']
|
I just tried it and it worked fine for me. This is what I did, let us know if you did anything different
1. Created a new Hybrid app
2. Added jquery.geocomplete.js to common/js folder
3. Updated the index.html code with the code sample provided by the api
documentation
4. Tested on common preview (works fine)
5. Created an android environment and executed it on a Nexus 7 device(android 4.4.2) -
Worked fine.
With "worked fine" I mean that I can see the list of options provided while I type in the text field and I can tap one of the options and it will fill the text field.
This is the code for index.html
```
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>googleplaces</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<style type="text/css" media="screen">
form {
background: url(https://developers.google.com/maps/documentation/places/images/powered-by-google-on-white.png) no-repeat center right;
}
</style>
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<form>
<input id="geocomplete" type="text" placeholder="Type in an address" size="90" />
<input id="find" type="button" value="find" />
</form>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/jquery.geocomplete.js"></script>
<script>
$(function(){
$("#geocomplete").geocomplete()
.bind("geocode:result", function(event, result){
$.log("Result: " + result.formatted_address);
})
.bind("geocode:error", function(event, status){
$.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
$.log("Multiple: " + results.length + " results found");
});
$("#find").click(function(){
$("#geocomplete").trigger("geocode");
});
});
</script>
</body>
</html>
```
|
Try Stopping propagation
```
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.stopImmediatePropagation demo</title>
<style>
p {
height: 30px;
width: 150px;
background-color: #ccf;
}
div {
height: 30px;
width: 150px;
background-color: #cfc;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>paragraph</p>
<div>division</div>
<script>
$( "p" ).click(function( event ) {
event.stopImmediatePropagation();
});
$( "p" ).click(function( event ) {
// This function won't be executed
$( this ).css( "background-color", "#f00" );
});
$( "div" ).click(function( event ) {
// This function will be executed
$( this ).css( "background-color", "#f00" );
});
</script>
</body>
</html>
```
|
24,642,453 |
I'm trying to get Google Places Autocomplete API working on WorkLight, but it looks like there is something wrong.
When using my computer's browser, once I start typing the name of a place, the Autocomplete suggestions works fine and I am able to pick one. But when running the app on a mobile device (either Android or iPhone), I am able to see the autocomplete results, but nothing happens when I tap them.
I found some js libraries that makes it easier to get GooglePlaces Autocomplete API working - I mean, except on mobile devices (WorkLight / Cordova App)
I Also found some people reporting that problem with cordova. Some were able to fix the problem by adding a "needclick" class to google's element, but that didn't work for me
Here is a JS Library for testing:
<http://ubilabs.github.io/geocomplete/>
StackOverflow link with related issue:
[can't tap on item in google autocomplete list on mobile](https://stackoverflow.com/questions/9972080/cant-tap-on-item-in-google-autocomplete-list-on-mobile)
Does anyone have any idea for a possible solution?
|
2014/07/08
|
['https://Stackoverflow.com/questions/24642453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1117919/']
|
I just tried it and it worked fine for me. This is what I did, let us know if you did anything different
1. Created a new Hybrid app
2. Added jquery.geocomplete.js to common/js folder
3. Updated the index.html code with the code sample provided by the api
documentation
4. Tested on common preview (works fine)
5. Created an android environment and executed it on a Nexus 7 device(android 4.4.2) -
Worked fine.
With "worked fine" I mean that I can see the list of options provided while I type in the text field and I can tap one of the options and it will fill the text field.
This is the code for index.html
```
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>googleplaces</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<style type="text/css" media="screen">
form {
background: url(https://developers.google.com/maps/documentation/places/images/powered-by-google-on-white.png) no-repeat center right;
}
</style>
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<form>
<input id="geocomplete" type="text" placeholder="Type in an address" size="90" />
<input id="find" type="button" value="find" />
</form>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/jquery.geocomplete.js"></script>
<script>
$(function(){
$("#geocomplete").geocomplete()
.bind("geocode:result", function(event, result){
$.log("Result: " + result.formatted_address);
})
.bind("geocode:error", function(event, status){
$.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
$.log("Multiple: " + results.length + " results found");
});
$("#find").click(function(){
$("#geocomplete").trigger("geocode");
});
});
</script>
</body>
</html>
```
|
If you use Ionic, the issue is caused by the css attribute "pointer-events:none" set by ionicModal;
Try to add this to you css file:
```
.pac-container {
pointer-events:auto;
}
```
|
13,212,654 |
So, my data are stored in a file, called log.txt, and I want to view the content of it, in GUI. So i've got these two classes which i'm using, one is Engine, where I read the log.txt file, and the other one is GUI, where is used to apply the methods used in Engine.
So, in my engine, I've got these codes:
```
public void loadLog()
{
try
{
java.io.File cpFile = new java.io.File( "log.txt" );
if ( cpFile.exists() == true )
{
File file = cpFile;
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String strLine="";
String logPrint="";
fis = new FileInputStream ( file );
// Here is BufferedInputStream added for fast reading
bis = new BufferedInputStream ( fis );
dis = new DataInputStream ( bis );
// New Buffer Reader
BufferedReader br = new BufferedReader( new InputStreamReader( fis ) );
while ( ( strLine = br.readLine() ) != null )
{
StringTokenizer st = new StringTokenizer ( strLine, ";" );
while ( st.hasMoreTokens() )
{
logPrint = st.nextToken();
System.out.println(logPrint);
}
log = new Log();
//regis.addLog( log );
}
}
}
catch ( Exception e ){
}
}
```
and then, in my GUI, I'd try to apply the codes used in my engine:
```
// create exit menu
Logout = new JMenu("Exit");
// create JMenuItem for about menu
reportItem = new JMenuItem ( "Report" );
// add about menu to menuBar
menuBar.add ( Logout );
menuBar.setBorder ( new BevelBorder(BevelBorder.RAISED) );
Logout.add ( reportItem );
/* --------------------------------- ACTION LISTENER FOR ABOUT MENU ------------------------------------------ */
reportItem.addActionListener ( new ActionListener()
{
public void actionPerformed ( ActionEvent e )
{
engine.loadLog();
mainPanel.setVisible (false);
mainPanel = home();
toolBar.setVisible(false);
vasToolBar.setVisible(false);
cpToolBar.setVisible(false);
add ( mainPanel, BorderLayout.CENTER );
add ( toolBar, BorderLayout.NORTH );
toolBar.setVisible(false);
mainPanel.setVisible ( true );
pack();
setSize(500, 500);
}
});
```
NOW,
my question is, how can I print out whatever is read in my Engine's method, inside the GUI part? I want them to be either inside a JLabel or JTextArea. How am I supposed to do that?
|
2012/11/03
|
['https://Stackoverflow.com/questions/13212654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1748691/']
|
Perhaps you want your loadLog method to *return* a String that holds the text that it read from the file, and then in the GUI call the method and display the returned String as you desire. Also, never have an empty catch block when doing I & O.
|
Forgive me if I am misunderstanding your question, but here goes nothing:
You're going to want to read your text file line by line, and add each line to the JTextArea.
```
BufferedReader reader = new BufferedReader(new FileReader("pathToFile")); //This code creates a new buffered reader with the specified file input. Replace pathToFile with the path to your text file.
String text = reader.readLine();
while(text != null) {
myTextArea.append("\n" + text); //Replace myTextArea with your JTextArea
text = reader.readLine();
}
```
|
13,212,654 |
So, my data are stored in a file, called log.txt, and I want to view the content of it, in GUI. So i've got these two classes which i'm using, one is Engine, where I read the log.txt file, and the other one is GUI, where is used to apply the methods used in Engine.
So, in my engine, I've got these codes:
```
public void loadLog()
{
try
{
java.io.File cpFile = new java.io.File( "log.txt" );
if ( cpFile.exists() == true )
{
File file = cpFile;
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String strLine="";
String logPrint="";
fis = new FileInputStream ( file );
// Here is BufferedInputStream added for fast reading
bis = new BufferedInputStream ( fis );
dis = new DataInputStream ( bis );
// New Buffer Reader
BufferedReader br = new BufferedReader( new InputStreamReader( fis ) );
while ( ( strLine = br.readLine() ) != null )
{
StringTokenizer st = new StringTokenizer ( strLine, ";" );
while ( st.hasMoreTokens() )
{
logPrint = st.nextToken();
System.out.println(logPrint);
}
log = new Log();
//regis.addLog( log );
}
}
}
catch ( Exception e ){
}
}
```
and then, in my GUI, I'd try to apply the codes used in my engine:
```
// create exit menu
Logout = new JMenu("Exit");
// create JMenuItem for about menu
reportItem = new JMenuItem ( "Report" );
// add about menu to menuBar
menuBar.add ( Logout );
menuBar.setBorder ( new BevelBorder(BevelBorder.RAISED) );
Logout.add ( reportItem );
/* --------------------------------- ACTION LISTENER FOR ABOUT MENU ------------------------------------------ */
reportItem.addActionListener ( new ActionListener()
{
public void actionPerformed ( ActionEvent e )
{
engine.loadLog();
mainPanel.setVisible (false);
mainPanel = home();
toolBar.setVisible(false);
vasToolBar.setVisible(false);
cpToolBar.setVisible(false);
add ( mainPanel, BorderLayout.CENTER );
add ( toolBar, BorderLayout.NORTH );
toolBar.setVisible(false);
mainPanel.setVisible ( true );
pack();
setSize(500, 500);
}
});
```
NOW,
my question is, how can I print out whatever is read in my Engine's method, inside the GUI part? I want them to be either inside a JLabel or JTextArea. How am I supposed to do that?
|
2012/11/03
|
['https://Stackoverflow.com/questions/13212654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1748691/']
|
File IO operations are considered blocking/time consuming.
You should avoid running them in the Event Dispatching Thread, as this will prevent the UI from begin updated, making your application look like its hung/crashed
You could use a [`SwingWorker`](http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html) to perform the file loading part, passing each line to the `publish` method and adding the lines to the text area via the `process` method...
```
public class FileReaderWorker extends SwingWorker<List<String>, String> {
private final File inFile;
private final JTextArea output;
public FileReaderWorker(File file, JTextArea output) {
inFile = file;
this.output = output;
}
public File getInFile() {
return inFile;
}
public JTextArea getOutput() {
return output;
}
@Override
protected void process(List<String> chunks) {
for (String line : chunks) {
output.append(line);
}
}
@Override
protected List<String> doInBackground() throws Exception {
List<String> lines = new ArrayList<String>(25);
java.io.File cpFile = getInFile();
if (cpFile != null && cpFile.exists() == true) {
File file = cpFile;
BufferedReader br = null;
String strLine = "";
String logPrint = "";
try {
// New Buffer Reader
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((strLine = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(strLine, ";");
while (st.hasMoreTokens()) {
logPrint = st.nextToken();
publish(logPrint);
}
}
} catch (Exception e) {
publish("Failed read in file: " + e);
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception e) {
}
}
} else {
publish("Input file does not exist/hasn't not begin specified");
}
return lines;
}
}
```
Take a look at [Lesson: Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information
|
Perhaps you want your loadLog method to *return* a String that holds the text that it read from the file, and then in the GUI call the method and display the returned String as you desire. Also, never have an empty catch block when doing I & O.
|
13,212,654 |
So, my data are stored in a file, called log.txt, and I want to view the content of it, in GUI. So i've got these two classes which i'm using, one is Engine, where I read the log.txt file, and the other one is GUI, where is used to apply the methods used in Engine.
So, in my engine, I've got these codes:
```
public void loadLog()
{
try
{
java.io.File cpFile = new java.io.File( "log.txt" );
if ( cpFile.exists() == true )
{
File file = cpFile;
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String strLine="";
String logPrint="";
fis = new FileInputStream ( file );
// Here is BufferedInputStream added for fast reading
bis = new BufferedInputStream ( fis );
dis = new DataInputStream ( bis );
// New Buffer Reader
BufferedReader br = new BufferedReader( new InputStreamReader( fis ) );
while ( ( strLine = br.readLine() ) != null )
{
StringTokenizer st = new StringTokenizer ( strLine, ";" );
while ( st.hasMoreTokens() )
{
logPrint = st.nextToken();
System.out.println(logPrint);
}
log = new Log();
//regis.addLog( log );
}
}
}
catch ( Exception e ){
}
}
```
and then, in my GUI, I'd try to apply the codes used in my engine:
```
// create exit menu
Logout = new JMenu("Exit");
// create JMenuItem for about menu
reportItem = new JMenuItem ( "Report" );
// add about menu to menuBar
menuBar.add ( Logout );
menuBar.setBorder ( new BevelBorder(BevelBorder.RAISED) );
Logout.add ( reportItem );
/* --------------------------------- ACTION LISTENER FOR ABOUT MENU ------------------------------------------ */
reportItem.addActionListener ( new ActionListener()
{
public void actionPerformed ( ActionEvent e )
{
engine.loadLog();
mainPanel.setVisible (false);
mainPanel = home();
toolBar.setVisible(false);
vasToolBar.setVisible(false);
cpToolBar.setVisible(false);
add ( mainPanel, BorderLayout.CENTER );
add ( toolBar, BorderLayout.NORTH );
toolBar.setVisible(false);
mainPanel.setVisible ( true );
pack();
setSize(500, 500);
}
});
```
NOW,
my question is, how can I print out whatever is read in my Engine's method, inside the GUI part? I want them to be either inside a JLabel or JTextArea. How am I supposed to do that?
|
2012/11/03
|
['https://Stackoverflow.com/questions/13212654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1748691/']
|
File IO operations are considered blocking/time consuming.
You should avoid running them in the Event Dispatching Thread, as this will prevent the UI from begin updated, making your application look like its hung/crashed
You could use a [`SwingWorker`](http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html) to perform the file loading part, passing each line to the `publish` method and adding the lines to the text area via the `process` method...
```
public class FileReaderWorker extends SwingWorker<List<String>, String> {
private final File inFile;
private final JTextArea output;
public FileReaderWorker(File file, JTextArea output) {
inFile = file;
this.output = output;
}
public File getInFile() {
return inFile;
}
public JTextArea getOutput() {
return output;
}
@Override
protected void process(List<String> chunks) {
for (String line : chunks) {
output.append(line);
}
}
@Override
protected List<String> doInBackground() throws Exception {
List<String> lines = new ArrayList<String>(25);
java.io.File cpFile = getInFile();
if (cpFile != null && cpFile.exists() == true) {
File file = cpFile;
BufferedReader br = null;
String strLine = "";
String logPrint = "";
try {
// New Buffer Reader
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((strLine = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(strLine, ";");
while (st.hasMoreTokens()) {
logPrint = st.nextToken();
publish(logPrint);
}
}
} catch (Exception e) {
publish("Failed read in file: " + e);
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception e) {
}
}
} else {
publish("Input file does not exist/hasn't not begin specified");
}
return lines;
}
}
```
Take a look at [Lesson: Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information
|
Forgive me if I am misunderstanding your question, but here goes nothing:
You're going to want to read your text file line by line, and add each line to the JTextArea.
```
BufferedReader reader = new BufferedReader(new FileReader("pathToFile")); //This code creates a new buffered reader with the specified file input. Replace pathToFile with the path to your text file.
String text = reader.readLine();
while(text != null) {
myTextArea.append("\n" + text); //Replace myTextArea with your JTextArea
text = reader.readLine();
}
```
|
355,820 |
Maybe related to [this question](https://math.stackexchange.com/questions/36308/expected-value-of-max-min-of-random-variables)
In the comments of this question they say that it gets easier if the variables are identically and independently distributed.
But i don't see how because in my case the variable is discrete
**Here is my problem :**
I toss 4 dice and keep the 3 best results. What is the expected value of the result ?
I think tossing 4 dice and keep the 3 best is like tossing 4 dice and removing the minimum.
* Let X be the result of a standard die.
* Let Y be tossing 4 dice and keeping the 3 best
Is that correct : $E(Y) = 4\*E(X) - E(min)$ ?
So how calculate E(min) ?
I know if the variable was uniform on [0,1] I could have started with $F\_Y = 1 - ( 1-F\_X )^p$ where p is the number of dice I toss, but here the variable is discrete so i don't know where to start.
**Generalization :**
How to calculate the expected value of k realizations of a discrete random variable in [0-n]?
It's been a while since i studied probability, so my basic calculation may be wrong. Also,
English is not my mother tongue, so please forgive my mistakes.
edit : spelling mistakes
|
2013/04/09
|
['https://math.stackexchange.com/questions/355820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71720/']
|
For clarity, suppose that the dice have ID numbers $1,2,3,4$. Let $X\_i$ be the result on die $i$. Let $Y$ be the sum of the three largest of the $X\_i$, and let $W$ be the minimum of the $X\_i$.
Then $Y=X\_1+X\_2+X\_3+X\_4-W$. By the **linearity of expectation**, it follows that
$$E(Y)=E(X\_1)+E(X\_2)+E(X\_3)+E(X\_4)-E(W).$$
The linearity of expectation is a very useful result. Note that linearity *always* holds: independence is not required.
The expectation of the minimum can be calculated by first finding the distribution of the minimum $W$.
The minimum is $1$ unless the dice all show a number $\ge 2$. The probability of this is $1-\left(\frac{5}{6}\right)^4$. We rewrite this as $\frac{6^4-5^4}{6^4}$.
The minimum is $2$ if all the dice are $\ge 2$ but not all are $\ge 3$. The probability of this is $\frac{5^4-4^4}{6^4}$/
The minimum is $3$ if all results are $\ge 3$ but not all are $\ge 4$. This has probability $\frac{4^4-3^4}{6^4}$.
And so on. Now use the ordinary formula for expectation. We get that the expectation of $W$ is
$$\frac{1}{6^4}\left(1(6^4-5^4)+ 2(5^4-4^4)+3(4^4-3^4)+4(3^4-2^4)+5(2^4-1^4)+6(1^4-0^4) \right).$$
We leave you the task of computing. *Before* computing, simplify!
**Generalization:** Suppose we toss $k$ "fair" $(n+1)$-sided dice, with the numbers $0$ to $n$ written on them. For $i=1$ to $k$, let $X\_i$ be the number showing on the $i$-th die. Let $S$ be the sum of the dice. Then $S=X\_1+\cdots+X\_k$. The expectation of $X\_i$ is $\frac{0+1+\cdots +n}{n+1}$. By the usual expression for the sum of consecutive integers, $E(X\_i)=\frac{n}{2}$ and therefore $E(S)=\frac{kn}{2}$.
The analysis of the minimum $W$ goes along the same lines as the earlier one. The probability that the minimum is $j$ is $\frac{(n+1-j)^k -(n-j)^k}{(n+1)^k}$. If we use the ordinary formula for expectation, and simplify, we find that
$$E(W)=\frac{1^k+2^k+\cdots+n^k}{(n+1)^k}.$$
**A nice way to find $E(W)$:** The following is a useful general result. Let $X$ be a random variable that only takes non-negative integer values. Then
$$E(X)=\sum\_{i=1}^\infty \Pr(X\ge i).$$
We apply that to the case of the random variable $W$ which is the minimum of $X\_1,\dots,X\_4$. The probability that $W\ge i$ in that case is $\frac{(7-i)^k}{6^k}$.
The same procedure works for the more general situation you asked about.
|
Yes, your equation is correct, and this is a good and efficient way to perform this calculation. To find the expected value of the minimum, consider the hypercubes $[k,6]^4$ for $k=1,\dotsc,6$. The number of these hypercubes that a result is in is given by the minimum value of the dice. Thus we get the expected value of the minimum by adding up the probabilities of hitting these hypercubes:
$$\mathbb E[\min]=\frac{\displaystyle\sum\_{k=1}^6k^4}{6^4}=\left.\frac1{30}\frac{n(n+1)(2n+1)(3n^2+3n-1)}{6^4}\right|\_{n=6}=\frac{2275}{1296}\approx1.7554\;.$$
|
46,658,424 |
I require some help in creating a product slider in Shopify that allows you to add images and videos. At the moment the slider is working fine but I am having issues adding product videos to the slider.
From what I have read you can use the alt tag to add a YouTube embed code that will overwrite the image and display the video. I can get this working for the first image but it has a tenancy to break the rest of the slider. I believe I might need to change up the default slider and head with another alternative.
Here is what I have so far
```
$('#FeaturedImageZoom-product-template .product-featured-img').each (function() {
var videoid = $(this).attr("alt");
console.log(videoid);
if ($('.product-featured-img').attr("alt") == videoid) {
$(this).replaceWith('<iframe width="500px" height="500px" src="'+videoid+'?autoplay=1&showinfo=0&controls=0&modestbranding=1&rel=0" frameborder="0" allowfullscreen></iframe>');
}
});
```
And here is the liquid code to go with that:
```
<div class="grid product-single">
<div class="grid__item product-single__photos {{ product_image_width }}{% if section.settings.image_size == 'full' %} product-single__photos--full{% endif %}">
{%- assign featured_img_src = current_variant.featured_image.src | default: product.featured_image.src -%}
{%- assign featured_img_alt = current_variant.featured_image.alt | default: product.featured_image.alt -%}
<div id="FeaturedImageZoom-{{ section.id }}" class="product-single__photo{% if product.images.size > 1 %} product-single__photo--has-thumbnails{% endif %}" {% if enable_zoom %}data-zoom="{{ featured_img_src | img_url: product_image_zoom_size, scale: product_image_scale }}"{% endif %}>
<img src="{{ featured_img_src | img_url: product_image_size, scale: product_image_scale }}" alt="{{ featured_img_alt }}" id="FeaturedImage-{{ section.id }}" class="product-featured-img{% if enable_zoom %} js-zoom-enabled{% endif %}">
</div>
{% if product.images.size > 1 %}
{% if product.images.size > 3 %}
{%- assign enable_thumbnail_slides = true -%}
{% endif %}
<div class="thumbnails-wrapper{% if enable_thumbnail_slides == true %} thumbnails-slider--active{% endif %}">
{% if enable_thumbnail_slides == true %}
<button type="button" class="btn btn--link medium-up--hide thumbnails-slider__btn thumbnails-slider__prev thumbnails-slider__prev--{{ section.id }}">
{% include 'icon-chevron-left' %}
<span class="icon__fallback-text">{{ 'sections.slideshow.previous_slide' | t }}</span>
</button>
{% endif %}
<ul class="grid grid--uniform product-single__thumbnails product-single__thumbnails-{{ section.id }}">
{% for image in product.images %}
<li class="grid__item {{ product_thumbnail_width }} product-single__thumbnails-item">
<a
href="{{ image.src | img_url: product_image_size, scale: product_image_scale }}"
class="text-link product-single__thumbnail product-single__thumbnail--{{ section.id }}"
{% if enable_zoom %}data-zoom="{{ image.src | img_url: product_image_zoom_size, scale: product_image_scale }}"{% endif %}>
<img class="product-single__thumbnail-image" src="{{ image.src | img_url: product_thumb_size, scale: product_image_scale }}" alt="{{ image.alt | escape }}">
</a>
</li>
{% endfor %}
</ul>
{% if enable_thumbnail_slides == true %}
<button type="button" class="btn btn--link medium-up--hide thumbnails-slider__btn thumbnails-slider__next thumbnails-slider__next--{{ section.id }}">
{% include 'icon-chevron-right' %}
<span class="icon__fallback-text">{{ 'sections.slideshow.next_slide' | t }}</span>
</button>
{% endif %}
</div>
{% endif %}
</div>
```
I have read a couple of posts that outline a similar issue with developers trying to add a product videos however I have yet to come across a solution.
If anyone can help out here that would be appreciated.
Thanks
|
2017/10/10
|
['https://Stackoverflow.com/questions/46658424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3492429/']
|
Why use javascript for this when you can use simply liquid?
You just need to add check for the `alt` attribute if it contains `youtube` or something unique.
So for example:
```
{% if image.alt contains 'youtube' %}
<iframe width="500px" height="500px" src="{{image.alt}}?autoplay=1&showinfo=0&controls=0&modestbranding=1&rel=0" frameborder="0" allowfullscreen></iframe>
{% else %}
<a
href="{{ image.src | img_url: product_image_size, scale: product_image_scale }}"
class="text-link product-single__thumbnail product-single__thumbnail--{{ section.id }}"
{% if enable_zoom %}data-zoom="{{ image.src | img_url: product_image_zoom_size, scale: product_image_scale }}"{% endif %}>
<img class="product-single__thumbnail-image" src="{{ image.src | img_url: product_thumb_size, scale: product_image_scale }}" alt="{{ image.alt | escape }}">
</a>
{% endif %}
```
|
I just wanted to post the solution I arrived at based on the answer above by "drip". I hope this might help someone else down the track.
```
<!-- Product Slider w/ Video -->
<div id="product-flexslider" class="flexslider product_gallery product-{{ product.id }}-gallery {% if product-images == blank %}product_slider{% endif %} {% if settings.product_thumbs == false %}animated fadeInUp{% endif %}">
<ul class="slides">
{% for image in product.images %}
<li data-thumb="{{ image | product_img_url: '1024x1024' }}" data-title="{% if image.alt contains 'youtube' or image.alt contains 'vimeo' %}{{ product.title }}{% else %}{{ image.alt | escape }}{% endif %}">
{% if image.alt contains 'youtube' or image.alt contains 'vimeo' %}
{% assign src = image.alt | split: 'src="' %}
{% assign src = src[1] | split: '"' | first %}
{% if src contains '?' %}
{% assign src = src | append: '&autoplay=1' %}
{% else %}
{% assign src = src | append: '?autoplay=1' %}
{% endif %}
<div class="video-container {% if image.alt contains 'vimeo' %}vimeo{% else %}youtube{% endif %}">
<div>
<a href="{{ src }}" title="{{ product.title | escape }}">
{{ image.alt }}
</a>
</div>
</div>
{% else %}
<a href="{{ image | product_img_url: 'master' }}" title="{{ image.alt | escape }}">
<img src="{{ image | product_img_url: '1024x1024' }}" alt="{{ image.alt | escape }}"/>
</a>
{% endif %}
</li>
{% endfor %}
</ul>
</div>
<!-- Carousel -->
<div id="product-carousel" class="flexslider product_gallery product-{{ product.id }}-gallery {% if product-images == blank %}product_slider{% endif %} {% if settings.product_thumbs == false %}animated fadeInUp{% endif %}">
<ul class="slides">
{% for image in product.images %}
<li data-thumb="{{ image | product_img_url: '1024x1024' }}" data-title="{% if image.alt contains 'youtube' or image.alt contains 'vimeo' %}{{ product.title }}{% else %}{{ image.alt | escape }}{% endif %}">
<a href="{{ image | product_img_url: 'master' }}" title="{{ image.alt | escape }}">
<img src="{{ image | product_img_url: '1024x1024' }}" alt="{{ image.alt | escape }}" />
</a>
</li>
{% endfor %}
</ul>
</div>
<!-- End Slider -->
<!-- FlexSlider -->
{{ 'jquery.flexslider-min.js' | asset_url | script_tag }}
{{ 'flexslider.css' | asset_url | stylesheet_tag }}
<script type="text/javascript" charset="utf-8">
(function($) {
$(window).load(function(){
$('#product-carousel').flexslider({
animation: "slide",
controlNav: false,
itemWidth: 41,
itemMargin: 5,
asNavFor: '#product-flexslider'
});
$('#product-flexslider').flexslider({
animation: "slide",
controlNav: false,
sync: "#product-carousel"
});
});
})(jQuery);
</script>
```
Once you have updated the code you can place the embed code in the ALT tag of the image while using the image as a thumbnail placeholder.
FlexSlider properties can be located here:
<https://github.com/woocommerce/FlexSlider/wiki/FlexSlider-Properties>
The solution was also helped by the post here which was relating to another issue:
<https://ecommerce.shopify.com/c/ecommerce-discussion/t/issue-with-variable-image-444159>
|
4,504,132 |
I am occasionally getting odd behavior from boost::lower, when called on a std::wstring. In particular, I have seen the following assertion fail in a release build (but *not* in a debug build):
```
Assertion failed: !is_singular(), file C:\boost_1_40_0\boost/range/iterator_range.hpp, line 281
```
I have also seen what appear to be memory errors after calling boost::to\_lower in contexts such as:
```
void test(const wchar_t* word) {
std::wstring buf(word);
boost::to_lower(buf);
...
}
```
Replacing the calls `boost::tolower(wstr)` with `std::transform(wstr.begin(), wstr.end(), wstr.begin(), towlower)` appears to fix the problem; but I'd like to know what's going wrong.
My best guess is that perhaps the problem has something to do with changing the case of unicode characters -- perhaps the encoding size of the downcased character is different from the encoding size of the source character?
Does anyone have any ideas what might be going on here? It might help if I knew what "is\_singular()" means in the context of boost, but after doing a few google searches I wasn't able to find any documentation for it.
*Relevant software versions: Boost 1.40.0; MS Visual Studio 2008.*
|
2010/12/21
|
['https://Stackoverflow.com/questions/4504132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222329/']
|
After further debugging, I figured out what was going on.
The cause of my trouble was that one project in the solution was not defining NDEBUG (despite being in release mode), while all the other modules were. Boost allocates some extra fields in its data structures, which it uses to store debug information (such as whether a data structure has been initialized). If module A has debugging turned off, then it will create data structures that don't contain those fields. Then when module B, which has debugging turned on, gets its hands on that data structure, it will try to check those fields (which were not allocated), resulting in random memory errors.
Defining NDEBUG in *all* projects in the solution fixed the problem.
|
An iterator range should only be singular if it's been constructed with the default constructor (stores singular iterators, i.e doesn't represent a range). As it's rather hard to believe that the boost's `to_lower` function manages to create a singular range, it suggests that the problem might also be elsewhere (a result of some undefined behavior, such as using uninitialized variables which might be initialized to some known value in debug builds).
Read more on [Heisenbugs](https://stackoverflow.com/questions/1762088/common-reasons-for-bugs-in-release-version-not-present-in-debug-mode).
|
73,605 |
I'm looking to try and identify the year this bike was built. Currently struggling to add photo's. [](https://i.stack.imgur.com/ibxeW.jpg)
I will try and add some more in a minute. The frame number of the bike is 14246
Many thanks
Wesley
|
2020/11/27
|
['https://bicycles.stackexchange.com/questions/73605', 'https://bicycles.stackexchange.com', 'https://bicycles.stackexchange.com/users/53900/']
|
Nice bike - from the overall lines of the frame its definitely something from the 80s.
The head tube is relatively short, so I'm guessing this is a smaller frame, maybe a 50cm or less.
The pronounced curve of the front fork became straighter as time went on due to manufacturing changes. Also the right fork tine has a lamp mount which was common for the time.
The three silver cable clamps on the top tube are more of a 70s design, but they may not be original.
The bike has U brakes rather than cheaper calipers, so its a mid-range bike not a budget bike. These require a cable stop, so are probably original equipment.
I'm sure the chainrings tell a story too - they have quite a difference between the large and small, in terms of tooth count.
Your rims are interesting - I can't tell if they are steel or aluminium (ie replaced later)
The only damage I can see is the two stays holding the rear of the front mudguard. Normally they'd be straight, not bent up which suggests something got in the spokes once. Minor as long as nothing's rubbing.
I suggest you clean that filthy chain and cassette, then relubricate. That blackness is suspended grit which is slowly grinding away at the components of the transmission.
**I would call this a touring bike from the early 1980s.** Its not a race bike, but that crankset would help it get up hills when loaded. The better brakes also help a heavily loaded bike come down the other side.
Overall, looks like a loverly bike and a pleasure to ride.
|
Falccon continued to make high class bikes into the early 80s, the Olympic was a good alternative to something like a Dawes Galaxy - but rode even better, ime.
The one in the pic looks very well used - look at the teeth on the chainrings.
|
73,605 |
I'm looking to try and identify the year this bike was built. Currently struggling to add photo's. [](https://i.stack.imgur.com/ibxeW.jpg)
I will try and add some more in a minute. The frame number of the bike is 14246
Many thanks
Wesley
|
2020/11/27
|
['https://bicycles.stackexchange.com/questions/73605', 'https://bicycles.stackexchange.com', 'https://bicycles.stackexchange.com/users/53900/']
|
Adding information to Criggie's accurate answer.
This is not the same bike but it is an Olympic and the style of decal matches your bike.
Your frame has the wrap around stays and this one does not.
[](https://i.stack.imgur.com/dqPpH.jpg)
I don't view an ebay post as authoritative. The add says it's a 1980 - that's possible - but it's also possible that it's more like early 80s as opposed to exactly 1980.
I'm still searching for a catalog or something more authoritative.
[According to the ebay add](https://www.ebay.co.uk/itm/Falcon-Olympic-1980-Designed-by-Ernie-Clements-Classic-Eroica-Britannia-Bicycle/224234243858?hash=item3435670712:g:1Q0AAOSw5otfYLVF):
>
> Falcon Olympic 1980
>
> Make: Falcon Cycles
>
> Model:Olympic designed by Ernie Clements
>
> Year: 1980
>
> Size:Seat Tube: C2C 54cm , Top to C BB 55.5cm , Top tube C2C 55cm front to back 58cm
>
> Tubing: Reynolds 531
>
> Brakes: Weinmann Vainquer Black Label Centre Pulls
>
> Brake Levers: Weinmann. Hooded
>
> Crankset: Sugino Super Maxy - 52 - 42
>
> Crank Arm length: 165
>
> Shifters: Shimano 600 Arabesque
>
> Rear Derailleur: Shimano 600 Arabesque (Long Cage)
>
> Front Derailleur: Shimano 600 Arabesque
>
> Freewheel/ Block: Shimano 5 Speed
>
> Hubs: Mailard Large Flange
>
>
>
|
Falccon continued to make high class bikes into the early 80s, the Olympic was a good alternative to something like a Dawes Galaxy - but rode even better, ime.
The one in the pic looks very well used - look at the teeth on the chainrings.
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
var promises = [];
obj.data.forEach(function(entry) {
promises.push(findMore(entry.id));
});
return Promise.all(promises);
})
.then(function (response) {
// Here response is an array with all the responses
// from your calls to findMore
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options);
}
```
|
You want to use Promise.all.
So first thing first, you need an array of promises. Inside your for each loop, set findMore to a variable, and make it return the promise. Then have a line where you do Promise.all(promiseArr).then(function(){console.log("done)})
Your code would look like this
```
function getData() {
var promiseArr = []
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
var p = findMore(entry.id)
promiseArr.push(p)
});
}).then(function(){
Promise.all(promiseArr).then(function(){
console.log("this is all done")
})
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
the basic idea of Promise.all is that it only executes once all promises in the array have been resolved, or when any of the promises fail. You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
A couple of things to think about:
**If you care about the fate of a promise, always return it**.
In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise.
**You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).**
>
> The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
>
>
>
Lets put these to use on your example:
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
var obj = JSON.parse(apires);
var findMorePromises = obj.data.map(function(entry) {
return findMore(entry.id)
});
return Promise.all(findMorePromises);
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
return JSON.parse(apires);
})
}
```
I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code.
It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.
|
You want to use Promise.all.
So first thing first, you need an array of promises. Inside your for each loop, set findMore to a variable, and make it return the promise. Then have a line where you do Promise.all(promiseArr).then(function(){console.log("done)})
Your code would look like this
```
function getData() {
var promiseArr = []
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
var p = findMore(entry.id)
promiseArr.push(p)
});
}).then(function(){
Promise.all(promiseArr).then(function(){
console.log("this is all done")
})
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
the basic idea of Promise.all is that it only executes once all promises in the array have been resolved, or when any of the promises fail. You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
var promises = [];
obj.data.forEach(function(entry) {
promises.push(findMore(entry.id));
});
return Promise.all(promises);
})
.then(function (response) {
// Here response is an array with all the responses
// from your calls to findMore
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options);
}
```
|
You need to use `Promise.all` to run all async requests in parallel. Also you *must* return the result of `findMore` and `getData` (they are promises).
```
function getData() {
var options = {...};
return request(options)
.then(function(apires) {
console.log("complete 1");
var obj = JSON.parse(apires);
var ops = obj.data.map(function(entry) {
return findMore(entry.id);
});
return Promise.all(ops);
}
function findMore(id) {
var options = {...};
return request(options)
.then(function(apires) {
console.log("complete 2");
return JSON.parse(apires);
});
}
getData()
.then(data => console.log(data))
.catch(err => console.log(err));
```
If you can use ES7, it can be written with async/await:
```
let getData = async () => {
let options = {...};
let res = awit request(options);
let ops = res.data.map(entry => findMore(entry.id));
let data = await Promise.all(ops);
return data;
};
let findMore = async (id) => {
let options = {...};
let apires = awit request(options);
return JSON.parse(apires);
};
```
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
A couple of things to think about:
**If you care about the fate of a promise, always return it**.
In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise.
**You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).**
>
> The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
>
>
>
Lets put these to use on your example:
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
var obj = JSON.parse(apires);
var findMorePromises = obj.data.map(function(entry) {
return findMore(entry.id)
});
return Promise.all(findMorePromises);
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
return JSON.parse(apires);
})
}
```
I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code.
It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.
|
You need to use `Promise.all` to run all async requests in parallel. Also you *must* return the result of `findMore` and `getData` (they are promises).
```
function getData() {
var options = {...};
return request(options)
.then(function(apires) {
console.log("complete 1");
var obj = JSON.parse(apires);
var ops = obj.data.map(function(entry) {
return findMore(entry.id);
});
return Promise.all(ops);
}
function findMore(id) {
var options = {...};
return request(options)
.then(function(apires) {
console.log("complete 2");
return JSON.parse(apires);
});
}
getData()
.then(data => console.log(data))
.catch(err => console.log(err));
```
If you can use ES7, it can be written with async/await:
```
let getData = async () => {
let options = {...};
let res = awit request(options);
let ops = res.data.map(entry => findMore(entry.id));
let data = await Promise.all(ops);
return data;
};
let findMore = async (id) => {
let options = {...};
let apires = awit request(options);
return JSON.parse(apires);
};
```
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
var promises = [];
obj.data.forEach(function(entry) {
promises.push(findMore(entry.id));
});
return Promise.all(promises);
})
.then(function (response) {
// Here response is an array with all the responses
// from your calls to findMore
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options);
}
```
|
EDIT: As others have mentioned, using a Promise.all() is likely a better solution in this case.
If you are open to using jQuery (a JavaScript library), then you can use the .ajaxStop() event handler and specify your own function. Sample code:
```
$(document).ajaxStop(function(){
alert("All AJAX requests are completed.");
});
```
You will need to include the jQuery module. The instructions for Node.js are:
1. Install module through npm:
```
npm install jquery
```
2. Then use a "require" to use jQuery in your JavaScript code (a window with a document is required but there is no such "window" in Node so you can mock one with jsdom), see [npm - jQuery](https://www.npmjs.com/package/jquery) for details:
```
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
```
If you want to stick to a pure JavaScript approach, you will need to create your own "module" to keep track of AJAX requests. In this module you can keep track of how many pending requests there are and remove them once they are terminated. Please see: [Check when all Ajax Requests are complete - Pure JavaScript](https://stackoverflow.com/questions/25971224/check-when-all-ajax-requests-are-complete-pure-javascript) for more details.
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
You can make your findMore method return a promise, so you can pass an array of those to Promise.all and handle the .then when all promises have finished.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
var promises = [];
obj.data.forEach(function(entry) {
promises.push(findMore(entry.id));
});
return Promise.all(promises);
})
.then(function (response) {
// Here response is an array with all the responses
// from your calls to findMore
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options);
}
```
|
A couple of things to think about:
**If you care about the fate of a promise, always return it**.
In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise.
**You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).**
>
> The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
>
>
>
Lets put these to use on your example:
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
var obj = JSON.parse(apires);
var findMorePromises = obj.data.map(function(entry) {
return findMore(entry.id)
});
return Promise.all(findMorePromises);
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
return JSON.parse(apires);
})
}
```
I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code.
It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.
|
45,825,412 |
Hello I'm new to NodeJs and am trying to work out the best way to get this chain of events working. I have to do two API calls get all the information I need. The first API call is just a list of IDs, then the second API call I pass the ID to get the rest of the information for each object.
However using the method below, I have no idea when everything is finished. Please can someone help me out.
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 1");
var obj = JSON.parse(apires);
obj.data.forEach(function(entry) {
findMore(entry.id)
});
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
request(options).then(function(apires){
console.log("complete 2");
var obj = JSON.parse(apires);
})
}
```
|
2017/08/22
|
['https://Stackoverflow.com/questions/45825412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4071548/']
|
A couple of things to think about:
**If you care about the fate of a promise, always return it**.
In your case, `findMore` does not return the promise from `request`, so `getData` has no handle to track the resolution (or rejection) of that promise.
**You can track the resolution of multiple promises with [Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).**
>
> The Promise.all() method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
>
>
>
Lets put these to use on your example:
```
function getData() {
var options = {
method: 'GET',
uri: 'https://api.call1.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
var obj = JSON.parse(apires);
var findMorePromises = obj.data.map(function(entry) {
return findMore(entry.id)
});
return Promise.all(findMorePromises);
})
}
function findMore(id) {
var options = {
method: 'GET',
uri: 'https://api.call2.com',
qs: {
access_token: _accessToken,
}
};
return request(options)
.then(function(apires){
return JSON.parse(apires);
})
}
```
I've used [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to construct the array of promises, but you could just as well use a `foreach` and push into an array similar to be more similar to your example code.
It's also good practice to make sure you are handling rejection of any promises (via `catch`), but I'll assume that is out of the scope of this question.
|
EDIT: As others have mentioned, using a Promise.all() is likely a better solution in this case.
If you are open to using jQuery (a JavaScript library), then you can use the .ajaxStop() event handler and specify your own function. Sample code:
```
$(document).ajaxStop(function(){
alert("All AJAX requests are completed.");
});
```
You will need to include the jQuery module. The instructions for Node.js are:
1. Install module through npm:
```
npm install jquery
```
2. Then use a "require" to use jQuery in your JavaScript code (a window with a document is required but there is no such "window" in Node so you can mock one with jsdom), see [npm - jQuery](https://www.npmjs.com/package/jquery) for details:
```
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
```
If you want to stick to a pure JavaScript approach, you will need to create your own "module" to keep track of AJAX requests. In this module you can keep track of how many pending requests there are and remove them once they are terminated. Please see: [Check when all Ajax Requests are complete - Pure JavaScript](https://stackoverflow.com/questions/25971224/check-when-all-ajax-requests-are-complete-pure-javascript) for more details.
|
11,760,258 |
Consider the following Java class definitions:
```
class Animal {}
class Lion extends Animal {}
```
When defining a covariant `Cage` for `Animal`s I use this code in Java:
```
class Cage<T extends Animal> {
void add(T animal) { System.out.println("Adding animal..."); }
}
```
But the following Java example ...
```
public static void main(String... args) {
Cage<? extends Animal> animals = null;
Cage<Lion> lions = null;
animals = lions; // Works!
animals.add(new Lion()); // Error!
}
```
... fails to compile with the following error:
>
> *The method add(capture#2-of ? extends Animal)
> in the type Cage
> is not applicable to for the arguments (Lion)*
>
>
>
Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime?
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`?
(I know that I could replace `add`'s `T` with `Animal`.)
|
2012/08/01
|
['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']
|
I think this question might answer that for you:
[java generics covariance](https://stackoverflow.com/questions/2660827/java-generics-covariance)
Basically, Java generics are not covariant.
The best explanation I know for this comes, of course, from Effective Java 2nd Edition.
You can read about it here:
<http://java.sun.com/docs/books/effective/generics.pdf>
I think the hypothetical rule would be quite hard to enforce in runtime. The compiler could theoretically check if all objects explicitly added to the list are indeed of the same type of animal, but I'm sure that there are conditions that could break this in runtime.
|
If so, that is likely a bug in the Scala compiler. Odersky et al. write in [An Overview of the Scala Programming Language](http://www.scala-lang.org/docu/files/ScalaOverview.pdf):
>
> Scala’s type system ensures that variance annotations are
> sound by keeping track of the positions where a type pa-
> rameter is used. These positions are classied as covariant
> for the types of immutable elds and method results, and
> contravariant for method argument types and upper type
> parameter bounds. Type arguments to a non-variant type
> parameter are always in non-variant position. The position
> ips between contra- and co-variant inside a type argument
> that corresponds to a contravariant parameter. The type
> system enforces that covariant (respectively, contravariant)
> type parameters are only used in covariant (contravariant)
> positions.
>
>
>
Therefore, the covariant type parameter T must not appear as method argument, because that is a contravariant position.
A similar rule (with more special cases, none of which matter in this case) is also present in the the [Scala Language Specification (version 2.9)](http://www.scala-lang.org/docu/files/ScalaReference.pdf), section 4.5.
|
11,760,258 |
Consider the following Java class definitions:
```
class Animal {}
class Lion extends Animal {}
```
When defining a covariant `Cage` for `Animal`s I use this code in Java:
```
class Cage<T extends Animal> {
void add(T animal) { System.out.println("Adding animal..."); }
}
```
But the following Java example ...
```
public static void main(String... args) {
Cage<? extends Animal> animals = null;
Cage<Lion> lions = null;
animals = lions; // Works!
animals.add(new Lion()); // Error!
}
```
... fails to compile with the following error:
>
> *The method add(capture#2-of ? extends Animal)
> in the type Cage
> is not applicable to for the arguments (Lion)*
>
>
>
Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime?
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`?
(I know that I could replace `add`'s `T` with `Animal`.)
|
2012/08/01
|
['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']
|
In java :
```
Cage<? extends Animal> animals = null;
```
This is a cage, but you don't know what kind of animals it accepts.
```
animals = lions; // Works!
```
Ok, you add no opinion about what sort of cage animals was, so lion violates no expectation.
```
animals.add(new Lion()); // Error!
```
You don't know what sort of cage animals is. In this particular case, it happens to be a cage for lions you put a lion in, fine, but the rule that would allow that would just allow putting any sort of animal into any cage. It is properly disallowed.
In Scala :
`Cage[+T]` : if `B` extends `A`, then a `Cage[B]` should be considered a `Cage[A]`.
Given that, `animals = lions` is allowed.
But this is different from java, the type parameter is definitely `Animal`, not the wildcard `? extends Animal`. You are allowed to put an animal in a `Cage[Animal]`, a lion is an animal, so you can put a lion in a Cage[Animal] that could possibly be a Cage[Bird]. This is quite bad.
Except that it is in fact not allowed (fortunately). Your code should not compile (if it compiled for you, you observed a compiler bug). A covariant generic parameter is not allowed to appear as an argument to a method. The reason being precisely that allowing it would allow putting lions in a bird cage. It T appears as `+T` in the definition of `Cage`, it cannot appears as an argument to method `add`.
So both language disallow putting lions in birdcages.
---
Regarding your updated questions.
Is it done because otherwise a tiger could be added?
Yes, this is of course the reason, the point of the type system is to make that impossible. Would that cause un runtime error? In all likelihood, it would at some point, but not at the moment you call add, as actual type of generic is not checked at run time (type erasure). But the type system usually rejects every program for which it cannot prove that (some kind of) errors will not happen, not just program where it can prove that they do happen.
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of Animal?
Maybe. Note that you still have two types of animals, namely `Animal` and `Lion`. So the important fact is that a `Lion` instance belongs to both types. On the other hand, an `Animal` instance does not belong to type `Lion`. `animals.add(new Lion())` could be allowed (the cage is either a cage for any animals, or for lions only, both ok) , but `animals.add(new Animal())` should not (as animals could be a cage for lions only).
But anyway, it sounds like a very bad idea. The point of inheritance in object oriented system is that sometime later, someone else working somewhere else can add subtype, and that will not cause a correct system to become incorrect. In fact, the old code does not even need to be recompiled (maybe you do not have the source). With such a rule, that would not be true any more
|
I think this question might answer that for you:
[java generics covariance](https://stackoverflow.com/questions/2660827/java-generics-covariance)
Basically, Java generics are not covariant.
The best explanation I know for this comes, of course, from Effective Java 2nd Edition.
You can read about it here:
<http://java.sun.com/docs/books/effective/generics.pdf>
I think the hypothetical rule would be quite hard to enforce in runtime. The compiler could theoretically check if all objects explicitly added to the list are indeed of the same type of animal, but I'm sure that there are conditions that could break this in runtime.
|
11,760,258 |
Consider the following Java class definitions:
```
class Animal {}
class Lion extends Animal {}
```
When defining a covariant `Cage` for `Animal`s I use this code in Java:
```
class Cage<T extends Animal> {
void add(T animal) { System.out.println("Adding animal..."); }
}
```
But the following Java example ...
```
public static void main(String... args) {
Cage<? extends Animal> animals = null;
Cage<Lion> lions = null;
animals = lions; // Works!
animals.add(new Lion()); // Error!
}
```
... fails to compile with the following error:
>
> *The method add(capture#2-of ? extends Animal)
> in the type Cage
> is not applicable to for the arguments (Lion)*
>
>
>
Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime?
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`?
(I know that I could replace `add`'s `T` with `Animal`.)
|
2012/08/01
|
['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']
|
When you *declare* your variable with this type: `Cage<? extends Animal>`; you're basically saying that your variable is a cage with some *unkown* class that inherits from `Animal`. It could be a `Tiger` or a `Whale`; so the compiler doesn't have enough information to let you add a `Lion` to it. To have what you want, you declare your variable either as a `Cage<Animal>` or a `Cage<Lion>`.
|
If so, that is likely a bug in the Scala compiler. Odersky et al. write in [An Overview of the Scala Programming Language](http://www.scala-lang.org/docu/files/ScalaOverview.pdf):
>
> Scala’s type system ensures that variance annotations are
> sound by keeping track of the positions where a type pa-
> rameter is used. These positions are classied as covariant
> for the types of immutable elds and method results, and
> contravariant for method argument types and upper type
> parameter bounds. Type arguments to a non-variant type
> parameter are always in non-variant position. The position
> ips between contra- and co-variant inside a type argument
> that corresponds to a contravariant parameter. The type
> system enforces that covariant (respectively, contravariant)
> type parameters are only used in covariant (contravariant)
> positions.
>
>
>
Therefore, the covariant type parameter T must not appear as method argument, because that is a contravariant position.
A similar rule (with more special cases, none of which matter in this case) is also present in the the [Scala Language Specification (version 2.9)](http://www.scala-lang.org/docu/files/ScalaReference.pdf), section 4.5.
|
11,760,258 |
Consider the following Java class definitions:
```
class Animal {}
class Lion extends Animal {}
```
When defining a covariant `Cage` for `Animal`s I use this code in Java:
```
class Cage<T extends Animal> {
void add(T animal) { System.out.println("Adding animal..."); }
}
```
But the following Java example ...
```
public static void main(String... args) {
Cage<? extends Animal> animals = null;
Cage<Lion> lions = null;
animals = lions; // Works!
animals.add(new Lion()); // Error!
}
```
... fails to compile with the following error:
>
> *The method add(capture#2-of ? extends Animal)
> in the type Cage
> is not applicable to for the arguments (Lion)*
>
>
>
Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime?
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`?
(I know that I could replace `add`'s `T` with `Animal`.)
|
2012/08/01
|
['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']
|
In java :
```
Cage<? extends Animal> animals = null;
```
This is a cage, but you don't know what kind of animals it accepts.
```
animals = lions; // Works!
```
Ok, you add no opinion about what sort of cage animals was, so lion violates no expectation.
```
animals.add(new Lion()); // Error!
```
You don't know what sort of cage animals is. In this particular case, it happens to be a cage for lions you put a lion in, fine, but the rule that would allow that would just allow putting any sort of animal into any cage. It is properly disallowed.
In Scala :
`Cage[+T]` : if `B` extends `A`, then a `Cage[B]` should be considered a `Cage[A]`.
Given that, `animals = lions` is allowed.
But this is different from java, the type parameter is definitely `Animal`, not the wildcard `? extends Animal`. You are allowed to put an animal in a `Cage[Animal]`, a lion is an animal, so you can put a lion in a Cage[Animal] that could possibly be a Cage[Bird]. This is quite bad.
Except that it is in fact not allowed (fortunately). Your code should not compile (if it compiled for you, you observed a compiler bug). A covariant generic parameter is not allowed to appear as an argument to a method. The reason being precisely that allowing it would allow putting lions in a bird cage. It T appears as `+T` in the definition of `Cage`, it cannot appears as an argument to method `add`.
So both language disallow putting lions in birdcages.
---
Regarding your updated questions.
Is it done because otherwise a tiger could be added?
Yes, this is of course the reason, the point of the type system is to make that impossible. Would that cause un runtime error? In all likelihood, it would at some point, but not at the moment you call add, as actual type of generic is not checked at run time (type erasure). But the type system usually rejects every program for which it cannot prove that (some kind of) errors will not happen, not just program where it can prove that they do happen.
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of Animal?
Maybe. Note that you still have two types of animals, namely `Animal` and `Lion`. So the important fact is that a `Lion` instance belongs to both types. On the other hand, an `Animal` instance does not belong to type `Lion`. `animals.add(new Lion())` could be allowed (the cage is either a cage for any animals, or for lions only, both ok) , but `animals.add(new Animal())` should not (as animals could be a cage for lions only).
But anyway, it sounds like a very bad idea. The point of inheritance in object oriented system is that sometime later, someone else working somewhere else can add subtype, and that will not cause a correct system to become incorrect. In fact, the old code does not even need to be recompiled (maybe you do not have the source). With such a rule, that would not be true any more
|
If so, that is likely a bug in the Scala compiler. Odersky et al. write in [An Overview of the Scala Programming Language](http://www.scala-lang.org/docu/files/ScalaOverview.pdf):
>
> Scala’s type system ensures that variance annotations are
> sound by keeping track of the positions where a type pa-
> rameter is used. These positions are classied as covariant
> for the types of immutable elds and method results, and
> contravariant for method argument types and upper type
> parameter bounds. Type arguments to a non-variant type
> parameter are always in non-variant position. The position
> ips between contra- and co-variant inside a type argument
> that corresponds to a contravariant parameter. The type
> system enforces that covariant (respectively, contravariant)
> type parameters are only used in covariant (contravariant)
> positions.
>
>
>
Therefore, the covariant type parameter T must not appear as method argument, because that is a contravariant position.
A similar rule (with more special cases, none of which matter in this case) is also present in the the [Scala Language Specification (version 2.9)](http://www.scala-lang.org/docu/files/ScalaReference.pdf), section 4.5.
|
11,760,258 |
Consider the following Java class definitions:
```
class Animal {}
class Lion extends Animal {}
```
When defining a covariant `Cage` for `Animal`s I use this code in Java:
```
class Cage<T extends Animal> {
void add(T animal) { System.out.println("Adding animal..."); }
}
```
But the following Java example ...
```
public static void main(String... args) {
Cage<? extends Animal> animals = null;
Cage<Lion> lions = null;
animals = lions; // Works!
animals.add(new Lion()); // Error!
}
```
... fails to compile with the following error:
>
> *The method add(capture#2-of ? extends Animal)
> in the type Cage
> is not applicable to for the arguments (Lion)*
>
>
>
Is this done because otherwise a different type like `Tiger` could be added after `animals = lions` and fail at runtime?
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of `Animal`?
(I know that I could replace `add`'s `T` with `Animal`.)
|
2012/08/01
|
['https://Stackoverflow.com/questions/11760258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']
|
In java :
```
Cage<? extends Animal> animals = null;
```
This is a cage, but you don't know what kind of animals it accepts.
```
animals = lions; // Works!
```
Ok, you add no opinion about what sort of cage animals was, so lion violates no expectation.
```
animals.add(new Lion()); // Error!
```
You don't know what sort of cage animals is. In this particular case, it happens to be a cage for lions you put a lion in, fine, but the rule that would allow that would just allow putting any sort of animal into any cage. It is properly disallowed.
In Scala :
`Cage[+T]` : if `B` extends `A`, then a `Cage[B]` should be considered a `Cage[A]`.
Given that, `animals = lions` is allowed.
But this is different from java, the type parameter is definitely `Animal`, not the wildcard `? extends Animal`. You are allowed to put an animal in a `Cage[Animal]`, a lion is an animal, so you can put a lion in a Cage[Animal] that could possibly be a Cage[Bird]. This is quite bad.
Except that it is in fact not allowed (fortunately). Your code should not compile (if it compiled for you, you observed a compiler bug). A covariant generic parameter is not allowed to appear as an argument to a method. The reason being precisely that allowing it would allow putting lions in a bird cage. It T appears as `+T` in the definition of `Cage`, it cannot appears as an argument to method `add`.
So both language disallow putting lions in birdcages.
---
Regarding your updated questions.
Is it done because otherwise a tiger could be added?
Yes, this is of course the reason, the point of the type system is to make that impossible. Would that cause un runtime error? In all likelihood, it would at some point, but not at the moment you call add, as actual type of generic is not checked at run time (type erasure). But the type system usually rejects every program for which it cannot prove that (some kind of) errors will not happen, not just program where it can prove that they do happen.
Could a special (hypothetical) rule be made that would not rejected it iff there would be only one sub-type of Animal?
Maybe. Note that you still have two types of animals, namely `Animal` and `Lion`. So the important fact is that a `Lion` instance belongs to both types. On the other hand, an `Animal` instance does not belong to type `Lion`. `animals.add(new Lion())` could be allowed (the cage is either a cage for any animals, or for lions only, both ok) , but `animals.add(new Animal())` should not (as animals could be a cage for lions only).
But anyway, it sounds like a very bad idea. The point of inheritance in object oriented system is that sometime later, someone else working somewhere else can add subtype, and that will not cause a correct system to become incorrect. In fact, the old code does not even need to be recompiled (maybe you do not have the source). With such a rule, that would not be true any more
|
When you *declare* your variable with this type: `Cage<? extends Animal>`; you're basically saying that your variable is a cage with some *unkown* class that inherits from `Animal`. It could be a `Tiger` or a `Whale`; so the compiler doesn't have enough information to let you add a `Lion` to it. To have what you want, you declare your variable either as a `Cage<Animal>` or a `Cage<Lion>`.
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all`
```
library(stringr)
str_extract(str1, '(?<=\\()[0-9-]+(?=\\))')
#[1] "123-456-789"
str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))')
```
In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)`
With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`).
```
strsplit(str1, '[()]')[[1]][2]
#[1] "123-456-789"
```
If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep`
```
lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE))
```
Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`).
```
library(stringi)
stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]]
#[1] "123-456-789"
stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE)
```
Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets.
```
library(qdapRegex)
rm_round(str1, extract=TRUE)[[1]]
#[1] "123-456-789"
rm_round(str2, extract=TRUE)
```
### data
```
str1 <- "A B C (123-456-789)"
str2 <- c("A B C (123-425-478) A", "ABC(123-423-428)",
"(123-423-498) ABCDD",
"(123-432-423)", "ABC (123-423-389) GR (124-233-848) AK")
```
|
or with `sub` from `base R`:
```
sub("[^(]+\\(([^)]+)\\).*", "\\1", "A B C (123-456-789)")
#[1] "123-456-789"
```
Explanation:
`[^(]+` : matches anything except an opening bracket
`\\(` : matches an opening bracket, which is just before what you want
`([^)]+)` : matches the pattern you want to capture (which is then retrieved in `replacement="\\1"`), which is anything except a closing bracket
`\\).*` matches a closing bracket followed by anything, 0 or more times
***Another option with look-ahead and look-behind***
```
sub(".*(?<=\\()(.+)(?=\\)).*", "\\1", "A B C (123-456-789)", perl=TRUE)
#[1] "123-456-789"
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all`
```
library(stringr)
str_extract(str1, '(?<=\\()[0-9-]+(?=\\))')
#[1] "123-456-789"
str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))')
```
In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)`
With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`).
```
strsplit(str1, '[()]')[[1]][2]
#[1] "123-456-789"
```
If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep`
```
lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE))
```
Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`).
```
library(stringi)
stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]]
#[1] "123-456-789"
stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE)
```
Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets.
```
library(qdapRegex)
rm_round(str1, extract=TRUE)[[1]]
#[1] "123-456-789"
rm_round(str2, extract=TRUE)
```
### data
```
str1 <- "A B C (123-456-789)"
str2 <- c("A B C (123-425-478) A", "ABC(123-423-428)",
"(123-423-498) ABCDD",
"(123-432-423)", "ABC (123-423-389) GR (124-233-848) AK")
```
|
Try this also:
```
k<-"A B C (123-456-789)"
regmatches(k,gregexpr("*.(\\d+).*",k))[[1]]
[1] "(123-456-789)"
```
With suggestion from @Arun:
```
regmatches(k, gregexpr('(?<=\\()[^A-Z ]+(?=\\))', k, perl=TRUE))[[1]]
```
With suggestion from @akrun:
```
regmatches(k, gregexpr('[0-9-]+', k))[[1]]
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all`
```
library(stringr)
str_extract(str1, '(?<=\\()[0-9-]+(?=\\))')
#[1] "123-456-789"
str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))')
```
In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)`
With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`).
```
strsplit(str1, '[()]')[[1]][2]
#[1] "123-456-789"
```
If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep`
```
lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE))
```
Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`).
```
library(stringi)
stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]]
#[1] "123-456-789"
stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE)
```
Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets.
```
library(qdapRegex)
rm_round(str1, extract=TRUE)[[1]]
#[1] "123-456-789"
rm_round(str2, extract=TRUE)
```
### data
```
str1 <- "A B C (123-456-789)"
str2 <- c("A B C (123-425-478) A", "ABC(123-423-428)",
"(123-423-498) ABCDD",
"(123-432-423)", "ABC (123-423-389) GR (124-233-848) AK")
```
|
The capture groups in `sub` will target your desired output:
```
sub('.*\\((.*)\\).*', '\\1', str1)
[1] "123-456-789"
```
Extra check to make sure I pass @akrun's extended example:
```
sub('.*\\((.*)\\).*', '\\1', str2)
[1] "123-425-478" "123-423-428" "123-423-498" "123-432-423" "124-233-848"
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
If we want to extract the digits with `-` between the braces, one option is `str_extract`. If there are multiple patterns within a string, use `str_extract_all`
```
library(stringr)
str_extract(str1, '(?<=\\()[0-9-]+(?=\\))')
#[1] "123-456-789"
str_extract_all(str2, '(?<=\\()[0-9-]+(?=\\))')
```
In the above codes, we are using regex lookarounds to extract the numbers and the `-`. The positive lookbehind `(?<=\\()[0-9-]+` matches numbers along with `-` (`[0-9-]+`) in `(123-456-789` and not in `123-456-789`. Similarly the lookahead ('[0-9-]+(?=\)') matches numbers along with `-` in `123-456-789)` and not in `123-456-798`. Taken together it matches all the cases that satisfy both the conditions `(123-456-789)` and extract those in between the lookarounds and not with cases like `(123-456-789` or `123-456-789)`
With `strsplit` you can specify the `split` as `[()]`. We keep the `()` inside the square brackets to `[]` to treat it as characters or else we have to escape the parentheses (`'\\(|\\)'`).
```
strsplit(str1, '[()]')[[1]][2]
#[1] "123-456-789"
```
If there are multiple substrings to extract from a string, we could loop with `lapply` and extract the numeric split parts with `grep`
```
lapply(strsplit(str2, '[()]'), function(x) grep('\\d', x, value=TRUE))
```
Or we can use `stri_split` from `stringi` which has the option to remove the empty strings as well (`omit_empty=TRUE`).
```
library(stringi)
stri_split_regex(str1, '[()A-Z ]', omit_empty=TRUE)[[1]]
#[1] "123-456-789"
stri_split_regex(str2, '[()A-Z ]', omit_empty=TRUE)
```
Another option is `rm_round` from `qdapRegex` if we are interested in extracting the contents inside the brackets.
```
library(qdapRegex)
rm_round(str1, extract=TRUE)[[1]]
#[1] "123-456-789"
rm_round(str2, extract=TRUE)
```
### data
```
str1 <- "A B C (123-456-789)"
str2 <- c("A B C (123-425-478) A", "ABC(123-423-428)",
"(123-423-498) ABCDD",
"(123-432-423)", "ABC (123-423-389) GR (124-233-848) AK")
```
|
You may try these gsub functions.
```
> gsub("[^\\d-]", "", x, perl=T)
[1] "123-456-789"
> gsub(".*\\(|\\)", "", x)
[1] "123-456-789"
> gsub("[^0-9-]", "", x)
[1] "123-456-789"
```
Few more...
```
> gsub("[0-9-](*SKIP)(*F)|.", "", x, perl=T)
[1] "123-456-789"
> gsub("(?:(?![0-9-]).)*", "", x, perl=T)
[1] "123-456-789"
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
or with `sub` from `base R`:
```
sub("[^(]+\\(([^)]+)\\).*", "\\1", "A B C (123-456-789)")
#[1] "123-456-789"
```
Explanation:
`[^(]+` : matches anything except an opening bracket
`\\(` : matches an opening bracket, which is just before what you want
`([^)]+)` : matches the pattern you want to capture (which is then retrieved in `replacement="\\1"`), which is anything except a closing bracket
`\\).*` matches a closing bracket followed by anything, 0 or more times
***Another option with look-ahead and look-behind***
```
sub(".*(?<=\\()(.+)(?=\\)).*", "\\1", "A B C (123-456-789)", perl=TRUE)
#[1] "123-456-789"
```
|
Try this also:
```
k<-"A B C (123-456-789)"
regmatches(k,gregexpr("*.(\\d+).*",k))[[1]]
[1] "(123-456-789)"
```
With suggestion from @Arun:
```
regmatches(k, gregexpr('(?<=\\()[^A-Z ]+(?=\\))', k, perl=TRUE))[[1]]
```
With suggestion from @akrun:
```
regmatches(k, gregexpr('[0-9-]+', k))[[1]]
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
or with `sub` from `base R`:
```
sub("[^(]+\\(([^)]+)\\).*", "\\1", "A B C (123-456-789)")
#[1] "123-456-789"
```
Explanation:
`[^(]+` : matches anything except an opening bracket
`\\(` : matches an opening bracket, which is just before what you want
`([^)]+)` : matches the pattern you want to capture (which is then retrieved in `replacement="\\1"`), which is anything except a closing bracket
`\\).*` matches a closing bracket followed by anything, 0 or more times
***Another option with look-ahead and look-behind***
```
sub(".*(?<=\\()(.+)(?=\\)).*", "\\1", "A B C (123-456-789)", perl=TRUE)
#[1] "123-456-789"
```
|
You may try these gsub functions.
```
> gsub("[^\\d-]", "", x, perl=T)
[1] "123-456-789"
> gsub(".*\\(|\\)", "", x)
[1] "123-456-789"
> gsub("[^0-9-]", "", x)
[1] "123-456-789"
```
Few more...
```
> gsub("[0-9-](*SKIP)(*F)|.", "", x, perl=T)
[1] "123-456-789"
> gsub("(?:(?![0-9-]).)*", "", x, perl=T)
[1] "123-456-789"
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
The capture groups in `sub` will target your desired output:
```
sub('.*\\((.*)\\).*', '\\1', str1)
[1] "123-456-789"
```
Extra check to make sure I pass @akrun's extended example:
```
sub('.*\\((.*)\\).*', '\\1', str2)
[1] "123-425-478" "123-423-428" "123-423-498" "123-432-423" "124-233-848"
```
|
Try this also:
```
k<-"A B C (123-456-789)"
regmatches(k,gregexpr("*.(\\d+).*",k))[[1]]
[1] "(123-456-789)"
```
With suggestion from @Arun:
```
regmatches(k, gregexpr('(?<=\\()[^A-Z ]+(?=\\))', k, perl=TRUE))[[1]]
```
With suggestion from @akrun:
```
regmatches(k, gregexpr('[0-9-]+', k))[[1]]
```
|
31,292,853 |
Suppose I have a string like "A B C (123-456-789)", I'm wondering what's the best way to retrieve "123-456-789" from it.
```
strsplit("A B C (123-456-789)", "\\(")
[[1]]
[1] "A B C" "123-456-789)"
```
|
2015/07/08
|
['https://Stackoverflow.com/questions/31292853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015453/']
|
The capture groups in `sub` will target your desired output:
```
sub('.*\\((.*)\\).*', '\\1', str1)
[1] "123-456-789"
```
Extra check to make sure I pass @akrun's extended example:
```
sub('.*\\((.*)\\).*', '\\1', str2)
[1] "123-425-478" "123-423-428" "123-423-498" "123-432-423" "124-233-848"
```
|
You may try these gsub functions.
```
> gsub("[^\\d-]", "", x, perl=T)
[1] "123-456-789"
> gsub(".*\\(|\\)", "", x)
[1] "123-456-789"
> gsub("[^0-9-]", "", x)
[1] "123-456-789"
```
Few more...
```
> gsub("[0-9-](*SKIP)(*F)|.", "", x, perl=T)
[1] "123-456-789"
> gsub("(?:(?![0-9-]).)*", "", x, perl=T)
[1] "123-456-789"
```
|
345,177 |
Just curious if the time you're stuck in a bury is the same for all attacks that cause you to be buried, or the amount of mashing needed to get out is the same?
Examples include:
* G&W down smash
* KKR's down throw
* DK's side special
* Wii Fit trainer's neutral normal 3-hit combo
* Pitfall items
* etc.
|
2019/01/17
|
['https://gaming.stackexchange.com/questions/345177', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/18916/']
|
If you haven't heard of [Beefy Smash Dudes](https://www.youtube.com/channel/UCeCEq4Sz1nNK4wn3Z4Ozk2w), I highly suggest checking them out. They have some amazing technical Smash content, and they're always my go to for keeping up with new Smash techniques. Not to mention they just [put out a video on Smash Ultimate buries](https://www.youtube.com/watch?v=fWsCApe4e94) 4 days ago!
To sum up, each burying attack has a "base duration." In other words, **not all bury attacks are created equal.** From the video linked above, here are the base bury times (in seconds) for different moves at 0% without mashing:
[](https://i.stack.imgur.com/b2mOH.jpg)
The more percent a buried character has, the longer they'll stay buried. But just from this graphic it's clear that *some* buries are many times more powerful than others (looking at you, Inkling).
Mashing will help to shorten the time, but different mashes will reduce the time different amounts. An input like `A`, `B`, `L` or `X` will reduce bury time by **.25 seconds** or 15 frames. Directional inputs on your control stick on the other hand, reduce the buy by half that of the buttons, or about **.13 seconds** or 8 frames (however, the game only counts the cardinal directions--up/down/left/right--as inputs on the stick). For more on the technicalities of mashing, see [Beefy's Smash 4 mashing video](https://www.youtube.com/watch?v=pwfXtDiQA24), since the mechanic has remained the same in Ultimate.
|
In previous games, bury time is purely based on knockback dealt (as in the amount of knockback that would have been applied if it weren't a bury attack). In Ultimate, it appears to also be based on current damage (though less so). The exact formula isn't known yet.
Each input of mashing reduces bury time by 8 frames.
|
17,735,661 |
I need to parse log files and get some values to variable.
The log file will have a string
```
String logStr = "21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]";
```
I need to get StrValue1,StrValue2,StrValue3,DateValue4 and DateValue5 to varaibles these values are changing fields when ever there is an error.
First i was trying to at least get StrValue1. But not getting the expected result.
```
Pattern twsPattern = Pattern.compile(".*?ID ?[([^]:]*):([^]|]*)|([^]]*)]");//.*ID\\s$.([^]:]*.):.([^]|]*.)|.([^]]*.).]
Matcher twsMatcher = twsPattern.matcher(logStr);
if(twsMatcher.find()){
System.out.println(twsMatcher.start());
System.out.println(twsMatcher.group());
System.out.println(twsMatcher.end());
}
```
I am not able to understand the grouping stuff, in regex.
|
2013/07/18
|
['https://Stackoverflow.com/questions/17735661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713328/']
|
Try regexp `([a-zA-z]+) \[([^\]]+)\]`.
For string `21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]` it returns:
* `ID` and `StrValue1:StrValu2|StrValue3`
* `Instance` and `4053`
* `SetStatus` and `0`
* `AckStatus` and `1`
* `SetTime` and `DateValue4`
* `ClearedTime` and `DateValue5`
You can test it [here](http://fiddle.re/tv12a).
|
I like more general solutions, but here is a very specific pattern you can use if it suits you. It will capture all of the values in a string as long as they are follow the same, very specific pattern.
```
ID (?:\[([^\]:]+):([^\]|]+)\|([^\]]+)\]).*?SetTime \[([^\]]+)\], ClearedTime \[([^\]]+)\]
```
Here is the result:
```
1: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]
[1]: StrValue1
[2]: StrValu2
[3]: StrValue3
[4]: DateValue4
[5]: DateValue5
```
[Try it out](http://rey.gimenez.biz/s/gpqqpzcn)
-----------------------------------------------
**Multiple Matches per line**
This version will just match each instance in a string of ID, SetTime, or ClearedTime followed by a bracketed value.
```
(ID|SetTime|ClearedTime) \[([^\]]+)\
```
Results
```
1: ID [StrValue1:StrValu2|StrValue3]
[1]: ID
[2]: StrValue1:StrValu2|StrValue3
1: SetTime [DateValue4]
[1]: SetTime
[2]: DateValue4
1: ClearedTime [DateValue5]
[1]: ClearedTime
[2]: DateValue5
```
[Try it out](http://rey.gimenez.biz/s/qz9s6fqb)
-----------------------------------------------
|
17,735,661 |
I need to parse log files and get some values to variable.
The log file will have a string
```
String logStr = "21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]";
```
I need to get StrValue1,StrValue2,StrValue3,DateValue4 and DateValue5 to varaibles these values are changing fields when ever there is an error.
First i was trying to at least get StrValue1. But not getting the expected result.
```
Pattern twsPattern = Pattern.compile(".*?ID ?[([^]:]*):([^]|]*)|([^]]*)]");//.*ID\\s$.([^]:]*.):.([^]|]*.)|.([^]]*.).]
Matcher twsMatcher = twsPattern.matcher(logStr);
if(twsMatcher.find()){
System.out.println(twsMatcher.start());
System.out.println(twsMatcher.group());
System.out.println(twsMatcher.end());
}
```
I am not able to understand the grouping stuff, in regex.
|
2013/07/18
|
['https://Stackoverflow.com/questions/17735661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713328/']
|
Good on you for the attempt! You're actually doing quite well. You need to escape square brackets that you don't mean as character classes, *i.e.*
```
.*?ID ?\[
^
```
And hopefully you are aware that by `([^]:]*)` you are meaning, "The longest possible string of characters *without* a closing square bracket or colon."
You probably also want to escape the `|`, as that is an alternation operator in regular expressions, *i.e.*
```
\|
```
|
I like more general solutions, but here is a very specific pattern you can use if it suits you. It will capture all of the values in a string as long as they are follow the same, very specific pattern.
```
ID (?:\[([^\]:]+):([^\]|]+)\|([^\]]+)\]).*?SetTime \[([^\]]+)\], ClearedTime \[([^\]]+)\]
```
Here is the result:
```
1: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]
[1]: StrValue1
[2]: StrValu2
[3]: StrValue3
[4]: DateValue4
[5]: DateValue5
```
[Try it out](http://rey.gimenez.biz/s/gpqqpzcn)
-----------------------------------------------
**Multiple Matches per line**
This version will just match each instance in a string of ID, SetTime, or ClearedTime followed by a bracketed value.
```
(ID|SetTime|ClearedTime) \[([^\]]+)\
```
Results
```
1: ID [StrValue1:StrValu2|StrValue3]
[1]: ID
[2]: StrValue1:StrValu2|StrValue3
1: SetTime [DateValue4]
[1]: SetTime
[2]: DateValue4
1: ClearedTime [DateValue5]
[1]: ClearedTime
[2]: DateValue5
```
[Try it out](http://rey.gimenez.biz/s/qz9s6fqb)
-----------------------------------------------
|
17,735,661 |
I need to parse log files and get some values to variable.
The log file will have a string
```
String logStr = "21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]";
```
I need to get StrValue1,StrValue2,StrValue3,DateValue4 and DateValue5 to varaibles these values are changing fields when ever there is an error.
First i was trying to at least get StrValue1. But not getting the expected result.
```
Pattern twsPattern = Pattern.compile(".*?ID ?[([^]:]*):([^]|]*)|([^]]*)]");//.*ID\\s$.([^]:]*.):.([^]|]*.)|.([^]]*.).]
Matcher twsMatcher = twsPattern.matcher(logStr);
if(twsMatcher.find()){
System.out.println(twsMatcher.start());
System.out.println(twsMatcher.group());
System.out.println(twsMatcher.end());
}
```
I am not able to understand the grouping stuff, in regex.
|
2013/07/18
|
['https://Stackoverflow.com/questions/17735661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713328/']
|
Long story short, your regex lacks escaping some chars, like `[` and `|` (this one, if outside a character class - `[]`).
So when you want to actually match the `[` char, you have to use `\[` (or `\\[` inside the java string). Also, the negation in the group `([^]:]*)` is not what it seems. You probably want just `([^:]*)`, which matches everything until a `:`.
To make it work, then, you would simply use [`Matcher#group(int)`](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28int%29) to retrieve the values. This is the adapted code with the final regex:
```
String logStr = "21:19:03 -[ 8b4]- ERROR - Jhy AlarmOccure::OnAdd - Updated existing alarm: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]";
Pattern twsPattern = Pattern.compile(".*?ID ?\\[([^:]*):([^|]*)\\|([^\\]]*)\\].*?SetTime ?\\[([^\\]]*)\\][^\\[]+\\[([^\\]]*)\\]");
Matcher twsMatcher = twsPattern.matcher(logStr);
if (twsMatcher.find()){
System.out.println(twsMatcher.group(1)); // StrValue1
System.out.println(twsMatcher.group(2)); // StrValu2
System.out.println(twsMatcher.group(3)); // StrValue3
System.out.println(twsMatcher.group(4)); // DateValue4
System.out.println(twsMatcher.group(5)); // DateValue5
}
```
|
I like more general solutions, but here is a very specific pattern you can use if it suits you. It will capture all of the values in a string as long as they are follow the same, very specific pattern.
```
ID (?:\[([^\]:]+):([^\]|]+)\|([^\]]+)\]).*?SetTime \[([^\]]+)\], ClearedTime \[([^\]]+)\]
```
Here is the result:
```
1: ID [StrValue1:StrValu2|StrValue3], Instance [4053], SetStatus [0], AckStatus [1], SetTime [DateValue4], ClearedTime [DateValue5]
[1]: StrValue1
[2]: StrValu2
[3]: StrValue3
[4]: DateValue4
[5]: DateValue5
```
[Try it out](http://rey.gimenez.biz/s/gpqqpzcn)
-----------------------------------------------
**Multiple Matches per line**
This version will just match each instance in a string of ID, SetTime, or ClearedTime followed by a bracketed value.
```
(ID|SetTime|ClearedTime) \[([^\]]+)\
```
Results
```
1: ID [StrValue1:StrValu2|StrValue3]
[1]: ID
[2]: StrValue1:StrValu2|StrValue3
1: SetTime [DateValue4]
[1]: SetTime
[2]: DateValue4
1: ClearedTime [DateValue5]
[1]: ClearedTime
[2]: DateValue5
```
[Try it out](http://rey.gimenez.biz/s/qz9s6fqb)
-----------------------------------------------
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
Ok. Just for anyone wondering
Just uninstalling and reinstalling the packages that were giving the error worked for me
```
pip uninstall matplotlib
pip install matplotlib
```
|
Have you tried uninstalling it and reinstalling the latest python update and restarting you PC/Laptop?
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with:
```
Segmentation fault: 11
```
after updating.
As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib:
```
pip uninstall matplotlib
pip install matplotlib
```
Thank you!
|
Have you tried uninstalling it and reinstalling the latest python update and restarting you PC/Laptop?
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
Ok. Just for anyone wondering
Just uninstalling and reinstalling the packages that were giving the error worked for me
```
pip uninstall matplotlib
pip install matplotlib
```
|
I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with:
```
Segmentation fault: 11
```
after updating.
As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib:
```
pip uninstall matplotlib
pip install matplotlib
```
Thank you!
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
Ok. Just for anyone wondering
Just uninstalling and reinstalling the packages that were giving the error worked for me
```
pip uninstall matplotlib
pip install matplotlib
```
|
I also had the same issue:
**Segmentation fault: 11**
I guess, it is because of the statement line:
**plt.show()**
As stated above, uninstallation and reinstallation of matplotlib worked for me.
Thank you!
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
Ok. Just for anyone wondering
Just uninstalling and reinstalling the packages that were giving the error worked for me
```
pip uninstall matplotlib
pip install matplotlib
```
|
Reinstalling is the best option but you can also use:
```
import matplotlib as mpl
mpl.use('MacOSX')
import numpy as np
import matplotlib.pyplot as plt
```
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
Ok. Just for anyone wondering
Just uninstalling and reinstalling the packages that were giving the error worked for me
```
pip uninstall matplotlib
pip install matplotlib
```
|
i had to drop my dpi from 400 to 50 on the OSX machine. none of these other approaches worked. fwiw, my update was to Catalina, not Big Sur.
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with:
```
Segmentation fault: 11
```
after updating.
As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib:
```
pip uninstall matplotlib
pip install matplotlib
```
Thank you!
|
I also had the same issue:
**Segmentation fault: 11**
I guess, it is because of the statement line:
**plt.show()**
As stated above, uninstallation and reinstallation of matplotlib worked for me.
Thank you!
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with:
```
Segmentation fault: 11
```
after updating.
As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib:
```
pip uninstall matplotlib
pip install matplotlib
```
Thank you!
|
Reinstalling is the best option but you can also use:
```
import matplotlib as mpl
mpl.use('MacOSX')
import numpy as np
import matplotlib.pyplot as plt
```
|
64,841,086 |
I am trying to below file operation using python
input 1: unix shell cat command given below data file name: input1.txt
```
11/13/2020 07:41:09 TREE count1: id1 green001
11/13/2020 07:43:09 TREE count1: id1 black001
11/13/2020 07:45:09 TREE count1: id2 black001
11/13/2020 07:45:09 PLAN count1: id3 green002
```
Lookup data: file name: lookup.csv
```
ID,item,message
id1,item1,message 1
id2,item2,message 2
id3,item3,message 3
```
Need output like: where id field in [id1, id2, id3, etc ..in] input1 lookup in ID filed in lookup table.\
Output.txt
```
Time,Type,counts,id,item,message,colour
11/13/2020 07:41:09,TREE,count1,id1,item1,message 1,green001
11/13/2020 07:43:09,TREE,count1,id1,item1,message 1,black001
11/13/2020 07:45:09,TREE,count1,id2,item2,message 2,black001
11/13/2020 07:45:09,PLAN,count1,id3,item3,message 3,green002
```
I've been trying to use this code, but I am getting errors.
```
r = pandas.read_csv(file1, sep=' ', index_col='ID')
with open('/home/s/lookup.csv','r') as w:
x = pandas.read_csv(w)
# w is not indexable
col = w['ID']
for line in w:
# w is not a table.
for col in w:
for row in r:
if row in col:
print(line)
```
Any advice would be appreciated!
|
2020/11/15
|
['https://Stackoverflow.com/questions/64841086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14632454/']
|
I had the same issue - a Python program that was working fine before updating to Big Sur, and crashing with:
```
Segmentation fault: 11
```
after updating.
As previous responses have advised, just uninstalling and reinstalling the offending Python libraries fixed the problem. For me, that meant matplotlib:
```
pip uninstall matplotlib
pip install matplotlib
```
Thank you!
|
i had to drop my dpi from 400 to 50 on the OSX machine. none of these other approaches worked. fwiw, my update was to Catalina, not Big Sur.
|
23,687,250 |
I have this code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
```
It's the default android app code, except:
```
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
```
`siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`.
I found a similar bug here:
<https://code.google.com/p/android/issues/detail?id=11533>
Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result
---
With the line `if(siteViewer != null)` commented out, this is the logcat:
```
05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM
05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8)
05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main
05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201
05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more
```
Here is `activity_main.xml`:
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.webviewtest.MainActivity"
tools:ignore="MergeRootFrame" />
```
Here is `fragment_main.xml`:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webviewtest.MainActivity$PlaceholderFragment" >
<WebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
```
---
Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`:
```
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
}
```
|
2014/05/15
|
['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']
|
`siteViewer` is `null`, because there is no such element with id = `webView` found at the `activity_main.xml`. Please double check that you've typed it correctly.
|
did you set the permission to access the internet in manifest file?
```
<uses-permission android:name="android.permission.INTERNET" />
```
|
23,687,250 |
I have this code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
```
It's the default android app code, except:
```
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
```
`siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`.
I found a similar bug here:
<https://code.google.com/p/android/issues/detail?id=11533>
Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result
---
With the line `if(siteViewer != null)` commented out, this is the logcat:
```
05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM
05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8)
05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main
05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201
05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more
```
Here is `activity_main.xml`:
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.webviewtest.MainActivity"
tools:ignore="MergeRootFrame" />
```
Here is `fragment_main.xml`:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webviewtest.MainActivity$PlaceholderFragment" >
<WebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
```
---
Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`:
```
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
}
```
|
2014/05/15
|
['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']
|
In your Activity you are inflating main\_layout which doesn't contain a WebView at all. Therefore the findViewById won't find anything and siteViewer is null.
Move your code to load the Url into your fragment.
Since you'r using a PlaceHolderFragment I guess it will be replaced by a real one later. That's the place to put your code. You'll probably inflate your fragment\_main.xml in the fragments onCreateView and then you can load the Url in the fragment's onResume method.
To find the WebView do the following:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) rootView.findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
```
Note the rootView.findViewById(R.id.webView) instead of the simple findViewById(R.id.webView). Fragments don't have a findViewById method but since you'r inflating the layout yourself you can use the View.findViewById.
|
`siteViewer` is `null`, because there is no such element with id = `webView` found at the `activity_main.xml`. Please double check that you've typed it correctly.
|
23,687,250 |
I have this code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
```
It's the default android app code, except:
```
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
```
`siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`.
I found a similar bug here:
<https://code.google.com/p/android/issues/detail?id=11533>
Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result
---
With the line `if(siteViewer != null)` commented out, this is the logcat:
```
05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM
05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8)
05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main
05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201
05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more
```
Here is `activity_main.xml`:
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.webviewtest.MainActivity"
tools:ignore="MergeRootFrame" />
```
Here is `fragment_main.xml`:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webviewtest.MainActivity$PlaceholderFragment" >
<WebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
```
---
Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`:
```
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
}
```
|
2014/05/15
|
['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']
|
I will answer from my knowledge since i didnt know the project heirarchy ...
I) .suppose you have the activity in `package com.another.package` and your project package which is declared in the manifest is `com.main.package` now if you will try to access the webview using `R.id.webView` in package `com.another.package` it wont be available hence you will get null pointer exception so to fix that import com.main.package.R.\*; in the crashing activity.
II). suppose the crashing activity is in the same package `com.main.package` then plz cross check dat whether webview named `webView` is present in the `activity_main`.
III). may be u are casting other layout to webView like `webView` is id of other than webview ( but in this case you wont get null pointer exception just for info).
Hope it helps ... Thx
|
did you set the permission to access the internet in manifest file?
```
<uses-permission android:name="android.permission.INTERNET" />
```
|
23,687,250 |
I have this code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
```
It's the default android app code, except:
```
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
```
`siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`.
I found a similar bug here:
<https://code.google.com/p/android/issues/detail?id=11533>
Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result
---
With the line `if(siteViewer != null)` commented out, this is the logcat:
```
05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM
05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8)
05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main
05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201
05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more
```
Here is `activity_main.xml`:
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.webviewtest.MainActivity"
tools:ignore="MergeRootFrame" />
```
Here is `fragment_main.xml`:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webviewtest.MainActivity$PlaceholderFragment" >
<WebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
```
---
Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`:
```
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
}
```
|
2014/05/15
|
['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']
|
In your Activity you are inflating main\_layout which doesn't contain a WebView at all. Therefore the findViewById won't find anything and siteViewer is null.
Move your code to load the Url into your fragment.
Since you'r using a PlaceHolderFragment I guess it will be replaced by a real one later. That's the place to put your code. You'll probably inflate your fragment\_main.xml in the fragments onCreateView and then you can load the Url in the fragment's onResume method.
To find the WebView do the following:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) rootView.findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
```
Note the rootView.findViewById(R.id.webView) instead of the simple findViewById(R.id.webView). Fragments don't have a findViewById method but since you'r inflating the layout yourself you can use the View.findViewById.
|
did you set the permission to access the internet in manifest file?
```
<uses-permission android:name="android.permission.INTERNET" />
```
|
23,687,250 |
I have this code:
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
```
It's the default android app code, except:
```
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
```
`siteViewer` is always `null`. If I don't use the `if()` statement, the app will crash immediately upon opening, otherwise it just skips `loadURL`.
I found a similar bug here:
<https://code.google.com/p/android/issues/detail?id=11533>
Apparently some OS's don't allow it? I'm running it on 4.4.2 in an emulator. I also tried it on a Motorola Razr with 4.1.2 and I get the same result
---
With the line `if(siteViewer != null)` commented out, this is the logcat:
```
05-15 16:05:35.112: D/AndroidRuntime(1201): Shutting down VM
05-15 16:05:35.112: W/dalvikvm(1201): threadid=1: thread exiting with uncaught exception (group=0xada41ba8)
05-15 16:05:35.142: E/AndroidRuntime(1201): FATAL EXCEPTION: main
05-15 16:05:35.142: E/AndroidRuntime(1201): Process: com.example.webviewtest, PID: 1201
05-15 16:05:35.142: E/AndroidRuntime(1201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webviewtest/com.example.webviewtest.MainActivity}: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 16:05:35.142: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method)
05-15 16:05:35.142: E/AndroidRuntime(1201): Caused by: java.lang.NullPointerException
05-15 16:05:35.142: E/AndroidRuntime(1201): at com.example.webviewtest.MainActivity.onCreate(MainActivity.java:25)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Activity.performCreate(Activity.java:5231)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 16:05:35.142: E/AndroidRuntime(1201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-15 16:05:35.142: E/AndroidRuntime(1201): ... 11 more
```
Here is `activity_main.xml`:
```
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.webviewtest.MainActivity"
tools:ignore="MergeRootFrame" />
```
Here is `fragment_main.xml`:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webviewtest.MainActivity$PlaceholderFragment" >
<WebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
```
---
Following the suggestion given, this is the PlaceHolderFragment code, with the WebView code included, that gives me the error `cannot make a static reference to the non-static method findViewById(int) from the type Activity`:
```
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
}
```
|
2014/05/15
|
['https://Stackoverflow.com/questions/23687250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2016196/']
|
In your Activity you are inflating main\_layout which doesn't contain a WebView at all. Therefore the findViewById won't find anything and siteViewer is null.
Move your code to load the Url into your fragment.
Since you'r using a PlaceHolderFragment I guess it will be replaced by a real one later. That's the place to put your code. You'll probably inflate your fragment\_main.xml in the fragments onCreateView and then you can load the Url in the fragment's onResume method.
To find the WebView do the following:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
WebView siteViewer = (WebView) rootView.findViewById(R.id.webView);
if(siteViewer != null)
siteViewer.loadUrl("http://www.website.com");
return rootView;
}
```
Note the rootView.findViewById(R.id.webView) instead of the simple findViewById(R.id.webView). Fragments don't have a findViewById method but since you'r inflating the layout yourself you can use the View.findViewById.
|
I will answer from my knowledge since i didnt know the project heirarchy ...
I) .suppose you have the activity in `package com.another.package` and your project package which is declared in the manifest is `com.main.package` now if you will try to access the webview using `R.id.webView` in package `com.another.package` it wont be available hence you will get null pointer exception so to fix that import com.main.package.R.\*; in the crashing activity.
II). suppose the crashing activity is in the same package `com.main.package` then plz cross check dat whether webview named `webView` is present in the `activity_main`.
III). may be u are casting other layout to webView like `webView` is id of other than webview ( but in this case you wont get null pointer exception just for info).
Hope it helps ... Thx
|
323,637 |
I would like to understand the best practices regarding nonce validation in REST APIs.
I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest.
That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`?
If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?)
|
2018/12/22
|
['https://wordpress.stackexchange.com/questions/323637', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/27278/']
|
You should pass the special `wp_rest` nonce as part of the request. Without it, the `global $current_user` object will not be available in your REST class. You can pass this from several ways, from $\_GET to $\_POST to headers.
The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using [Basic Auth](https://github.com/WP-API/Basic-Auth), [OAuth2](https://github.com/WP-API/OAuth2), or [JWT](https://github.com/WP-API/jwt-auth) from an external server even without the `wp_rest` nonce, but if you add an action nonce as well, it won't work.
So the action nonce is optional. Add it if you want the endpoint to work locally only.
Example:
```
/**
* First step, registering, localizing and enqueueing the JavaScript
*/
wp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] );
wp_localize_script( 'main-js', 'data', [
'rest' => [
'endpoints' => [
'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ),
],
'timeout' => (int) apply_filters( "my_plugin_rest_timeout", 60 ),
'nonce' => wp_create_nonce( 'wp_rest' ),
//'action_nonce' => wp_create_nonce( 'action_nonce' ),
],
] );
wp_enqueue_script( 'main-js' );
/**
* Second step, the request on the JavaScript file
*/
jQuery(document).on('click', '#some_element', function () {
let ajax_data = {
'some_value': jQuery( ".some_value" ).val(),
//'action_nonce': data.rest.action_nonce
};
jQuery.ajax({
url: data.rest.endpoints.my_endpoint,
method: "GET",
dataType: "json",
timeout: data.rest.timeout,
data: ajax_data,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce);
}
}).done(function (results) {
console.log(results);
alert("Success!");
}).fail(function (xhr) {
console.log(results);
alert("Error!");
});
});
/**
* Third step, the REST endpoint itself
*/
class My_Endpoint {
public function registerRoutes() {
register_rest_route( 'my_plugin', 'v1/my_endpoint', [
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_something' ],
'args' => [
'some_value' => [
'required' => true,
],
],
'permission_callback' => function ( WP_REST_Request $request ) {
return true;
},
] );
}
/**
* @return WP_REST_Response
*/
private function get_something( WP_REST_Request $request ) {
//if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) {
// return false;
//}
$some_value = $request['some_value'];
if ( strlen( $some_value ) < 5 ) {
return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 );
}
// Since we are passing the "X-WP-Nonce" header, this will work:
$user = wp_get_current_user();
if ( $user instanceof WP_User ) {
return new WP_REST_Response( 'Sorry, could not get the name.', 400 );
} else {
return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 );
}
}
}
```
|
Building on what @lucas-bustamante wrote (which helped me a ton!), once you have the X-WP-Nonce header setup in your custom routes you can do the following:
```php
register_rest_route('v1', '/my_post', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'create_post'],
'args' => [
'post_title' => [
'required' => true,
],
'post_excerpt' => [
'required' => true,
]
],
'permission_callback' => function ( ) {
return current_user_can( 'publish_posts' );
},
]);
```
Note that the `permission_callback` is on the root level not under args ([documented here](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback)) and I've removed the additional `nonce` check from `args` since checking the permission alone will fail if the nonce is invalid or not supplied (I've tested this extensively and can confirm I get an error when no nonce is supplied or it's invalid).
|
323,637 |
I would like to understand the best practices regarding nonce validation in REST APIs.
I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest.
That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`?
If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?)
|
2018/12/22
|
['https://wordpress.stackexchange.com/questions/323637', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/27278/']
|
You should pass the special `wp_rest` nonce as part of the request. Without it, the `global $current_user` object will not be available in your REST class. You can pass this from several ways, from $\_GET to $\_POST to headers.
The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using [Basic Auth](https://github.com/WP-API/Basic-Auth), [OAuth2](https://github.com/WP-API/OAuth2), or [JWT](https://github.com/WP-API/jwt-auth) from an external server even without the `wp_rest` nonce, but if you add an action nonce as well, it won't work.
So the action nonce is optional. Add it if you want the endpoint to work locally only.
Example:
```
/**
* First step, registering, localizing and enqueueing the JavaScript
*/
wp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] );
wp_localize_script( 'main-js', 'data', [
'rest' => [
'endpoints' => [
'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ),
],
'timeout' => (int) apply_filters( "my_plugin_rest_timeout", 60 ),
'nonce' => wp_create_nonce( 'wp_rest' ),
//'action_nonce' => wp_create_nonce( 'action_nonce' ),
],
] );
wp_enqueue_script( 'main-js' );
/**
* Second step, the request on the JavaScript file
*/
jQuery(document).on('click', '#some_element', function () {
let ajax_data = {
'some_value': jQuery( ".some_value" ).val(),
//'action_nonce': data.rest.action_nonce
};
jQuery.ajax({
url: data.rest.endpoints.my_endpoint,
method: "GET",
dataType: "json",
timeout: data.rest.timeout,
data: ajax_data,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce);
}
}).done(function (results) {
console.log(results);
alert("Success!");
}).fail(function (xhr) {
console.log(results);
alert("Error!");
});
});
/**
* Third step, the REST endpoint itself
*/
class My_Endpoint {
public function registerRoutes() {
register_rest_route( 'my_plugin', 'v1/my_endpoint', [
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_something' ],
'args' => [
'some_value' => [
'required' => true,
],
],
'permission_callback' => function ( WP_REST_Request $request ) {
return true;
},
] );
}
/**
* @return WP_REST_Response
*/
private function get_something( WP_REST_Request $request ) {
//if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) {
// return false;
//}
$some_value = $request['some_value'];
if ( strlen( $some_value ) < 5 ) {
return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 );
}
// Since we are passing the "X-WP-Nonce" header, this will work:
$user = wp_get_current_user();
if ( $user instanceof WP_User ) {
return new WP_REST_Response( 'Sorry, could not get the name.', 400 );
} else {
return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 );
}
}
}
```
|
One thing to note about @Lucas Bustamante's answer is that the verification process described is user-based authentication. This means if you have an anonymous API end point which doesn't require a user, then by simply by not providing the `X-WP-NONCE` header you'll pass the described nonce check. Supplying an incorrect nonce will still throw an error.
The reason for this is that the `rest_cookie_check_errors` which is what does the verification will simply set the `current_user` to empty if no nonce is provided. This works fine when a user is required, but not otherwise. (see: <https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/>)
If you want to expand on Lucas' answer to also include annonymous end points, then you can add a manual nonce check to the start of your end point, like this:
```
if ( !$_SERVER['HTTP_X_WP_NONCE'] || !wp_verify_nonce( $_SERVER['HTTP_X_WP_NONCE'], 'wp_rest' ) ) {
header('HTTP/1.0 403 Forbidden');
exit;
}
```
|
323,637 |
I would like to understand the best practices regarding nonce validation in REST APIs.
I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest.
That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`?
If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?)
|
2018/12/22
|
['https://wordpress.stackexchange.com/questions/323637', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/27278/']
|
Building on what @lucas-bustamante wrote (which helped me a ton!), once you have the X-WP-Nonce header setup in your custom routes you can do the following:
```php
register_rest_route('v1', '/my_post', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'create_post'],
'args' => [
'post_title' => [
'required' => true,
],
'post_excerpt' => [
'required' => true,
]
],
'permission_callback' => function ( ) {
return current_user_can( 'publish_posts' );
},
]);
```
Note that the `permission_callback` is on the root level not under args ([documented here](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback)) and I've removed the additional `nonce` check from `args` since checking the permission alone will fail if the nonce is invalid or not supplied (I've tested this extensively and can confirm I get an error when no nonce is supplied or it's invalid).
|
One thing to note about @Lucas Bustamante's answer is that the verification process described is user-based authentication. This means if you have an anonymous API end point which doesn't require a user, then by simply by not providing the `X-WP-NONCE` header you'll pass the described nonce check. Supplying an incorrect nonce will still throw an error.
The reason for this is that the `rest_cookie_check_errors` which is what does the verification will simply set the `current_user` to empty if no nonce is provided. This works fine when a user is required, but not otherwise. (see: <https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/>)
If you want to expand on Lucas' answer to also include annonymous end points, then you can add a manual nonce check to the start of your end point, like this:
```
if ( !$_SERVER['HTTP_X_WP_NONCE'] || !wp_verify_nonce( $_SERVER['HTTP_X_WP_NONCE'], 'wp_rest' ) ) {
header('HTTP/1.0 403 Forbidden');
exit;
}
```
|
16,801,403 |
I'm looking for information/documentation on creating a custom icon for a document type in my iOS app. I am sure I have seen some Apple developer guide with information about this, but I have been searching and cannot find it!
In the app's Info.plist I have specified a custom document type, and a corresponding exported UTI (conforming to com.apple.package). Xcode makes it quite easy to specify images for these under the "Info" tab of the target settings, but I can't find the information regarding what sizes they should be, or in what situations the document icon will be visible. I believe that iOS automatically creates a 'default' document icon for you using the app icon (as per [this section](http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW15) of the HIG), so if I made it possible for users to share the document via email, another user with the app installed on their iOS device would see this default document icon.
Where else might this document icon be seen? Currently in iTunes file sharing the document appears as a directory with the custom file extension - presumably this would change if an icon was specified for the document? When viewing one of the documents in the OS X file system, it appears as a standard white document (i.e. looks like an unknown file type) - is there any way for this to appear with the proper icon, or would the user need a Mac app installed that specifies such a file type?
|
2013/05/28
|
['https://Stackoverflow.com/questions/16801403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/429427/']
|
You already found the HIG documentation. I'm not certain if document icons show up in iTunes, but I doubt it. I've never seen this from any other app.
From the [Information Property List Key Reference](https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-SW9) (search for "Document Icons"):
**Document Icons**
>
> In iOS, the `CFBundleTypeIconFiles` key contains an array of strings with the names of the image files to use for the document icon. Table 3 lists the icon sizes you can include for each device type. You can name the image files however you want but the file names in your `Info.plist` file must match the image resource filenames exactly. (For iPhone and iPod touch, the usable area of your icon is actually much smaller.) For more information on how to create these icons, see *iOS Human Interface Guidelines*.
>
>
>
**Table 3** Document icon sizes for iOS
```
+-----------------------+----------------------------------+
| Device | Sizes |
+-----------------------+----------------------------------+
| iPad | 64 x 64 pixels |
| | 320 x 320 pixels |
+-----------------------+----------------------------------+
| iPhone and iPod touch | 22 x 29 pixels |
| | 44 x 58 pixels (high resolution) |
+-----------------------+----------------------------------+
```
|
Thanks @TomSwift for your answer help me a lot. I just add this if you have Xcode 6.3.2.
You can not add icon files drag and drop or press "+" button inside info section, instead you must add the icon files names directly info.plist 
You must add the fours icons as image above.
Then you can see the icon inside Document Types.

|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it.
Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render.
```
React.useEffect(() => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}, [])
```
I have found the below codesandbox example online which demonstrates the above two behaviour.
<https://codesandbox.io/s/402pn5l989>
If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb.
In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching.
However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.
|
**REACT 18 UPDATE**
-------------------
With React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like.
Source: [React 18 Batching](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching)
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it.
Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render.
```
React.useEffect(() => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}, [])
```
I have found the below codesandbox example online which demonstrates the above two behaviour.
<https://codesandbox.io/s/402pn5l989>
If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb.
In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching.
However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.
|
You can merge all states into one
```
function usePolicyFormRequirements(policy) {
const [values, setValues] = useState({
addresses: [],
pools: [],
schedules: [],
services: [],
tunnels: [],
zones: [],
groups: [],
advancedServices: [],
profiles: [],
});
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(newValues) => setValues({ ...newValues }));
}, [policy]);
return values;
}
```
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
I thought I'd post this answer here since it hasn't already been mentioned.
There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not.
```
import React, { useState, useEffect} from 'react'
import {unstable_batchedUpdates} from 'react-dom'
export default function SingleRender() {
const [A, setA] = useState(0)
const [B, setB] = useState(0)
const [C, setC] = useState(0)
const setValues = () => {
unstable_batchedUpdates(() => {
setA(5)
setB(6)
setC(7)
})
}
useEffect(() => {
setValues()
}, [])
return (
<div>
<h2>{A}</h2>
<h2>{B}</h2>
<h2>{C}</h2>
</div>
)
}
```
While the name "unstable" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.
|
You can merge all states into one
```
function usePolicyFormRequirements(policy) {
const [values, setValues] = useState({
addresses: [],
pools: [],
schedules: [],
services: [],
tunnels: [],
zones: [],
groups: [],
advancedServices: [],
profiles: [],
});
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(newValues) => setValues({ ...newValues }));
}, [policy]);
return values;
}
```
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it.
Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render.
```
React.useEffect(() => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}, [])
```
I have found the below codesandbox example online which demonstrates the above two behaviour.
<https://codesandbox.io/s/402pn5l989>
If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb.
In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching.
However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.
|
>
> Isn't there any way I could tell React, or React would know itself, that, after this setState another setState is coming along, so skip re-render until you find a second to breath.
>
>
>
You can't, React batches (as for React 17) state updates only on event handlers and lifecycle methods, therefore batching in promise like it your case is not possible.
To solve it, you need to reduce the hook state to a single source.
From React 18 you have [automatic batching even in promises](https://github.com/reactwg/react-18/discussions/21).
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
I thought I'd post this answer here since it hasn't already been mentioned.
There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not.
```
import React, { useState, useEffect} from 'react'
import {unstable_batchedUpdates} from 'react-dom'
export default function SingleRender() {
const [A, setA] = useState(0)
const [B, setB] = useState(0)
const [C, setC] = useState(0)
const setValues = () => {
unstable_batchedUpdates(() => {
setA(5)
setB(6)
setC(7)
})
}
useEffect(() => {
setValues()
}, [])
return (
<div>
<h2>{A}</h2>
<h2>{B}</h2>
<h2>{C}</h2>
</div>
)
}
```
While the name "unstable" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.
|
>
> Isn't there any way I could tell React, or React would know itself, that, after this setState another setState is coming along, so skip re-render until you find a second to breath.
>
>
>
You can't, React batches (as for React 17) state updates only on event handlers and lifecycle methods, therefore batching in promise like it your case is not possible.
To solve it, you need to reduce the hook state to a single source.
From React 18 you have [automatic batching even in promises](https://github.com/reactwg/react-18/discussions/21).
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it.
Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render.
```
React.useEffect(() => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}, [])
```
I have found the below codesandbox example online which demonstrates the above two behaviour.
<https://codesandbox.io/s/402pn5l989>
If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb.
In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching.
However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.
|
By the way, I just found out React 18 adds automatic update-batching out of the box. Read more: <https://github.com/reactwg/react-18/discussions/21>
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
I thought I'd post this answer here since it hasn't already been mentioned.
There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not.
```
import React, { useState, useEffect} from 'react'
import {unstable_batchedUpdates} from 'react-dom'
export default function SingleRender() {
const [A, setA] = useState(0)
const [B, setB] = useState(0)
const [C, setC] = useState(0)
const setValues = () => {
unstable_batchedUpdates(() => {
setA(5)
setB(6)
setC(7)
})
}
useEffect(() => {
setValues()
}, [])
return (
<div>
<h2>{A}</h2>
<h2>{B}</h2>
<h2>{C}</h2>
</div>
)
}
```
While the name "unstable" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.
|
By the way, I just found out React 18 adds automatic update-batching out of the box. Read more: <https://github.com/reactwg/react-18/discussions/21>
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
I thought I'd post this answer here since it hasn't already been mentioned.
There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not.
```
import React, { useState, useEffect} from 'react'
import {unstable_batchedUpdates} from 'react-dom'
export default function SingleRender() {
const [A, setA] = useState(0)
const [B, setB] = useState(0)
const [C, setC] = useState(0)
const setValues = () => {
unstable_batchedUpdates(() => {
setA(5)
setB(6)
setC(7)
})
}
useEffect(() => {
setValues()
}, [])
return (
<div>
<h2>{A}</h2>
<h2>{B}</h2>
<h2>{C}</h2>
</div>
)
}
```
While the name "unstable" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.
|
If the state changes are triggered asynchronously, `React` will not batch your multiple state updates. For eg, in your case since you are calling setState after resolving policiesService.getPolicyFormRequirements(policy), react won't be batching it.
Instead if it is just the following way, React would have batched the setState calls and in this case there would be only 1 re-render.
```
React.useEffect(() => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}, [])
```
I have found the below codesandbox example online which demonstrates the above two behaviour.
<https://codesandbox.io/s/402pn5l989>
If you look at the console, when you hit the button “with promise”, it will first show a aa and b b, then a aa and b bb.
In this case, it will not render aa - bb right away, each state change triggers a new render, there is no batching.
However, when you click the button “without promise”, the console will show a aa and b bb right away. So in this case, React does batch the state changes and does one render for both together.
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
You can merge all states into one
```
function usePolicyFormRequirements(policy) {
const [values, setValues] = useState({
addresses: [],
pools: [],
schedules: [],
services: [],
tunnels: [],
zones: [],
groups: [],
advancedServices: [],
profiles: [],
});
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(newValues) => setValues({ ...newValues }));
}, [policy]);
return values;
}
```
|
**REACT 18 UPDATE**
-------------------
With React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like.
Source: [React 18 Batching](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching)
|
59,163,378 |
Suppose I have the following code: (which is too verbose)
```
function usePolicyFormRequirements(policy) {
const [addresses, setAddresses] = React.useState([]);
const [pools, setPools] = React.useState([]);
const [schedules, setSchedules] = React.useState([]);
const [services, setServices] = React.useState([]);
const [tunnels, setTunnels] = React.useState([]);
const [zones, setZones] = React.useState([]);
const [groups, setGroups] = React.useState([]);
const [advancedServices, setAdvancedServices] = React.useState([]);
const [profiles, setProfiles] = React.useState([]);
React.useEffect(() => {
policiesService
.getPolicyFormRequirements(policy)
.then(
({
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
}) => {
setAddresses(addresses);
setPools(pools);
setSchedules(schedules);
setServices(services);
setTunnels(tunnels);
setZones(zones);
setGroups(groups);
setAdvancedServices(advancedServices);
setProfiles(profiles);
}
);
}, [policy]);
return {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
};
}
```
When I use this custom Hook inside of my function component, after `getPolicyFormRequirements` resolves, my function component re-renders `9` times (the count of all entities that I call `setState` on)
I know the solution to this particular use case would be to aggregate them into one state and call `setState` on it once, but as I remember (correct me, if I'm wrong) on event handlers (e.g. `onClick`) if you call multiple consecutive `setState`s, only one re-render occurs after event handler finishes executing.
**Isn't there any way I could tell `React`, or `React` would know itself, that, after this `setState` another `setState` is coming along, so skip re-render until you find a second to breath.**
I'm not looking for performance-optimization tips, I'm looking to know the answer to the above (**Bold**) question!
Or do you think I am thinking wrong?
Thanks!
--------------
--------------
---
**UPDATE**
How I checked my component rendered 9 times?
```
export default function PolicyForm({ onSubmit, policy }) {
const [formState, setFormState, formIsValid] = usePgForm();
const {
addresses,
pools,
schedules,
services,
tunnels,
zones,
groups,
advancedServices,
profiles,
actions,
rejects,
differentiatedServices,
packetTypes,
} = usePolicyFormRequirements(policy);
console.log(' --- re-rendering'); // count of this
return <></>;
}
```
|
2019/12/03
|
['https://Stackoverflow.com/questions/59163378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908277/']
|
I thought I'd post this answer here since it hasn't already been mentioned.
There is a way to force the batching of state updates. See [this article](https://blog.logrocket.com/simplifying-state-management-in-react-apps-with-batched-updates/) for an explanation. Below is a fully functional component that only renders once, regardless of whether the setValues function is async or not.
```
import React, { useState, useEffect} from 'react'
import {unstable_batchedUpdates} from 'react-dom'
export default function SingleRender() {
const [A, setA] = useState(0)
const [B, setB] = useState(0)
const [C, setC] = useState(0)
const setValues = () => {
unstable_batchedUpdates(() => {
setA(5)
setB(6)
setC(7)
})
}
useEffect(() => {
setValues()
}, [])
return (
<div>
<h2>{A}</h2>
<h2>{B}</h2>
<h2>{C}</h2>
</div>
)
}
```
While the name "unstable" might be concerning, the React team has previously recommended the use of this API where appropriate, and I have found it very useful to cut down on the number of renders without clogging up my code.
|
**REACT 18 UPDATE**
-------------------
With React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like.
Source: [React 18 Batching](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching)
|
69,247,371 |
devs, I'm trying to deploy a simple cloud function to the firebase console, everything working very well (installation of npm & configuration & other stuff...).
then I wrote a simple function in the **index.js** file :
```
'use strict'
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notififcation/{user_id}/{notififcation_id}').onWrite(
event =>
{
const user_id = event.params.user_id;
const notififcation_id = event.params.notififcation_id;
console.log('this id is the ' , user_id);
}
):
```
then, when I wanna deploy it to firebase with this command **firebase deploy**, This error keeps appearing,
this is the error :
---
```
C:\Users\nasro\Desktop\oussamaproject\notifyfun\functions\index.js
14:2 error Parsing error: Unexpected token :
? 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional l
ging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\nasro\AppData\Roaming\npm-cache\_logs\2021-09-19T21_28_2
892Z-debug.log
events.js:292
throw er; // Unhandled 'error' event
^
Error: spawn npm --prefix "C:\Users\nasro\Desktop\oussamaproject\notifyfun\fun
ions" run lint ENOENT
at notFoundError (C:\Users\nasro\AppData\Roaming\npm\node_modules\firebase
ools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
at verifyENOENT (C:\Users\nasro\AppData\Roaming\npm\node_modules\firebase-
ols\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
at ChildProcess.cp.emit (C:\Users\nasro\AppData\Roaming\npm\node_modules\f
ebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:2
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess.cp.emit (C:\Users\nasro\AppData\Roaming\npm\node_modules\f
ebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:3
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn npm --prefix "C:\\Users\\nasro\\Desktop\\oussamaproject\\not
yfun\\functions" run lint',
path: 'npm --prefix "C:\\Users\\nasro\\Desktop\\oussamaproject\\notifyfun\\f
ctions" run lint',
spawnargs: []
}
Error: functions predeploy error: Command terminated with non-zero exit code1
```
so after searching for a solution in firebase documentation and articles, I tried those solutions
**solution one:**
in **firebase.json** by default:
```
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
]
```
i Modified it to:
```
"predeploy": [
"npm --prefix \"%RESOURCE_DIR%\" run lint"
]
```
the error keeps appearing again with the same error message, so I tried solution 2
**Solution two**
I modified again the file **firebase.json** to :
```
"predeploy": [
"npm --prefix \"%RESOURCE_DIR%\" run lint",
"npm --prefix \"%RESOURCE_DIR%\" run build"
]
```
and the error keeps appearing again and again with the same error message (**btw** I'm using windows7)
So any solution or suggestions for this error ..
|
2021/09/19
|
['https://Stackoverflow.com/questions/69247371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15094547/']
|
try this
```
List<decimal> prices = new List<decimal>();
decimal price=0;
int count=0;
do
{
count++;
Console.WriteLine("Item {0}", count);
Console.WriteLine(" Enter Price: $ ");
price = Convert.ToDecimal(Console.ReadLine());
prices.Add(price);
} while ( price != -1);
Console.WriteLine ("Price history:");
foreach(var item in prices)
{
Console.WriteLine(item.ToString());
}
```
|
I would store your prices in a dictionary as to ensure that prices for the same item have not been added. Here is a fiddle with an example: <https://dotnetfiddle.net/uZQqDp>
```
public static void Main()
{
Dictionary<int, decimal> prices = new Dictionary<int, decimal>();
int count = 0;
bool finished = false;
do
{
Console.Write("Item {0}:\tEnter Price: $", count);
var price = Console.ReadLine();
var convertedPrice = Convert.ToDecimal(price);
if(convertedPrice != -1)
{
prices.Add(count, convertedPrice);
count++;
}
else
{
finished = true;
}
} while(!finished);
Console.WriteLine("Price History");
foreach(var price in prices)
{
Console.WriteLine("Item {0}:\tPrice: ${1}", price.Key, price.Value);
}
}
```
|
8,074,168 |
I am basically trying to convert a string similar to this one: "`2011-11-9 18:24:12.3`" into a format that I can insert into a database table claiming this particular column to be of the "datetime" type. I figured I could do something along the lines of `preparedStatement.setTimestamp(...)`, but I can't seem to get a Timestamp created correctly. Can anyone suggest the easiest way to convert a string like the one above to either a Timestamp or some other type which is compatible with MySQL's "datetime" type? Any help would be appreciated.
Thus far, I've tried doing something like this:
```
String strDateTime = "2011-11-9 18:24:12.3";
Timestamp timeStamp = new Timestamp((new Date(strDateTime)).getTime());
preparedStatement.setTimestamp(1, timeStamp);
```
|
2011/11/10
|
['https://Stackoverflow.com/questions/8074168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967968/']
|
Ah, so, the problem is most likely not with the datetime of mysql but with the date.
The `Date(Strings s)` constructor is [currently deprecated](http://download.oracle.com/javase/6/docs/api/java/util/Date.html#Date%28java.lang.String%29) and is recommended to use a [SimpleDateFormat](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) which would let you use any format you want.
|
Have you tried splitting and making it into a format you can use? This assumes that this is in the same format all the time. Create a new string that takes apart a split of the old string and rearranges it in a useful way. If this is a string provided by the end-user, you may have to validate it first and check to make sure it is usable.
|
56,815,600 |
I am using POM in automation and in the test I have 3 classes. let's say `test1, test2 and test3`
tester is providing a class name in property file so if tester provide like `test1` in a property file, I have put conditions in java code to run class based on what tester provide in property file.
But now I want to set up the same thing from Jenkins using a single build. I do not want to create 3 builds for 3 classes, So if in property file tester provide value `test1`, it should run class `test1` from jenkins.
I did check for conditional build steps but seems could not satisfy my need.
|
2019/06/29
|
['https://Stackoverflow.com/questions/56815600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4213132/']
|
Using the `includeFile` property of the Maven surefire plugin, you can explicitly say which Test classes should be run. You can provide this file from the command line (e.g. in Jenkins) by using an expression like `-Dsurefire.includesFile={yourfile}`.
|
You can proceed as before and let the tester provide the test class names in a file. That file is either already available on your system, or it can be uploaded by the tester when the Jenkins job builds. For that you have to parameterize the Jenkins job, and define a file upload parameter. See [Jenkins Wiki](https://wiki.jenkins.io/plugins/servlet/mobile?contentId=34930782#content/view/34930782) for a start point, and these two Stackoverflow questions: [How to upload a generic file into a Jenkins job?](https://stackoverflow.com/questions/27491789/how-to-upload-a-generic-file-into-a-jenkins-job) and [How to use file parameter in jenkins](https://stackoverflow.com/questions/42224691/how-to-use-file-parameter-in-jenkins/42242113)
Now, this file upload is tedious for the testers. Why not change the job parameter to a input field respectively a text field, and provide at job build the tests class names as comma separated string respectively multi line text?
|
32,862,638 |
Is there a `MIN` constant for `datetime`?
I need it to represent the expiration date of a resource, and I want to have a `datetime` that represents "always expires" as default value (instead of `None` so I can use the same expiration comparison no matter what).
So right now I'm using `datetime.datetime(datetime.MINYEAR,1,1,0,0,tzusc())` as my `MIN datetime` but I wonder if there is some other way to represents "the lowest possible time" (even if it's not a `datetime`).
|
2015/09/30
|
['https://Stackoverflow.com/questions/32862638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90580/']
|
You can try - [`datetime.datetime.min`](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) . According to [documentation](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) -
>
> **`datetime.min`**
>
>
> The earliest representable datetime, datetime(MINYEAR, 1, 1, tzinfo=None).
>
>
>
|
You could use `time.gmtime(0)` which is the epoch.
[Time Documentation](https://docs.python.org/2/library/time.html)
>
> The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the “time since the epoch” is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0).
>
>
>
|
32,862,638 |
Is there a `MIN` constant for `datetime`?
I need it to represent the expiration date of a resource, and I want to have a `datetime` that represents "always expires" as default value (instead of `None` so I can use the same expiration comparison no matter what).
So right now I'm using `datetime.datetime(datetime.MINYEAR,1,1,0,0,tzusc())` as my `MIN datetime` but I wonder if there is some other way to represents "the lowest possible time" (even if it's not a `datetime`).
|
2015/09/30
|
['https://Stackoverflow.com/questions/32862638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90580/']
|
You can try - [`datetime.datetime.min`](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) . According to [documentation](https://docs.python.org/2/library/datetime.html#datetime.datetime.min) -
>
> **`datetime.min`**
>
>
> The earliest representable datetime, datetime(MINYEAR, 1, 1, tzinfo=None).
>
>
>
|
`datetime.datetime.fromtimestamp(0)` it will gives you:
```
datetime.datetime(1970, 1, 1, 1, 0)
```
>
> Return the local date corresponding to the POSIX timestamp, such as is
> returned by time.time(). This may raise ValueError, if the timestamp
> is out of the range of values supported by the platform C localtime()
> function. It’s common for this to be restricted to years from 1970
> through 2038. Note that on non-POSIX systems that include leap seconds
> in their notion of a timestamp, leap seconds are ignored by
> fromtimestamp().
>
>
>
|
63,563 |
I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two.
Thanks
|
2011/09/11
|
['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
|
a one to one function can be injective or bijective but a one to one correspondence can only be bijective
|
I would say (hand waveingly) a one to one function is a mapping from A to B that puts A & B into one-to-one correspondence with each other, for one to one and function as defined in your previous questions.
|
63,563 |
I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two.
Thanks
|
2011/09/11
|
['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
|
Hope this helps you understand things a bit better. I too had the same question a while ago...
**Types of Mappings/Functions**
a. **Injective mapping (injection)**: **one-to-one mapping** = is a function that preserves distinctness: it never maps distinct elements of its domain to the same element of its codomain.
b. **Surjection**: onto mapping = a function f from a set X to a set Y is surjective (or onto), or a surjection, if for every element y in the codomain Y of f there is at least one element x in the domain X of f such that f(x) = y. It is not required that x be unique; the function f may map one or more elements of X to the same element of Y.
c. **Bijective mapping (bijection)**: one-to-one and onto mapping = **one-to-one correspondence**
[NOTE: bijectivity (one-to-one **correspondence**) is a necessary condition for functions to have inverses, whereas injectivity (one-to-one **mapping**) solely will not help in guaranteeing inverses].
[](https://i.stack.imgur.com/QdE2r.png)
|
I would say (hand waveingly) a one to one function is a mapping from A to B that puts A & B into one-to-one correspondence with each other, for one to one and function as defined in your previous questions.
|
63,563 |
I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two.
Thanks
|
2011/09/11
|
['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
|
I would say (hand waveingly) a one to one function is a mapping from A to B that puts A & B into one-to-one correspondence with each other, for one to one and function as defined in your previous questions.
|
1. one to one means injective (a mapping $f$ which maps distinct
elements of its domain to distinct elements of its codomain, i.e. $f(x) \neq f(y)$
whenever $x \neq y$ )
2. one to one correspondence means bijective (a mapping $f$ which is injective AND for every element $y$ in the codomain of $f$, there exists an element of $x$ in the domain of $f$ such that $f(x) = y$ )
|
63,563 |
I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two.
Thanks
|
2011/09/11
|
['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
|
a one to one function can be injective or bijective but a one to one correspondence can only be bijective
|
1. one to one means injective (a mapping $f$ which maps distinct
elements of its domain to distinct elements of its codomain, i.e. $f(x) \neq f(y)$
whenever $x \neq y$ )
2. one to one correspondence means bijective (a mapping $f$ which is injective AND for every element $y$ in the codomain of $f$, there exists an element of $x$ in the domain of $f$ such that $f(x) = y$ )
|
63,563 |
I am confused in the difference between one to one function and one to one correspondence. Please help me out to distinguish between the two.
Thanks
|
2011/09/11
|
['https://math.stackexchange.com/questions/63563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']
|
Hope this helps you understand things a bit better. I too had the same question a while ago...
**Types of Mappings/Functions**
a. **Injective mapping (injection)**: **one-to-one mapping** = is a function that preserves distinctness: it never maps distinct elements of its domain to the same element of its codomain.
b. **Surjection**: onto mapping = a function f from a set X to a set Y is surjective (or onto), or a surjection, if for every element y in the codomain Y of f there is at least one element x in the domain X of f such that f(x) = y. It is not required that x be unique; the function f may map one or more elements of X to the same element of Y.
c. **Bijective mapping (bijection)**: one-to-one and onto mapping = **one-to-one correspondence**
[NOTE: bijectivity (one-to-one **correspondence**) is a necessary condition for functions to have inverses, whereas injectivity (one-to-one **mapping**) solely will not help in guaranteeing inverses].
[](https://i.stack.imgur.com/QdE2r.png)
|
1. one to one means injective (a mapping $f$ which maps distinct
elements of its domain to distinct elements of its codomain, i.e. $f(x) \neq f(y)$
whenever $x \neq y$ )
2. one to one correspondence means bijective (a mapping $f$ which is injective AND for every element $y$ in the codomain of $f$, there exists an element of $x$ in the domain of $f$ such that $f(x) = y$ )
|
145,334 |
One of the players of the oneshot campaign that I'm writing chose the feat **Pierce Magical Concealment** (Complete Arcane, p.81), as a DM I'm not sure how it would work in an encounter I am planning.
The manual states about the Pierce Magical Concealment feat:
>
> You ignore the miss chance provided by certain magical effects.
>
>
> Your fierce contempt for magic allows you to disregard the miss chance granted by spells or spell-like abilities such as *darkness*, *blur*, *invisibility*, *obscuring mist*, *ghostform* (see page 109), and spells when used to create concealment effects (such as a wizard using *permanent image* to fill a corridor with illusory fire and smoke). In addition, when facing a creature protected by *mirror image*, you can immediately pick out the real creature from its figments. Your ability to ignore the miss chance granted by magical concealment doesn't grant you any ability to ignore nonmagical concealment (so you would still have a 20% miss chance against an invisible creature hiding in fog, for example).
>
>
>
This doesn't specify if a character with this feat can actually **see** an enemy that is, for example, under the effect of the spell **Invisibility** (Player's Handbook, p. 245).
I am planning an encounter in which the party will be invited by a wizard for dinner, an assassin under the effect of invisibility will pretend to be an **Unseen Servant** (Player's Handbook, p. 297) until the wizard gives him the signal to attack the party.
Will the character that has the **Pierce Magical Concealment** feat be able to see the assassin, or at least have any advantage in noticing he is not an Unseen Servant?
|
2019/04/17
|
['https://rpg.stackexchange.com/questions/145334', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/51527/']
|
The feat indeed doesn't specify if the character can or cannot see its target and the final decision would be up to the GM. However we still have some pieces of information to use to try to find a more satisfying answer.
If you proceed logically, the 50% miss chance when attacking an invisible target results from the Total Concealment, which implies that the character doesn't attack directly the creature, but the square it occupies :
>
> You can’t attack an opponent that has total concealment, though you
> can attack into a square that you think he occupies. A successful
> attack into a square occupied by an enemy with total concealment has a
> 50% miss chance
>
>
>
Therefore ignoring these 50% miss chance would imply that the character doesn't attack the square anymore but directly the creature and so has a way to distinguish it. Note that being able to distinguish the invisible creature doesn't necessarily involve that it can see it properly. For your example, the character could be able to see the assassin as a shapeless form, being enough to target it if he wants to attack him, but not enough to be able to say if it really is an Unseen servant or not (especially as the Unseen servant is described as a *shapeless force*).
By this way, you can create a clear difference between this feat and other features that are clearly designed to allow to see the invisible like the See Invisibility spell, avoiding to make such features obsolete because of this feat.
|
No.
You can negate the miss chance for concealment, but that doesn't mean you can see invisibility. It is not explained how this works, so there is no textual basis for believing you could distinguish between an unseen servant and an assassin. Perhaps you can see a glowing interface layer, perhaps there is some distortion at the creature boundary, perhaps you're mildly precognitive.
On the other hand, you probably do need opposed disguise/spot checks for the assassin to imitate an invisible stalker (likely with a very large bonus for the assassin). Were I running that game, I would be inclined to allow a generic circumstance bonus to those spot checks for the ability to Pierce Magical Concealment.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.