qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
15,481,759 |
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this -
```js
data: {
user_id: 1,
taskid: "1234",
list: {
"item-1": { one: 1, two: 2 },
"item-2": { one: 1, two: 2 }
//.. where number of items is unknown
}
}
```
I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way
```
public class Data {
public int user_id { get; set; }
public string taskid { get; set; }
public List<object> list { get; set; }
}
public class DataList {
List<Data> data { get; set; }
}
// if isPost etc..
var decodedData = JSON.Decode<DataList>(Request["data"])
```
But when I try and iterate over decodedData I am getting an error -
>
> foreach statement cannot operate on variables of type
> 'ASP.\_Page\_that\_cshtml.DataList' because
> 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition
> for 'GetEnumerator'
>
>
>
When I try casting the decodedData to a List this way -
```
List<Data> decodedData = JSON.Decode<DataList>(Request["data"])
```
I throw another error
>
> CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`'
>
>
>
Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it?
PS: trailing semi-colons omitted on-purpose
|
2013/03/18
|
[
"https://Stackoverflow.com/questions/15481759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95055/"
] |
Your example is not [valid json](http://jsonlint.com/). You should have a collection `[]` for list:
```
data: {
"user_id": 1,
"taskid": "1234",
"list": [
{
"one": 1,
"two": 2
},
{
"one": 1,
"two": 2
}
]
}
```
|
You can try decoding the JSON into an array of Data objects, and then calling the ToList() extension method on that array.
```
var dataArray = JSON.Decode<Data[]>(Request["data"]);
var list = dataArray.ToList();
```
|
15,481,759 |
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this -
```js
data: {
user_id: 1,
taskid: "1234",
list: {
"item-1": { one: 1, two: 2 },
"item-2": { one: 1, two: 2 }
//.. where number of items is unknown
}
}
```
I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way
```
public class Data {
public int user_id { get; set; }
public string taskid { get; set; }
public List<object> list { get; set; }
}
public class DataList {
List<Data> data { get; set; }
}
// if isPost etc..
var decodedData = JSON.Decode<DataList>(Request["data"])
```
But when I try and iterate over decodedData I am getting an error -
>
> foreach statement cannot operate on variables of type
> 'ASP.\_Page\_that\_cshtml.DataList' because
> 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition
> for 'GetEnumerator'
>
>
>
When I try casting the decodedData to a List this way -
```
List<Data> decodedData = JSON.Decode<DataList>(Request["data"])
```
I throw another error
>
> CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`'
>
>
>
Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it?
PS: trailing semi-colons omitted on-purpose
|
2013/03/18
|
[
"https://Stackoverflow.com/questions/15481759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95055/"
] |
```
List<Data> decodedData = JSON.Decode<DataList>(Request["data"])
```
Should Be
```
var decodedData = JSON.Decode<List<Data>>(Request["data"])
var myDataList = new DataList() { data = decodedData; }
```
|
The first error you are getting is quite right, your class `DataList` does not contain a definition for `GetEnumerator` which is required for a foreach statement. You will need to iterate over the property, so iterate over decodedData.data.
The second error is again correct, as you are trying to cast DataList to a type of List, something C# has no idea how to do. You would again need to create your DataList, then set the property data to the type List.
|
15,481,759 |
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this -
```js
data: {
user_id: 1,
taskid: "1234",
list: {
"item-1": { one: 1, two: 2 },
"item-2": { one: 1, two: 2 }
//.. where number of items is unknown
}
}
```
I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way
```
public class Data {
public int user_id { get; set; }
public string taskid { get; set; }
public List<object> list { get; set; }
}
public class DataList {
List<Data> data { get; set; }
}
// if isPost etc..
var decodedData = JSON.Decode<DataList>(Request["data"])
```
But when I try and iterate over decodedData I am getting an error -
>
> foreach statement cannot operate on variables of type
> 'ASP.\_Page\_that\_cshtml.DataList' because
> 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition
> for 'GetEnumerator'
>
>
>
When I try casting the decodedData to a List this way -
```
List<Data> decodedData = JSON.Decode<DataList>(Request["data"])
```
I throw another error
>
> CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`'
>
>
>
Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it?
PS: trailing semi-colons omitted on-purpose
|
2013/03/18
|
[
"https://Stackoverflow.com/questions/15481759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95055/"
] |
The first error you are getting is quite right, your class `DataList` does not contain a definition for `GetEnumerator` which is required for a foreach statement. You will need to iterate over the property, so iterate over decodedData.data.
The second error is again correct, as you are trying to cast DataList to a type of List, something C# has no idea how to do. You would again need to create your DataList, then set the property data to the type List.
|
You can try decoding the JSON into an array of Data objects, and then calling the ToList() extension method on that array.
```
var dataArray = JSON.Decode<Data[]>(Request["data"]);
var list = dataArray.ToList();
```
|
15,481,759 |
I am trying to convert a nested JSON object on an ASP.NET server. The incoming JSON string looks something like this -
```js
data: {
user_id: 1,
taskid: "1234",
list: {
"item-1": { one: 1, two: 2 },
"item-2": { one: 1, two: 2 }
//.. where number of items is unknown
}
}
```
I have tried to decode the data using [JSON.Decode](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.decode%28v=vs.111%29.aspx) this way
```
public class Data {
public int user_id { get; set; }
public string taskid { get; set; }
public List<object> list { get; set; }
}
public class DataList {
List<Data> data { get; set; }
}
// if isPost etc..
var decodedData = JSON.Decode<DataList>(Request["data"])
```
But when I try and iterate over decodedData I am getting an error -
>
> foreach statement cannot operate on variables of type
> 'ASP.\_Page\_that\_cshtml.DataList' because
> 'ASP.\_Page\_that\_cshtml.DataList' does not contain a public definition
> for 'GetEnumerator'
>
>
>
When I try casting the decodedData to a List this way -
```
List<Data> decodedData = JSON.Decode<DataList>(Request["data"])
```
I throw another error
>
> CS0030: Cannot convert type '`ASP._Page_that_cshtml.DataList`' to '`System.Collections.Generic.List<ASP._Page_that_cshtml.DataList>`'
>
>
>
Could you please suggest an appropriate method to convert nested JSON objects into a C# object and iterating over it?
PS: trailing semi-colons omitted on-purpose
|
2013/03/18
|
[
"https://Stackoverflow.com/questions/15481759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95055/"
] |
```
List<Data> decodedData = JSON.Decode<DataList>(Request["data"])
```
Should Be
```
var decodedData = JSON.Decode<List<Data>>(Request["data"])
var myDataList = new DataList() { data = decodedData; }
```
|
You can try decoding the JSON into an array of Data objects, and then calling the ToList() extension method on that array.
```
var dataArray = JSON.Decode<Data[]>(Request["data"]);
var list = dataArray.ToList();
```
|
6,990,667 |
I have a page app/views/new/news.html.erb and I simply want to link to this page from within my layouts/application.html.erb. Can someone please help! I have been struggling with this all morning.
I have tried things like <%= link\_to "News", ... But I'm not really sure where to go from there.
|
2011/08/09
|
[
"https://Stackoverflow.com/questions/6990667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852974/"
] |
If you have it setup correctly you should have a plural for your controller (i.e. news instead of new) and the following should work:
```
<%= link_to 'News', :controller => "news", :action => :news %>
```
This is assuming you are using scaffold.
If are adding this folder and page manually: for dynamic page, you have to create an action in your controller. For static page, you have to put it in your public folder.
|
You don't "link" to a view, you link to a controller which renders that view. Then, you'll need an entry in your routes.rb to wire up the url routing for that controller. If you have a controller named NewsController with a method called index and an entry in your routes.rb that looks like `resources :news` the following link\_to should work: `link_to "News", news_path`.
In case it's not clear, the index method in your NewsController needs to have `render :news` in it.
Sounds like you may want to check out the guide on this topic: <http://guides.rubyonrails.org/routing.html>
|
6,990,667 |
I have a page app/views/new/news.html.erb and I simply want to link to this page from within my layouts/application.html.erb. Can someone please help! I have been struggling with this all morning.
I have tried things like <%= link\_to "News", ... But I'm not really sure where to go from there.
|
2011/08/09
|
[
"https://Stackoverflow.com/questions/6990667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852974/"
] |
You don't "link" to a view, you link to a controller which renders that view. Then, you'll need an entry in your routes.rb to wire up the url routing for that controller. If you have a controller named NewsController with a method called index and an entry in your routes.rb that looks like `resources :news` the following link\_to should work: `link_to "News", news_path`.
In case it's not clear, the index method in your NewsController needs to have `render :news` in it.
Sounds like you may want to check out the guide on this topic: <http://guides.rubyonrails.org/routing.html>
|
You can always run
```
rake routes > routes.txt
```
in your application directory, which will dump a list of all routes into a txt file. Choose path that leads to action and controller you want, and then supply it as a param for link\_to method :)
|
6,990,667 |
I have a page app/views/new/news.html.erb and I simply want to link to this page from within my layouts/application.html.erb. Can someone please help! I have been struggling with this all morning.
I have tried things like <%= link\_to "News", ... But I'm not really sure where to go from there.
|
2011/08/09
|
[
"https://Stackoverflow.com/questions/6990667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852974/"
] |
If you have it setup correctly you should have a plural for your controller (i.e. news instead of new) and the following should work:
```
<%= link_to 'News', :controller => "news", :action => :news %>
```
This is assuming you are using scaffold.
If are adding this folder and page manually: for dynamic page, you have to create an action in your controller. For static page, you have to put it in your public folder.
|
You can always run
```
rake routes > routes.txt
```
in your application directory, which will dump a list of all routes into a txt file. Choose path that leads to action and controller you want, and then supply it as a param for link\_to method :)
|
63,180,246 |
Is there a way that I can read multiple partitioned parquet files having different basePath in one go, by using wildcard(\*) when using basePath option with spark read? E.g.:
```
spark.read.option("basePath","s3://latest/data/*/").parquet(*dir)
```
Error gotten:
```
error: pyspark.sql.utils.IllegalArgumentException: u"Option 'basePath' must be a directory"
```
|
2020/07/30
|
[
"https://Stackoverflow.com/questions/63180246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5370631/"
] |
No. You can have multiple `paths` in combination with a single base path for getting partitioning columns in the DF schema, but you cannot specify multiple `base paths` or use a wildcard as part of that base path.string.
|
You can simply give the root path,
```
spark.read.parquet("s3://latest/data/")
```
with the options.
```
spark.hive.mapred.supports.subdirectories true
spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive true
```
Then, the spark will look for the parquet files recursively from the `/data/` folder to the subdirectories.
Below code is the sample.
```
import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.sql.SparkSession
val conf = new SparkConf()
.setMaster("local[2]")
.setAppName("test")
.set("spark.hive.mapred.supports.subdirectories","true")
.set("spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive","true")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.read.parquet("s3a://bucket/path/to/base/")
```
---
**SCALA:** I have tested with my multiple CSV files. The tree structure of the directories is
```
.
|-- test=1
| `-- test1.csv
`-- test=2
`-- test2.csv
```
where the base path is `s3://bucket/test/`. For each CSV hs the contents
```
test1.csv
x,y,z
tes,45,34
tes,43,67
tes,56,43
raj,45,43
raj,44,67
test2.csv
x,y,z
shd,43,34
adf,2,67
```
and the command
```
val df = spark.read.option("header","true").csv("s3a://bucket/test/")
df.show(false)
```
gives the result as below:
```
+---+---+---+----+
|x |y |z |test|
+---+---+---+----+
|tes|45 |34 |1 |
|tes|43 |67 |1 |
|tes|56 |43 |1 |
|raj|45 |43 |1 |
|raj|44 |67 |1 |
|shd|43 |34 |2 |
|adf|2 |67 |2 |
+---+---+---+----+
```
---
**PYSPARK**
```
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.master("yarn") \
.appName("test") \
.config("spark.hive.mapred.supports.subdirectories","true") \
.config("spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive","true") \
.getOrCreate()
df = spark.read.option("header","true").csv("s3a://bucket/test/")
df.show(10, False)
+---+---+---+----+
|x |y |z |test|
+---+---+---+----+
|tes|45 |34 |1 |
|tes|43 |67 |1 |
|tes|56 |43 |1 |
|raj|45 |43 |1 |
|raj|44 |67 |1 |
|shd|43 |34 |2 |
|adf|2 |67 |2 |
+---+---+---+----+
```
When I test the pyspark code, I did not break the lines. So, please check it whether it is correct or not. Well, I put the path such as `test=x` and it is recognized as a partition structure, so the results are giving that as a column.
|
22,290,320 |
I have a list loaded through `ng-repeat` where each element contains an `img` tag. I'd like to show some sort of loading indicator (occluding the list items) until every image within every item has finished loading.
I guess I would need to hook into some event broadcast by the angular `back-img` directive but I don't really know where to start here.
|
2014/03/10
|
[
"https://Stackoverflow.com/questions/22290320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/831862/"
] |
Okay, so I solved my problem. First of all, @Vladimir, you're totally right -- `back-img` was a directive my colleague wrote, which obscured the solution to me for a while.
What I've done is write a really simple directive that calls a `$scope`-bound function on the `img`'s `load` event. My controller counts the number of images that have loaded, and once enough images have loaded, it removes the loading indicator and shows the list of images. Here's a summary of the code:
My directive:
```
app.directive('loadedImage', function($parse) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
element.bind("load", function(event) {
var invoker = $parse(attrs.loadedCallback);
invoker(scope);
});
}
}
});
```
Within the element:
```
<img ng-src='{{ item.large }}' loaded-image loaded-callback="imageLoaded(r.id)">
```
And finally, within the controller:
```
$scope.numLoaded = 0;
$scope.showLoading = true;
$scope.showImages = false;
$scope.imageLoaded = function(id) {
$scope.numLoaded++;
if ($scope.numLoaded > 9) {
$scope.showLoading = false;
$timeout(function() {
$scope.showImages = true;
}, 500) //show images once loading indicator has faded away
};
};
```
I'm not sure this is the right approach, but it reliably works for me!
|
I am not aware of any back-img directive, but image loading is asynchronous and you cant generally guarantee that your 3rd image will load before your 8th image.
WHat I would do is add an 'onload' listener to every img tag that gets added by ng-repeat and simply figure out when all of your images have loaded by keeping count of 'onload' hits and comparing it against the total number of images.
This is essentially what <https://github.com/desandro/imagesloaded> does, but in the jquery-land.
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
Rhino Mocks appears to be catching and handling this exception. You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. It appears that you can safely continue running past this exception breakpoint and it all works as expected.
|
Your code works properly. You likely have some other code not shown which is causing the problem. Post your whole unit test here and we'll diagnose the issue for you.
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
This happens when you have NOT got "Just my code" enabled under Tools->Options->Debugging->General, and you have CLR exceptions, "Thrown" selected under Debug->Exceptions. Easiest way to fix it is enable "just my code" under Tools->Options->Debugging->General.

|
Your code works properly. You likely have some other code not shown which is causing the problem. Post your whole unit test here and we'll diagnose the issue for you.
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
Your code works properly. You likely have some other code not shown which is causing the problem. Post your whole unit test here and we'll diagnose the issue for you.
|
I second that - It's not an issue with code.
It is VS debug setting.
I get the same exception while on debug on the code below, while trying to send Arg.Is.Anything as a parameter to a stub.
```
mockPermissionManager.Stub(item => item.HasAccess(Arg<string>.Is.Anything)).Return(true);
```
The exception is handled and code/mocking works as expected, just do F5
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
Rhino Mocks appears to be catching and handling this exception. You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. It appears that you can safely continue running past this exception breakpoint and it all works as expected.
|
I have the same problem, it has to be some VS studio debug setting or some insufficient access rights for rhino mocks i guess.
I am pretty sure that its not the code that is causing this.
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
This happens when you have NOT got "Just my code" enabled under Tools->Options->Debugging->General, and you have CLR exceptions, "Thrown" selected under Debug->Exceptions. Easiest way to fix it is enable "just my code" under Tools->Options->Debugging->General.

|
I have the same problem, it has to be some VS studio debug setting or some insufficient access rights for rhino mocks i guess.
I am pretty sure that its not the code that is causing this.
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
I have the same problem, it has to be some VS studio debug setting or some insufficient access rights for rhino mocks i guess.
I am pretty sure that its not the code that is causing this.
|
I second that - It's not an issue with code.
It is VS debug setting.
I get the same exception while on debug on the code below, while trying to send Arg.Is.Anything as a parameter to a stub.
```
mockPermissionManager.Stub(item => item.HasAccess(Arg<string>.Is.Anything)).Return(true);
```
The exception is handled and code/mocking works as expected, just do F5
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
Rhino Mocks appears to be catching and handling this exception. You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. It appears that you can safely continue running past this exception breakpoint and it all works as expected.
|
This happens when you have NOT got "Just my code" enabled under Tools->Options->Debugging->General, and you have CLR exceptions, "Thrown" selected under Debug->Exceptions. Easiest way to fix it is enable "just my code" under Tools->Options->Debugging->General.

|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
Rhino Mocks appears to be catching and handling this exception. You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. It appears that you can safely continue running past this exception breakpoint and it all works as expected.
|
I second that - It's not an issue with code.
It is VS debug setting.
I get the same exception while on debug on the code below, while trying to send Arg.Is.Anything as a parameter to a stub.
```
mockPermissionManager.Stub(item => item.HasAccess(Arg<string>.Is.Anything)).Return(true);
```
The exception is handled and code/mocking works as expected, just do F5
|
931,845 |
Running this code:
```
_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");
```
When
```
public interface IBar
{
string Foo();
}
public class Bar : IBar
{
public string Foo()
{
throw new NotImplementedException();
}
}
```
throws NotSupportedException - "Can't create mocks of sealed classes". I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ?
|
2009/05/31
|
[
"https://Stackoverflow.com/questions/931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
This happens when you have NOT got "Just my code" enabled under Tools->Options->Debugging->General, and you have CLR exceptions, "Thrown" selected under Debug->Exceptions. Easiest way to fix it is enable "just my code" under Tools->Options->Debugging->General.

|
I second that - It's not an issue with code.
It is VS debug setting.
I get the same exception while on debug on the code below, while trying to send Arg.Is.Anything as a parameter to a stub.
```
mockPermissionManager.Stub(item => item.HasAccess(Arg<string>.Is.Anything)).Return(true);
```
The exception is handled and code/mocking works as expected, just do F5
|
58,096 |
In my personal budget, I allocate a fixed amount £x per month to mortgage repayments. This amount includes a sum which is going towards overpaying the mortgage so that I can get the thing over with as soon as possible. Each of these overpayments is above the threshold for reducing the subsequent monthly regular payment amount, so every month a larger proportion of £x is being allocated to overpaying and a smaller to the regular payment.
All mortgage overpayment calculators I've found assume you are overpaying a fixed £ or % amount each period and don't let you fix the total overpayment + regular payment amount, so it's hard for me to see how this strategy is going to play out. I'm interested in seeing how the payments are going to fall month on month, and how long it's going to take me in total to pay the thing off.
I played around with creating a spreadsheet using the IPMT family of functions but the results I came up with were always a few % off the lender's calculations even over one month, so over the remaining 23 years the figures wouldn't be very accurate.
If such a calculator exists I'd be more than happy to use it, or to receive advice on how to make a spreadsheet which has a good level of accuracy.
|
2016/01/14
|
[
"https://money.stackexchange.com/questions/58096",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/36597/"
] |
Happy to share my personal spreadsheet for this purpose. Go here:
[Mortgage overpayment comparison sheet (.xlsx) on Scribd](https://www.scribd.com/doc/294640994/Mortgage-Amortization-Sheet-Mortgage-Overpayment-Comparison)
- download it and modify freely in Excel.
This assumes:
* interest is calculated monthly
* payment is applied at the end of that month, pays off interest
* your lender doesn't recalculate your monthly payment every time. Rather, they keep requesting the same amount, but *apply the (increasing proportion of) overpayment to the capital* until it's paid off – which I gather from your question is what you want to do.
If your lender calculates interest daily or on a different frequency than monthly, then yes this will be slightly out from their figures. But I doubt you'll need it to be too precise. The sheet will give a ballpark date for paying off the mortgage, and also show you roughly what you'll owe on a given future date so you can plan your remortgage / house move etc. if that's part of your plans.
|
You didn't say how you setup your test spreadsheet, but since IPMT is defined as "calculates the interest payment, during a specific period of a loan or investment that is paid in **constant periodic payments**, with a constant interest rate," (emphasis added) I think you could be making mistakes in how you use it. Are you attempting to use it for anything other than the first period?
Also, since you say the overpayments you are making cause the lender to recalculate the subsequent monthly regular payment, you'll need to understand exactly how and when they're doing this to be able to match it in your own forecasting. Hopefully, they're simply re-amortizing the outstanding principle for the remaining term, and doing this promptly upon receiving your payment. But it could be there's a lag time and your next payment's division into interest and principle is based on a previous month's calculation.
I do think setting up your own spreadsheet is the right way to go.
I think you'll need a row or column for each month individually, being very careful to get the outstanding principal balance right at the start of each month, to understand exactly how your lender is calculating interest, to understand exactly how your lender is recalculating payments amounts, and to match these through appropriate use of PMT, IPMT, PPMT, etc functions. You'd then create enough rows or columns to carry this forward until you hit loan payoff. (i.e. a brute force approach)
|
58,096 |
In my personal budget, I allocate a fixed amount £x per month to mortgage repayments. This amount includes a sum which is going towards overpaying the mortgage so that I can get the thing over with as soon as possible. Each of these overpayments is above the threshold for reducing the subsequent monthly regular payment amount, so every month a larger proportion of £x is being allocated to overpaying and a smaller to the regular payment.
All mortgage overpayment calculators I've found assume you are overpaying a fixed £ or % amount each period and don't let you fix the total overpayment + regular payment amount, so it's hard for me to see how this strategy is going to play out. I'm interested in seeing how the payments are going to fall month on month, and how long it's going to take me in total to pay the thing off.
I played around with creating a spreadsheet using the IPMT family of functions but the results I came up with were always a few % off the lender's calculations even over one month, so over the remaining 23 years the figures wouldn't be very accurate.
If such a calculator exists I'd be more than happy to use it, or to receive advice on how to make a spreadsheet which has a good level of accuracy.
|
2016/01/14
|
[
"https://money.stackexchange.com/questions/58096",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/36597/"
] |
You didn't say how you setup your test spreadsheet, but since IPMT is defined as "calculates the interest payment, during a specific period of a loan or investment that is paid in **constant periodic payments**, with a constant interest rate," (emphasis added) I think you could be making mistakes in how you use it. Are you attempting to use it for anything other than the first period?
Also, since you say the overpayments you are making cause the lender to recalculate the subsequent monthly regular payment, you'll need to understand exactly how and when they're doing this to be able to match it in your own forecasting. Hopefully, they're simply re-amortizing the outstanding principle for the remaining term, and doing this promptly upon receiving your payment. But it could be there's a lag time and your next payment's division into interest and principle is based on a previous month's calculation.
I do think setting up your own spreadsheet is the right way to go.
I think you'll need a row or column for each month individually, being very careful to get the outstanding principal balance right at the start of each month, to understand exactly how your lender is calculating interest, to understand exactly how your lender is recalculating payments amounts, and to match these through appropriate use of PMT, IPMT, PPMT, etc functions. You'd then create enough rows or columns to carry this forward until you hit loan payoff. (i.e. a brute force approach)
|
Further to the previous answers, there's nothing sacred about the lender's ideas about what the regular payment is for any particular month, and what is the "extra" amount" that you are paying.
You have debt balance, it's growing each month because of interest at some rate, and you're reducing it each month by throwing the **same total amount** of money into it. You and the lender will agree on all three of these figures.
So just use a mortgage calculator with these three figures as input, and find the total number of payments. Or put in a certain number of payment so find the balance owing at that time.
Or have I completely missed your problem?
|
58,096 |
In my personal budget, I allocate a fixed amount £x per month to mortgage repayments. This amount includes a sum which is going towards overpaying the mortgage so that I can get the thing over with as soon as possible. Each of these overpayments is above the threshold for reducing the subsequent monthly regular payment amount, so every month a larger proportion of £x is being allocated to overpaying and a smaller to the regular payment.
All mortgage overpayment calculators I've found assume you are overpaying a fixed £ or % amount each period and don't let you fix the total overpayment + regular payment amount, so it's hard for me to see how this strategy is going to play out. I'm interested in seeing how the payments are going to fall month on month, and how long it's going to take me in total to pay the thing off.
I played around with creating a spreadsheet using the IPMT family of functions but the results I came up with were always a few % off the lender's calculations even over one month, so over the remaining 23 years the figures wouldn't be very accurate.
If such a calculator exists I'd be more than happy to use it, or to receive advice on how to make a spreadsheet which has a good level of accuracy.
|
2016/01/14
|
[
"https://money.stackexchange.com/questions/58096",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/36597/"
] |
You didn't say how you setup your test spreadsheet, but since IPMT is defined as "calculates the interest payment, during a specific period of a loan or investment that is paid in **constant periodic payments**, with a constant interest rate," (emphasis added) I think you could be making mistakes in how you use it. Are you attempting to use it for anything other than the first period?
Also, since you say the overpayments you are making cause the lender to recalculate the subsequent monthly regular payment, you'll need to understand exactly how and when they're doing this to be able to match it in your own forecasting. Hopefully, they're simply re-amortizing the outstanding principle for the remaining term, and doing this promptly upon receiving your payment. But it could be there's a lag time and your next payment's division into interest and principle is based on a previous month's calculation.
I do think setting up your own spreadsheet is the right way to go.
I think you'll need a row or column for each month individually, being very careful to get the outstanding principal balance right at the start of each month, to understand exactly how your lender is calculating interest, to understand exactly how your lender is recalculating payments amounts, and to match these through appropriate use of PMT, IPMT, PPMT, etc functions. You'd then create enough rows or columns to carry this forward until you hit loan payoff. (i.e. a brute force approach)
|
It is a little unclear to me exactly what feature you are looking for in a calculator. However, check out this calculator [here](http://mortgagevista.com/#m=2), it might offer what you are looking for.
It allows you to define an extra payment amount that will be applied each month in addition to your "regular" payment. This "over-payment" reduces the principal so that the amount of interest charged on all future payments is less, creating a scenario where more of your "regular" payment is being applied to principal each month rather that interest and thus will pay off the mortgage faster.
Is this what you mean by:
>
>
> >
> > Each of these overpayments is above the threshold for reducing the subsequent >>monthly regular payment amount, so every month a larger proportion of £x is >>being allocated to overpaying and a smaller to the regular payment.
> >
> >
> >
>
>
>
Also, it allows you to include several large lump sum payments of extra principal so you can see how that affects the mortgage schedule.
|
58,096 |
In my personal budget, I allocate a fixed amount £x per month to mortgage repayments. This amount includes a sum which is going towards overpaying the mortgage so that I can get the thing over with as soon as possible. Each of these overpayments is above the threshold for reducing the subsequent monthly regular payment amount, so every month a larger proportion of £x is being allocated to overpaying and a smaller to the regular payment.
All mortgage overpayment calculators I've found assume you are overpaying a fixed £ or % amount each period and don't let you fix the total overpayment + regular payment amount, so it's hard for me to see how this strategy is going to play out. I'm interested in seeing how the payments are going to fall month on month, and how long it's going to take me in total to pay the thing off.
I played around with creating a spreadsheet using the IPMT family of functions but the results I came up with were always a few % off the lender's calculations even over one month, so over the remaining 23 years the figures wouldn't be very accurate.
If such a calculator exists I'd be more than happy to use it, or to receive advice on how to make a spreadsheet which has a good level of accuracy.
|
2016/01/14
|
[
"https://money.stackexchange.com/questions/58096",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/36597/"
] |
Happy to share my personal spreadsheet for this purpose. Go here:
[Mortgage overpayment comparison sheet (.xlsx) on Scribd](https://www.scribd.com/doc/294640994/Mortgage-Amortization-Sheet-Mortgage-Overpayment-Comparison)
- download it and modify freely in Excel.
This assumes:
* interest is calculated monthly
* payment is applied at the end of that month, pays off interest
* your lender doesn't recalculate your monthly payment every time. Rather, they keep requesting the same amount, but *apply the (increasing proportion of) overpayment to the capital* until it's paid off – which I gather from your question is what you want to do.
If your lender calculates interest daily or on a different frequency than monthly, then yes this will be slightly out from their figures. But I doubt you'll need it to be too precise. The sheet will give a ballpark date for paying off the mortgage, and also show you roughly what you'll owe on a given future date so you can plan your remortgage / house move etc. if that's part of your plans.
|
Further to the previous answers, there's nothing sacred about the lender's ideas about what the regular payment is for any particular month, and what is the "extra" amount" that you are paying.
You have debt balance, it's growing each month because of interest at some rate, and you're reducing it each month by throwing the **same total amount** of money into it. You and the lender will agree on all three of these figures.
So just use a mortgage calculator with these three figures as input, and find the total number of payments. Or put in a certain number of payment so find the balance owing at that time.
Or have I completely missed your problem?
|
58,096 |
In my personal budget, I allocate a fixed amount £x per month to mortgage repayments. This amount includes a sum which is going towards overpaying the mortgage so that I can get the thing over with as soon as possible. Each of these overpayments is above the threshold for reducing the subsequent monthly regular payment amount, so every month a larger proportion of £x is being allocated to overpaying and a smaller to the regular payment.
All mortgage overpayment calculators I've found assume you are overpaying a fixed £ or % amount each period and don't let you fix the total overpayment + regular payment amount, so it's hard for me to see how this strategy is going to play out. I'm interested in seeing how the payments are going to fall month on month, and how long it's going to take me in total to pay the thing off.
I played around with creating a spreadsheet using the IPMT family of functions but the results I came up with were always a few % off the lender's calculations even over one month, so over the remaining 23 years the figures wouldn't be very accurate.
If such a calculator exists I'd be more than happy to use it, or to receive advice on how to make a spreadsheet which has a good level of accuracy.
|
2016/01/14
|
[
"https://money.stackexchange.com/questions/58096",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/36597/"
] |
Happy to share my personal spreadsheet for this purpose. Go here:
[Mortgage overpayment comparison sheet (.xlsx) on Scribd](https://www.scribd.com/doc/294640994/Mortgage-Amortization-Sheet-Mortgage-Overpayment-Comparison)
- download it and modify freely in Excel.
This assumes:
* interest is calculated monthly
* payment is applied at the end of that month, pays off interest
* your lender doesn't recalculate your monthly payment every time. Rather, they keep requesting the same amount, but *apply the (increasing proportion of) overpayment to the capital* until it's paid off – which I gather from your question is what you want to do.
If your lender calculates interest daily or on a different frequency than monthly, then yes this will be slightly out from their figures. But I doubt you'll need it to be too precise. The sheet will give a ballpark date for paying off the mortgage, and also show you roughly what you'll owe on a given future date so you can plan your remortgage / house move etc. if that's part of your plans.
|
It is a little unclear to me exactly what feature you are looking for in a calculator. However, check out this calculator [here](http://mortgagevista.com/#m=2), it might offer what you are looking for.
It allows you to define an extra payment amount that will be applied each month in addition to your "regular" payment. This "over-payment" reduces the principal so that the amount of interest charged on all future payments is less, creating a scenario where more of your "regular" payment is being applied to principal each month rather that interest and thus will pay off the mortgage faster.
Is this what you mean by:
>
>
> >
> > Each of these overpayments is above the threshold for reducing the subsequent >>monthly regular payment amount, so every month a larger proportion of £x is >>being allocated to overpaying and a smaller to the regular payment.
> >
> >
> >
>
>
>
Also, it allows you to include several large lump sum payments of extra principal so you can see how that affects the mortgage schedule.
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
Basically there is no distinction, which sometimes makes it difficult to understand.
So when I say `Das ist meine Freundin` it's not obvious whether she is my girlfriend or just a friend.
Usually people then say something like `Das ist eine Freundin (von mir)` for the 2nd case.
Concerning the same sex - a colleague of mine is homosexual and when I speak of his `Freund` it's not obvious for others that I mean his boyfriend.
So, German pretty much lacks a word here...
|
The only correct answer is: no. Both friend and boyfriend are "Freund" in German, and this often causes confusion.
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
Basically there is no distinction, which sometimes makes it difficult to understand.
So when I say `Das ist meine Freundin` it's not obvious whether she is my girlfriend or just a friend.
Usually people then say something like `Das ist eine Freundin (von mir)` for the 2nd case.
Concerning the same sex - a colleague of mine is homosexual and when I speak of his `Freund` it's not obvious for others that I mean his boyfriend.
So, German pretty much lacks a word here...
|
As a gay man who has close German relatives I refer to my boyfriend with them (so for introductions or clarification) as *Liebesfreund* (implying a romantic relationship) versus referring to male friends of mine as *ein Freund.*
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
Basically there is no distinction, which sometimes makes it difficult to understand.
So when I say `Das ist meine Freundin` it's not obvious whether she is my girlfriend or just a friend.
Usually people then say something like `Das ist eine Freundin (von mir)` for the 2nd case.
Concerning the same sex - a colleague of mine is homosexual and when I speak of his `Freund` it's not obvious for others that I mean his boyfriend.
So, German pretty much lacks a word here...
|
German does not have a single word for this - and in fact, this isn't as easy to express as in english.
In german, when you say
>
> Das ist *mein(e)* Freund(in)
>
>
>
most people will assume its your *boyfriend/girlfriend*.
However, if you say
>
> Das ist *ein(e)* Freund(in) (von mir)
>
>
>
then most people will understand its *just a friend*, not your boyfriend/girlfriend.
So the difference is in *mein(e)/ein(e)*, which makes it a bit hard to grasp.
---
With same-sex relationships, its not that easy. Most people will simply not assume you are gay/lesbian, unless you came out to them before.
You can, however, use other terms to refer to your boyfriend/gilfriend.
While young people (teens mostly) will prefer "Freund(in)", adults often use **Partner(in)** or **Lebensgefährt(e/in)** to describe their romantic partner.
This works very well for same-sex partnerships, too, and is in fact what I'd recommend using.
If a male person introduces someone as his "Lebengefährte", its quite damn clear what he meant. No confusions. Same applies for female and "Lebensgefährtin".
Its also clear if you talk about other persons. If you have a gay friend and talk about his "Lebensgefährte", everyone will understand. If you talk about his "Freund", not so much.
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
A boyfriend could be called »*fester* Freund«, a girlfriend »*feste* Freundin«.
There is also the term *Partner* (*Partnerin*) or, to clarify that it’s not a business partner, *Lebenspartner* (*Lebenspartnerin*).
Another term is *Lebensgefährte* (*Lebensgefährtin*).
|
The only correct answer is: no. Both friend and boyfriend are "Freund" in German, and this often causes confusion.
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
A boyfriend could be called »*fester* Freund«, a girlfriend »*feste* Freundin«.
There is also the term *Partner* (*Partnerin*) or, to clarify that it’s not a business partner, *Lebenspartner* (*Lebenspartnerin*).
Another term is *Lebensgefährte* (*Lebensgefährtin*).
|
As a gay man who has close German relatives I refer to my boyfriend with them (so for introductions or clarification) as *Liebesfreund* (implying a romantic relationship) versus referring to male friends of mine as *ein Freund.*
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
A boyfriend could be called »*fester* Freund«, a girlfriend »*feste* Freundin«.
There is also the term *Partner* (*Partnerin*) or, to clarify that it’s not a business partner, *Lebenspartner* (*Lebenspartnerin*).
Another term is *Lebensgefährte* (*Lebensgefährtin*).
|
German does not have a single word for this - and in fact, this isn't as easy to express as in english.
In german, when you say
>
> Das ist *mein(e)* Freund(in)
>
>
>
most people will assume its your *boyfriend/girlfriend*.
However, if you say
>
> Das ist *ein(e)* Freund(in) (von mir)
>
>
>
then most people will understand its *just a friend*, not your boyfriend/girlfriend.
So the difference is in *mein(e)/ein(e)*, which makes it a bit hard to grasp.
---
With same-sex relationships, its not that easy. Most people will simply not assume you are gay/lesbian, unless you came out to them before.
You can, however, use other terms to refer to your boyfriend/gilfriend.
While young people (teens mostly) will prefer "Freund(in)", adults often use **Partner(in)** or **Lebensgefährt(e/in)** to describe their romantic partner.
This works very well for same-sex partnerships, too, and is in fact what I'd recommend using.
If a male person introduces someone as his "Lebengefährte", its quite damn clear what he meant. No confusions. Same applies for female and "Lebensgefährtin".
Its also clear if you talk about other persons. If you have a gay friend and talk about his "Lebensgefährte", everyone will understand. If you talk about his "Freund", not so much.
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
The only correct answer is: no. Both friend and boyfriend are "Freund" in German, and this often causes confusion.
|
As a gay man who has close German relatives I refer to my boyfriend with them (so for introductions or clarification) as *Liebesfreund* (implying a romantic relationship) versus referring to male friends of mine as *ein Freund.*
|
5,028 |
In English when a man is in a relationship with another man, he can say he's his boyfriend. In German, saying "Freund" when both are of the same sex is usually understood to mean the equivalent of "friend", not implying a relationship. Same goes for women.
Is there a german word for this?
|
2012/08/15
|
[
"https://german.stackexchange.com/questions/5028",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/293/"
] |
German does not have a single word for this - and in fact, this isn't as easy to express as in english.
In german, when you say
>
> Das ist *mein(e)* Freund(in)
>
>
>
most people will assume its your *boyfriend/girlfriend*.
However, if you say
>
> Das ist *ein(e)* Freund(in) (von mir)
>
>
>
then most people will understand its *just a friend*, not your boyfriend/girlfriend.
So the difference is in *mein(e)/ein(e)*, which makes it a bit hard to grasp.
---
With same-sex relationships, its not that easy. Most people will simply not assume you are gay/lesbian, unless you came out to them before.
You can, however, use other terms to refer to your boyfriend/gilfriend.
While young people (teens mostly) will prefer "Freund(in)", adults often use **Partner(in)** or **Lebensgefährt(e/in)** to describe their romantic partner.
This works very well for same-sex partnerships, too, and is in fact what I'd recommend using.
If a male person introduces someone as his "Lebengefährte", its quite damn clear what he meant. No confusions. Same applies for female and "Lebensgefährtin".
Its also clear if you talk about other persons. If you have a gay friend and talk about his "Lebensgefährte", everyone will understand. If you talk about his "Freund", not so much.
|
As a gay man who has close German relatives I refer to my boyfriend with them (so for introductions or clarification) as *Liebesfreund* (implying a romantic relationship) versus referring to male friends of mine as *ein Freund.*
|
20,304,453 |
I want to make a search, but I need to bring the registers that have status Canceled or modified.
I thought that this would work but It didn't
```
citasotras = citas_agendarcita.objects.filter(cita_agendar_status="Modificada" or "",citas_tipodepaciente="mediexcel")
```
|
2013/11/30
|
[
"https://Stackoverflow.com/questions/20304453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712575/"
] |
In your example, The expression `"Modificada" or ""` evaluates to `"Modificada"`.
```
>>> "Modificada" or ""
'Modificada'
```
Therefore, your example is as if you simply had:
```
citasotras = citas_agendarcita.objects.filter(cita_agendar_status="Modificada", citas_tipodepaciente="mediexcel")
```
You want any objects where the `cita_agendar_status` is equal to any of the items in the list `["Modificada", ""]`. You can use `__in` to do this:
```
citasotras = citas_agendarcita.objects.filter(cita_agendar_status__in=["Modificada", ""] ,citas_tipodepaciente="mediexcel")
```
See the [Django docs](https://docs.djangoproject.com/en/1.6/ref/models/querysets/#in) for more information.
|
For AND/OR conditions [Q objects](https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) can be used:
```
citas_agendarcita.objects.filter(Q(cita_agendar_status="Modificada")|Q(cita_agendar_status=""), \
citas_tipodepaciente="mediexcel")
```
|
50,382,346 |
I have 2 application servers, which are connecting to a replicaSet (Primary, Secondary and Arbitrer).
Issue i'm facing is
```
[ 'MongoError: no primary found in replicaset',
' at ../server/node_modules/mongodb-core/lib/topologies/replset.js:524:28',
' at null.<anonymous> (../server/node_modules/mongodb-core/lib/topologies/replset.js:303:24)',
' at g (events.js:260:16)',
' at emitOne (events.js:77:13)',
' at emit (events.js:169:7)',
' at null.<anonymous> (../server/node_modules/mongodb-core/lib/topologies/server.js:326:21)',
' at emitOne (events.js:77:13)',
' at emit (events.js:169:7)',
' at null.<anonymous> (../server/node_modules/mongodb-core/lib/connection/pool.js:270:12)',
' at g (events.js:260:16)',
' at emitTwo (events.js:87:13)',
' at emit (events.js:172:7)',
' at Socket.<anonymous> (../server/node_modules/mongodb-core/lib/connection/connection.js:175:49)',
' at Socket.g (events.js:260:16)',
' at emitOne (events.js:77:13)',
' at Socket.emit (events.js:169:7)',
' at connectErrorNT (net.js:996:8)',
' at nextTickCallbackWith2Args (node.js:442:9)',
' at process._tickCallback (node.js:356:17)' ]
```
*ReplicaSet config on application :*
```
"mongodb" : {
"replicaset": {
"db" : "test",
"user" : "admin",
"password" : "*********",
"name":"rs1",
"replicas": [{"host":"App1Box.dmz.mytest.com.au","port":27017}, {"host":"App2Box.dmz.mytest.com.au","port":27018}]
}
```
*rs.status() output*
```
rs1:PRIMARY> rs.status()
{
"set" : "rs1",
"date" : ISODate("2018-05-17T03:50:01Z"),
"myState" : 1,
"members" : [
{
"_id" : 2,
"name" : "App3Box:27018",
"health" : 1,
"state" : 7,
"stateStr" : "ARBITER",
"uptime" : 7180,
"lastHeartbeat" : ISODate("2018-05-17T03:50:00Z"),
"lastHeartbeatRecv" : ISODate("2018-05-17T03:50:00Z"),
"pingMs" : 0
},
{
"_id" : 3,
"name" : "App2Box:27018",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 7528,
"optime" : Timestamp(1526521846, 1),
"optimeDate" : ISODate("2018-05-17T01:50:46Z"),
"electionTime" : Timestamp(1526521798, 1),
"electionDate" : ISODate("2018-05-17T01:49:58Z"),
"self" : true
},
{
"_id" : 4,
"name" : "App1Box:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 7139,
"optime" : Timestamp(1526521846, 1),
"optimeDate" : ISODate("2018-05-17T01:50:46Z"),
"lastHeartbeat" : ISODate("2018-05-17T03:50:01Z"),
"lastHeartbeatRecv" : ISODate("2018-05-17T03:50:01Z"),
"pingMs" : 0,
"syncingTo" : "App2Box:27018"
}
],
"ok" : 1
}
```
However, I'm seeing this only from one of the app server which is connecting to MongoDB say App1Box. I'm not seeing this issue on App2Box.
I've tried removing members from replicaSets and re-added, issue still exists.
>
> Mongo version : 2.6.8
> node version : 4.4.3
> npm version : 3.8.9
>
>
>
I can see all the members in replicaSet from mongo console while performing rs.status() on primary and secondary.
Thanks for your help.
|
2018/05/17
|
[
"https://Stackoverflow.com/questions/50382346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6312882/"
] |
Found the issue to be not using fully qualified DNS names, while adding members to replicaSet. Thanks to @Neil Lunn.
|
1)Please check your connection string contain all DB sever names following bellow link
<https://docs.mongodb.com/manual/reference/connection-string/#standard-connection-string-format>
2) Do a fail-over
To do that log into primary node and execute below command
```
rs.stepDown()
```
|
34,085,256 |
I'm new to d3 js. I'm looking for a chart like [this](http://www.highcharts.com/demo/columnrange) one done in highcharts. In highcharts it is called column range graph. Is there any way to achieve this.
When I search in google the best thing I can get is a [basic bar chart](http://localhost:8088/Bar%20graph%20test/). Can any one help me how to make it a ranged graph?
|
2015/12/04
|
[
"https://Stackoverflow.com/questions/34085256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1958114/"
] |
Imagine I have dataset like this:
```
//these are the various categories
var categories = ['', 'Accessories', 'Audiophile', 'Camera & Photo', 'Cell Phones', 'Computers', 'eBook Readers', 'Gadgets', 'GPS & Navigation', 'Home Audio', 'Office Electronics', 'Portable Audio', 'Portable Video', 'Security & Surveillance', 'Service', 'Television & Video', 'Car & Vehicle'];
//these are the various categories cost
var dollars = [[100,213], [75,209], [50,190], [100,179], [140,156], [138, 209], [90, 190], [65,179], [100, 213], [100, 209], [50, 190], [76,179], [45,156], [80,209], [75,190], [55,190]];
```
Here in the dataset `Car&Vehicle` will have a cost range from `55$ to 190$`. Here `Television & Video` will have a cost range from `75$ to 190$` depending on quality.
Let's make x scale.
```
var xscale = d3.scale.linear()
.domain([10, 250])//minimum cast can be 10$ and maximum cost 250$
.range([0, 722]);
```
Lets make the rectangle bars.
```
var chart = canvas.append('g')
.attr("transform", "translate(150,0)")
.attr('id', 'bars')
.selectAll('rect')
.data(dollars)
.enter()
.append('rect')
.attr('height', 19)
.attr({
'x': function(d) {
return xscale(d[0]);//this defines the start position of the bar
},
'y': function(d, i) {
return yscale(i) + 19;
}
})
.style('fill', function(d, i) {
return colorScale(i);
})
.attr('width', function(d) {
return 0;
});
```
Now for transition the width of the bar will be:
```
var transit = d3.select("svg").selectAll("rect")
.data(dollars)
.transition()
.duration(1000)
.attr("width", function(d) {
return xscale(d[1]) - xscale(d[0]);//width of the bar will be upper range - lower range.
});
```
Full working code [here](http://plnkr.co/edit/XNsDCqZsUUajBH6Y1sNY?p=preview).
|
Your link to a basic bar chart does not work. That just looks like a horizontal bar chart, of which there are many exapmles. Here is one: <http://bl.ocks.org/mbostock/2368837>
|
48,878,418 |
I'm getting a **'Circular dependency detected'** error when I'm trying to install **Akavache 6.0.0-alpha0038** into my Xamarin.IOs project in Visual Studio 2017.
This is the error in detail,
```
Error Circular dependency detected 'akavache 6.0.0-alpha0038 => akavache.core 6.0.0-alpha0038 => System.Reactive 3.1.1 => System.Reactive.PlatformServices 4.0.0-preview00001 => System.Reactive 3.1.1'
```
How can I resolve this issue?
|
2018/02/20
|
[
"https://Stackoverflow.com/questions/48878418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4294275/"
] |
In your visual studio, open **Options Menu** (Tools > Options),
Then, Under, **NuGet Package Manager > General**, choose ***PackageReference*** as the *Default package management format* for Package Management *(refer image)*
[](https://i.stack.imgur.com/KMI4a.jpg)
Now try installing the nuget package, in this case **Akavache 6.0.0-alpha0038**.
Worked for me
**Note:** You have to remove *packages.config* file if it exists. You can remove the file, then install the package, then re-add the file.
|
Open nuget manager
select package
open options and select dropdown from 'install and update optoins' -'Ignore Dependency'
Same way for uninstall
[](https://i.stack.imgur.com/ea1Wt.jpg)
|
44,602,646 |
Let's assume:
```
CREATE TABLE Client(
ID_Client int primary key,
Name varchar(20));
CREATE TABLE Sale(
X int primary key,
ID_Client int REFERENCES Client(ID_Client));
INSERT INTO Client VALUES(123456, 'Sam');
INSERT INTO Sale VALUES(1, 123456);
```
How do I delete 'Sam' without deleting the Sale, and without losing It's FK value?
|
2017/06/17
|
[
"https://Stackoverflow.com/questions/44602646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7231775/"
] |
You can use an overlay to add some invisible edge on the side of the map that does capture the gesture for opening the drawer.
looks something like this:
```
const Screen = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
};
class Foo extends React.Component<Props, object> {
render() {
return (
<View style={styles.container}>
<MapView
style={styles.mapContainer}
/>
<View style={styles.mapDrawerOverlay} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
mapContainer: {
width: Screen.width,
height: Dimensions.get('window').height,
},
mapDrawerOverlay: {
position: 'absolute',
left: 0,
top: 0,
opacity: 0.0,
height: Dimensions.get('window').height,
width: 10,
},
});
```
This will use an overlay that is transparent and covers a small fraction of the map view. Beginning a drag-gesture in this area now can trigger the drawer.
[](https://i.stack.imgur.com/XtKWz.gif)
|
Do not use ...StyleSheet.absoluteFillObject on your map styles.
Doing this will resolve your issue
```html
const React = require("react-native");
const { StyleSheet, Dimensions } = React;
const { width, height } = Dimensions.get("window");
export default {
map: {
width: width,
height: height
}
};
```
|
44,602,646 |
Let's assume:
```
CREATE TABLE Client(
ID_Client int primary key,
Name varchar(20));
CREATE TABLE Sale(
X int primary key,
ID_Client int REFERENCES Client(ID_Client));
INSERT INTO Client VALUES(123456, 'Sam');
INSERT INTO Sale VALUES(1, 123456);
```
How do I delete 'Sam' without deleting the Sale, and without losing It's FK value?
|
2017/06/17
|
[
"https://Stackoverflow.com/questions/44602646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7231775/"
] |
You can use an overlay to add some invisible edge on the side of the map that does capture the gesture for opening the drawer.
looks something like this:
```
const Screen = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
};
class Foo extends React.Component<Props, object> {
render() {
return (
<View style={styles.container}>
<MapView
style={styles.mapContainer}
/>
<View style={styles.mapDrawerOverlay} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
mapContainer: {
width: Screen.width,
height: Dimensions.get('window').height,
},
mapDrawerOverlay: {
position: 'absolute',
left: 0,
top: 0,
opacity: 0.0,
height: Dimensions.get('window').height,
width: 10,
},
});
```
This will use an overlay that is transparent and covers a small fraction of the map view. Beginning a drag-gesture in this area now can trigger the drawer.
[](https://i.stack.imgur.com/XtKWz.gif)
|
You need to activate ToggleDrawer() when you hit the side of the map which is covered by a thin TouchableOpacity window. here is the example code in homeview. make sure to bring in props as a variable to your function.
```
import React from 'react';
import {View, Text, SafeAreaView, StyleSheet, Dimensions, TouchableOpacity} from 'react-native';
import MapView, {Marker} from 'react-native-maps';
const HomeScreen = (props) => {
return(
<SafeAreaView style = {{flex: 1}}>
<View style = {styles.container}>
<MapView
style={styles.mapStyle}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
}
/>
</MapView>
<TouchableOpacity style = {styles.mapDrawerOverlay} onPress = {() => {
props.navigationProps.toggleDrawer();}
} />
</View>
</SafeAreaView>
);
};
export default HomeScreen;
const styles = StyleSheet.create({
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'flex-end',
},
mapDrawerOverlay:{
position: 'absolute',
left: 0,
top: 0,
opacity: 0.0,
height: Dimensions.get('window').height,
width:10,
},
mapStyle: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
});
```
|
70,437,884 |
To prepare my upgrade from mysql 5.7 to mysql 8, I want to run the [upgrade utility checker](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-utilities-upgrade.html). Here's what I did so far:
1. installed [mysqlsh](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-install.html) on my machine
2. started mysqlsh
3. executed `util.checkForServerUpgrade` targeting the server that I want to upgrade
Here's the exact command that I used in step 3:
```
util.checkForServerUpgrade('root@my-remote-host:3306', { "password":"my-password" })
```
This runs fine but some checks are not executed because I don't provide the `configPath` parameter. For example, here's a warning that I get:
```
14) Removed system variables for error logging to the system log configuration
To run this check requires full path to MySQL server configuration file to be specified at 'configPath' key of options dictionary
More information:
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-13.html#mysqld-8-0-13-logging
```
Anybody knows the value that I should provide for the `configPath` parameter?
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70437884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679757/"
] |
At its root I believe you're asking a style question, which means you're unlikely to get a definitive answer. Opinions on style are, well, opinions.
Some people believe that you should use C's "natural" types — `char`, `short`, `int`, `long`, and their `unsigned` variants — most of the time, and that you should use exact-size types like `int32_t` only when you absolutely have to.
Some people believe that the variability implied by the "natural" types is an unrelenting source of bugs, and they believe that you should use exact-size types always.
Now, with that said, the specific case of writing
```
int32_t main(int32_t argc, int8_t *argv[])
```
is objectively wrong, for at least three reasons:
1. On a platform where type `int` is 16 bits, this wrongly declares `main`'s return type, and the type of the `argc` argument, as a 32-bit type.
2. On a platform where type `char` is unsigned, this wrongly declares `argv` as an array of signed character pointers. That's probably what gcc was complaining about for you.
3. On a more philosophical level, `main` is not a function whose function signature you get to pick. Somebody else declared `main`, somebody else is calling `main`, your job is only to provide a definition for `main`. So you simply have to use the types somebody else specified, even if your rule is that you want to use exact-size types whenever you can. Here, you can't.
Bottom line: Please use one of these two (equivalent) forms for `main` with arguments:
```
int main(int argc, char *argv[])
int main(int argc, char **argv)
```
Unless you're writing "freestanding" code, anything else is confusing, misleading, nonstandard, or wrong. (It's also acceptable to define a `main` that takes no arguments.)
>
> What is the best practice to use int8\_t?
>
>
>
I would say, when you really, really need a tiny, 8-bit, signed integer, or perhaps when you're manipulating memory as signed bytes. But I would not go using `int8_t` instead of `char` everywhere, because it's going to cause you lots of problems, and it's not going to buy you anything.
|
What you have posted is an implementation-defined form of `main()`. It is only allowed in two cases:
* Either it is 100% compatible with `int main (int argc, char** argv)`, or
* It is an implementation-defined form that the compiler documentation have told you is fine to use.
It is the C standard and the compiler which decide the acceptable forms of main(), never the programmer.
Notably `int8_t` may or may not be compatible with `char`, since `char` has implementation-defined signedness.
|
70,437,884 |
To prepare my upgrade from mysql 5.7 to mysql 8, I want to run the [upgrade utility checker](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-utilities-upgrade.html). Here's what I did so far:
1. installed [mysqlsh](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-install.html) on my machine
2. started mysqlsh
3. executed `util.checkForServerUpgrade` targeting the server that I want to upgrade
Here's the exact command that I used in step 3:
```
util.checkForServerUpgrade('root@my-remote-host:3306', { "password":"my-password" })
```
This runs fine but some checks are not executed because I don't provide the `configPath` parameter. For example, here's a warning that I get:
```
14) Removed system variables for error logging to the system log configuration
To run this check requires full path to MySQL server configuration file to be specified at 'configPath' key of options dictionary
More information:
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-13.html#mysqld-8-0-13-logging
```
Anybody knows the value that I should provide for the `configPath` parameter?
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70437884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679757/"
] |
At its root I believe you're asking a style question, which means you're unlikely to get a definitive answer. Opinions on style are, well, opinions.
Some people believe that you should use C's "natural" types — `char`, `short`, `int`, `long`, and their `unsigned` variants — most of the time, and that you should use exact-size types like `int32_t` only when you absolutely have to.
Some people believe that the variability implied by the "natural" types is an unrelenting source of bugs, and they believe that you should use exact-size types always.
Now, with that said, the specific case of writing
```
int32_t main(int32_t argc, int8_t *argv[])
```
is objectively wrong, for at least three reasons:
1. On a platform where type `int` is 16 bits, this wrongly declares `main`'s return type, and the type of the `argc` argument, as a 32-bit type.
2. On a platform where type `char` is unsigned, this wrongly declares `argv` as an array of signed character pointers. That's probably what gcc was complaining about for you.
3. On a more philosophical level, `main` is not a function whose function signature you get to pick. Somebody else declared `main`, somebody else is calling `main`, your job is only to provide a definition for `main`. So you simply have to use the types somebody else specified, even if your rule is that you want to use exact-size types whenever you can. Here, you can't.
Bottom line: Please use one of these two (equivalent) forms for `main` with arguments:
```
int main(int argc, char *argv[])
int main(int argc, char **argv)
```
Unless you're writing "freestanding" code, anything else is confusing, misleading, nonstandard, or wrong. (It's also acceptable to define a `main` that takes no arguments.)
>
> What is the best practice to use int8\_t?
>
>
>
I would say, when you really, really need a tiny, 8-bit, signed integer, or perhaps when you're manipulating memory as signed bytes. But I would not go using `int8_t` instead of `char` everywhere, because it's going to cause you lots of problems, and it's not going to buy you anything.
|
>
> What is the best practice to use int8\_t?
>
>
>
When you need a very small signed integer. That's not the same as `char`. `char` comes in three flavours:
```
signed char
unsigned char
char
```
If you *know* you want a signed `int8_t`, use it. If you are dealing with standard string API:s, like `main`, use `char`.
`int8_t` doesn't even need to exist. It's implementation specific. There are platforms where it doesn't exist.
The same goes for `int32_t` that you use instead of `int`. It doesn't necessarily exist and even if it does, it's not always a `typedef` for `int` - so use `int` if you want to stay portable.
|
70,437,884 |
To prepare my upgrade from mysql 5.7 to mysql 8, I want to run the [upgrade utility checker](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-utilities-upgrade.html). Here's what I did so far:
1. installed [mysqlsh](https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-install.html) on my machine
2. started mysqlsh
3. executed `util.checkForServerUpgrade` targeting the server that I want to upgrade
Here's the exact command that I used in step 3:
```
util.checkForServerUpgrade('root@my-remote-host:3306', { "password":"my-password" })
```
This runs fine but some checks are not executed because I don't provide the `configPath` parameter. For example, here's a warning that I get:
```
14) Removed system variables for error logging to the system log configuration
To run this check requires full path to MySQL server configuration file to be specified at 'configPath' key of options dictionary
More information:
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-13.html#mysqld-8-0-13-logging
```
Anybody knows the value that I should provide for the `configPath` parameter?
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70437884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679757/"
] |
At its root I believe you're asking a style question, which means you're unlikely to get a definitive answer. Opinions on style are, well, opinions.
Some people believe that you should use C's "natural" types — `char`, `short`, `int`, `long`, and their `unsigned` variants — most of the time, and that you should use exact-size types like `int32_t` only when you absolutely have to.
Some people believe that the variability implied by the "natural" types is an unrelenting source of bugs, and they believe that you should use exact-size types always.
Now, with that said, the specific case of writing
```
int32_t main(int32_t argc, int8_t *argv[])
```
is objectively wrong, for at least three reasons:
1. On a platform where type `int` is 16 bits, this wrongly declares `main`'s return type, and the type of the `argc` argument, as a 32-bit type.
2. On a platform where type `char` is unsigned, this wrongly declares `argv` as an array of signed character pointers. That's probably what gcc was complaining about for you.
3. On a more philosophical level, `main` is not a function whose function signature you get to pick. Somebody else declared `main`, somebody else is calling `main`, your job is only to provide a definition for `main`. So you simply have to use the types somebody else specified, even if your rule is that you want to use exact-size types whenever you can. Here, you can't.
Bottom line: Please use one of these two (equivalent) forms for `main` with arguments:
```
int main(int argc, char *argv[])
int main(int argc, char **argv)
```
Unless you're writing "freestanding" code, anything else is confusing, misleading, nonstandard, or wrong. (It's also acceptable to define a `main` that takes no arguments.)
>
> What is the best practice to use int8\_t?
>
>
>
I would say, when you really, really need a tiny, 8-bit, signed integer, or perhaps when you're manipulating memory as signed bytes. But I would not go using `int8_t` instead of `char` everywhere, because it's going to cause you lots of problems, and it's not going to buy you anything.
|
Your approach has many drawbacks:
* the prototype for `main()` is not compatible with any of the standard ones, even if `int` has 32 bits and if `char` is signed because `char` and `signed char` are different yet compatible types but `char *` and `signed char *` are incompatible types.
* if `int` is not the same as `int32_t`, the prototype is definitely incompatible with the standard one and the behavior is undefined.
* `printf("argv[%d] = %s\n", i, argv[i]);` would have undefined behavior if type `int` is not exactly the same as `int`. You could use the macros from `<inttypes.h>`, but they are rather cumbersome and would be the code less readable.
Hence the prototype for your `main` function should be `int main(int argc, char *argv[])` and for consistency, `i` should be defined with the same type as `argc`: `int`.
The resulting code is quite simple and readable:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
if (argc < 1) {
printf("Error\n");
}
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
```
I would argue that best practice regarding `int8_t` vs `char` is to use standard prototypes unchanged for `main` and all library functions. It is also advisable to use `char` for actual characters used for text as opposed to `int8_t` and `uint8_t` for signed and unsigned bytes read from binary contents. String literals should be considered `const` and manipulated via `const char *`. Code should behave in a defined manner regardless of the signedness of the char type. This is not just a question of style, it is a sane habit to improve code readability and sturdiness, avoid confusion and some mistakes.
|
73,922,977 |
ALL,
I finally moved away from the bitmaps and trying to use SVG in my C++ code.
I made an SVG using an InkScape and saved it as Compressed.
Then I edited the resulting file by adding the
```
static const char data[] =
```
in front of the XML and place every single line of XML inside double quotes.
The resulting file then is saved as .h file and included in the C++ source code.
However when compiling I am getting following:
```
error: stray ‘#’ in program
13 | " <g stroke="#000">"
| ^
```
What can I do? Linux does not have a notion of resources and I'd rather embed the graphics, than allow external file.
TIA!!
Below is the beginning of the header file in question:
`
static const char query[] =
""
""
" "
" rdf:RDF"
" <cc:Work rdf:about="">"
" <dc:format>image/svg+xml</dc:format>"
" <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>"
" <dc:title/>"
" </cc:Work>"
" </rdf:RDF>"
" "
" "
" "
" "
`
|
2022/10/02
|
[
"https://Stackoverflow.com/questions/73922977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945871/"
] |
You may want raw string literal introduced in C++ 11.
```
static const char data[] = R"xxx(<?xml version="1.0"...)xxx";
```
This is equivalent to
```
static const char data[] = "<?xml version=\"1.0\"...";
```
|
You need to format the data properly. To aid with this, please use an IDE or a good text editor such as Visual studio, Visual Studio Code or something similar. This would help you visualize the problem and fix it yourself
But to answer your question...
Use `' '` in place of `" "` to break the lines up.
Example:
`'<?xml version="1.0" encoding="UTF-8"?>'`
in place of
`"<?xml version="1.0" encoding="UTF-8"?>"`
|
73,922,977 |
ALL,
I finally moved away from the bitmaps and trying to use SVG in my C++ code.
I made an SVG using an InkScape and saved it as Compressed.
Then I edited the resulting file by adding the
```
static const char data[] =
```
in front of the XML and place every single line of XML inside double quotes.
The resulting file then is saved as .h file and included in the C++ source code.
However when compiling I am getting following:
```
error: stray ‘#’ in program
13 | " <g stroke="#000">"
| ^
```
What can I do? Linux does not have a notion of resources and I'd rather embed the graphics, than allow external file.
TIA!!
Below is the beginning of the header file in question:
`
static const char query[] =
""
""
" "
" rdf:RDF"
" <cc:Work rdf:about="">"
" <dc:format>image/svg+xml</dc:format>"
" <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>"
" <dc:title/>"
" </cc:Work>"
" </rdf:RDF>"
" "
" "
" "
" "
`
|
2022/10/02
|
[
"https://Stackoverflow.com/questions/73922977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945871/"
] |
I'm not sure if it's still fashionable, but a well known technique is to use a program called a *Resource Compiler* which can accept the file you give it and transform it into the encoded textual form that can be embedded into the code. Often these will produce a header file that creates a `char[]` object (or a `string` too, probably).
|
You need to format the data properly. To aid with this, please use an IDE or a good text editor such as Visual studio, Visual Studio Code or something similar. This would help you visualize the problem and fix it yourself
But to answer your question...
Use `' '` in place of `" "` to break the lines up.
Example:
`'<?xml version="1.0" encoding="UTF-8"?>'`
in place of
`"<?xml version="1.0" encoding="UTF-8"?>"`
|
73,922,977 |
ALL,
I finally moved away from the bitmaps and trying to use SVG in my C++ code.
I made an SVG using an InkScape and saved it as Compressed.
Then I edited the resulting file by adding the
```
static const char data[] =
```
in front of the XML and place every single line of XML inside double quotes.
The resulting file then is saved as .h file and included in the C++ source code.
However when compiling I am getting following:
```
error: stray ‘#’ in program
13 | " <g stroke="#000">"
| ^
```
What can I do? Linux does not have a notion of resources and I'd rather embed the graphics, than allow external file.
TIA!!
Below is the beginning of the header file in question:
`
static const char query[] =
""
""
" "
" rdf:RDF"
" <cc:Work rdf:about="">"
" <dc:format>image/svg+xml</dc:format>"
" <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>"
" <dc:title/>"
" </cc:Work>"
" </rdf:RDF>"
" "
" "
" "
" "
`
|
2022/10/02
|
[
"https://Stackoverflow.com/questions/73922977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945871/"
] |
You may want raw string literal introduced in C++ 11.
```
static const char data[] = R"xxx(<?xml version="1.0"...)xxx";
```
This is equivalent to
```
static const char data[] = "<?xml version=\"1.0\"...";
```
|
I'm not sure if it's still fashionable, but a well known technique is to use a program called a *Resource Compiler* which can accept the file you give it and transform it into the encoded textual form that can be embedded into the code. Often these will produce a header file that creates a `char[]` object (or a `string` too, probably).
|
10,911,976 |
I'm doing a project in JSP. I am using IDE and tomcat 6.0.35.
When I click on my first .jsp and say run on server, it runs fine. But if I only type the URL `localhost:8080` on the server it cannot display the homepage of tomcat.
Also when I start tomcat using the command line, it displays the tomcat home page but cannot display my first .jsp. It is giving an error like: `The requested resource (/project/first.jsp) is not available`.
|
2012/06/06
|
[
"https://Stackoverflow.com/questions/10911976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372442/"
] |
There's no such type as "a var type". A declaration using `var` just makes the compiler *infer* the type of the variable. It's still statically typed, and works as if you'd explicitly declared it - although it allows you to declare variables which use an *anonymous type*.
In your case we don't know what any of the methods involved do, which means we can't really tell what's going on. It sounds like `Query` is probably of type `IEnumerable<AccessPointItem>`. You'll need to express in code how to convert from an `AccessPointItem` to an `AccessPoint`.
A few points to note:
* Your query expression is somewhat pointless - you probably *just* want to call `tsvc.CreateQuery<AccessPointItem>()`
* Conventionally, local variables in C# use camel casing (starting with lower case letters) not Pascal case
* You create an array for no purpose - why?
* `Select()` will never return null, so you don't need to check for it
* Calling `Cast` will attempt to just cast each `AccessPointItem` to `AccessPoint`... is that really what you intended?
|
It looks as though you're you're mixing up your classes `AccessPoint` and `AccessPointItem`. Try this:
```
public static AccessPoint[] getAllAps()
{
return tsvc.CreateQuery<AccessPoint>("AccessPointTable").ToArray();
}
```
or this:
```
public static AccessPointItem[] getAllAps()
{
return tsvc.CreateQuery<AccessPointItem>("AccessPointTable").ToArray();
}
```
|
10,911,976 |
I'm doing a project in JSP. I am using IDE and tomcat 6.0.35.
When I click on my first .jsp and say run on server, it runs fine. But if I only type the URL `localhost:8080` on the server it cannot display the homepage of tomcat.
Also when I start tomcat using the command line, it displays the tomcat home page but cannot display my first .jsp. It is giving an error like: `The requested resource (/project/first.jsp) is not available`.
|
2012/06/06
|
[
"https://Stackoverflow.com/questions/10911976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1372442/"
] |
There's no such type as "a var type". A declaration using `var` just makes the compiler *infer* the type of the variable. It's still statically typed, and works as if you'd explicitly declared it - although it allows you to declare variables which use an *anonymous type*.
In your case we don't know what any of the methods involved do, which means we can't really tell what's going on. It sounds like `Query` is probably of type `IEnumerable<AccessPointItem>`. You'll need to express in code how to convert from an `AccessPointItem` to an `AccessPoint`.
A few points to note:
* Your query expression is somewhat pointless - you probably *just* want to call `tsvc.CreateQuery<AccessPointItem>()`
* Conventionally, local variables in C# use camel casing (starting with lower case letters) not Pascal case
* You create an array for no purpose - why?
* `Select()` will never return null, so you don't need to check for it
* Calling `Cast` will attempt to just cast each `AccessPointItem` to `AccessPoint`... is that really what you intended?
|
There is something wrong with the types involved.
First you read `AccessPointItem`:
```
var Query = from APs in tsvc.CreateQuery<AccessPointItem>(...)
```
Then you try to cast it to `AccessPoint`:
```
return Query.Cast<AccessPoint>()
```
You're gonna need to implement some kind of conversion method in order for that to work (unfortunately I never did it myself, but from a quick Google run I see plenty of info about the subject is available). I'll give it a shot off the top of my head:
```
//inside AccessPointItem.cs
public static AccessPoint ToAccessPoint(this AccessPointItem item) // extension method looks good for the job
{
AccessPoint retObj = new AccessPoint();
// assign properties from 'item' to 'retObj'
return retObj;
}
//Usage example in your case
return Query.Select(singleAccessPointItem => singleAccessPointItem.ToAccessPoint());
```
|
32,329,611 |
The [hibernate documentation](https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch02.html#d0e1472) says:
>
> With CMT, transaction demarcation is declared in session bean deployment descriptors, rather than performed in a programmatic manner.
>
>
>
but I can't find any complete example on how to do this.
This is what I have in mind my code should look like:
```
@Stateless
public class Dao{
@Inject // or some other annotation
private SessionFactory factory;
public void doDaoStuff(){
Object obj = factory.getCurrentSession().get(Entity.class, "Id");
// do something with obj
return;
}
}
```
It is free from all the boilerplate that hibernate has as transaction should be started, committed and roll backed by container.
So, Is it possible to do this? Although the documentation says that required declarations should be specified in **bean deployment descriptors**, doing it with annotations would be great.
|
2015/09/01
|
[
"https://Stackoverflow.com/questions/32329611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2965883/"
] |
In JavaEE environments Hibernate can use the CMT (Container Managed Transaction) strategy which will bind hibernate transactions with the underlying JTA transaction eliminating the need to manually begin, commit and rollback transactions. Example [here](http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#transactions-api-cmt-example).
However, there are problems:
1. This doesn't work in all Java EE Containers. Newer versions of Websphere are not supported and quoting from the [source code of hibernate](https://github.com/hibernate/hibernate-orm/blob/0a2a5c622e3eb30724e80bc8661c0ac55ebfb2be/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/WebSphereExtendedJtaPlatform.java) - *WebSphere, however, is not a sane JEE/JTA container...*
2. This restricts to one session one transaction idiom. Thus during the invocation of a EJB business method, there can be only one JTA or Hibernate transaction.
Luckily, using [CDI](http://cdi-spec.org/), and some custom interceptors this can be solved and a lot of Hibernate boilerplate can be removed. I wrote a sample on [github](https://github.com/vivekkr12/cdi-hibernate).
This approach creates a wrapper for [Hibernate SessionFactory](http://docs.jboss.org/hibernate/orm/5.1/javadocs/org/hibernate/SessionFactory.html) and provides most commonly used APIs. Using CDI, [`@RequestScoped`](http://docs.oracle.com/javaee/6/api/javax/enterprise/context/RequestScoped.html) Sessions are opened and closed automatically. Transactions are managed using an Interceptor. `@RequestScoped` ensures one `Session` per request so sessions aren't shared among multiple requests.
```
import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
@RequestScoped
public class MySessionFactory implements SessionFactoryTemplate{
@Inject
private SessionFactory sessionFactory;// Inject after creating the singleton instance
private Session currentSession;
public Session openSession(){
return sessionFactory.openSession();
}
public Session getCurrentSession(){
if(currentSession == null){
currentSession = sessionFactory.openSession();
}
return currentSession;
}
public StatelessSession openStatelessSession() {
return sessionFactory.openStatelessSession();
}
@PreDestroy
private void closeSession(){
if(currentSession!=null && currentSession.isOpen()) {
currentSession.close();
}
}
}
```
This implementation is then injected in database layer and used to obtain sessions.
```
import org.ares.cdi.hibernate.sf.MySessionFactory;
import org.ares.cdi.hibernate.interceptors.Transactional;
public class Dao {
@Inject
private MySessionFactory sf;
public void get(int id){
sf.getCurrentSession().get(clazz,id);
}
@Transactional
public void add(Object entity){
sf.getCurrentSesion().add(entity);
}
}
```
Transactions are managed by `TranscationManager` interceptor and declared by `@Transactional` annotation.
```
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.ares.cdi.hibernate.sf.MySessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.resource.transaction.spi.TransactionStatus;
@Interceptor
@Transactional
public class TransactionManager {
@Inject
private MySessionFactory sessionFactory;
@AroundInvoke
public Object handleTransaction(InvocationContext context) throws Exception{
Session session = sessionFactory.getCurrentSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
return context.proceed();
}
catch(Exception e){
tx.rollback();
throw e;
}
finally{
if(tx.getStatus().equals(TransactionStatus.ACTIVE)){
try{
tx.commit();
}
catch(Exception e){
tx.rollback();
throw e;
}
}
}
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Transactional {
}
```
|
EJB methods are transactional by default.
You can tweak their behavior using the [TransactionAttribute](http://docs.oracle.com/javaee/7/api/javax/ejb/TransactionAttribute.html) annotation.
You can read more about CMT here:
<https://docs.oracle.com/javaee/7/tutorial/transactions003.htm#BNCIJ>
<https://docs.oracle.com/javaee/7/tutorial/transactions.htm#BNCIH>
|
32,329,611 |
The [hibernate documentation](https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch02.html#d0e1472) says:
>
> With CMT, transaction demarcation is declared in session bean deployment descriptors, rather than performed in a programmatic manner.
>
>
>
but I can't find any complete example on how to do this.
This is what I have in mind my code should look like:
```
@Stateless
public class Dao{
@Inject // or some other annotation
private SessionFactory factory;
public void doDaoStuff(){
Object obj = factory.getCurrentSession().get(Entity.class, "Id");
// do something with obj
return;
}
}
```
It is free from all the boilerplate that hibernate has as transaction should be started, committed and roll backed by container.
So, Is it possible to do this? Although the documentation says that required declarations should be specified in **bean deployment descriptors**, doing it with annotations would be great.
|
2015/09/01
|
[
"https://Stackoverflow.com/questions/32329611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2965883/"
] |
In JavaEE environments Hibernate can use the CMT (Container Managed Transaction) strategy which will bind hibernate transactions with the underlying JTA transaction eliminating the need to manually begin, commit and rollback transactions. Example [here](http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#transactions-api-cmt-example).
However, there are problems:
1. This doesn't work in all Java EE Containers. Newer versions of Websphere are not supported and quoting from the [source code of hibernate](https://github.com/hibernate/hibernate-orm/blob/0a2a5c622e3eb30724e80bc8661c0ac55ebfb2be/hibernate-core/src/main/java/org/hibernate/engine/transaction/jta/platform/internal/WebSphereExtendedJtaPlatform.java) - *WebSphere, however, is not a sane JEE/JTA container...*
2. This restricts to one session one transaction idiom. Thus during the invocation of a EJB business method, there can be only one JTA or Hibernate transaction.
Luckily, using [CDI](http://cdi-spec.org/), and some custom interceptors this can be solved and a lot of Hibernate boilerplate can be removed. I wrote a sample on [github](https://github.com/vivekkr12/cdi-hibernate).
This approach creates a wrapper for [Hibernate SessionFactory](http://docs.jboss.org/hibernate/orm/5.1/javadocs/org/hibernate/SessionFactory.html) and provides most commonly used APIs. Using CDI, [`@RequestScoped`](http://docs.oracle.com/javaee/6/api/javax/enterprise/context/RequestScoped.html) Sessions are opened and closed automatically. Transactions are managed using an Interceptor. `@RequestScoped` ensures one `Session` per request so sessions aren't shared among multiple requests.
```
import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
@RequestScoped
public class MySessionFactory implements SessionFactoryTemplate{
@Inject
private SessionFactory sessionFactory;// Inject after creating the singleton instance
private Session currentSession;
public Session openSession(){
return sessionFactory.openSession();
}
public Session getCurrentSession(){
if(currentSession == null){
currentSession = sessionFactory.openSession();
}
return currentSession;
}
public StatelessSession openStatelessSession() {
return sessionFactory.openStatelessSession();
}
@PreDestroy
private void closeSession(){
if(currentSession!=null && currentSession.isOpen()) {
currentSession.close();
}
}
}
```
This implementation is then injected in database layer and used to obtain sessions.
```
import org.ares.cdi.hibernate.sf.MySessionFactory;
import org.ares.cdi.hibernate.interceptors.Transactional;
public class Dao {
@Inject
private MySessionFactory sf;
public void get(int id){
sf.getCurrentSession().get(clazz,id);
}
@Transactional
public void add(Object entity){
sf.getCurrentSesion().add(entity);
}
}
```
Transactions are managed by `TranscationManager` interceptor and declared by `@Transactional` annotation.
```
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.ares.cdi.hibernate.sf.MySessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.resource.transaction.spi.TransactionStatus;
@Interceptor
@Transactional
public class TransactionManager {
@Inject
private MySessionFactory sessionFactory;
@AroundInvoke
public Object handleTransaction(InvocationContext context) throws Exception{
Session session = sessionFactory.getCurrentSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
return context.proceed();
}
catch(Exception e){
tx.rollback();
throw e;
}
finally{
if(tx.getStatus().equals(TransactionStatus.ACTIVE)){
try{
tx.commit();
}
catch(Exception e){
tx.rollback();
throw e;
}
}
}
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Transactional {
}
```
|
Your Typical example would be like--
```
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
@TransactionManagement(TransactionManagementType.CONTAINER)
@Stateless(..)
public class YourBean{
@TransactionAttribute(TransactionAttributeType.REQUIRED) // if in case you wanted to use 'existing' transaction
public void DoStuff(){
}
}
```
And in your server configurations you require below tag under `<enterprise-beans>`
```
<transaction-type>Container</transaction-type>
```
|
7,415,960 |
I am working in selenium webdriver.I have few text boxes whose ids are going to change all the time.
e.g `id=ctl00_SPWebPartManager1_g_ad39b78c_a97b_4431_aedb_c9e6270134c6_ctl00_wizNotification_ucChangeData_txtAddress1`
but last part remains same always. in above example `wizNotification_ucChangeData_txtAddress1`
i have tried to go with xpath like:
```
//input[contains(@id,'txtAddress1')
//input[ends-with(@id,'txtAddress1')]
```
but while running not able to identify the textarea.
Any suggestions please.
I tried as well with: `//input[ends-with(@id,'wizNotification_ucChangeData_txtAddress1')]` but no Luck :(
|
2011/09/14
|
[
"https://Stackoverflow.com/questions/7415960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944554/"
] |
Xpaths are slow in IE because IE does not have native Xpath engine. You should instead use CSS Selector for better performance. As for your case, you can try below css selector which finds an input for which the id ends with txtAddress1
**E[foo$="bar"] an E element whose "foo" attribute value ends exactly with the string "bar"**
```
WebElement element = driver.findElement(By.cssSelector("input[id$='txtAddress1']"));
```
|
Try:
.//input[@id[contains(.,'txtAddress1')]]
Be careful, if is a textarea it won't be detected as an input.
|
7,415,960 |
I am working in selenium webdriver.I have few text boxes whose ids are going to change all the time.
e.g `id=ctl00_SPWebPartManager1_g_ad39b78c_a97b_4431_aedb_c9e6270134c6_ctl00_wizNotification_ucChangeData_txtAddress1`
but last part remains same always. in above example `wizNotification_ucChangeData_txtAddress1`
i have tried to go with xpath like:
```
//input[contains(@id,'txtAddress1')
//input[ends-with(@id,'txtAddress1')]
```
but while running not able to identify the textarea.
Any suggestions please.
I tried as well with: `//input[ends-with(@id,'wizNotification_ucChangeData_txtAddress1')]` but no Luck :(
|
2011/09/14
|
[
"https://Stackoverflow.com/questions/7415960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944554/"
] |
Try:
.//input[@id[contains(.,'txtAddress1')]]
Be careful, if is a textarea it won't be detected as an input.
|
In case of webelements with dynamic Ids, instead of going for Xpath with Ids we can go for other way of finding elements like 'by tagname', CSSlocator,.. it worked for me.
|
7,415,960 |
I am working in selenium webdriver.I have few text boxes whose ids are going to change all the time.
e.g `id=ctl00_SPWebPartManager1_g_ad39b78c_a97b_4431_aedb_c9e6270134c6_ctl00_wizNotification_ucChangeData_txtAddress1`
but last part remains same always. in above example `wizNotification_ucChangeData_txtAddress1`
i have tried to go with xpath like:
```
//input[contains(@id,'txtAddress1')
//input[ends-with(@id,'txtAddress1')]
```
but while running not able to identify the textarea.
Any suggestions please.
I tried as well with: `//input[ends-with(@id,'wizNotification_ucChangeData_txtAddress1')]` but no Luck :(
|
2011/09/14
|
[
"https://Stackoverflow.com/questions/7415960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944554/"
] |
Xpaths are slow in IE because IE does not have native Xpath engine. You should instead use CSS Selector for better performance. As for your case, you can try below css selector which finds an input for which the id ends with txtAddress1
**E[foo$="bar"] an E element whose "foo" attribute value ends exactly with the string "bar"**
```
WebElement element = driver.findElement(By.cssSelector("input[id$='txtAddress1']"));
```
|
In case of webelements with dynamic Ids, instead of going for Xpath with Ids we can go for other way of finding elements like 'by tagname', CSSlocator,.. it worked for me.
|
51,865,604 |
I was trying `USART` using a [`STM32F407VGT6`](https://www.st.com/en/microcontrollers/stm32f407vg.html) and `CubeMX`.
I am able to send and receive data using Interrupts. But I am getting a problem which I am not able to understand:
I am using `HAL_UART_Transmit_IT` to send the data.
I have enabled `__HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);`.
Here is my code:
```
int main(void)
{
HAL_Init();
MX_GPIO_Init();
MX_USART3_UART_Init();
Green_Blink(100);
Orange_Blink(100);
Blue_Blink(100);
Red_Blink(100);
HAL_Delay(100);
__HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);
char buff[] = {'2','4','.','0','0'};
while (1)
{
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
HAL_Delay(1000);
Blue_Blink(100);
}
}
```
So I am sending this kind of data. First, I am sending `OK` and then I am sending the buffer data as you can see.
But in terminal(*tera term* in my case) I can't see the buffer data.
I can see `OK`.
I don't know why this is happening. And how to resolve it?
Any suggestions?
|
2018/08/15
|
[
"https://Stackoverflow.com/questions/51865604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10231078/"
] |
You need to wait for the callback, which indicates the end of transmission . It is the interrupt function which is executed asynchronously. It does not have a chance to send even a single byte.
You just override the buffer and start the transmission over.
For this kind of messages, use blocking functions. Use DMA or interrupt ones when your main program is doing something during the communication, and you want the communication to be done in the background.
Edit
====
Some explanation.
HAL interrupt functions do not wait until the transmission is completed. They return **immediately** to the caller and the communication is completed in the background. The main program can execute in parallel doing another tasks.
When all bytes are sent (or on error) HAL library invokes the appropriate callback. For end of transmission it is: `void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)`
Because of the asynchronous execution if you want to start another transmission you need to know if the previous one has already completed.
Edit 2
======
In this case it does not make any sense to send asynchronously. You need to wait for the end of the previous transmissions:
```
volatile int USART3TransferCompleted;
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
USART3TransferCompleted = 1; // this functions should check the instance as well
}
```
and in main function:
```
USART3TransferCompleted = 0;
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
while(!USART3TransferCompleted);
USART3TransferCompleted = 0;
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
while(!USART3TransferCompleted);
...
```
|
```
if(HAL_UART_Transmit(&huart2, (uint8_t*)aTxBuffer, TXBUFFERSIZE, 5000)!= HAL_OK)
{
Error_Handler();
}
```
use this HAL function without callback interrupt.
|
51,865,604 |
I was trying `USART` using a [`STM32F407VGT6`](https://www.st.com/en/microcontrollers/stm32f407vg.html) and `CubeMX`.
I am able to send and receive data using Interrupts. But I am getting a problem which I am not able to understand:
I am using `HAL_UART_Transmit_IT` to send the data.
I have enabled `__HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);`.
Here is my code:
```
int main(void)
{
HAL_Init();
MX_GPIO_Init();
MX_USART3_UART_Init();
Green_Blink(100);
Orange_Blink(100);
Blue_Blink(100);
Red_Blink(100);
HAL_Delay(100);
__HAL_UART_ENABLE_IT(&huart3,UART_IT_TC);
char buff[] = {'2','4','.','0','0'};
while (1)
{
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
HAL_Delay(1000);
Blue_Blink(100);
}
}
```
So I am sending this kind of data. First, I am sending `OK` and then I am sending the buffer data as you can see.
But in terminal(*tera term* in my case) I can't see the buffer data.
I can see `OK`.
I don't know why this is happening. And how to resolve it?
Any suggestions?
|
2018/08/15
|
[
"https://Stackoverflow.com/questions/51865604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10231078/"
] |
You need to wait for the callback, which indicates the end of transmission . It is the interrupt function which is executed asynchronously. It does not have a chance to send even a single byte.
You just override the buffer and start the transmission over.
For this kind of messages, use blocking functions. Use DMA or interrupt ones when your main program is doing something during the communication, and you want the communication to be done in the background.
Edit
====
Some explanation.
HAL interrupt functions do not wait until the transmission is completed. They return **immediately** to the caller and the communication is completed in the background. The main program can execute in parallel doing another tasks.
When all bytes are sent (or on error) HAL library invokes the appropriate callback. For end of transmission it is: `void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)`
Because of the asynchronous execution if you want to start another transmission you need to know if the previous one has already completed.
Edit 2
======
In this case it does not make any sense to send asynchronously. You need to wait for the end of the previous transmissions:
```
volatile int USART3TransferCompleted;
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
USART3TransferCompleted = 1; // this functions should check the instance as well
}
```
and in main function:
```
USART3TransferCompleted = 0;
HAL_UART_Transmit_IT(&huart3,(uint8_t*)"OK\r\n ",5);
while(!USART3TransferCompleted);
USART3TransferCompleted = 0;
HAL_UART_Transmit_IT(&huart3,(uint8_t*)buff,5);
while(!USART3TransferCompleted);
...
```
|
I created my account just to say thanks to P\_\_J\_\_.
I struggled to send multiple HAL\_UART\_Transmit\_IT in a row as below.
HAL\_UART\_Transmit\_IT(&huart1,(uint8\_t\*) Test\_Buffer1, length1);
HAL\_Delay (1000);
HAL\_UART\_Transmit\_IT(&huart1,(uint8\_t\*) Test\_Buffer2, length2);
P\_\_J\_\_ solution above by using HAL\_UART\_TxCpltCallback to wait for the end of the previous transmissions WORKS perfectly.
|
2,641,858 |
I have a program in C using Solaris with VERY ancient compatibility it seems. Many examples, even here on SO, don't work, as well as lots of code I've written on Mac OS X.
**So when using very strict C, what is the safest way to pass strings?**
I'm currently using char pointers all over the place, due to what I thought was simplicity. So I have functions that return char\*, I'm passing char\* to them, etc.
I'm already seeing strange behavior, like a char\* I passed having its value right when I enter a function, and then the value being mysteriously gone OR corrupted/overwritten after something simple like one printf() or an malloc to some other pointer.
One approach to the functions, which I'm sure is incorrect, could be:
```
char *myfunction(char *somestr) {
char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr);
free(somestr);
/* ... some work ... */
char *returnstr = strdup(localstr);
return returnstr;
}
```
This seems...sloppy. Can anyone point me in the right direction on a simple requirement?
**Update**
One example of a function where I am at a loss for what is happening. Not sure if this is enough to figure it out, but here goes:'
```
char *get_fullpath(char *command, char *paths) {
printf("paths inside function %s\n", paths); // Prints value of paths just fine
char *fullpath = malloc(MAX_STRLENGTH*sizeof(char*));
printf("paths after malloc %s\n", paths); // paths is all of a sudden just blank
}
```
|
2010/04/15
|
[
"https://Stackoverflow.com/questions/2641858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158740/"
] |
Well-written C code adheres to the following convention:
* All functions return a status code of type **int**, where a return value of 0 indicates success, and a -1 indicates failure. On failure, the function should set `errno` with an appropriate value (e.g. EINVAL).
* Values that are "reported" by a function should be reported via the use of "out parameters". In other words, one of the parameters should be a pointer to the destination object.
* Ownership of pointers should belong to the invoker; consequently, a function should not `free` any of its parameters, and should only `free` objects that it, itself, allocates with `malloc/calloc`.
* Strings should be passed either as `const char*` objects or as `char*` objects, depending on whether the string is to be overwritten. If the string is not to be modified, then `const char*` should be used.
* Whenever an array is passed that is not a NUL-terminated string, a parameter should be provided indicating the the number of elements in the array or the capacity of that array.
* When a modifiable string/buffer (i.e. `char*`) object is passed into a function, and that function is to overwrite, append, or otherwise modify the string, a parameter indicating the capacity of the string/buffer needs to be provided (so as to allow for dynamic buffer sizes and to avoid bufffer overflow).
I should point out that in your example code, you are returning `localstr` and not `returnstr`. Consequently, you are returning an address of an object in the current function's stack frame. The current function's stack frame will disappear once the function has returned. Invoking another function immediately afterwards will likely alter the data in that location, leading to the corruption that you have observed. Returning the address of a local variable leads to "undefined behavior" and is incorrect.
**Edit**
Based on your updated code (get\_fullpath), it is clear that the problem is not in your function get\_fullpath, but rather in the function that is calling it. Most likely, the `paths` variable is being supplied by a function that returns the address of a local variable. Consequently, when you create a local variable within get\_fullpath, it is using the same exact location on the stack that paths previously occupied. Since "paths" is aliasing "fullpaths", it is basically overwritten with the address of the buffer that you've malloced, which is blank.
**Edit 2**
I have created a [C Coding Conventions](http://sites.google.com/site/michaelsafyan/coding/design/coding-best-practices/coding-conventions-for-c) page on [my website](http://sites.google.com/site/michaelsafyan/) with more detailed recommendations, explanations, and examples for writing C code, in case you are interested. Also, the statement that localstr is being returned instead of returnstr is no longer true since the question has last been edited.
|
You can't return a pointer to an array that's allocated locally within the function. As soon as the function returns, that array is going to be clobbered.
Also, when you put
```
char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr);
```
what happens is that strcpy() will copy the bytes into the localstr[] array, but then you have an unnecessary assignment thing going on. You could probably get the intended effect as two lines, thus ..
```
char localstr[MAX_STRLENGTH];
strcpy(localstr, somestr);
```
Also, it's bad form to embed a free() call inside a function like this. Ideally the free() should be visible at the same level of scope where the malloc() occurred. By the same logic it's a little dubious to allocate memory down in a function this way.
If you want a function to modify a string, a common convention goes something like so
```
// use a prototype like this to use the same buffer for both input and output
int modifyMyString(char buffer[], int bufferSize) {
// .. operate you find in buffer[],
// leaving the result in buffer[]
// and be sure not to exceed buffer length
// depending how it went, return EXIT_FAILURE or maybe
return EXIT_SUCCESS;
// or separate input and outputs
int workOnString(char inBuffer[], int inBufSize, char outBuffer[], int outBufSize) {
// (notice, you could replace inBuffer with const char *)
// leave result int outBuffer[], return pass fail status
return EXIT_SUCCESS;
```
Not embedding malloc() or free() inside will also help avoid memory leaks.
|
2,641,858 |
I have a program in C using Solaris with VERY ancient compatibility it seems. Many examples, even here on SO, don't work, as well as lots of code I've written on Mac OS X.
**So when using very strict C, what is the safest way to pass strings?**
I'm currently using char pointers all over the place, due to what I thought was simplicity. So I have functions that return char\*, I'm passing char\* to them, etc.
I'm already seeing strange behavior, like a char\* I passed having its value right when I enter a function, and then the value being mysteriously gone OR corrupted/overwritten after something simple like one printf() or an malloc to some other pointer.
One approach to the functions, which I'm sure is incorrect, could be:
```
char *myfunction(char *somestr) {
char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr);
free(somestr);
/* ... some work ... */
char *returnstr = strdup(localstr);
return returnstr;
}
```
This seems...sloppy. Can anyone point me in the right direction on a simple requirement?
**Update**
One example of a function where I am at a loss for what is happening. Not sure if this is enough to figure it out, but here goes:'
```
char *get_fullpath(char *command, char *paths) {
printf("paths inside function %s\n", paths); // Prints value of paths just fine
char *fullpath = malloc(MAX_STRLENGTH*sizeof(char*));
printf("paths after malloc %s\n", paths); // paths is all of a sudden just blank
}
```
|
2010/04/15
|
[
"https://Stackoverflow.com/questions/2641858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158740/"
] |
You can't return a pointer to an array that's allocated locally within the function. As soon as the function returns, that array is going to be clobbered.
Also, when you put
```
char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr);
```
what happens is that strcpy() will copy the bytes into the localstr[] array, but then you have an unnecessary assignment thing going on. You could probably get the intended effect as two lines, thus ..
```
char localstr[MAX_STRLENGTH];
strcpy(localstr, somestr);
```
Also, it's bad form to embed a free() call inside a function like this. Ideally the free() should be visible at the same level of scope where the malloc() occurred. By the same logic it's a little dubious to allocate memory down in a function this way.
If you want a function to modify a string, a common convention goes something like so
```
// use a prototype like this to use the same buffer for both input and output
int modifyMyString(char buffer[], int bufferSize) {
// .. operate you find in buffer[],
// leaving the result in buffer[]
// and be sure not to exceed buffer length
// depending how it went, return EXIT_FAILURE or maybe
return EXIT_SUCCESS;
// or separate input and outputs
int workOnString(char inBuffer[], int inBufSize, char outBuffer[], int outBufSize) {
// (notice, you could replace inBuffer with const char *)
// leave result int outBuffer[], return pass fail status
return EXIT_SUCCESS;
```
Not embedding malloc() or free() inside will also help avoid memory leaks.
|
Is your "update" example complete? I wouldn't think that would compile: it calls for a return value but you never return anything. You never do anything will fullpath, but perhaps that's deliberate, maybe your point is just to say that when you do the malloc, other things break.
Without seeing the caller, it's impossible to say definitively what is happening here. My guess is that paths is a dynamically-allocated block that was free'd before you called this function. Depending on the compiler implementation, a free'd block could still appear to contain valid data until a future malloc takes over the space.
**Update: to actually answer the question**
String handling is a well-known problem in C. If you create a fixed-size array to hold the string, you have to worry about a long string overflowing the allocated space. This means constantly checking string sizes on copies, using strncpy and strncat instead of the plain strcpy and strcat, or similar techniques. You can skip this and just say, "Well, no one would ever have a name longer than 60 characters" or some such, but there's always the danger then that someone will. Even on something that should have a known size, like a social security number or an ISBN, someone could make a mistake entering it and hit a key twice, or a malicious user could deliberately enter something long. Etc. Of course this is mostly an issue on data entry or reading files. Once you have a string in a field of some known size, then for any copies or other manipulation, you know the size.
The alternative is to use dynamically-allocated buffers where you can make them as big as needed. This sounds like a good solution when you first hear it, but in practice it's a giantic pain in C, because allocating the buffers and freeing them when you no longer need them is a lot of trouble. Another poster here said that the function that allocates a buffer should be the same one that frees it. A good rule of thumb, I generally agree, but ... What if a subroutine wants to return a string? So it allocates the buffer, returns it, and ... how can it free it? It can't because the whole point is that it wants to return it to the caller. The caller can't allocate the buffer because it doesn't know the size. Also, seemingly simple things like:
```
if (strcmp(getMeSomeString(),stringIWantToCompareItTo)==0) etc
```
are impossible. If the getMeSomeString function allocates the string, sure, it can return it so we do the compare, but now we've lost the handle and we can never free it. You end up having to write awkward code like
```
char* someString=getMeSomeString();
int f=strcmp(someString,stringIWantToCompareItTo);
free(someString);
if (f==0)
etc
```
So okay, it works, but readability just plummetted.
In practice, I've found that when strings can reasonably be expected to be of a knowable size, I allocate fixed-length buffers. If an input is bigger than the buffer, I either truncate it or give an error message, depending on the context. I only resort to dynamically-allocated buffers when the size is potentially large and unpredictable.
|
2,641,858 |
I have a program in C using Solaris with VERY ancient compatibility it seems. Many examples, even here on SO, don't work, as well as lots of code I've written on Mac OS X.
**So when using very strict C, what is the safest way to pass strings?**
I'm currently using char pointers all over the place, due to what I thought was simplicity. So I have functions that return char\*, I'm passing char\* to them, etc.
I'm already seeing strange behavior, like a char\* I passed having its value right when I enter a function, and then the value being mysteriously gone OR corrupted/overwritten after something simple like one printf() or an malloc to some other pointer.
One approach to the functions, which I'm sure is incorrect, could be:
```
char *myfunction(char *somestr) {
char localstr[MAX_STRLENGTH] = strcpy(localstr, somestr);
free(somestr);
/* ... some work ... */
char *returnstr = strdup(localstr);
return returnstr;
}
```
This seems...sloppy. Can anyone point me in the right direction on a simple requirement?
**Update**
One example of a function where I am at a loss for what is happening. Not sure if this is enough to figure it out, but here goes:'
```
char *get_fullpath(char *command, char *paths) {
printf("paths inside function %s\n", paths); // Prints value of paths just fine
char *fullpath = malloc(MAX_STRLENGTH*sizeof(char*));
printf("paths after malloc %s\n", paths); // paths is all of a sudden just blank
}
```
|
2010/04/15
|
[
"https://Stackoverflow.com/questions/2641858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158740/"
] |
Well-written C code adheres to the following convention:
* All functions return a status code of type **int**, where a return value of 0 indicates success, and a -1 indicates failure. On failure, the function should set `errno` with an appropriate value (e.g. EINVAL).
* Values that are "reported" by a function should be reported via the use of "out parameters". In other words, one of the parameters should be a pointer to the destination object.
* Ownership of pointers should belong to the invoker; consequently, a function should not `free` any of its parameters, and should only `free` objects that it, itself, allocates with `malloc/calloc`.
* Strings should be passed either as `const char*` objects or as `char*` objects, depending on whether the string is to be overwritten. If the string is not to be modified, then `const char*` should be used.
* Whenever an array is passed that is not a NUL-terminated string, a parameter should be provided indicating the the number of elements in the array or the capacity of that array.
* When a modifiable string/buffer (i.e. `char*`) object is passed into a function, and that function is to overwrite, append, or otherwise modify the string, a parameter indicating the capacity of the string/buffer needs to be provided (so as to allow for dynamic buffer sizes and to avoid bufffer overflow).
I should point out that in your example code, you are returning `localstr` and not `returnstr`. Consequently, you are returning an address of an object in the current function's stack frame. The current function's stack frame will disappear once the function has returned. Invoking another function immediately afterwards will likely alter the data in that location, leading to the corruption that you have observed. Returning the address of a local variable leads to "undefined behavior" and is incorrect.
**Edit**
Based on your updated code (get\_fullpath), it is clear that the problem is not in your function get\_fullpath, but rather in the function that is calling it. Most likely, the `paths` variable is being supplied by a function that returns the address of a local variable. Consequently, when you create a local variable within get\_fullpath, it is using the same exact location on the stack that paths previously occupied. Since "paths" is aliasing "fullpaths", it is basically overwritten with the address of the buffer that you've malloced, which is blank.
**Edit 2**
I have created a [C Coding Conventions](http://sites.google.com/site/michaelsafyan/coding/design/coding-best-practices/coding-conventions-for-c) page on [my website](http://sites.google.com/site/michaelsafyan/) with more detailed recommendations, explanations, and examples for writing C code, in case you are interested. Also, the statement that localstr is being returned instead of returnstr is no longer true since the question has last been edited.
|
Is your "update" example complete? I wouldn't think that would compile: it calls for a return value but you never return anything. You never do anything will fullpath, but perhaps that's deliberate, maybe your point is just to say that when you do the malloc, other things break.
Without seeing the caller, it's impossible to say definitively what is happening here. My guess is that paths is a dynamically-allocated block that was free'd before you called this function. Depending on the compiler implementation, a free'd block could still appear to contain valid data until a future malloc takes over the space.
**Update: to actually answer the question**
String handling is a well-known problem in C. If you create a fixed-size array to hold the string, you have to worry about a long string overflowing the allocated space. This means constantly checking string sizes on copies, using strncpy and strncat instead of the plain strcpy and strcat, or similar techniques. You can skip this and just say, "Well, no one would ever have a name longer than 60 characters" or some such, but there's always the danger then that someone will. Even on something that should have a known size, like a social security number or an ISBN, someone could make a mistake entering it and hit a key twice, or a malicious user could deliberately enter something long. Etc. Of course this is mostly an issue on data entry or reading files. Once you have a string in a field of some known size, then for any copies or other manipulation, you know the size.
The alternative is to use dynamically-allocated buffers where you can make them as big as needed. This sounds like a good solution when you first hear it, but in practice it's a giantic pain in C, because allocating the buffers and freeing them when you no longer need them is a lot of trouble. Another poster here said that the function that allocates a buffer should be the same one that frees it. A good rule of thumb, I generally agree, but ... What if a subroutine wants to return a string? So it allocates the buffer, returns it, and ... how can it free it? It can't because the whole point is that it wants to return it to the caller. The caller can't allocate the buffer because it doesn't know the size. Also, seemingly simple things like:
```
if (strcmp(getMeSomeString(),stringIWantToCompareItTo)==0) etc
```
are impossible. If the getMeSomeString function allocates the string, sure, it can return it so we do the compare, but now we've lost the handle and we can never free it. You end up having to write awkward code like
```
char* someString=getMeSomeString();
int f=strcmp(someString,stringIWantToCompareItTo);
free(someString);
if (f==0)
etc
```
So okay, it works, but readability just plummetted.
In practice, I've found that when strings can reasonably be expected to be of a knowable size, I allocate fixed-length buffers. If an input is bigger than the buffer, I either truncate it or give an error message, depending on the context. I only resort to dynamically-allocated buffers when the size is potentially large and unpredictable.
|
4,692,805 |
I have an int id column that I need to do a one-time maintenance/fix update on.
```
For example, currently the values look like this:
1
2
3
I need to make the following change:
1=3
2=1
3=2
```
Is there a way to do this in one statement? I keep imagining that the update will get confused if say the change from 1=3 to occurs then when it comes to 3=2 it will change that 1=3 update to 3=2 which gives
```
Incorrectly:
2
1
2
```
If that makes sense,
rod.
|
2011/01/14
|
[
"https://Stackoverflow.com/questions/4692805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] |
All of the assignments within an UPDATE statement (both the assignments within the SET clause, and the assignments on individual rows) are made as if they all occurred simultaneously.
So
```
UPDATE Table Set ID = ((ID + 1) % 3) + 1
```
(or whatever the right logic is, since I can't work out what "direction" is needed from the second table) would act correctly.
You can even use this knowledge to swap the value of two columns:
```
UPDATE Table SET a=b,b=a
```
will swap the contents of the columns, rather than (as you might expect) end up with both columns set to the same value.
|
In the past, I've done stuff like this by creating a temp table (whose structure is the same as the target table) with an extra column to hold the new value. Once I have all the new values, I'll then copy them to the target column in the target table, and delete the temp table.
|
4,692,805 |
I have an int id column that I need to do a one-time maintenance/fix update on.
```
For example, currently the values look like this:
1
2
3
I need to make the following change:
1=3
2=1
3=2
```
Is there a way to do this in one statement? I keep imagining that the update will get confused if say the change from 1=3 to occurs then when it comes to 3=2 it will change that 1=3 update to 3=2 which gives
```
Incorrectly:
2
1
2
```
If that makes sense,
rod.
|
2011/01/14
|
[
"https://Stackoverflow.com/questions/4692805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] |
This is how I usually do it
```
DECLARE @Update Table (@oldvalue int, @newvalue int)
INSERT INTO @Update Values (1,3)
INSERT INTO @Update Values (2,1)
INSERT INTO @Update Values (3,2)
Update Table
SET
yourField = NewValue
FROM
table t
INNER JOIN @Update
on t.yourField = @update.oldvalue
```
|
In the past, I've done stuff like this by creating a temp table (whose structure is the same as the target table) with an extra column to hold the new value. Once I have all the new values, I'll then copy them to the target column in the target table, and delete the temp table.
|
4,692,805 |
I have an int id column that I need to do a one-time maintenance/fix update on.
```
For example, currently the values look like this:
1
2
3
I need to make the following change:
1=3
2=1
3=2
```
Is there a way to do this in one statement? I keep imagining that the update will get confused if say the change from 1=3 to occurs then when it comes to 3=2 it will change that 1=3 update to 3=2 which gives
```
Incorrectly:
2
1
2
```
If that makes sense,
rod.
|
2011/01/14
|
[
"https://Stackoverflow.com/questions/4692805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] |
What about a sql case statement (something like this)?
```
UPDATE table SET intID = CASE
WHEN intID = 3 THEN 2
WHEN intID = 1 THEN 3
WHEN intID = 2 THEN 1
END
```
|
In the past, I've done stuff like this by creating a temp table (whose structure is the same as the target table) with an extra column to hold the new value. Once I have all the new values, I'll then copy them to the target column in the target table, and delete the temp table.
|
4,692,805 |
I have an int id column that I need to do a one-time maintenance/fix update on.
```
For example, currently the values look like this:
1
2
3
I need to make the following change:
1=3
2=1
3=2
```
Is there a way to do this in one statement? I keep imagining that the update will get confused if say the change from 1=3 to occurs then when it comes to 3=2 it will change that 1=3 update to 3=2 which gives
```
Incorrectly:
2
1
2
```
If that makes sense,
rod.
|
2011/01/14
|
[
"https://Stackoverflow.com/questions/4692805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] |
All of the assignments within an UPDATE statement (both the assignments within the SET clause, and the assignments on individual rows) are made as if they all occurred simultaneously.
So
```
UPDATE Table Set ID = ((ID + 1) % 3) + 1
```
(or whatever the right logic is, since I can't work out what "direction" is needed from the second table) would act correctly.
You can even use this knowledge to swap the value of two columns:
```
UPDATE Table SET a=b,b=a
```
will swap the contents of the columns, rather than (as you might expect) end up with both columns set to the same value.
|
This is how I usually do it
```
DECLARE @Update Table (@oldvalue int, @newvalue int)
INSERT INTO @Update Values (1,3)
INSERT INTO @Update Values (2,1)
INSERT INTO @Update Values (3,2)
Update Table
SET
yourField = NewValue
FROM
table t
INNER JOIN @Update
on t.yourField = @update.oldvalue
```
|
4,692,805 |
I have an int id column that I need to do a one-time maintenance/fix update on.
```
For example, currently the values look like this:
1
2
3
I need to make the following change:
1=3
2=1
3=2
```
Is there a way to do this in one statement? I keep imagining that the update will get confused if say the change from 1=3 to occurs then when it comes to 3=2 it will change that 1=3 update to 3=2 which gives
```
Incorrectly:
2
1
2
```
If that makes sense,
rod.
|
2011/01/14
|
[
"https://Stackoverflow.com/questions/4692805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139698/"
] |
What about a sql case statement (something like this)?
```
UPDATE table SET intID = CASE
WHEN intID = 3 THEN 2
WHEN intID = 1 THEN 3
WHEN intID = 2 THEN 1
END
```
|
This is how I usually do it
```
DECLARE @Update Table (@oldvalue int, @newvalue int)
INSERT INTO @Update Values (1,3)
INSERT INTO @Update Values (2,1)
INSERT INTO @Update Values (3,2)
Update Table
SET
yourField = NewValue
FROM
table t
INNER JOIN @Update
on t.yourField = @update.oldvalue
```
|
66,439,731 |
I try to display all values of tab but only 8 first elements are displayed no more
```
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
printf("taille %d: \n", sizeof(tab));
for (int i=0; i<sizeof(tab); i++)
{
printf("indice : %d et valeur :%d \n", i, *(tab + i ));
}
```
|
2021/03/02
|
[
"https://Stackoverflow.com/questions/66439731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8051903/"
] |
`sizeof(tab)` yields the size in bytes of all the array `tab` that contains `13` elements each of them having the size equal to `sizeof( int )` (that is the same as `sizeof( *tab )`). That is
`sizeof(tab)` is equal to `13 * sizeof( int )` that in turn can be equal to `52` provided that `sizeof( int )` is equal to `4`.
But you need to output only 13 elements of the array.
So you should write for example
```
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
const size_t N = sizeof( tab ) / sizeof( *tab );
printf( "taille %zu: \n", N );
for ( size_t i = 0; i < N; i++ )
{
printf( "indice : %zu et valeur :%d \n", i, *(tab + i ) );
}
putchar( '\n' );
```
Pay attention to that to output an object of the type `size_t` you need to use the conversion specifier `zu`.
Here is a demonstrative program where the array output is placed in a separate function.
```
#include <stdio.h>
FILE * output( const int tab[], size_t n, FILE *fp )
{
fprintf( fp, "taille %zu: \n", n );
for ( size_t i = 0; i < n; i++ )
{
fprintf( fp, "indice : %zu et valeur :%d \n", i, *(tab + i ) );
}
return fp;
}
int main(void)
{
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
const size_t N = sizeof( tab ) / sizeof( *tab );
fputc( '\n', output( tab, N, stdout ) );
return 0;
}
```
The program output is
```
taille 13:
indice : 0 et valeur :0
indice : 1 et valeur :2
indice : 2 et valeur :5
indice : 3 et valeur :3
indice : 4 et valeur :9
indice : 5 et valeur :0
indice : 6 et valeur :8
indice : 7 et valeur :9
indice : 8 et valeur :2
indice : 9 et valeur :0
indice : 10 et valeur :4
indice : 11 et valeur :3
indice : 12 et valeur :0
```
|
The line
```
printf("taille %d: \n", sizeof(tab));
```
invokes *undefined behavior*, allowing anything to happen, by passind data having wrong type to `printf()`. `%d` expects `int`, but `sizeof` returns `size_t`. The correct format specifier to print `size_t` in decimal is `%zu`.
Then, `sizeof(tab)` is the size of the array `tab` in bytes (number of `char`, strictly speaking). It is not the number of elements. To obtain the number of elements, you have to divide that by the size of one element `sizeof(*tab)`.
```
int tab[] = {0,2,5,3,9,0,8,9,2,0,4,3,0};
printf("taille %zu: \n", sizeof(tab));
for (int i=0; i<sizeof(tab)/sizeof(*tab); i++)
{
printf("indice : %d et valeur :%d \n", i, *(tab + i ));
}
```
|
14,422,193 |
I was trying to convert the content scraped into a list for data manipulation, but got the following error: TypeError: 'NoneType' object is not callable
```
#! /usr/bin/python
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import os
import re
# Copy all of the content from the provided web page
webpage = urlopen("http://www.optionstrategist.com/calculators/free-volatility- data").read()
# Grab everything that lies between the title tags using a REGEX
preBegin = webpage.find('<pre>') # Locate the pre provided
preEnd = webpage.find('</pre>') # Locate the /pre provided
# Copy the content between the pre tags
voltable = webpage[preBegin:preEnd]
# Pass the content to the Beautiful Soup Module
raw_data = BeautifulSoup(voltable).splitline()
```
|
2013/01/20
|
[
"https://Stackoverflow.com/questions/14422193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1906046/"
] |
The problem is the default hash value you give is a mutable value (partially, at least—see below), you need to instead use `Hash.new`’s block parameter:
```
hash = Hash.new { |h, k| h[k] = [] }
```
You get the correct result:
```
function ['cars', 'for', 'potatoes', 'racs', 'four']
#=> {"acrs"=>["cars", "racs"],
# "for"=>["for"],
# "aeoopstt"=>["potatoes"],
# "foru"=>["four"]}
```
The problem with what you have is that `hash[sorted]` returns `[]`, but never actually assigns to it. So you change the array, but never put it in the hash. If you use `+=` instead (leaving your `Hash.new([])`, you can that this also works:
```
hash[sorted] += [words]
```
|
### Assign Values to Hash Keys With `=`
You can fix your code easily by replacing `hash[sorted] << word` with the following:
```rb
hash[sorted] = word
```
That's the only change you actually needed to make your original code work. Consider:
```rb
def function(words)
hash = Hash.new([])
words.each do |word|
sorted = word.chars.sort.join
hash[sorted] = word
end
return hash
end
```
which returns:
```rb
function %w[cars for potatoes racs four]
# => {"acrs"=>"racs", "for"=>"for", "aeoopstt"=>"potatoes", "foru"=>"four"}
```
almost as you expected. In your posted example, *word* is a string, not an array. If you don't want to just fix the assignment, but to also cast the hash values as arrays, see the suggested refactoring below.
### Your Code Refactored
There are a number of ways you can clean this up your original method. For example, here's one way to refactor your code so that it's more idiomatic and easier to read.
```rb
def sort_words words
hash = {}
words.map { |word| hash[word.chars.sort.join] = Array(word) }
hash
end
sort_words %w[cars for potatoes racs four]
# => {"acrs"=>["racs"], "for"=>["for"], "aeoopstt"=>["potatoes"], "foru"=>["four"]}
```
Other refactorings are certainly possible---Ruby is a very flexible and expressive language---but this should get you started on the right path.
|
34,482,928 |
Happy Holidays! How do i get this function running? I can see the console.log running on the mouse wheel, however the function set to run once does not run. On the start i have also made sure that the body contains both the required classes.
```
var $body = $('body');
//using index
if(index == 2){
$body.css({
overflow: 'hidden'
});
if($body.hasClass('fp-viewing-secondPage')) {
$('html').on('mousewheel', function (e) {
console.log('fucks');
var delta = e.originalEvent.wheelDelta;
if($body.hasClass('setAn1')){
var something = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an1');
secret = true;
}
};
});
something();
}
if($body.hasClass('setAn2')){
var something2 = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an2');
secret = true;
}
};
});
something2();
}
});
}
}
```
|
2015/12/27
|
[
"https://Stackoverflow.com/questions/34482928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4917079/"
] |
```
var something = (function() {
var secret = false;
return function () {
if(!secret) {
console.log('call me once please an1');
secret = true;
}
};
})();
```
You have the above block which is an IIFE. I believe what it's doing is assigning the below function to the something variable.
```
function () {
if(!secret) {
console.log('call me once please an1');
secret = true;
}
```
You'd have to then call the something() here.
```
secret = true;
}
};
})();
something();
}
```
I ported the structure of your program over into jfiddle. Your primary problem is that you're modifying a value who was defined inside of the scope created by the definition of the function. This value only lasts as long as that function is currently executing, once you leave the function the value leaves scope. What you need to do is define the variable outside the scope of the function so that you won't lose the state you're trying to keep between clicks.
Here's a minimal example. You'll see the secret gets set once you go through the loop, and then prevents the function's if() condition from being evaluated again.
```
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
var secret = false;
$('img').on('click', function(e) {
console.log('what is my secret outside?', secret);
if (!secret) {
console.log('what is my secret inside?', secret);
secret = true;
}
});
```
<https://jsfiddle.net/wa819y2j/9/>
|
```
var something = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an1');
secret = true;
}
};
});
var something2 = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an2');
secret = true;
}
};
});
var $body = $('body');
//using index
if(index == 2){
$body.css({
overflow: 'hidden'
});
if($body.hasClass('fp-viewing-secondPage')) {
$('html').on('mousewheel', function (e) {
console.log('fucks');
var delta = e.originalEvent.wheelDelta;
if($body.hasClass('setAn1')){
something();
}
if($body.hasClass('setAn2')){
something2();
}
});
}
}
```
Or else:
```
function runOnce(fun) {
var secret = false;
return function () {
if(!secret){
fun();
secret = true;
}
};
}
var something = runOnce(function() {
console.log('call me once please an1');
});
var something2 = runOnce(function() {
console.log('call me once please an2');
});
```
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
Short Answer
------------
Because modded Minecraft tech support questions are a problem, similar questions for other games are not. 99% of the time we can't provide a fix, even with a crash dump, and the best we can do is identify what's breaking.
Long Answer
-----------
There's a few factors which mean that Minecraft mod tech support is an issue:
* Minecraft crash questions usually consist of dealing with a crash dump.
* Minecraft modding goes deep enough that crashes are frequent, especially when mods are combined.
* Mods are often combined into modpacks, leading to a very large number of variables to try and deal with.
* When Minecraft crashes, to a non-technical player, there's no observable difference between it being a Minecraft problem or a mod problem.
* Minecraft (I'd wager) has a younger player-base than most other games. These people are sometimes less able to understand and articulate a technical question well.
* Minecraft is still the largest tag on the site, and mods are hugely popular due to their use by popular YouTubers (appealing to the younger players).
I did a bit of searching. Another heavily modded game, Skyrim (our second largest tag) has three mod/crash questions. The nature of modding in this game is very different, and all three have accepted answers.
Given the massive scope of Minecraft mod/packs, part of the reason this decision has been made is that 99% of the time there isn't a good answer, or there isn't an answer at all.
|
We need answerable questions. Many Minecraft questions, featuring complications from mods, do not meet the [Real Questions Have Answers](http://blog.stackoverflow.com/2011/01/real-questions-have-answers/) criteria.
From the end of that article, there is this:
>
> real questions have answers, not items or ideas or opinions.
>
>
>
I personally believe that several of the questions that have come up do not meet this point.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
**Good question**. I think the main reason the discussion centered around Minecraft is because it has been the most active and most problematic category of technical issues questions by several orders of magnitude. But the notion that Minecraft technical support in particular is problematic as a category is... troubling. Singling out one game in particular just because it is popular is extremely problematic.
If we're going to disallow technical issues questions, let's just disallow them, rather than focus on one game that has been producing them. Banning Minecraft technical issues questions in particular is extremely arbitrary at best, and at worst, gives an appearance that we just don't want to deal with Minecraft anymore.
|
We need answerable questions. Many Minecraft questions, featuring complications from mods, do not meet the [Real Questions Have Answers](http://blog.stackoverflow.com/2011/01/real-questions-have-answers/) criteria.
From the end of that article, there is this:
>
> real questions have answers, not items or ideas or opinions.
>
>
>
I personally believe that several of the questions that have come up do not meet this point.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
Ok, I've thought about this a bit more:
We're not banning Minecraft mod tech support
============================================
We're discussing what the close reason should be for unanswerable Minecraft mod crash questions - which we get a lot of - and are *nearly* all unanswerable.
With that in mind...
--------------------
We should aim for this description to be general enough, so that *unanswerable* crash questions relating to other games are also covered.
|
We need answerable questions. Many Minecraft questions, featuring complications from mods, do not meet the [Real Questions Have Answers](http://blog.stackoverflow.com/2011/01/real-questions-have-answers/) criteria.
From the end of that article, there is this:
>
> real questions have answers, not items or ideas or opinions.
>
>
>
I personally believe that several of the questions that have come up do not meet this point.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
I think Mods, and even Minecraft are a red herring - they produce most of our issues, simply because of the sheer quantity of Minecraft questions, and because of the specific kinds of ways in which Minecraft fails, which are uniquely problematic, but not unique to Minecraft.
What kind of Tech Support questions are we good at, regardless of the specific game in question?
* Configuration - especially things like running games at non standard resolutions, or managing file locations.
* Clearly defined, reproducible *gameplay* bugs.
* Specific, well defined, and widely known issues, often associated with specific *error codes*, as opposed to verbose crash dumps.
What kind of Tech Support questions are we bad at, regardless of the specific game in question?
* Anything involving a crash that doesn't recur in a clearly defined, reproducible manner.
* Anything involving a verbose crash-log that requires *significant* effort and decoding in order to even have a chance at retrieving potentially useful information.
Which then leaves a fairly clear boundary for what kind of tech support questions we don't allow: anything involving a game crash that is not repeatable and reproducible. A sample close reason for this *might* look like:
>
> Questions seeking **Technical Support For Non-Reproducible Issues**, as well as **Technical Support Based on Crash Dumps or Logs** are off topic. Without clear steps to identify and reproduce your problem, the Q&A format isn't an appropriate format for in-depth troubleshooting, and tends not to produce results that are useful to future visitors. Your best option is probably to contact the manufacturer of your hardware, or the developer of your game or any mods you might be using, as appropriate.
>
>
>
(Actually, that's 100 characters too long. Here's a shortened version that I don't like as much. Suggestions welcome.)
>
> Questions seeking **Technical Support For Non-Reproducible Issues**, as well as those **Based on Crash Dumps or Logs** are off topic. Without clear steps to identify and reproduce your problem, the Q&A format isn't an appropriate format for in-depth troubleshooting. Your best option is probably to contact the the developer of your game or any mods you might be using, as appropriate.
>
>
>
|
We need answerable questions. Many Minecraft questions, featuring complications from mods, do not meet the [Real Questions Have Answers](http://blog.stackoverflow.com/2011/01/real-questions-have-answers/) criteria.
From the end of that article, there is this:
>
> real questions have answers, not items or ideas or opinions.
>
>
>
I personally believe that several of the questions that have come up do not meet this point.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
Ok, I've thought about this a bit more:
We're not banning Minecraft mod tech support
============================================
We're discussing what the close reason should be for unanswerable Minecraft mod crash questions - which we get a lot of - and are *nearly* all unanswerable.
With that in mind...
--------------------
We should aim for this description to be general enough, so that *unanswerable* crash questions relating to other games are also covered.
|
Short Answer
------------
Because modded Minecraft tech support questions are a problem, similar questions for other games are not. 99% of the time we can't provide a fix, even with a crash dump, and the best we can do is identify what's breaking.
Long Answer
-----------
There's a few factors which mean that Minecraft mod tech support is an issue:
* Minecraft crash questions usually consist of dealing with a crash dump.
* Minecraft modding goes deep enough that crashes are frequent, especially when mods are combined.
* Mods are often combined into modpacks, leading to a very large number of variables to try and deal with.
* When Minecraft crashes, to a non-technical player, there's no observable difference between it being a Minecraft problem or a mod problem.
* Minecraft (I'd wager) has a younger player-base than most other games. These people are sometimes less able to understand and articulate a technical question well.
* Minecraft is still the largest tag on the site, and mods are hugely popular due to their use by popular YouTubers (appealing to the younger players).
I did a bit of searching. Another heavily modded game, Skyrim (our second largest tag) has three mod/crash questions. The nature of modding in this game is very different, and all three have accepted answers.
Given the massive scope of Minecraft mod/packs, part of the reason this decision has been made is that 99% of the time there isn't a good answer, or there isn't an answer at all.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
I think Mods, and even Minecraft are a red herring - they produce most of our issues, simply because of the sheer quantity of Minecraft questions, and because of the specific kinds of ways in which Minecraft fails, which are uniquely problematic, but not unique to Minecraft.
What kind of Tech Support questions are we good at, regardless of the specific game in question?
* Configuration - especially things like running games at non standard resolutions, or managing file locations.
* Clearly defined, reproducible *gameplay* bugs.
* Specific, well defined, and widely known issues, often associated with specific *error codes*, as opposed to verbose crash dumps.
What kind of Tech Support questions are we bad at, regardless of the specific game in question?
* Anything involving a crash that doesn't recur in a clearly defined, reproducible manner.
* Anything involving a verbose crash-log that requires *significant* effort and decoding in order to even have a chance at retrieving potentially useful information.
Which then leaves a fairly clear boundary for what kind of tech support questions we don't allow: anything involving a game crash that is not repeatable and reproducible. A sample close reason for this *might* look like:
>
> Questions seeking **Technical Support For Non-Reproducible Issues**, as well as **Technical Support Based on Crash Dumps or Logs** are off topic. Without clear steps to identify and reproduce your problem, the Q&A format isn't an appropriate format for in-depth troubleshooting, and tends not to produce results that are useful to future visitors. Your best option is probably to contact the manufacturer of your hardware, or the developer of your game or any mods you might be using, as appropriate.
>
>
>
(Actually, that's 100 characters too long. Here's a shortened version that I don't like as much. Suggestions welcome.)
>
> Questions seeking **Technical Support For Non-Reproducible Issues**, as well as those **Based on Crash Dumps or Logs** are off topic. Without clear steps to identify and reproduce your problem, the Q&A format isn't an appropriate format for in-depth troubleshooting. Your best option is probably to contact the the developer of your game or any mods you might be using, as appropriate.
>
>
>
|
Short Answer
------------
Because modded Minecraft tech support questions are a problem, similar questions for other games are not. 99% of the time we can't provide a fix, even with a crash dump, and the best we can do is identify what's breaking.
Long Answer
-----------
There's a few factors which mean that Minecraft mod tech support is an issue:
* Minecraft crash questions usually consist of dealing with a crash dump.
* Minecraft modding goes deep enough that crashes are frequent, especially when mods are combined.
* Mods are often combined into modpacks, leading to a very large number of variables to try and deal with.
* When Minecraft crashes, to a non-technical player, there's no observable difference between it being a Minecraft problem or a mod problem.
* Minecraft (I'd wager) has a younger player-base than most other games. These people are sometimes less able to understand and articulate a technical question well.
* Minecraft is still the largest tag on the site, and mods are hugely popular due to their use by popular YouTubers (appealing to the younger players).
I did a bit of searching. Another heavily modded game, Skyrim (our second largest tag) has three mod/crash questions. The nature of modding in this game is very different, and all three have accepted answers.
Given the massive scope of Minecraft mod/packs, part of the reason this decision has been made is that 99% of the time there isn't a good answer, or there isn't an answer at all.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
Ok, I've thought about this a bit more:
We're not banning Minecraft mod tech support
============================================
We're discussing what the close reason should be for unanswerable Minecraft mod crash questions - which we get a lot of - and are *nearly* all unanswerable.
With that in mind...
--------------------
We should aim for this description to be general enough, so that *unanswerable* crash questions relating to other games are also covered.
|
**Good question**. I think the main reason the discussion centered around Minecraft is because it has been the most active and most problematic category of technical issues questions by several orders of magnitude. But the notion that Minecraft technical support in particular is problematic as a category is... troubling. Singling out one game in particular just because it is popular is extremely problematic.
If we're going to disallow technical issues questions, let's just disallow them, rather than focus on one game that has been producing them. Banning Minecraft technical issues questions in particular is extremely arbitrary at best, and at worst, gives an appearance that we just don't want to deal with Minecraft anymore.
|
10,568 |
[As we are making the Minecraft mod technical questions ban super-duper official](https://gaming.meta.stackexchange.com/questions/10564/what-should-an-off-topic-close-reason-for-minecraft-crash-dumps-look-like) with a close-reason and everything, I feel that this question remains in dire need of a satisfactory answer:
**Why just Minecraft?**
What about Minecraft, and Minecraft modding specifically, makes the game so *extraordinary* that we are drafting our very first rule targeting one and only one game? Why is Minecraft special? What could make a game in the future become just as special as Minecraft?
There are quite a few games with lots of mods out there. I'm sure there are elventy bajillion combinations of mutually incompatible mods for, say, Skyrim. Why are technical questions involving Skyrim mods on-topic, then?
|
2015/05/22
|
[
"https://gaming.meta.stackexchange.com/questions/10568",
"https://gaming.meta.stackexchange.com",
"https://gaming.meta.stackexchange.com/users/23/"
] |
I think Mods, and even Minecraft are a red herring - they produce most of our issues, simply because of the sheer quantity of Minecraft questions, and because of the specific kinds of ways in which Minecraft fails, which are uniquely problematic, but not unique to Minecraft.
What kind of Tech Support questions are we good at, regardless of the specific game in question?
* Configuration - especially things like running games at non standard resolutions, or managing file locations.
* Clearly defined, reproducible *gameplay* bugs.
* Specific, well defined, and widely known issues, often associated with specific *error codes*, as opposed to verbose crash dumps.
What kind of Tech Support questions are we bad at, regardless of the specific game in question?
* Anything involving a crash that doesn't recur in a clearly defined, reproducible manner.
* Anything involving a verbose crash-log that requires *significant* effort and decoding in order to even have a chance at retrieving potentially useful information.
Which then leaves a fairly clear boundary for what kind of tech support questions we don't allow: anything involving a game crash that is not repeatable and reproducible. A sample close reason for this *might* look like:
>
> Questions seeking **Technical Support For Non-Reproducible Issues**, as well as **Technical Support Based on Crash Dumps or Logs** are off topic. Without clear steps to identify and reproduce your problem, the Q&A format isn't an appropriate format for in-depth troubleshooting, and tends not to produce results that are useful to future visitors. Your best option is probably to contact the manufacturer of your hardware, or the developer of your game or any mods you might be using, as appropriate.
>
>
>
(Actually, that's 100 characters too long. Here's a shortened version that I don't like as much. Suggestions welcome.)
>
> Questions seeking **Technical Support For Non-Reproducible Issues**, as well as those **Based on Crash Dumps or Logs** are off topic. Without clear steps to identify and reproduce your problem, the Q&A format isn't an appropriate format for in-depth troubleshooting. Your best option is probably to contact the the developer of your game or any mods you might be using, as appropriate.
>
>
>
|
**Good question**. I think the main reason the discussion centered around Minecraft is because it has been the most active and most problematic category of technical issues questions by several orders of magnitude. But the notion that Minecraft technical support in particular is problematic as a category is... troubling. Singling out one game in particular just because it is popular is extremely problematic.
If we're going to disallow technical issues questions, let's just disallow them, rather than focus on one game that has been producing them. Banning Minecraft technical issues questions in particular is extremely arbitrary at best, and at worst, gives an appearance that we just don't want to deal with Minecraft anymore.
|
22,076,269 |
(I believe) I know about overloading functions based on const-ness: if the instant is const, the const method is called, otherwise the non-const one.
Example (also at [ideone](http://ideone.com/E9AIXV)):
```
#include <iostream>
struct S
{
void print() const { std::cout << "const method" <<std::endl };
void print() { std::cout << "non-const method" <<std::endl };
};
int main()
{
S const s1;
s1.print(); // prints "const method"
S s2;
s2.print(); // prints "non-const method"
return 0;
};
```
I try/tried to make use of that in my code, but ran into some issues when the `const` overloaded methods don't have the same access category. It might be bad style, but here is an example that reflects the idea of returning references to avoid copying and using `const` to limit unintended alterations:
```
struct Color;
struct Shape
{
double area;
};
class Geometry
{
public:
// everybody can alter the color of the geometry, so
// they get a mutable reference
Color& color() { return m_color; };
// not everybody can alter the shape of the Geometry, so
// they get a constant reference to the shape.
Shape const& shape() const { return m_shape; };
protected:
// derived classes can alter the shape, so they get
// access to the mutable reference to alter the shape.
Shape & shape() { return m_shape; };
private:
Shape m_shape;
Color m_color;
};
```
The problem I am facing now is that I want the compiler to pick up the public, `const`-returning shape function if some other function messes with the Geometries, say color them by their area, for which this would need to access the shape of the Geometry:
```
// this one fails
void colorByArea() {
for( Geometry g : geometryList )
{ g.color() = colorMap[g.shape().area]; }
}
// this one is a clunky workaround
void colorByArea() {
for( Geometry g : geometryList )
{
Geometry const& g_const = g;
g.color() = colorMap[g_const.shape().area];
}
}
```
This (or something similar) fails with the following fairly understandable error:
```
‘Shape& Geometry::shape()’ is protected
Shape & shape() { return m_shape; };
^ error: within this context
g.color() = colorMap[g.shape().area];
```
(I put up a slightly simplified non-compiling example at [ideone](http://ideone.com/POKMDj).)
I get (to a degree) why this is happeding:`g` is not `const` and hence the non-const shape(), which is protectec, is supposedly to be called -- but that obviously fails.
So I guess my **QUESTION** is:
*Is there a way to get some sort of "fall back" to a const-function if a non-const function is not accessible?*
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22076269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1984137/"
] |
>
> *Is there a way to get some sort of "fall back" to a const-function if a non-const function is not accessible?*
>
>
>
No; overload resolution occurs before access check.
This is not just bad style; it is bad design. A public getter function is *conceptually different* from a protected function that lets code with knowledge of internals modify the object's internal state. In general the two functions need not even have related return types. Therefore they should not have the same name.
|
You may use `const_cast` to allow to call the const version as:
```
int main()
{
S s2;
const_cast<const S&>(s2).print(); // prints "const method"
return 0;
};
```
But it would be better/simpler to rename one of the method.
|
50,116,383 |
Say I have the following array:
```
$n[5] = "hello";
$n[10]= "goodbye";`
```
I would like to find out the highest index of this array.
In Javascript, I could do `$n.length - 1` which would return `10`.
In PHP, though, `count($n)` returns 2, which is the number of elements in the array.
So how to get the highest index of the array?
|
2018/05/01
|
[
"https://Stackoverflow.com/questions/50116383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4821689/"
] |
Use [max()](http://php.net/manual/en/function.max.php) and [array\_keys()](http://php.net/manual/en/function.array-keys.php)
```
echo max(array_keys($n));
```
Output:-<https://eval.in/997652>
|
```
$n = [];
$n[5] = "hello";
$n[10]= "goodbye";
// get the list of key
$keyList = array_keys($n);
// get the biggest key
$maxIndex = max($keyList);
echo $n[$maxIndex];
```
output
```
goodbye
```
|
9,165 |
I have found a conflict in how I want to UV unwrap my model for cloth modeling:
For material patches, it seems natural to make use of the seams the real thing would have (easier to paint the texture correctly).
For making seams look like seams I need to be able to paint over the real seam, making it hard if I use the real seam as UV seam.
How are such cases usually handled?
|
2014/05/06
|
[
"https://blender.stackexchange.com/questions/9165",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/3258/"
] |
I really wish Blender supported this out the box and it could be as easy as enabling/disabling 3D manipulator. But the simplest way I found is the following. Assuming you started with default scene with a cube:
1. Enable Rigid Body for the cube in *Properties > Physics* and select the first Cube and *Properties > Physics* choose **Passive** for *Rigid Body > Type*.
2. Duplicate it (`Shift``D`) and move (`G`, `X`) new cube somewhere so it does not touch original.
3. Set *End frame* to big number, for example, **10000**. Make sure *Properties > Scene > Rigid Body World* is enabled and set *End* in *Rigid Body Cache* to the same big number (10000 in this case). You also may want to disable *Gravity*.
4. Select the second cube and duplicate it and in Edit mode with pivot set to *Median Point* scale up the third cube slightly (for example, **1.01**), set its **Maximum Draw Type** (in *Properties > Object > Display*) to **Wire**. In *Properties > Physics > Rigid Body Collisions* choose **Mesh as Shape** and (assuming 1 BU = 1m) *Margin* to **3mm** (if it fly away immediately when you start playing animation at step #6 - try smaller value and return to frame 1 to start again). Go back to *Object Mode*.
5. Select the second Cube (the one you actually want to move) and in *Properties > Physics* choose **Active** for *Rigid Body > Type*.
6. Click Play Animation. To manipulate, select the third cube (displayed as *Wire*) and move it. Second cube will follow and *Rigid Body Physics* will do its best to prevent collisions, but if you force it too much, it may fly away; if it does, press `Esc` and go back to first frame to try again. To put it on other object without intersection, move it slowly, when it start shaking it means slight intersection happened, move it away a bit and when it stops shaking, stop moving. When done moving/rotating, pause animation, select all, `Ctrl``A` to **Apply** and choose **Visual Transform** and then go back to Start frame.
Obvious drawbacks is that you have to enable Rigid Body on objects and create temporary object to move object you want to move, then delete temporary object, not to mention the temporary object introduces problems - direct manipulation would be much more convenient.
|
In the latest version of Blender, right now it is 2.71, there is a selection called mesh in the collision tab. This seems to work very well for most active rigid body objects.
There is a tutorial by PHYMEC on YouTube addressing this very issue and he goes into great depth about the sphere of influence of an object on another object:
[Great video on collisions for rigid bodies](https://www.youtube.com/watch?v=BGAwRKPlpCw&list=UUSO_wccIgWaT7Zha99EZpEg)
|
57,367,558 |
I'm trying to set up a google cloud function to use a cloud storage SDK. That cloud storage SDK requires a JSON formated configuration file that it generates when you register your application with your account. I am using Node.js 10
How I import a JSON object into a google cloud function?
So far I've already tried using the environment variables in the google cloud console. I copied the json object into the value space and it did not work. I tried uploading the project as a zip file with a normal json file and used the fs module to read the json object but that did not work.
Here is the JSON object I need to use. (obviously the keys have been changed to random values
```
{
"randomAppSettings": {
"clientID": "jk321hgg5h1l5j234gjl23",
"clientSecret": "akhfusafkhdsjghlsakdfkdj",
"appAuth": {
"publicKeyID": "243532kj5kh",
"privateKey": "23k4j32hvj4hh",
"passphrase": "jk321g5hg12l534kj521"
}
},
"enterpriseID": "4235614785",
"webhooks": {
"primaryKey": "3jh24gkj34`j2hkhj23g1hk5gk2jhkjhk",
"secondaryKey": "125gk4j5h325432bkjhkjhekjh642"
}
}
```
As you can see its not a simple key/value pair, I don't know if that has something to do with it.
This is the method of reading the information used in the actual code (with the normal fs attempt)
```
let configFile = fs.readFileSync("baconConfig.json");
const randAppConfig = JSON.parse(configFile); //variable for security and configuration management
```
The expected results are to read the file with the JSON.parse method, however the log is outputting errors that are centered around trying to read the json config.
Any help please?
|
2019/08/06
|
[
"https://Stackoverflow.com/questions/57367558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8196400/"
] |
One of the best practice is to put the file in a bucket, to allow the function service account (the default one or a specific identity) to read this bucket and to load the file at runtime.
One of the main reason is that you don't have to commit your security file, you just have to keep a reference to a bucket.
|
You can place your JSON strings in environment variables. Maybe you have to remove line breaks.
Usage in Cloud Functions code (Python):
```
import os
import json
foobar_json_string = os.environ.get('foobar_json_string', '{}')
foobar_dict = json.loads(foobar_json_string)
```
|
39,898 |
I have info path form with three text boxes (tb1, tb2, tb3) and have calculated value field with (tb1+tb2+tb3).
Eg: If 1,2,3 are entered then it shows 6 in the calculated value field.
My Requirement:
If calculated value field is between 1-4 then it should show Low
If calculated value field is between 5-10 then it should show Medium
If calculated value field is between 11-14 then it should show High.
Now I need to Show whether it is Low/Medium/High based on the calculated value field on the info path form. Can anyone please explain step by step how to get it.
|
2012/06/29
|
[
"https://sharepoint.stackexchange.com/questions/39898",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/6531/"
] |
It is more correct to realize it with rules but it is a lot of typing so I made it with custom C# code.
In Infopath Designer 2010 create a form naming controls accordingly:


On ribbon click **Developer** tab click **Changed Event** button having chosen each of text boxes, verifying changes in the code in opened VSTA (Visual Studio Tools for Applications) upon each click.
Make changes according this code snippet:
```
using Microsoft.Office.InfoPath;
using System;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using mshtml;
namespace IP_Calculated_Value {
public partial class FormCode
{
int iTextBox1, iTextBox2, iTextBox3;
XPathNavigator calculatedNode, textBox1Node, textBox2Node, textBox3Node;
public void InternalStartup()
{
calculatedNode = this.MainDataSource.CreateNavigator().
SelectSingleNode("/my:myFields/my:Calculated", NamespaceManager);
calculatedNode.SetValue
("Enter integers into textboxes and click outside to see calculated value");
textBox1Node = this.MainDataSource.CreateNavigator().
SelectSingleNode("/my:myFields/my:TextBox1", NamespaceManager);
textBox2Node=this.MainDataSource.CreateNavigator().
SelectSingleNode("/my:myFields/my:TextBox2", NamespaceManager);
textBox3Node = this.MainDataSource.CreateNavigator().
SelectSingleNode("/my:myFields/my:TextBox3", NamespaceManager);
EventManager.XmlEvents["/my:myFields/my:TextBox1"].Changed +=
new XmlChangedEventHandler(TextBox1_Changed);
EventManager.XmlEvents["/my:myFields/my:TextBox3"].Changed +=
new XmlChangedEventHandler(TextBox3_Changed);
EventManager.XmlEvents["/my:myFields/my:TextBox2"].Changed +=
new XmlChangedEventHandler(TextBox2_Changed);
}
public void TextBox1_Changed(object sender, XmlEventArgs e)
{
iTextBox1 = Convert.ToInt32(textBox1Node.Value);
ShowCalculated();
}
public void TextBox2_Changed(object sender, XmlEventArgs e)
{
iTextBox2 = Convert.ToInt32(textBox2Node.Value);
ShowCalculated();
}
public void TextBox3_Changed(object sender, XmlEventArgs e)
{
iTextBox3 = Convert.ToInt32(textBox3Node.Value);
ShowCalculated();
}
public void ShowCalculated()
{
int sum = iTextBox1 + iTextBox2 + iTextBox3;
calculatedNode.SetValue("Outside of permitted sum range");
if (sum >= 1 && sum <= 4) calculatedNode.SetValue("Low");
if (sum >= 5 && sum <= 10) calculatedNode.SetValue("Medium");
if (sum >= 11 && sum < 14) calculatedNode.SetValue("High");
}
} }
```
|
just add 3 calculated fields with text low, medium and high. on each calculated field add a formatting rule. the formatting rule hides the calculted field if it's not a low/medium/high value.
Calculated Field A: Value = Low, rule: hide when calculatedValue > 4 or calculatedValue < 1
Calculated Field B: Value = Medium, rule: hide when calculatedValue < 5 or calculatedValue > 10
Calculated Field C: Value = High, rule: hide when calculatedValue < 11 or calculatedValue > 14
Hope i got it right. Maybe you have to set the calculatedfield with a rule too.
I think c#-code is not necessary here.
|
57,611 |
In the list view, I want to display the 3 most important attributes of the product below the productname.
What is the best way to fix this?
Is there a way to highlight some attribute, so that these can be displayed there?
|
2015/02/18
|
[
"https://magento.stackexchange.com/questions/57611",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] |
You issue with product image or product is not exiting in magento catalog
on items.phtml you call product image.it may this product is not this in magento.it delete but it details is in sales.
before before call the image you needcheck product is exit not
```
$prod=Mage::getModel('catalog/product')->load($_item->getProductId());
```
call image when product exit in magento
```
if($prod->getId()){
// put your image code
}
```
|
Try to enable error printing by renaming `local.xml`.sample file to `local.xml` in errors directory and uncomment `ini_set('display_errors', 1);` in `index.php` in root.
|
57,611 |
In the list view, I want to display the 3 most important attributes of the product below the productname.
What is the best way to fix this?
Is there a way to highlight some attribute, so that these can be displayed there?
|
2015/02/18
|
[
"https://magento.stackexchange.com/questions/57611",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/16894/"
] |
You issue with product image or product is not exiting in magento catalog
on items.phtml you call product image.it may this product is not this in magento.it delete but it details is in sales.
before before call the image you needcheck product is exit not
```
$prod=Mage::getModel('catalog/product')->load($_item->getProductId());
```
call image when product exit in magento
```
if($prod->getId()){
// put your image code
}
```
|
You should see a long number on the screen along with the error message.
Look in the var/report folder for a file with the same name as the long number. That one contains the error message and stacktrace.
But without knowing what the file contains I will shoot in the dark and say that you had a certain payment method enabled at one point, the order was placed using that payment method and then you removed it.
This is (from my point of view) a drawback of Magento. You cannot remove payment methods that have been used for past orders. You can just disable them.
In case I'm wrong, just paste the contents of the error file in your question and I will try to come up with something better.
|
278,999 |
There are lots of answers to the question 'Can I email a SharePoint document', but they often seem to suffer from two defects:
```
1. They assume the recipient has access to my SharePoint site
2. Many are years’ old and are obsolete.
```
I often need to send documents to an external contact, so they must be an attachment, not a link. Is this possible, as a one-step process? (I know I can download it from SharePoint, then upload it into Outlook.)
|
2020/04/15
|
[
"https://sharepoint.stackexchange.com/questions/278999",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/62819/"
] |
You can use a state object to toggle what is rendered. When a state object is updated it will force a re-render of the component:
```
<div>
{
this.state.showNewForm ?
<NewFormComponent onCompleted={()=>this.setState({ showNewForm: false})} />
:
<ListComponent />
}
<button onClick={this.setState({ showNewForm: true });>Create new item</button>
</div>
```
Reference: [State and Lifecycle - React](https://reactjs.org/docs/state-and-lifecycle.html)
|
I will highly recommend using [react-router-dom](https://www.npmjs.com/package/react-router-dom). Below is a sample code from [here](https://codeburst.io/getting-started-with-react-router-5c978f70df91).
```
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import { Route, Link, BrowserRouter as Router, Switch } from 'react-router-dom'
import App from './App'
import Users from './users'
import Contact from './contact'
import Notfound from './notfound'const routing = (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
<Switch>
<Route exact path="/" component={App} />
<Route path="/users" component={Users} />
<Route path="/contact" component={Contact} />
<Route component={Notfound} />
</Switch>
</div>
</Router>
)ReactDOM.render(routing, document.getElementById('root'))
```
Here, you have `Users` and `Contact` components. Using react router, you can switch between the components via URL path. It provides a lot more functionality like passing arguments to component. You can go through the before mentioned link.
|
39,006,341 |
I'm trying to do the following thing:
[](https://i.stack.imgur.com/Mlo14.png)
The red zone is an `AbsoluteLayout` that I want to move out of the screen as it's shown. I currently use `{Layout}.TranslateTo();` but it uses absolutes position so I don't know if it will work for every device as the picture..
It's hard to explain but just imagine that, I move this layout to 300px (x), then on the phone it works because the screen isn't that large, but on tablet, it will probably not work, because the screen is larger.
Also, if a rotation is made (horizontal mod), then the screen will larger than every other possibilities etc etc..
So, does it exists something, as the proportional values of `AbsoluteLayout` like 2.0 or -1.0 to put a layout out of the screen, but adapted for every device?
If you understand completely what I mean, do not hesitate to ask me more information about some point :)
Thank in advance !
|
2016/08/17
|
[
"https://Stackoverflow.com/questions/39006341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6093604/"
] |
`AbsoluteLayout` accepts proportional size between 0 to 1. So you can assign like:
```
AbsoluteLayout.LayoutBounds="0,0,1,1"
AbsoluteLayout.LayoutFlags="SizeProportional"
```
which means that starts from (0,0) point and fill entire screen.
Your translating call should be like:
**Xaml**
```
<AbsoluteLayout x:Name="yourRedOne" AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="SizeProportional">
<!--Your red container content goes here-->
</AbsoluteLayout>
</AbsolutLayout>
```
**Xaml.cs**
```
yourRedOne.TranslateTo(Width, 0);
```
for your orientation changes you should also override `OnSizeAllocated` method in tour `View` and call `TranslateTo` method again.
|
Given you are in a forms project I would read in the screen height and width when app is launched and store it in a global variable. Something like this.
Android onCreate of MainActivity
```
//Get Screen Size of Phone for Android
var metrics = Resources.DisplayMetrics;
var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
var heightInDp = ConvertPixelsToDp(metrics.HeightPixels);
Global.CurrentScreen.screenWidth = widthInDp;
Global.CurrentScreen.screenHeight = heightInDp;
private int ConvertPixelsToDp(float pixelValue)
{
var dp = (int)((pixelValue) / Resources.DisplayMetrics.Density);
return dp;
}
```
For iOS in AppDelegate finished launching
```
Global.CurrentScreen.screenHeight = (int)UIScreen.MainScreen.Bounds.Height;
Global.CurrentScreen.screenWidth = (int)UIScreen.MainScreen.Bounds.Width;
```
And then translate according to saved size.
|
96,490 |
Below are some puzzles you need to solve to make a **4 letter** word.
1.
>
>
> ```
> 105 35
> 315 ?
> ```
>
>
2.
>
>
> ```
> I am the most important element in your surrounding.
> I was found by a Scottish physician.
> Who am I?
> ```
>
>
3.
>
>
> ```
> I am made up of 3 digits.
> When you add the digits in me you will get a total of 11 and when you multiply the digits in me you get 9.
> My all digits are less then 10 and last digit is divisible by 3.
> What number am I?
> ```
>
>
When you have solved the above puzzles you will get some numbers and letters. **Decode** them, and you will get the required word.
Hint #1
>
> You can decode them in any order. After decoding you need to rearrange them to get the required word.
>
>
>
Hint #2
>
> Out of three puzzles, one puzzle will give you 2 identical letters.
>
>
>
Hint #3
>
> Visit my Stack Exchange Account.
>
>
>
|
2020/03/30
|
[
"https://puzzling.stackexchange.com/questions/96490",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/66237/"
] |
1. >
> Traversing diagonals of the square, we can get from a 3-digit number to a 2-digit number by removing the middle digit: $315$ to $35$ and $105$ to $15$. So the answer could be $15$.
>
>
>
2. >
> As Shivansh Sharma found, the answer is Nitrogen, a chemical element with number $7$ in the periodic table.
>
>
>
3. >
> The number here must be $119$.
>
>
>
So we can break up the solution as
>
> $15,7,119$ or $15,7,11,9$
>
>
>
which decodes as
>
> OGKI. Does this or its anagrams mean anything?
>
>
>
Although I suspect there may be another level of decoding and the final answer should be
>
> JAVA, given the title and the OP's profile page.
>
>
>
|
Partial Answer
1.
>
> Could be **105** or **945**
>
>
>
2.
>
> The most important element in our surroundings is **Nitrogen**, discovered by Rutherford, a Scottish Physician.
>
>
>
3.
>
> The 3 numbers are 9, 1, 1 together making **911**. (9 + 1 + 1 = 11, 9 \* 1 \* 1 = 9)
>
>
>
So overall I think
>
> We can get N from Nitrogen.
>
> 911 is one of the 8 N11 codes.
>
> 10-5(from 105) is a 10-code.
>
> Something in that direction.
>
>
>
|
96,490 |
Below are some puzzles you need to solve to make a **4 letter** word.
1.
>
>
> ```
> 105 35
> 315 ?
> ```
>
>
2.
>
>
> ```
> I am the most important element in your surrounding.
> I was found by a Scottish physician.
> Who am I?
> ```
>
>
3.
>
>
> ```
> I am made up of 3 digits.
> When you add the digits in me you will get a total of 11 and when you multiply the digits in me you get 9.
> My all digits are less then 10 and last digit is divisible by 3.
> What number am I?
> ```
>
>
When you have solved the above puzzles you will get some numbers and letters. **Decode** them, and you will get the required word.
Hint #1
>
> You can decode them in any order. After decoding you need to rearrange them to get the required word.
>
>
>
Hint #2
>
> Out of three puzzles, one puzzle will give you 2 identical letters.
>
>
>
Hint #3
>
> Visit my Stack Exchange Account.
>
>
>
|
2020/03/30
|
[
"https://puzzling.stackexchange.com/questions/96490",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/66237/"
] |
The answer to the puzzle is:
>
> **JAVA**
>
>
>
Puzzle 1:
>
> This is a puzzle of the form '105:315::35:?', i.e. '105 is to 315 as 35 is to ?' In this case, we see that we get 315 by tripling 105; do the same to 35 and we get the answer **105**. Note that the value of ASCII-105 is the letter '**I**'.
>
>
>
Puzzle 2:
>
> As noted by @ShavinshSharma, this describes Nitrogen, a gas first discovered and isolated by the Scottish physician Daniel Rutherford in 1772 (source: Wikipedia). A nitrogen molecule is written as '**N2**' i.e. we need *two copies* of the letter '**N**'.
>
>
>
Puzzle 3:
>
> The result of the mathematics here is the number **119**. Note that the value of ASCII-119 is the letter '**W**'.
>
>
>
Putting it all together:
>
> We have the four letters **I**, **N**, **N** and **W**.
>
>
>
> If we apply rot-13 to these letters (shift them 13 places in the alphabet) we get the letters **V**, **A**, **A** and **J**.
>
>
>
> This gives us an anagram of the word '**JAVA**', which - as a check of [the OP's profile page](https://puzzling.stackexchange.com/users/66237/swati) will tell you - is their 'favourite programming language', thus satisfying the title! (Note that @Rand'alThor had already made the same leap here, although I believe this answer now fully describes the logic behind the puzzle...)
>
>
>
|
Partial Answer
1.
>
> Could be **105** or **945**
>
>
>
2.
>
> The most important element in our surroundings is **Nitrogen**, discovered by Rutherford, a Scottish Physician.
>
>
>
3.
>
> The 3 numbers are 9, 1, 1 together making **911**. (9 + 1 + 1 = 11, 9 \* 1 \* 1 = 9)
>
>
>
So overall I think
>
> We can get N from Nitrogen.
>
> 911 is one of the 8 N11 codes.
>
> 10-5(from 105) is a 10-code.
>
> Something in that direction.
>
>
>
|
96,490 |
Below are some puzzles you need to solve to make a **4 letter** word.
1.
>
>
> ```
> 105 35
> 315 ?
> ```
>
>
2.
>
>
> ```
> I am the most important element in your surrounding.
> I was found by a Scottish physician.
> Who am I?
> ```
>
>
3.
>
>
> ```
> I am made up of 3 digits.
> When you add the digits in me you will get a total of 11 and when you multiply the digits in me you get 9.
> My all digits are less then 10 and last digit is divisible by 3.
> What number am I?
> ```
>
>
When you have solved the above puzzles you will get some numbers and letters. **Decode** them, and you will get the required word.
Hint #1
>
> You can decode them in any order. After decoding you need to rearrange them to get the required word.
>
>
>
Hint #2
>
> Out of three puzzles, one puzzle will give you 2 identical letters.
>
>
>
Hint #3
>
> Visit my Stack Exchange Account.
>
>
>
|
2020/03/30
|
[
"https://puzzling.stackexchange.com/questions/96490",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/66237/"
] |
The answer to the puzzle is:
>
> **JAVA**
>
>
>
Puzzle 1:
>
> This is a puzzle of the form '105:315::35:?', i.e. '105 is to 315 as 35 is to ?' In this case, we see that we get 315 by tripling 105; do the same to 35 and we get the answer **105**. Note that the value of ASCII-105 is the letter '**I**'.
>
>
>
Puzzle 2:
>
> As noted by @ShavinshSharma, this describes Nitrogen, a gas first discovered and isolated by the Scottish physician Daniel Rutherford in 1772 (source: Wikipedia). A nitrogen molecule is written as '**N2**' i.e. we need *two copies* of the letter '**N**'.
>
>
>
Puzzle 3:
>
> The result of the mathematics here is the number **119**. Note that the value of ASCII-119 is the letter '**W**'.
>
>
>
Putting it all together:
>
> We have the four letters **I**, **N**, **N** and **W**.
>
>
>
> If we apply rot-13 to these letters (shift them 13 places in the alphabet) we get the letters **V**, **A**, **A** and **J**.
>
>
>
> This gives us an anagram of the word '**JAVA**', which - as a check of [the OP's profile page](https://puzzling.stackexchange.com/users/66237/swati) will tell you - is their 'favourite programming language', thus satisfying the title! (Note that @Rand'alThor had already made the same leap here, although I believe this answer now fully describes the logic behind the puzzle...)
>
>
>
|
1. >
> Traversing diagonals of the square, we can get from a 3-digit number to a 2-digit number by removing the middle digit: $315$ to $35$ and $105$ to $15$. So the answer could be $15$.
>
>
>
2. >
> As Shivansh Sharma found, the answer is Nitrogen, a chemical element with number $7$ in the periodic table.
>
>
>
3. >
> The number here must be $119$.
>
>
>
So we can break up the solution as
>
> $15,7,119$ or $15,7,11,9$
>
>
>
which decodes as
>
> OGKI. Does this or its anagrams mean anything?
>
>
>
Although I suspect there may be another level of decoding and the final answer should be
>
> JAVA, given the title and the OP's profile page.
>
>
>
|
2,110,455 |
Consider $f(x) = \frac{1}{1+ \cos(x)}$ . I want to find $\lim \_{x\to \infty} f(x)$ using appropriate method.
My try : I'm really confused about limit of $\sin(x)$ and $\cos(x)$. Therefore I can't solve this problem.
|
2017/01/23
|
[
"https://math.stackexchange.com/questions/2110455",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/325808/"
] |
$\lim\_{x\rightarrow \infty}f(x)=\lim\_{x\rightarrow \infty}\frac{1}{1+cosx}=\lim\_{x\rightarrow \infty}\frac{1}{2\times cos^2(\frac{x}{2})}=\frac{1}{2}\lim\_{x\rightarrow \infty}\frac{1}{cos^2(\frac{x}{2})}$
which has liminf $=\frac{1}{2}$ and limsup $=\infty$ ( because $0\leq cos^2 \frac{x}{2}\leq 1$ ). So doesn't converge but oscillates between $\frac{1}{2}$ and $\infty$.
|
Okay lets take $x=t+\pi$ then we have that
$$\lim\_{x\to \infty}\frac{1}{1+\cos x}=\lim\_{t\to \infty}\frac{1}{1+\cos (t+\pi)}=\lim\_{t\to\infty}\frac{1}{1-\cos t}$$
So
$$\lim\_{x\to\infty}\frac{1}{1+\cos x}=\lim\_{x\to \infty}\frac{1}{1-\cos x}$$
This happens only if $\cos x\to 0$,now take $x=t-\pi/2$ and $x=t+\pi/2$ then we have
$$\lim\_{t\to\infty}\frac{1}{1+\sin t}=\lim\_{t\to\infty}\frac{1}{1-\sin t}$$Lets just change back the index to $x$ then we have that$$\lim\_{x\to\infty}\frac{1}{1+\sin t}=\lim\_{x\to\infty}\frac{1}{1-\sin t}$$
As before this implies that $\sin x\to 0$ but that's impossible when $\cos x\to 0$ hence contradiction the limit doesn't exist.
|
37,480 |
I was wondering if Nautilus has undo/redo features for basic file operations. To be specific, I want to be able to undo moving, renaming or deleting a file.
|
2011/04/28
|
[
"https://askubuntu.com/questions/37480",
"https://askubuntu.com",
"https://askubuntu.com/users/15192/"
] |
That's something that would be handled by Nautilus. I don't have it installed so I can't check (currently running Xubuntu) but I don't believe they have implemented it yet. [They are working on adding that feature](http://www.webupd8.org/2010/05/default-nautilus-will-soon-look-lot.html), and I believe [Nautilus Elementary](http://www.webupd8.org/2010/01/nautilus-elementary-simplified-nautilus.html) already has it. You could also use another file manager like [4pane](http://www.4pane.co.uk/) that already has undo/redo
[Dolphin](http://dolphin.kde.org/) also has undo/redo
|
Tried searching for undo option with an out-of-the box 11.04 Unity, seems like if you keep it stock, there is no option to undo changes.
|
37,480 |
I was wondering if Nautilus has undo/redo features for basic file operations. To be specific, I want to be able to undo moving, renaming or deleting a file.
|
2011/04/28
|
[
"https://askubuntu.com/questions/37480",
"https://askubuntu.com",
"https://askubuntu.com/users/15192/"
] |
That's something that would be handled by Nautilus. I don't have it installed so I can't check (currently running Xubuntu) but I don't believe they have implemented it yet. [They are working on adding that feature](http://www.webupd8.org/2010/05/default-nautilus-will-soon-look-lot.html), and I believe [Nautilus Elementary](http://www.webupd8.org/2010/01/nautilus-elementary-simplified-nautilus.html) already has it. You could also use another file manager like [4pane](http://www.4pane.co.uk/) that already has undo/redo
[Dolphin](http://dolphin.kde.org/) also has undo/redo
|
Nautilus just recently got this feature to undo changes in GNOME 3.4. You can read about this feature in this [bug report](https://bugzilla.gnome.org/show_bug.cgi?id=648658.) which discussed the feature before implementing it.
But, what this means is that you can only undo your changes if you are using 12.04 as the Nautilus in older versions do not have this feature.
|
37,480 |
I was wondering if Nautilus has undo/redo features for basic file operations. To be specific, I want to be able to undo moving, renaming or deleting a file.
|
2011/04/28
|
[
"https://askubuntu.com/questions/37480",
"https://askubuntu.com",
"https://askubuntu.com/users/15192/"
] |
Nautilus just recently got this feature to undo changes in GNOME 3.4. You can read about this feature in this [bug report](https://bugzilla.gnome.org/show_bug.cgi?id=648658.) which discussed the feature before implementing it.
But, what this means is that you can only undo your changes if you are using 12.04 as the Nautilus in older versions do not have this feature.
|
Tried searching for undo option with an out-of-the box 11.04 Unity, seems like if you keep it stock, there is no option to undo changes.
|
15,634,445 |
I am developing a camera app. I want to display a text view on the camera preview. If I add the text view, the app will show the text view with the default text. When I do setText, the app is crashing. Can any body tell what might be the reason for this?
```
<TextView android:layout_width="wrap_content" android:id="@+id/textView1"
android:layout_height="wrap_content" android:text="Text"
android:layout_gravity="center" android:paddingTop="25dp"
android:textSize="20dp" android:textStyle="bold" android:textColor="#FFFFFF" />
```
java code:
```
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("hi");
```
If I comment out setText line then app will display the default text.
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15634445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2060617/"
] |
There are a few tools to help you:
To get the history of a file you can just use `hg log FILE` which is probably the best starting point.
You can also use `hg annotate FILE` which lists every line in the file and says which revision changed it to be like it currently is. It can also take a revision using the `--rev REV` command tail to look at older versions of the file.
To just list the contents of a file at a given revision you can use `hg cat FILE --rev REV`.
If it proves too hard to track down the bug using those tools, you can just clone your repository somewhere else and use `hg bisect` to track it down.
|
hg bisect lets you find the changeset that intoduced a problem. To start the search run the `hg bisect --reset` command. It is well document in **Mercurial: The Definitive Guide**.
|
29,179,197 |
I have Office 365 Developer account & tenant in windows azure to manage office 365 users.
using consent framework "prompt=admin\_consent", i granted access rights to one of my web application already registered in Azure AD (which is managed by me) to use office 365 API services, After granting access using admin consent, all my Azure AD users are able to authenticate themselves against Azure AD.
I am able to see the applications that i granted access using <http://myapps.microsoft.com>
but i am not able to revoke access granted for applications using this URL.
How can i revoke the access granted to my or third party application from my organization's azure AD?
|
2015/03/21
|
[
"https://Stackoverflow.com/questions/29179197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549055/"
] |
Let me check with our Azure folks, but I believe if you granted admin consent you can remove it from the Azure Management Portal. When you navigate to apps, you will see apps that you've consented to along with apps that you've developed. You can remove it there.
|
After logging into your Microsoft user account, navigate to <https://account.live.com/consent/Manage>. This will display all the apps you've authorised to access resources on your behalf. Here select the application you want to revoke access for.
[](https://i.stack.imgur.com/2CZxK.png)
This will show you [which permissions](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#scopes-and-permissions) you've previously granted to the selected app and when you used them last. As you can see in the screenshot below I had granted `openid`, `Calendars.Read` and `Mail.Send`.
Once here all you have to do is click the button at the bottom labelled ***"Remove these permissions"*** and that should be it.
[](https://i.stack.imgur.com/2Mwx6.png)
|
29,179,197 |
I have Office 365 Developer account & tenant in windows azure to manage office 365 users.
using consent framework "prompt=admin\_consent", i granted access rights to one of my web application already registered in Azure AD (which is managed by me) to use office 365 API services, After granting access using admin consent, all my Azure AD users are able to authenticate themselves against Azure AD.
I am able to see the applications that i granted access using <http://myapps.microsoft.com>
but i am not able to revoke access granted for applications using this URL.
How can i revoke the access granted to my or third party application from my organization's azure AD?
|
2015/03/21
|
[
"https://Stackoverflow.com/questions/29179197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549055/"
] |
Let me check with our Azure folks, but I believe if you granted admin consent you can remove it from the Azure Management Portal. When you navigate to apps, you will see apps that you've consented to along with apps that you've developed. You can remove it there.
|
If you have an organisation account with Microsoft you should be able to access this page: <https://portal.office.com/account>
From there click either `App permissions` on the left, or `Change app permission` in the middle.
[](https://i.stack.imgur.com/AeRwV.png)
This will take you to a screen that looks like this:
[](https://i.stack.imgur.com/Uxbpv.png)
Where you can revoke which app permissions you don't want anymore.
|
29,179,197 |
I have Office 365 Developer account & tenant in windows azure to manage office 365 users.
using consent framework "prompt=admin\_consent", i granted access rights to one of my web application already registered in Azure AD (which is managed by me) to use office 365 API services, After granting access using admin consent, all my Azure AD users are able to authenticate themselves against Azure AD.
I am able to see the applications that i granted access using <http://myapps.microsoft.com>
but i am not able to revoke access granted for applications using this URL.
How can i revoke the access granted to my or third party application from my organization's azure AD?
|
2015/03/21
|
[
"https://Stackoverflow.com/questions/29179197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549055/"
] |
Let me check with our Azure folks, but I believe if you granted admin consent you can remove it from the Azure Management Portal. When you navigate to apps, you will see apps that you've consented to along with apps that you've developed. You can remove it there.
|
if you have an admin rights go straight to: <https://portal.azure.com/#blade/Microsoft_AAD_IAM/StartboardApplicationsMenuBlade/AllApps/menuId/>
and remove it there
|
29,179,197 |
I have Office 365 Developer account & tenant in windows azure to manage office 365 users.
using consent framework "prompt=admin\_consent", i granted access rights to one of my web application already registered in Azure AD (which is managed by me) to use office 365 API services, After granting access using admin consent, all my Azure AD users are able to authenticate themselves against Azure AD.
I am able to see the applications that i granted access using <http://myapps.microsoft.com>
but i am not able to revoke access granted for applications using this URL.
How can i revoke the access granted to my or third party application from my organization's azure AD?
|
2015/03/21
|
[
"https://Stackoverflow.com/questions/29179197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549055/"
] |
After logging into your Microsoft user account, navigate to <https://account.live.com/consent/Manage>. This will display all the apps you've authorised to access resources on your behalf. Here select the application you want to revoke access for.
[](https://i.stack.imgur.com/2CZxK.png)
This will show you [which permissions](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#scopes-and-permissions) you've previously granted to the selected app and when you used them last. As you can see in the screenshot below I had granted `openid`, `Calendars.Read` and `Mail.Send`.
Once here all you have to do is click the button at the bottom labelled ***"Remove these permissions"*** and that should be it.
[](https://i.stack.imgur.com/2Mwx6.png)
|
If you have an organisation account with Microsoft you should be able to access this page: <https://portal.office.com/account>
From there click either `App permissions` on the left, or `Change app permission` in the middle.
[](https://i.stack.imgur.com/AeRwV.png)
This will take you to a screen that looks like this:
[](https://i.stack.imgur.com/Uxbpv.png)
Where you can revoke which app permissions you don't want anymore.
|
29,179,197 |
I have Office 365 Developer account & tenant in windows azure to manage office 365 users.
using consent framework "prompt=admin\_consent", i granted access rights to one of my web application already registered in Azure AD (which is managed by me) to use office 365 API services, After granting access using admin consent, all my Azure AD users are able to authenticate themselves against Azure AD.
I am able to see the applications that i granted access using <http://myapps.microsoft.com>
but i am not able to revoke access granted for applications using this URL.
How can i revoke the access granted to my or third party application from my organization's azure AD?
|
2015/03/21
|
[
"https://Stackoverflow.com/questions/29179197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549055/"
] |
After logging into your Microsoft user account, navigate to <https://account.live.com/consent/Manage>. This will display all the apps you've authorised to access resources on your behalf. Here select the application you want to revoke access for.
[](https://i.stack.imgur.com/2CZxK.png)
This will show you [which permissions](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#scopes-and-permissions) you've previously granted to the selected app and when you used them last. As you can see in the screenshot below I had granted `openid`, `Calendars.Read` and `Mail.Send`.
Once here all you have to do is click the button at the bottom labelled ***"Remove these permissions"*** and that should be it.
[](https://i.stack.imgur.com/2Mwx6.png)
|
if you have an admin rights go straight to: <https://portal.azure.com/#blade/Microsoft_AAD_IAM/StartboardApplicationsMenuBlade/AllApps/menuId/>
and remove it there
|
29,179,197 |
I have Office 365 Developer account & tenant in windows azure to manage office 365 users.
using consent framework "prompt=admin\_consent", i granted access rights to one of my web application already registered in Azure AD (which is managed by me) to use office 365 API services, After granting access using admin consent, all my Azure AD users are able to authenticate themselves against Azure AD.
I am able to see the applications that i granted access using <http://myapps.microsoft.com>
but i am not able to revoke access granted for applications using this URL.
How can i revoke the access granted to my or third party application from my organization's azure AD?
|
2015/03/21
|
[
"https://Stackoverflow.com/questions/29179197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549055/"
] |
if you have an admin rights go straight to: <https://portal.azure.com/#blade/Microsoft_AAD_IAM/StartboardApplicationsMenuBlade/AllApps/menuId/>
and remove it there
|
If you have an organisation account with Microsoft you should be able to access this page: <https://portal.office.com/account>
From there click either `App permissions` on the left, or `Change app permission` in the middle.
[](https://i.stack.imgur.com/AeRwV.png)
This will take you to a screen that looks like this:
[](https://i.stack.imgur.com/Uxbpv.png)
Where you can revoke which app permissions you don't want anymore.
|
26,818,142 |
I have a silent post made when completing a paypal payflow. It returns a long string like:
&AVSZIP=X&TYPE=S&BILLTOEMAIL=no%40one.com
I inserted the bold part of the following script, which I had found searching around and thought it would do the trick. Perhaps I am completely misunderstanding how this works, but I thought that it would define $proArray and then email that to me in the silent post. It is sending the silent post email, but with nothing inside.
Please tell me if more information is needed, or if I am just an idiot. I also tried the parse\_str command, but I suppose I do not know how to use that correctly either.
```
<?php
//PLACE EMAIL BELOW:
$email="[email protected]";
$req = "";
if ($_POST)
{
// iterate through each name value pair
foreach ($_POST as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
**// Function to convert NTP string to an array
function NVPToArray($req)
{
$proArray = array();
while(strlen($req))
{
// name
$keypos= strpos($req,'=');
$keyval = substr($req,0,$keypos);
// value
$valuepos = strpos($req,'&') ? strpos($req,'&'): strlen($req);
$valueval = substr($req,$keypos+1,$valuepos-$keypos-1);
// decoding the respose
$proArray[$keyval] = urldecode($valueval);
$req = substr($req,$valuepos+1,strlen($req));
}
}**
//write to file
$fh = fopen("logpost.txt", 'a');//open file and create if does not exist
fwrite($fh, "\r\n/////////////////////////////////////////\r\n");//Just for spacing in log file
fwrite($fh, $req);//write data
fclose($fh);//close file
//Email
$mail_From = "From: [email protected]";
$mail_To = $email;
$mail_Subject = "POST EXISTS";
$mail_Body = $proArray;
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
//
//if posted return echo response
echo $req;
}
// No post data received
if (empty($_POST))
{
//write to file
$fh = fopen("logpost.txt", 'a');//open file and create if does not exist
fwrite($fh, "\r\n/////////////////////////////////////////\r\n");//Just for spacing in log file
fwrite($fh, "Empty Post");//write data
fclose($fh);//close file
//Email
$mail_From = "From: [email protected]";
$mail_To = $email;
$mail_Subject = "Empty Post";
$mail_Body = "";
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
//if posted return echo response
echo "Empty Post";
}
?>
```
|
2014/11/08
|
[
"https://Stackoverflow.com/questions/26818142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4181428/"
] |
```
$result = preg_replace('/\(.+?\)/sm', 'Put your text here', $string);
```
Try this code
Or to save () add them to replacement
```
$page = preg_replace('/\(.+?\)/sm', '(Put your text here)', $page);
```
|
This should work for you:
```
<?php
$string = "This is a (string)";
echo preg_replace("/\([^)]+\)/","",$string);
?>
```
Output:
```
This is a
```
|
26,818,142 |
I have a silent post made when completing a paypal payflow. It returns a long string like:
&AVSZIP=X&TYPE=S&BILLTOEMAIL=no%40one.com
I inserted the bold part of the following script, which I had found searching around and thought it would do the trick. Perhaps I am completely misunderstanding how this works, but I thought that it would define $proArray and then email that to me in the silent post. It is sending the silent post email, but with nothing inside.
Please tell me if more information is needed, or if I am just an idiot. I also tried the parse\_str command, but I suppose I do not know how to use that correctly either.
```
<?php
//PLACE EMAIL BELOW:
$email="[email protected]";
$req = "";
if ($_POST)
{
// iterate through each name value pair
foreach ($_POST as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
**// Function to convert NTP string to an array
function NVPToArray($req)
{
$proArray = array();
while(strlen($req))
{
// name
$keypos= strpos($req,'=');
$keyval = substr($req,0,$keypos);
// value
$valuepos = strpos($req,'&') ? strpos($req,'&'): strlen($req);
$valueval = substr($req,$keypos+1,$valuepos-$keypos-1);
// decoding the respose
$proArray[$keyval] = urldecode($valueval);
$req = substr($req,$valuepos+1,strlen($req));
}
}**
//write to file
$fh = fopen("logpost.txt", 'a');//open file and create if does not exist
fwrite($fh, "\r\n/////////////////////////////////////////\r\n");//Just for spacing in log file
fwrite($fh, $req);//write data
fclose($fh);//close file
//Email
$mail_From = "From: [email protected]";
$mail_To = $email;
$mail_Subject = "POST EXISTS";
$mail_Body = $proArray;
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
//
//if posted return echo response
echo $req;
}
// No post data received
if (empty($_POST))
{
//write to file
$fh = fopen("logpost.txt", 'a');//open file and create if does not exist
fwrite($fh, "\r\n/////////////////////////////////////////\r\n");//Just for spacing in log file
fwrite($fh, "Empty Post");//write data
fclose($fh);//close file
//Email
$mail_From = "From: [email protected]";
$mail_To = $email;
$mail_Subject = "Empty Post";
$mail_Body = "";
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
//if posted return echo response
echo "Empty Post";
}
?>
```
|
2014/11/08
|
[
"https://Stackoverflow.com/questions/26818142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4181428/"
] |
```
$result = preg_replace('/\(.+?\)/sm', 'Put your text here', $string);
```
Try this code
Or to save () add them to replacement
```
$page = preg_replace('/\(.+?\)/sm', '(Put your text here)', $page);
```
|
Just change that:
```
$search = "/ *\(.*?\)/";
```
|
26,818,142 |
I have a silent post made when completing a paypal payflow. It returns a long string like:
&AVSZIP=X&TYPE=S&BILLTOEMAIL=no%40one.com
I inserted the bold part of the following script, which I had found searching around and thought it would do the trick. Perhaps I am completely misunderstanding how this works, but I thought that it would define $proArray and then email that to me in the silent post. It is sending the silent post email, but with nothing inside.
Please tell me if more information is needed, or if I am just an idiot. I also tried the parse\_str command, but I suppose I do not know how to use that correctly either.
```
<?php
//PLACE EMAIL BELOW:
$email="[email protected]";
$req = "";
if ($_POST)
{
// iterate through each name value pair
foreach ($_POST as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
**// Function to convert NTP string to an array
function NVPToArray($req)
{
$proArray = array();
while(strlen($req))
{
// name
$keypos= strpos($req,'=');
$keyval = substr($req,0,$keypos);
// value
$valuepos = strpos($req,'&') ? strpos($req,'&'): strlen($req);
$valueval = substr($req,$keypos+1,$valuepos-$keypos-1);
// decoding the respose
$proArray[$keyval] = urldecode($valueval);
$req = substr($req,$valuepos+1,strlen($req));
}
}**
//write to file
$fh = fopen("logpost.txt", 'a');//open file and create if does not exist
fwrite($fh, "\r\n/////////////////////////////////////////\r\n");//Just for spacing in log file
fwrite($fh, $req);//write data
fclose($fh);//close file
//Email
$mail_From = "From: [email protected]";
$mail_To = $email;
$mail_Subject = "POST EXISTS";
$mail_Body = $proArray;
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
//
//if posted return echo response
echo $req;
}
// No post data received
if (empty($_POST))
{
//write to file
$fh = fopen("logpost.txt", 'a');//open file and create if does not exist
fwrite($fh, "\r\n/////////////////////////////////////////\r\n");//Just for spacing in log file
fwrite($fh, "Empty Post");//write data
fclose($fh);//close file
//Email
$mail_From = "From: [email protected]";
$mail_To = $email;
$mail_Subject = "Empty Post";
$mail_Body = "";
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
//if posted return echo response
echo "Empty Post";
}
?>
```
|
2014/11/08
|
[
"https://Stackoverflow.com/questions/26818142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4181428/"
] |
This should work for you:
```
<?php
$string = "This is a (string)";
echo preg_replace("/\([^)]+\)/","",$string);
?>
```
Output:
```
This is a
```
|
Just change that:
```
$search = "/ *\(.*?\)/";
```
|
1,181,457 |
The lifetimes of batteries are independent exponential random variables , each having parameter $\lambda$. A flashlight needs two batteries to work. If one has a flashlight and a stockpile of n batteries, What is the distribution of time that the flashlight can operate?
What I have so far:
Let $Y$ be the lifetime of the flashlight; $Y\_1=min(X\_1,...,X\_n)$ where $X\_i$ is the lifetime of a battery ($1\le i\le n$), and $Y\_2$ the second smallest of the $X\_i$ (so $Y\_1\le Y\_2$)
I wanted to compute: $P[Y\le t]=P[Y\_2\le k+m|Y\_1\le m]$ where $k+m=t$ then we have that $$P[Y\_2\le k+m|Y\_1\le m]={P[Y\_2\le k+m, Y\_1\le m]\over P[Y\_1\le m]}={P[Y\_2\le k+m] P[Y\_1\le m]\over P[Y\_1\le m]}=P[Y\_2\le k+m=t]$$ (because of the independence of the random variables)
So $P[Y\_2\le t]=P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]$ (assuming $X\_j=min(X\_1,...,X\_n)$) hence:
$$P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]= 1-P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\ge t]=1-P[X\_1\ge t,...,X\_{j-1}\ge t, X\_{j+1}\ge t,... X\_n\ge t]=1-e^{(n-1)\lambda t}$$
I would really appreciate if you can tell me if this is the correct approach :)
|
2015/03/08
|
[
"https://math.stackexchange.com/questions/1181457",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128422/"
] |
First, we need to be clear that in your problem $\lambda$ is the failure *rate* of each battery, not the mean time until failure. (Both parameterizations of the exponential distribution are in use.)
Second, we need to assume that all the batteries are subject to failure
from the start. Also, your flashlight is
useless after $n - 1$ battery failures.
Subject to these understandings, your approach is OK.
The general result is that if $X\_i$ ~ EXP($\lambda\_i$) independently, for
$i = 1, \dots, k$, then $Y = \min(X\_1, \dots X\_k)$ is exponential with
failure rate $\sum\_{i=1}^k \lambda\_i$. In your case $k = n-1$ and
$\lambda = \lambda\_i$, so the exponential failure rate is $(n-1)\lambda$.
I have to say that batteries would *not* be my favorite example of
items that have exponential lifetimes. The "no-memory" property of
exponential distributions states that for exponential $X$, we have
$P\{X > s+t | X > s\} = P\{X > t\},$ for $s, t > 0$. (This is what you
showed at the start of your answer.)
Sometimes, this property is
expressed by saying that "used is as good as new." In practice, the property holds
pretty well for computer chips, which mainly die by accident (electric shock
or cosmic ray) rather than by wearing out. For a battery, it does not
seem the case that a used one has the same reliability as a used one.
Also, the two batteries in a flashlight tend to wear out at the same time.
And by taking the max you are assuming the batteries in storage are
subject to the same risk as those in the flashlight. Altogether,
the exponential distribution does not match with my intuition about
batteries and flashlights, so I will not try to give you an intuitive
argument for your answer in terms of batteries.
Suppose a satellite has $n = 10$ computer chips, all of which must function
in order for the satellite to do its job. Each chip fails after an
exponentially distributed length of time with rate 1/15 (average lifetime
15 years), then the lifetime of the satellite is exponential with rate 10/15,
average $15/10 = 1.5$ years. Here is a simulation in R to confirm the
distribution of the minimum. (Based on 100,000 imaginary satellites,
each in a row of the matrix. Simulation results from one run of program: mean life 1.50, SD life 1.51, and the
probability of lasting more than a year is just above half.)
m = 100000; n = 10; lam = 1/15.
DIES = matrix(rexp(m\*n, lam), nrow=m) # m x n matrix of chips
x = apply(DIES, 1, min) # min of each row = satellite failure time
mean(x) # avg time to satellite failure, exact = 1.5
sd(x) # sd, exact = 1.5
mean(x > 1) # probability satellite survives more than 1 year
|
This is not an answer, but will not fit in a comment.
Given $n$ batteries with run times $x\_1,...,x\_n$ (unknown to the user), just computing the operating time is moderately complex.
For example, suppose we have 3 batteries.
One starts with batteries $1,2$, then replaces $1$ by $3$ if $x\_1<x\_2$ in which case the operating time is $T(x)= \min(x\_1+x\_3,x\_2)$ or
replaces $2$ by $3$ if $x\_1 > x\_2$ in which case the operating time is $T(x)= \min(x\_1, x\_2+x\_3)$. We can ignore the $x\_1=x\_2$ case, in this context.
So, using independence and symmetry, we have $F\_T(\alpha) = P\{x| T(x) \le \alpha \} = 2 P\{ x | x\_1 < x\_2 \text{ and } (x\_1+x\_3 \le \alpha \text{ or } x\_2 \le \alpha )\} $
Computing this, we have
$F\_T(\alpha) = 2\int\_{x\_2=0}^\alpha \int\_{x\_1=0}^{x\_2} \int\_{x\_3=0}^\infty \phi
+2\int\_{x\_2=\alpha}^\infty \int\_{x\_1=0}^{\alpha} \int\_{x\_3=0}^{\alpha-x\_1} \phi$,
where $\phi(x) = \lambda^3 e^{-\lambda(x\_1+x\_2+x\_3)}$.
Then $F\_T(\alpha) = 1- e^{-2 \alpha \lambda}(1+2 \alpha \lambda)$, for $\alpha \ge 0$.
It doesn't get simpler when we add more batteries...
|
1,181,457 |
The lifetimes of batteries are independent exponential random variables , each having parameter $\lambda$. A flashlight needs two batteries to work. If one has a flashlight and a stockpile of n batteries, What is the distribution of time that the flashlight can operate?
What I have so far:
Let $Y$ be the lifetime of the flashlight; $Y\_1=min(X\_1,...,X\_n)$ where $X\_i$ is the lifetime of a battery ($1\le i\le n$), and $Y\_2$ the second smallest of the $X\_i$ (so $Y\_1\le Y\_2$)
I wanted to compute: $P[Y\le t]=P[Y\_2\le k+m|Y\_1\le m]$ where $k+m=t$ then we have that $$P[Y\_2\le k+m|Y\_1\le m]={P[Y\_2\le k+m, Y\_1\le m]\over P[Y\_1\le m]}={P[Y\_2\le k+m] P[Y\_1\le m]\over P[Y\_1\le m]}=P[Y\_2\le k+m=t]$$ (because of the independence of the random variables)
So $P[Y\_2\le t]=P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]$ (assuming $X\_j=min(X\_1,...,X\_n)$) hence:
$$P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]= 1-P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\ge t]=1-P[X\_1\ge t,...,X\_{j-1}\ge t, X\_{j+1}\ge t,... X\_n\ge t]=1-e^{(n-1)\lambda t}$$
I would really appreciate if you can tell me if this is the correct approach :)
|
2015/03/08
|
[
"https://math.stackexchange.com/questions/1181457",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128422/"
] |
**Second answer,** for a different interpretation: Batteries cannot die before they go into the flashlight. Because this interpretation involves both the
minimum of two exponentials and the sum of several exponentials, it makes a
more interesting problem than did the assumptions in my first answer. It is the interpretation suggested in Andre's note and used copper.hat's multiple integration.
Step 1: Wait for one of two initial batteries to fail. This waiting time is
the minimum of two exponentials with failure rate $\lambda$, and hence
$X\_1$ ~ EXP($2\lambda$).
Step 2: Throw out dead battery, replace with new one. By the no-memory property,
the one of the two batteries in the flashlight that did not die is as good
as new. Waiting time for one of these two batteries to die is again
$X\_2$ ~ EXP($2\lambda$).
Last step $n-1$; Throw out dead battery, replace with $n$th (last remaining
replacement) battery: Light goes out after additional time
$X\_{n-1}$ ~ EXP($2\lambda$).
Total time flashlight is lit is $T = X\_1 + \dots + X\_{n-1}$. This is the
sum of $(n-1)$ exponentials, so $T$ ~ GAMMA($n-1,$ $2\lambda$).
This is a gamma distribution with shape parameter $n-1$ and rate parameter $2\lambda.$ When the shape parameter is a positive integer the gamma
distribution is sometimes called an Erlang distribution (especially in
queueing theory).
*Check:* A previous answer, apparently using the same assumptions and with $n=3,$
has the CDF of the random variable $T$ as
$F\_T(x) = 1 - \exp(-2\lambda x)(1 + 2\lambda x),$ for $x > 0$. The form of
the CDF does indeed get messier with increasing $n$, but the mean and variance
are simple expressions in $n$ and $\lambda.$
In R, we easily verify (in one instance, anyhow) that this is a special case of the gamma (Erlang)
distribution. Let $n = 3$, $\lambda = 1/15$, and $x = 1$. So this is the
(small) probability that the flashlight goes dark by time 1.
The code 'pgamma(1, 2, 2/15)' and the code '1 - exp(-2/15)\*(1 + 2/15)' both
return the probability 0.008136905. Also,
'qgamma(.5, 2, 2/15)' finds the exact median time the flaslhight burns to be 12.58760, and
'mean(rgamma(10^5, 2, 2/15))' approximates the mean as
14.97 (exact is 15).
|
First, we need to be clear that in your problem $\lambda$ is the failure *rate* of each battery, not the mean time until failure. (Both parameterizations of the exponential distribution are in use.)
Second, we need to assume that all the batteries are subject to failure
from the start. Also, your flashlight is
useless after $n - 1$ battery failures.
Subject to these understandings, your approach is OK.
The general result is that if $X\_i$ ~ EXP($\lambda\_i$) independently, for
$i = 1, \dots, k$, then $Y = \min(X\_1, \dots X\_k)$ is exponential with
failure rate $\sum\_{i=1}^k \lambda\_i$. In your case $k = n-1$ and
$\lambda = \lambda\_i$, so the exponential failure rate is $(n-1)\lambda$.
I have to say that batteries would *not* be my favorite example of
items that have exponential lifetimes. The "no-memory" property of
exponential distributions states that for exponential $X$, we have
$P\{X > s+t | X > s\} = P\{X > t\},$ for $s, t > 0$. (This is what you
showed at the start of your answer.)
Sometimes, this property is
expressed by saying that "used is as good as new." In practice, the property holds
pretty well for computer chips, which mainly die by accident (electric shock
or cosmic ray) rather than by wearing out. For a battery, it does not
seem the case that a used one has the same reliability as a used one.
Also, the two batteries in a flashlight tend to wear out at the same time.
And by taking the max you are assuming the batteries in storage are
subject to the same risk as those in the flashlight. Altogether,
the exponential distribution does not match with my intuition about
batteries and flashlights, so I will not try to give you an intuitive
argument for your answer in terms of batteries.
Suppose a satellite has $n = 10$ computer chips, all of which must function
in order for the satellite to do its job. Each chip fails after an
exponentially distributed length of time with rate 1/15 (average lifetime
15 years), then the lifetime of the satellite is exponential with rate 10/15,
average $15/10 = 1.5$ years. Here is a simulation in R to confirm the
distribution of the minimum. (Based on 100,000 imaginary satellites,
each in a row of the matrix. Simulation results from one run of program: mean life 1.50, SD life 1.51, and the
probability of lasting more than a year is just above half.)
m = 100000; n = 10; lam = 1/15.
DIES = matrix(rexp(m\*n, lam), nrow=m) # m x n matrix of chips
x = apply(DIES, 1, min) # min of each row = satellite failure time
mean(x) # avg time to satellite failure, exact = 1.5
sd(x) # sd, exact = 1.5
mean(x > 1) # probability satellite survives more than 1 year
|
1,181,457 |
The lifetimes of batteries are independent exponential random variables , each having parameter $\lambda$. A flashlight needs two batteries to work. If one has a flashlight and a stockpile of n batteries, What is the distribution of time that the flashlight can operate?
What I have so far:
Let $Y$ be the lifetime of the flashlight; $Y\_1=min(X\_1,...,X\_n)$ where $X\_i$ is the lifetime of a battery ($1\le i\le n$), and $Y\_2$ the second smallest of the $X\_i$ (so $Y\_1\le Y\_2$)
I wanted to compute: $P[Y\le t]=P[Y\_2\le k+m|Y\_1\le m]$ where $k+m=t$ then we have that $$P[Y\_2\le k+m|Y\_1\le m]={P[Y\_2\le k+m, Y\_1\le m]\over P[Y\_1\le m]}={P[Y\_2\le k+m] P[Y\_1\le m]\over P[Y\_1\le m]}=P[Y\_2\le k+m=t]$$ (because of the independence of the random variables)
So $P[Y\_2\le t]=P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]$ (assuming $X\_j=min(X\_1,...,X\_n)$) hence:
$$P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]= 1-P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\ge t]=1-P[X\_1\ge t,...,X\_{j-1}\ge t, X\_{j+1}\ge t,... X\_n\ge t]=1-e^{(n-1)\lambda t}$$
I would really appreciate if you can tell me if this is the correct approach :)
|
2015/03/08
|
[
"https://math.stackexchange.com/questions/1181457",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128422/"
] |
**Second answer,** for a different interpretation: Batteries cannot die before they go into the flashlight. Because this interpretation involves both the
minimum of two exponentials and the sum of several exponentials, it makes a
more interesting problem than did the assumptions in my first answer. It is the interpretation suggested in Andre's note and used copper.hat's multiple integration.
Step 1: Wait for one of two initial batteries to fail. This waiting time is
the minimum of two exponentials with failure rate $\lambda$, and hence
$X\_1$ ~ EXP($2\lambda$).
Step 2: Throw out dead battery, replace with new one. By the no-memory property,
the one of the two batteries in the flashlight that did not die is as good
as new. Waiting time for one of these two batteries to die is again
$X\_2$ ~ EXP($2\lambda$).
Last step $n-1$; Throw out dead battery, replace with $n$th (last remaining
replacement) battery: Light goes out after additional time
$X\_{n-1}$ ~ EXP($2\lambda$).
Total time flashlight is lit is $T = X\_1 + \dots + X\_{n-1}$. This is the
sum of $(n-1)$ exponentials, so $T$ ~ GAMMA($n-1,$ $2\lambda$).
This is a gamma distribution with shape parameter $n-1$ and rate parameter $2\lambda.$ When the shape parameter is a positive integer the gamma
distribution is sometimes called an Erlang distribution (especially in
queueing theory).
*Check:* A previous answer, apparently using the same assumptions and with $n=3,$
has the CDF of the random variable $T$ as
$F\_T(x) = 1 - \exp(-2\lambda x)(1 + 2\lambda x),$ for $x > 0$. The form of
the CDF does indeed get messier with increasing $n$, but the mean and variance
are simple expressions in $n$ and $\lambda.$
In R, we easily verify (in one instance, anyhow) that this is a special case of the gamma (Erlang)
distribution. Let $n = 3$, $\lambda = 1/15$, and $x = 1$. So this is the
(small) probability that the flashlight goes dark by time 1.
The code 'pgamma(1, 2, 2/15)' and the code '1 - exp(-2/15)\*(1 + 2/15)' both
return the probability 0.008136905. Also,
'qgamma(.5, 2, 2/15)' finds the exact median time the flaslhight burns to be 12.58760, and
'mean(rgamma(10^5, 2, 2/15))' approximates the mean as
14.97 (exact is 15).
|
This is not an answer, but will not fit in a comment.
Given $n$ batteries with run times $x\_1,...,x\_n$ (unknown to the user), just computing the operating time is moderately complex.
For example, suppose we have 3 batteries.
One starts with batteries $1,2$, then replaces $1$ by $3$ if $x\_1<x\_2$ in which case the operating time is $T(x)= \min(x\_1+x\_3,x\_2)$ or
replaces $2$ by $3$ if $x\_1 > x\_2$ in which case the operating time is $T(x)= \min(x\_1, x\_2+x\_3)$. We can ignore the $x\_1=x\_2$ case, in this context.
So, using independence and symmetry, we have $F\_T(\alpha) = P\{x| T(x) \le \alpha \} = 2 P\{ x | x\_1 < x\_2 \text{ and } (x\_1+x\_3 \le \alpha \text{ or } x\_2 \le \alpha )\} $
Computing this, we have
$F\_T(\alpha) = 2\int\_{x\_2=0}^\alpha \int\_{x\_1=0}^{x\_2} \int\_{x\_3=0}^\infty \phi
+2\int\_{x\_2=\alpha}^\infty \int\_{x\_1=0}^{\alpha} \int\_{x\_3=0}^{\alpha-x\_1} \phi$,
where $\phi(x) = \lambda^3 e^{-\lambda(x\_1+x\_2+x\_3)}$.
Then $F\_T(\alpha) = 1- e^{-2 \alpha \lambda}(1+2 \alpha \lambda)$, for $\alpha \ge 0$.
It doesn't get simpler when we add more batteries...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.