qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
You would need to extend KeyedDecodingContainer and add an implementation for Decimal.Type. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } } ``` Here is an example: ``` let json = """ { "capAmount": "123.45" } """ struct Status: Decodable { let capAmount: Decimal enum CodingKeys: String, CodingKey { case capAmount } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) capAmount = try container.decode(Decimal.self, forKey: .capAmount) } } // Execute it if let data = json.data(using: .utf8){ let status = try JSONDecoder().decode(Status.self, from: data) print(status.capAmount) } ```
That decoding strategy has nothing to do with numbers being represented as strings. What you need to do is to implement `init(from:)` and convert from string there ``` class MyClass : Codable { var decimal: Double? enum CodingKeys: String, CodingKey { case decimal = "test" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) decimal = Double(try container.decode(String.self, forKey: .decimal) //or if Decimal is used: //decimal = Decimal(string: try container.decode(String.self, forKey: .decimal) } } ``` Note that I am using Double instead of Decimal here to make it simpler
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
``` struct Root: Codable { let decimal: Decimal } ``` --- ``` extension Root { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) decimal = try Decimal(string: container.decode(String.self, forKey: .decimal)) ?? .zero } } ``` --- ``` let json = #"{"decimal":"0.007"}"# do { let root = try JSONDecoder().decode(Root.self, from: .init(json.utf8)) print(root) } catch { print(error) } ``` This will print > > Root(decimal: 0.007) > > >
The type should be Double and define also in the parsing as Double. Swift will figure out the rest ``` struct MyClass: Decodable { let decimal: Double //can be renamed to follow the API name. enum CodingKeys: String, CodingKey { case decimal } } extension MyClass { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) decimal = try values.decode(Double.self, forKey: .decimal) } } ```
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
You would need to extend KeyedDecodingContainer and add an implementation for Decimal.Type. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } } ``` Here is an example: ``` let json = """ { "capAmount": "123.45" } """ struct Status: Decodable { let capAmount: Decimal enum CodingKeys: String, CodingKey { case capAmount } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) capAmount = try container.decode(Decimal.self, forKey: .capAmount) } } // Execute it if let data = json.data(using: .utf8){ let status = try JSONDecoder().decode(Status.self, from: data) print(status.capAmount) } ```
I just add the following code. It supports optional as well. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } func decodeIfPresent(_ type: Decimal.Type, forKey key: K) throws -> Decimal? { guard let stringValue = try? decodeIfPresent(String.self, forKey: key), let decimalValue = Decimal(string: stringValue) else { return nil } return decimalValue } ``` }
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
``` struct Root: Codable { let decimal: Decimal } ``` --- ``` extension Root { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) decimal = try Decimal(string: container.decode(String.self, forKey: .decimal)) ?? .zero } } ``` --- ``` let json = #"{"decimal":"0.007"}"# do { let root = try JSONDecoder().decode(Root.self, from: .init(json.utf8)) print(root) } catch { print(error) } ``` This will print > > Root(decimal: 0.007) > > >
I believe that a cleaner solution is declare value not like a string but like a value: ``` "test": 0.007 ``` having a struct like that: ``` struct Stuff { var test: Decimal } ``` and then: ``` let decoder = JSONDecoder() let stuff = try decoder.decode(Stuff.self, from: json) ``` otherwise you can use this example: <https://forums.swift.org/t/parsing-decimal-values-from-json/6906/3>
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
``` struct Root: Codable { let decimal: Decimal } ``` --- ``` extension Root { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) decimal = try Decimal(string: container.decode(String.self, forKey: .decimal)) ?? .zero } } ``` --- ``` let json = #"{"decimal":"0.007"}"# do { let root = try JSONDecoder().decode(Root.self, from: .init(json.utf8)) print(root) } catch { print(error) } ``` This will print > > Root(decimal: 0.007) > > >
I just add the following code. It supports optional as well. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } func decodeIfPresent(_ type: Decimal.Type, forKey key: K) throws -> Decimal? { guard let stringValue = try? decodeIfPresent(String.self, forKey: key), let decimalValue = Decimal(string: stringValue) else { return nil } return decimalValue } ``` }
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
You would need to extend KeyedDecodingContainer and add an implementation for Decimal.Type. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } } ``` Here is an example: ``` let json = """ { "capAmount": "123.45" } """ struct Status: Decodable { let capAmount: Decimal enum CodingKeys: String, CodingKey { case capAmount } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) capAmount = try container.decode(Decimal.self, forKey: .capAmount) } } // Execute it if let data = json.data(using: .utf8){ let status = try JSONDecoder().decode(Status.self, from: data) print(status.capAmount) } ```
The type should be Double and define also in the parsing as Double. Swift will figure out the rest ``` struct MyClass: Decodable { let decimal: Double //can be renamed to follow the API name. enum CodingKeys: String, CodingKey { case decimal } } extension MyClass { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) decimal = try values.decode(Double.self, forKey: .decimal) } } ```
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
I just add the following code. It supports optional as well. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } func decodeIfPresent(_ type: Decimal.Type, forKey key: K) throws -> Decimal? { guard let stringValue = try? decodeIfPresent(String.self, forKey: key), let decimalValue = Decimal(string: stringValue) else { return nil } return decimalValue } ``` }
That decoding strategy has nothing to do with numbers being represented as strings. What you need to do is to implement `init(from:)` and convert from string there ``` class MyClass : Codable { var decimal: Double? enum CodingKeys: String, CodingKey { case decimal = "test" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) decimal = Double(try container.decode(String.self, forKey: .decimal) //or if Decimal is used: //decimal = Decimal(string: try container.decode(String.self, forKey: .decimal) } } ``` Note that I am using Double instead of Decimal here to make it simpler
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
I just add the following code. It supports optional as well. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } func decodeIfPresent(_ type: Decimal.Type, forKey key: K) throws -> Decimal? { guard let stringValue = try? decodeIfPresent(String.self, forKey: key), let decimalValue = Decimal(string: stringValue) else { return nil } return decimalValue } ``` }
I believe that a cleaner solution is declare value not like a string but like a value: ``` "test": 0.007 ``` having a struct like that: ``` struct Stuff { var test: Decimal } ``` and then: ``` let decoder = JSONDecoder() let stuff = try decoder.decode(Stuff.self, from: json) ``` otherwise you can use this example: <https://forums.swift.org/t/parsing-decimal-values-from-json/6906/3>
58,322,528
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far. ``` for(int i=0;i<checkBox_fiber_ID.length;i++){ int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName()); checkBoxes_fiber[i]=findViewById(temp); checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(checkBoxes_fiber[i].isChecked()){ //do something } } }); } ``` Any tips on how to solve this?
2019/10/10
[ "https://Stackoverflow.com/questions/58322528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8633966/" ]
You would need to extend KeyedDecodingContainer and add an implementation for Decimal.Type. ``` extension KeyedDecodingContainer { func decode(_ type: Decimal.Type, forKey key: K) throws -> Decimal { let stringValue = try decode(String.self, forKey: key) guard let decimalValue = Decimal(string: stringValue) else { let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") throw DecodingError.typeMismatch(type, context) } return decimalValue } } ``` Here is an example: ``` let json = """ { "capAmount": "123.45" } """ struct Status: Decodable { let capAmount: Decimal enum CodingKeys: String, CodingKey { case capAmount } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) capAmount = try container.decode(Decimal.self, forKey: .capAmount) } } // Execute it if let data = json.data(using: .utf8){ let status = try JSONDecoder().decode(Status.self, from: data) print(status.capAmount) } ```
I believe that a cleaner solution is declare value not like a string but like a value: ``` "test": 0.007 ``` having a struct like that: ``` struct Stuff { var test: Decimal } ``` and then: ``` let decoder = JSONDecoder() let stuff = try decoder.decode(Stuff.self, from: json) ``` otherwise you can use this example: <https://forums.swift.org/t/parsing-decimal-values-from-json/6906/3>
33,459,558
So I am relatively new with using Google Maps and I have no idea what I am doing wrong. As I am following [Google Maps - iOS documentation](https://developers.google.com/maps/documentation/ios-sdk/map#accessibility). Under the subtitle of Camera Position I have used this block of code: ``` - (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)cameraPosition { id handler = ^(GMSReverseGeocodeResponse *response, NSError *error) { if (error == nil) { GMSReverseGeocodeResult *result = response.firstResult; GMSMarker *marker = [GMSMarker markerWithPosition:cameraPosition.target]; marker.title = result.lines[0]; marker.snippet = result.lines[1]; marker.map = mapView; } }; [geocoder_ reverseGeocodeCoordinate:cameraPosition.target completionHandler:handler]; } ``` The main problem is the last line. ``` [geocoder_ reverseGeocodeCoordinate:cameraPosition.target completionHandler:handler]; ``` As Xcode gives me the following error - **"Use of undeclared identifier 'geocoder\_' "** Why is this occurring?
2015/11/01
[ "https://Stackoverflow.com/questions/33459558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4137154/" ]
Try like this ``` UPDATE employee SET Salary= CASE WHEN Salary < 10000 THEN Salary + 500 CASE WHEN Salary >= 10000 and Salary < 20000 then Salary+600 CASE WHEN Salary >= 20000 and Salary < 30000 then Salary+700 ELSE Salary END ```
Your description doesn't say what to do if the salary is above 30000. I'll assume the salary is to be updated by 800 in that case. With that assumption, you can do: ``` SELECT *, ( (Salary<10000)?(Salary+500):( (Salary>=10000 AND Salary < 20000)? (Salary + 600):( (Salary>=20000 AND Salary < 30000)? (Salary + 700): (Salary + 800)) ))) AS NewSalary FROM employee; ``` Hope this gives you an idea.
47,161,088
I want to insert new records into a table called `[dbo].[Local]` that has these columns: ``` [id] [uniqueidentifier] NOT NULL, [Component] [varchar](100) NULL, [Language] [varchar](10) NULL, [IsText] [bit] NULL, [key] [varchar](100) NULL, [value] [varchar](max) NULL, ``` And the primary key called [id] is key clustered as: ``` [id] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ``` The insert command is like shown below. But how can I set a value for the `[id]` column because I get an error when I try to enter the value in the `[id]` column. How can I insert value to this field automatically? ``` INSERT INTO [dbo].[Local] ([id], [Component], [Language], [IsText], [key],[value]) VALUES (00000000-0000-0000-000-00000000000, 'Transport.Web', 'en', 1, 'ResourceTypeEmployee', 'TypeOffice') GO ``` Thanks
2017/11/07
[ "https://Stackoverflow.com/questions/47161088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8343348/" ]
You need to cast the value you want to insert to `UNIQUEIDENTIFIER`-type: ``` INSERT INTO [dbo].[Local] ( [id], [Component], [Language], [IsText], [key], [value]) VALUES ( CAST('00000000-0000-0000-0000-000000000000' AS UNIQUEIDENTIFIER), 'Transport.Web', 'en', 1, 'ResourceTypeEmployee', 'TypeOffice' ) ``` For inserting a new random `UNIQUEIDENTIFIER` you can use `NEWID()`: ``` INSERT INTO [dbo].[Local] ( [id], [Component], [Language], [IsText], [key], [value]) VALUES ( NEWID(), 'Transport.Web', 'en', 1, 'ResourceTypeEmployee', 'TypeOffice' ) ```
the insert select face : ``` INSERT INTO foo ([UNIQUEIDENTIFIER_col] ,[col2] , [...]) select NEWID() , [bar.selected_col1] , [...] from bar where (condition) ```
15,350,007
I am a little confused about the differences between call by value and const call by reference. Could someone please explain this to me. For example, do they both protect against changing the callers argument, are they fast for all object sizes, do either copy the argument while one doesnt, and which use more memory when making a copy?
2013/03/11
[ "https://Stackoverflow.com/questions/15350007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207457/" ]
> > do they both protect against changing the callers argument > > > Passing by value creates a *copy* of the argument provided by the caller, so whatever the function does, it does it on a separate objects. This means the original object won't ever be touched, so in this case the answer is "**Yes**". Passing by reference to `const`, on the other hand, lets the function refer the very same object that the caller provided, but it won't let that function modify it... *Unless* (as correctly remarked by Luchian Grigore in the comments) the function's implementer uses `const_cast<>` to cast away the `const`-ness from the reference, which is something that can be safely done only if it is known that the object bound to the reference was *not* declared to be of a `const` type (otherwise, you would get Undefined Behavior). Since this does not seem to be the most likely scenario considering your question, and considering that in general accepting a reference to `const` represents a *promise* that the argument won't be touched, then the answer is that as long as we assume this promise to be fulfilled, passing by reference to `const` won't alter the argument provided by the caller. So the answer is "**Yes**" again - with the little *caveat* I mentioned above. > > are they fast for all object sizes > > > **No.** Although you should first define "fast". If the type of the object being passed is expensive to copy (or to move, if a move is performed rather than a copy), then passing by value might be slow. Passing by reference will always cost you the same (the size of an address), no matter what is the type of the value you are passing. Notice, that on some architecture and for some data types (like `char`) passing by value could be faster than passing by reference, while the opposite is generally true for large enough UDTs. > > and which use more memory when making a copy? > > > Since only one of them is causing a copy, the question has an obvious answer.
The main difference is that passing by `const` reference (or non-const) doesn't make a copy of the argument. (the copy is actually subject to copy elision, but theoretically it's a copy that's passed to the function when you pass by value) In some cases, passing by value is just as fast, or even faster (typically when the object is at most the size of a register). You'd usually pass basic types by value, and class-types by reference. When passing by `const` reference you can still modify the original value just by casting the const away (via `const_cast`), but that results in undefined behavior if the original value is `const`.
15,350,007
I am a little confused about the differences between call by value and const call by reference. Could someone please explain this to me. For example, do they both protect against changing the callers argument, are they fast for all object sizes, do either copy the argument while one doesnt, and which use more memory when making a copy?
2013/03/11
[ "https://Stackoverflow.com/questions/15350007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207457/" ]
> > do they both protect against changing the callers argument > > > Passing by value creates a *copy* of the argument provided by the caller, so whatever the function does, it does it on a separate objects. This means the original object won't ever be touched, so in this case the answer is "**Yes**". Passing by reference to `const`, on the other hand, lets the function refer the very same object that the caller provided, but it won't let that function modify it... *Unless* (as correctly remarked by Luchian Grigore in the comments) the function's implementer uses `const_cast<>` to cast away the `const`-ness from the reference, which is something that can be safely done only if it is known that the object bound to the reference was *not* declared to be of a `const` type (otherwise, you would get Undefined Behavior). Since this does not seem to be the most likely scenario considering your question, and considering that in general accepting a reference to `const` represents a *promise* that the argument won't be touched, then the answer is that as long as we assume this promise to be fulfilled, passing by reference to `const` won't alter the argument provided by the caller. So the answer is "**Yes**" again - with the little *caveat* I mentioned above. > > are they fast for all object sizes > > > **No.** Although you should first define "fast". If the type of the object being passed is expensive to copy (or to move, if a move is performed rather than a copy), then passing by value might be slow. Passing by reference will always cost you the same (the size of an address), no matter what is the type of the value you are passing. Notice, that on some architecture and for some data types (like `char`) passing by value could be faster than passing by reference, while the opposite is generally true for large enough UDTs. > > and which use more memory when making a copy? > > > Since only one of them is causing a copy, the question has an obvious answer.
call by value will copy all the elements of the object it does protect the callers argument because if you are going to change something it is only a copy you are changing. calling by const reference does not copy elements but because of the "const" it will protect caller's argument. You const reference.
15,350,007
I am a little confused about the differences between call by value and const call by reference. Could someone please explain this to me. For example, do they both protect against changing the callers argument, are they fast for all object sizes, do either copy the argument while one doesnt, and which use more memory when making a copy?
2013/03/11
[ "https://Stackoverflow.com/questions/15350007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207457/" ]
> > do they both protect against changing the callers argument > > > Passing by value creates a *copy* of the argument provided by the caller, so whatever the function does, it does it on a separate objects. This means the original object won't ever be touched, so in this case the answer is "**Yes**". Passing by reference to `const`, on the other hand, lets the function refer the very same object that the caller provided, but it won't let that function modify it... *Unless* (as correctly remarked by Luchian Grigore in the comments) the function's implementer uses `const_cast<>` to cast away the `const`-ness from the reference, which is something that can be safely done only if it is known that the object bound to the reference was *not* declared to be of a `const` type (otherwise, you would get Undefined Behavior). Since this does not seem to be the most likely scenario considering your question, and considering that in general accepting a reference to `const` represents a *promise* that the argument won't be touched, then the answer is that as long as we assume this promise to be fulfilled, passing by reference to `const` won't alter the argument provided by the caller. So the answer is "**Yes**" again - with the little *caveat* I mentioned above. > > are they fast for all object sizes > > > **No.** Although you should first define "fast". If the type of the object being passed is expensive to copy (or to move, if a move is performed rather than a copy), then passing by value might be slow. Passing by reference will always cost you the same (the size of an address), no matter what is the type of the value you are passing. Notice, that on some architecture and for some data types (like `char`) passing by value could be faster than passing by reference, while the opposite is generally true for large enough UDTs. > > and which use more memory when making a copy? > > > Since only one of them is causing a copy, the question has an obvious answer.
I suppose that you mean the difference between: ``` void Fn1(MyType x); ``` and ``` void Fn2(const MyType& x); ``` In former case, a copy of the object is always created, which makes it slower especially if the type has a non-trivial constructor. The original object will be unaffected by any changes done on the copy within the function, but the copy itself can be changed. The latter example will not create a copy and will in general be faster. Inside the function, only the const functions can be called on the argument (unless you resort to dirty tricks like casting away constness), thus guaranteeing that the object will not be modified. IMPORTANT: This discussion doesn't cover types with special semantics, like smart pointers. In that case, call by value will still allow you to change what is logically the same object, i.e. not the smart ptr instance itself but the object it points to. So here are the answers to your questions: * do they both protect against changing the callers argument: yes, the original object will remain unchanged (excluding tricks) * are they fast for all object sizes: they are not equally fast - call by reference is in general faster, except for some primitive types where speed is more or less the same or maybe even marginally faster, depending on compiler optimizations. * do either copy the argument while one doesnt: call by value creates a copy, call by reference doesn't * which use more memory when making a copy? call by reference doesn't create a copy so the answer is clear
15,350,007
I am a little confused about the differences between call by value and const call by reference. Could someone please explain this to me. For example, do they both protect against changing the callers argument, are they fast for all object sizes, do either copy the argument while one doesnt, and which use more memory when making a copy?
2013/03/11
[ "https://Stackoverflow.com/questions/15350007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207457/" ]
> > do they both protect against changing the callers argument > > > Passing by value creates a *copy* of the argument provided by the caller, so whatever the function does, it does it on a separate objects. This means the original object won't ever be touched, so in this case the answer is "**Yes**". Passing by reference to `const`, on the other hand, lets the function refer the very same object that the caller provided, but it won't let that function modify it... *Unless* (as correctly remarked by Luchian Grigore in the comments) the function's implementer uses `const_cast<>` to cast away the `const`-ness from the reference, which is something that can be safely done only if it is known that the object bound to the reference was *not* declared to be of a `const` type (otherwise, you would get Undefined Behavior). Since this does not seem to be the most likely scenario considering your question, and considering that in general accepting a reference to `const` represents a *promise* that the argument won't be touched, then the answer is that as long as we assume this promise to be fulfilled, passing by reference to `const` won't alter the argument provided by the caller. So the answer is "**Yes**" again - with the little *caveat* I mentioned above. > > are they fast for all object sizes > > > **No.** Although you should first define "fast". If the type of the object being passed is expensive to copy (or to move, if a move is performed rather than a copy), then passing by value might be slow. Passing by reference will always cost you the same (the size of an address), no matter what is the type of the value you are passing. Notice, that on some architecture and for some data types (like `char`) passing by value could be faster than passing by reference, while the opposite is generally true for large enough UDTs. > > and which use more memory when making a copy? > > > Since only one of them is causing a copy, the question has an obvious answer.
One other point worth mentioning is that call-by-reference functions are converted into inline functions.
318,977
A (real) polynomial *function* can be defined as a function $f : \mathbb{R} \rightarrow \mathbb{R}$ such that there exists a sequence $a : \mathbb{N} \rightarrow \mathbb{R}$ such that the terms of $a$ are ultimately zero, and for all $x \in \mathbb{R}$ it holds that $$f(x)=\sum\_{i=0}^{\infty}a\_ix^i.$$ We can also define a *root-finding function* $\rho$ that takes polynomial functions to multisets. For any polynomial function $f$, define that $\rho(f)$ is the multiset of all $x$ such that $f(x)=0$. However, this last statement is hideously imprecise. It makes sense to speak of, "The *set* of all $x$ such that ---condition---," but the *multiset*? How might one go about defining it rigorously?
2013/03/02
[ "https://math.stackexchange.com/questions/318977", "https://math.stackexchange.com", "https://math.stackexchange.com/users/42339/" ]
The root multiset arises naturally from the factorization of the polynomial $$\rm f(x) = (x-r)^j \cdots (x-s)^k g(x)\ \to\ \{\, j\cdot r,\:\ldots,\: k\cdot s\,\}$$ where $\rm\:g(x)\:$ has no roots over the coefficient ring. More precisely, define $\rm\ e\_r(f(x)) := max\{n\in\Bbb N\ :\ (x\!−\!r)^n\!\mid f(x)\,\ in\,\ \Bbb R[x]\}.\:$ Then the root multiset is $\rm\ \{e\_r(f)\cdot r\ :\ r\in roots(f)\},\:$ where $\rm\:n\cdot r\:$ denotes an element $\rm\:r\:$ of multiplicity $\rm\:n\:$ in a multiset. Note that, over a domain, these linear factors are *unique*, being products of primes $\rm\,x-r.\:$ This uniqueness implies that the root multiset is well-defined. It also implies that any two (correct) root-finding algorithms will compute the same multiset of roots. The answer does not depend on what order the algorithm discovers the roots (as it generally does in *nonunique* factorization domains).
**Not an answer but an alternative**. Instead of multiset, a rigorous way to deal with roots of polynomial over $\mathbb{C}$ with degree $n$ is to model the of roots of a polynomial as an element in a quotient space of $\mathbb{C}^n$. Two $n$-tuples $\lambda = (\lambda\_1,\ldots,\lambda\_n)$ and $\mu = (\mu\_1,\ldots,\mu\_n)$ are identified together if one can find a permutation $\sigma$ of the coordinates such that $\lambda\_j = \mu\_{\sigma(j)}$ for $j = 1,\ldots,n$. The space is usually denoted as $\mathbb{C}\_{sym}^n$. It inherits a natural quotient topology from $\mathbb{C}^n$ and has a natural metric calling *optimal matching distance*: > > For $\lambda = (\lambda\_1,\ldots,\lambda\_n)$ and $\mu = (\mu\_1,\ldots,\mu\_n) \in \mathbb{C}\_{sym}^n$, the optimal matching distance is defined as: > $$d(\lambda,\mu) = \min\_{\sigma} \max\_{1\le j \le n} |\lambda\_j - \mu\_{\sigma(j)}|$$ > where $\sigma$ runs over the set of permutations of the coordinates. > > > The most important point is under this metric/topology, the roots of a polynomial of degree $n$ depends continuously on its coefficients.
99,285
I have a inline VF page and trying to reload the parent window. I am getting > > Uncaught SecurityError: Blocked a frame with origin > "<https://ratan.ap1.visual.force.com>" from accessing a frame with > origin "<https://ap1.salesforce.com>". Protocols, domains, and ports > must match. > > > Error. Yaah i can understand this is not accessible because of inline VF page and the parent window domain is not same so it behave like this. It is not make sense to me since the my inline VF page and standard page both are in same org and I am able to access the both page then I should able to access the parent window. For reloading the page I found the workaround. I can use `window.top.location = /object.Id;`. But wanted to know why this is necessary to have. If i am able to view the parent window then this should be accessible in my javascript.
2015/11/13
[ "https://salesforce.stackexchange.com/questions/99285", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/18731/" ]
I believe the problem is different. In salesforce you can talk to only those servers which includes digital certificates which are signed by Certificate Authorities to which salesforce trusts. Here certificate authority for your endpoint- <https://apps.daikinapplied.com/McQuayToolsSrvc/Authentication.asmx> is "Kaspersky Antivirus Personal Root Certificate". This is not listed as trusted certificate in the list provided by Salesforce. <https://developer.salesforce.com/page/Outbound_Messaging_SSL_CA_Certificates#addtrustclass1ca> Also if you check at [https://www.digicert.com/help/](https://i.stack.imgur.com/ahCMl.png) [2](https://i.stack.imgur.com/ahCMl.png): <https://www.digicert.com/help/> your endpoints certificate is not trusted one. Attached image for your reference. So solution would be to ask your integration party to have a certificate installed which is signed by CA to which salesforce trusts.[![enter image description here](https://i.stack.imgur.com/ahCMl.png)](https://i.stack.imgur.com/ahCMl.png) Let me know if this helps.
Thank you for posting the hostname of the server you were trying to connect to, it makes debugging this easier. It looks like the server is [currently configured](https://www.ssllabs.com/ssltest/analyze.html?d=apps.daikinapplied.com) to respond to SSL2, SSL3, and TLS1.0. This is most likely the reason for your issue. On apex callouts, salesforce will look to connect over TLS1.1 or TLS1.2. Ideally, you would enable TLS1.1 and/or TLS1.2 on this server and disable the other protocols. The [salesforce documentation](https://help.salesforce.com/apex/HTViewSolution?id=000214850&language=en_US) goes into further detail: > > There are two methods to configure the remote endpoints: > > > 1. Configure TLS settings to support TLS 1.1, TLS 1.2 and SNI. This would be the ideal case and prevent any handshake failures. > 2. If customers can only enable TLS 1.0 and not the higher versions, then the remote endpoints should be configured to respond with a TLS > 1.0 ServerHello instead of throwing an error, when it receives a ClientHello from us with one of the higher protocols. This method of > re-negotiation is the only option as we do not have any rollback > options on the upcoming change. > > > Salesforce will continue support TLS 1.0, but for TLS 1.0 to be > negotiated, the remote server needs to respond as per the second > method mentioned above. If the endpoint does not follow TLS standards > in this regard and, instead, is configured to respond with an error > when it receives a "TLS 1.1/1.2 ClientHello," they will start seeing > handshake failures. > > >
11,847,891
relatively self explanatory, I have a `JTable (table)` and the `DefaultTableModel (model)`. I would like to save the contents of the **JTable** to a file, then read them into the **JTable** at a later time. How can i do this? More Details: the JTable contains short strings, and there shouldn't be more than, say 50KB of data toal.
2012/08/07
[ "https://Stackoverflow.com/questions/11847891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1332495/" ]
`DefaultTableModel` implements Serializable. So the simplest solution would be to use an `ObjectOutputStream` and to call `writeObject()` with your model. **Note:** Remember that objects which are hold by the `DefaultDataModel` needs to be `Serialazable`
Hmmm There are a couple of factors on that decision. Mainly how big the data are, and how often the data are going to be read/write Some ideas that pop into my head are to store the data into 1- XML files the simplest way to do that is to use the built in dom <http://www.roseindia.net/xml/dom/> 2- database I personally favour mysql. Its failry easy to use.Java offers a great set of sql functions <http://dev.mysql.com/usingmysql/java/> http://zetcode.com/databases/mysqljavatutorial/ If you have a huge set of data, or you need to randomly access elements in your table, then there are more to consider than these simple solutions Regards
40,912,072
I'm using mintty via Git-for-Windows and CPython35-32. Why does Python think it's not attached to a terminal? ``` $ python -c "import sys; print(sys.stdout.isatty())" False ``` Interestingly, I also have a problem that I can not start an interactive session of Python inside the mintty. It might be related to this issue ``` $ python <nothingness here...> ```
2016/12/01
[ "https://Stackoverflow.com/questions/40912072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791713/" ]
[mintty's console emulation uses pipes to emulate a tty](https://github.com/mintty/mintty/issues/56#issuecomment-108887055) behind the scenes which confuses native programs checking to see if they are attached to a tty. In your case Python's `isatty()` sees stdout as being attached to pipe due to the fake tty and returns False. This is another example of [mintty issue #56 - Improve support for native console programs](https://github.com/mintty/mintty/issues/56). The [mintty wiki entry "Input/Output interaction with alien programs"](https://github.com/mintty/mintty/wiki/Tips#inputoutput-interaction-with-alien-programs) points out you can work around the problem by using a wrapper like [winpty](https://github.com/rprichard/winpty) when running the problem program within mintty. The git commits mentioned by @vonc only work around the problem in the git program itself - they won't impact other programs (such as Python running in git-for-window's mintty) which would need to implement git's workaround in their own source.
You might want to try that with Git 2.12 (Q1 2017) See [commit a9b8a09](https://github.com/git/git/commit/a9b8a09c3c30886c79133da9f48ef9f98c21c3b2) (22 Dec 2016) by [Jeff Hostetler (`jeffhostetler`)](https://github.com/jeffhostetler). See [commit 8692483](https://github.com/git/git/commit/86924838e3d881cda2192fd79ac3a58aad75efd3) (22 Dec 2016) by [Alan Davies (`scooter6386`)](https://github.com/scooter6386). See [commit fee807c](https://github.com/git/git/commit/fee807c5f6da43ba03f4f92d832fd625ab57b0d7) (22 Dec 2016) by [Johannes Schindelin (`dscho`)](https://github.com/dscho). (Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 58fcd54](https://github.com/git/git/commit/58fcd54853023b28a44016c06bd84fc91d2556ed), 27 Dec 2016) > > `mingw`: replace `isatty()` hack > > > Git for Windows has carried a patch that depended on internals of MSVC runtime, but it does not work correctly with recent MSVC runtime. > > A replacement was written originally for compiling with VC++. > > > The patch in this message is a backport of that replacement, and it also fixes the previous attempt to make `isatty()` tell that `/dev/null` is *not* an interactive terminal. > > >
58,754,401
I am trying to avoid inserting duplicate value into sqlite in android but I couldn't figure out what is the way to avoid inserting duplicate value as I am newbie in android sqlite.i have tried to find out the solution in online but i didn't get any satifactory answer. please help me out for solving this problem. My code are given bellow. # My MainActivity Code: ``` public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText nameEditText, ageEditText, genderEditText; MyDatabaseHelper myDatabaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nameEditText = findViewById(R.id.nameEditTextId); ageEditText = findViewById(R.id.ageEditTextId); genderEditText = findViewById(R.id.genderEditTextId); Button addButton = findViewById(R.id.addButtonId); myDatabaseHelper = new MyDatabaseHelper(this); addButton.setOnClickListener(this); } @Override public void onClick(View view) { String name = nameEditText.getText().toString(); String age = ageEditText.getText().toString(); String gender = genderEditText.getText().toString(); if (view.getId() == R.id.addButtonId) { if(TextUtils.isEmpty(name) && TextUtils.isEmpty(age) && TextUtils.isEmpty(gender) ){ Toast.makeText(getApplicationContext(), "Enter details and submit ", Toast.LENGTH_LONG).show(); } else if (TextUtils.isEmpty(name)) { Toast.makeText(getApplicationContext(), "Insert the name first ", Toast.LENGTH_LONG).show(); }else if ( TextUtils.isEmpty(age)){ Toast.makeText(getApplicationContext(), "Insert an age ", Toast.LENGTH_LONG).show(); }else if (TextUtils.isEmpty(gender)){ Toast.makeText(getApplicationContext(), "Insert the gender ", Toast.LENGTH_LONG).show(); }else { long rowId = myDatabaseHelper.insertData(name, age, gender); if (rowId == -1) { Toast.makeText(getApplicationContext(), "unsuccessfull ", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Row " + rowId + " is sucessfully inserted ", Toast.LENGTH_LONG).show(); } //clear screen after inserting value; nameEditText.setText(""); ageEditText.setText(""); genderEditText.setText(""); } } } } ``` My MyDataBaseHelper Code: ========================= ``` public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "Student.db"; private static final String TABLE_NAME = "student_details"; private static final String ID = "_id"; private static final String NAME = "Name"; private static final String AGE = "Age"; private static final String GENDER = "Gender"; private static final int VERSION_NUMBER = 3 ; private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+AGE+" INTEGER, "+GENDER+"); "; private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME; private Context context; MyDatabaseHelper(@Nullable Context context) { super(context, DATABASE_NAME, null,VERSION_NUMBER); this.context = context; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { try { Toast.makeText(context,"onCreate is called ", Toast.LENGTH_LONG).show(); sqLiteDatabase.execSQL( CREATE_TABLE); }catch (Exception e){ Toast.makeText(context,"Exceptin : " +e, Toast.LENGTH_LONG).show(); } } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { try { Toast.makeText(context,"onUpgrade is called " , Toast.LENGTH_LONG).show(); sqLiteDatabase.execSQL(DROP_TABLE); onCreate(sqLiteDatabase); }catch (Exception e){ Toast.makeText(context,"Exceptin : " +e, Toast.LENGTH_LONG).show(); } } long insertData(String name, String age, String gender){ SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(NAME,name); contentValues.put(AGE,age); contentValues.put(GENDER,gender); return sqLiteDatabase.insert(TABLE_NAME,null,contentValues); } } ```
2019/11/07
[ "https://Stackoverflow.com/questions/58754401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7741722/" ]
Because you haven't specified the type(s) that the `CodeEntry::getButton*` methods return, I'm going to denote it `T` for my example. --- Your second `enum` parameter can be a `Function<CodeEntry, T>`, which will allow you to use a method reference: ``` private enum Radio { SPACE(" ", CodeEntry::getButtonWhite), PLUS("+", CodeEntry::getButtonGreen), MINUS("-", CodeEntry::getButtonRed); private final String value; private final Function<CodeEntry, T> buttonFunction; private Radio(final String value, Function<CodeEntry, T> buttonFunction) { this.value = value; this.buttonFunction = buttonFunction; } public static void setSelection(final CodeEntry entry, final String flag) { Arrays.stream(values()) .filter(radio -> flag.equals(radio.value)) .findAny() .ifPresent(radio -> { radio.buttonFunction.apply(entry).setSelection(true); }); } } ``` This assumes that the `flag` parameter will be either `" "`, `"+"`, or `"-"`.
Here is a solution using an `abstract` method: ``` private enum Radio { SPACE(" ") { @Override public void setSelection(final CodeEntry entry, final String flag) { // do whatever } }, ... public abstract void setSelection(final CodeEntry entry, final String flag); ``` Honestly I had a little trouble understanding exactly what you wanted, but hopefully that helps?
39,596,496
I'm sure I'm overlooking something in the [`Settings`](https://developer.android.com/reference/android/provider/Settings.html#constants) class documentation. What `Intent` can open the Settings app in the "Do not disturb" section? I expected it to be the [`ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS`](https://developer.android.com/reference/android/provider/Settings.html#ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS) action, but that is only for the screen which lists which apps have requested DND access.
2016/09/20
[ "https://Stackoverflow.com/questions/39596496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/467650/" ]
### Update Looking at the [`AndroidManifest.xml` for the *Settings* app](https://cs.android.com/android/platform/superproject/+/android-5.0.0_r1.0.1:packages/apps/Settings/AndroidManifest.xml;l=599) there is an `Activity` `Settings$ZenModeSettingsActivity` already from Android 5.0. To send the user to the "Do not disturb" screen you can use the action `android.settings.ZEN_MODE_SETTINGS` like this: ``` try { startActivity(new Intent("android.settings.ZEN_MODE_SETTINGS")); } catch (ActivityNotFoundException e) { // TODO: Handle activity not found } ``` ### Original answer **It looks like there are no screens in the Settings app (at least on Android 6+7) where you can enable/disable DND.** It seems like this is only available through the settings tile (and can be disabled in the dialog when changing the volume). I have a Samsung S6 (Android 6.0.1) which has this screen, but this is probably some custom Samsung changes. The screen is represented by the class `com.android.settings.Settings$ZenModeDNDSettingsActivity` which can be started by any app. This might be of help for some people out there. `AndroidManifest.xml` for Settings app for Android 6+7: * <https://android.googlesource.com/platform/packages/apps/Settings/+/android-6.0.1_r68/AndroidManifest.xml> * <https://android.googlesource.com/platform/packages/apps/Settings/+/android-7.0.0_r6/AndroidManifest.xml>
You have to use the following `Intent`: [ACTION\_VOICE\_CONTROL\_DO\_NOT\_DISTURB\_MODE](https://developer.android.com/reference/android/provider/Settings.html#ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE) and then pass a `boolean` through [EXTRA\_DO\_NOT\_DISTURB\_MODE\_ENABLED](https://developer.android.com/reference/android/provider/Settings.html#EXTRA_DO_NOT_DISTURB_MODE_ENABLED). Make note that the documentation specifies the following: `This intent MUST be started using startVoiceActivity.`
37,761,327
I am working on ionic project where i have to implement push notification but practically what to do i have no idea again my app is going to be used in corporate environment so what to do . Kindly suggest.
2016/06/11
[ "https://Stackoverflow.com/questions/37761327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522259/" ]
Lvalue points to a storage location which can be assigned with new values. All variables including `const` variables are lvalues. Lvalues persist beyond the expression that uses it. On the other hand, an rvalue is a temporary value that does not persist beyond the expression that uses it. Lvalues may appear on the left or right side of assignment operator. But rvalues can never appear on left side of assignment operator. In short: Lvalues are storage areas and rvalues are Values. Example: ``` int main(){ int i = 10; int j = 20; int* ip; int* jp; /* ip and jp are pointer variables, hence L-VALUES. they can appear BOTH sides of = operator. as shown below. */ ip = &i; jp = &j; jp = ip; /* values such as 1, 25, etc are Values, hence R-VALUES they can appear only RIGHT side of = operartor as shown below, 1 on left causes error not ip */ ip + 1 = &i; // invalid ip = &i + 1; // valid, however printf("%d", *ip); might print a Garbage value /* *ip and *jp are also L-VALUES, including *(ip + 1) or *(ip + 2) they can appear both sides */ *ip = 1 + *jp; return 0; } ``` You get a compilation error when you incorrectly use lvalues or rvalues.
According to the [C Standard, section 6.3.2.1](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf#page=72): > > An *lvalue* is an expression (with an object type other than void) that potentially designates an object. > > > Although this is rather vague, it continues with > > The name ‘‘lvalue’’ comes originally from the assignment expression **E1** = E2, in which the left operand **E1** is required to be a (modifiable) lvalue. > > > And further more > > What is sometimes called ‘‘rvalue’’ is in this International Standard described as the ‘‘value of an expression’’. > > > What this means to me is > > An *lvalue* is a value that supports assignment and is on the left side of the assignment operator. > > > An *rvalue* is any value not on the left hand side of the assignment operator. > > > So for example ``` #include <stdio.h> int main() { int array[1], *pointer, i = 42; // ^ ^-rvalue // lvalue *array = i; // ^ ^-rvalue //lvalue pointer = array; // ^ ^-rvalue //lvalue printf("%p\t%d\n", pointer, *pointer); // ^-rvalues-^ // causes segfault but compiles: *(int *)4 = 2; // ^ ^-rvalue // lvalue return 0; } ``` As above in the comments and to answer the question fully > > You'd have to use a compiler that lets you access the AST of a given compilation unit. > > >
21,771,386
I have developed an application that has one preferences activity for application setting so I want know about can we set custom graphics layout (XML) on preferences layout like CheckBox has own color Button while check and unchecked and list has own color if possible then how?
2014/02/14
[ "https://Stackoverflow.com/questions/21771386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this: ``` <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList> ``` and then : ``` protected void Page_Load(object sender, EventArgs e) { } protected void TextBox1_TextChanged(object sender, EventArgs e) { int count = Convert.ToInt32(this.TextBox1.Text); for (int i = 1; i <= count; i++) { this.DropDownList1.Items.Add(i.ToString()); } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Response.Write("Selected Value Is :" + this.DropDownList1.SelectedValue); } ``` Please let me know if you have some difficulty.
Example : txtCity.text = "Mysore,Bangalore,Delhi" ``` protected void txtCity_TextChanged(object sender, EventArgs e) { string[] _cities=this.txtCity.text.split(','); int _maxCities = _cities.count(); for (int _item = 1; _item <= _maxCities; _item++) { this.ddlCity.Items.Add(_item.ToString()); } } ```
277,350
Accidentaly touched PCB of motherboard,so if it got damaged by esd would it boot?
2016/12/29
[ "https://electronics.stackexchange.com/questions/277350", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/133462/" ]
The answer is *Yes* and *No*. The failure type due to static can be **immediate** (which is easy to detect or perceive) or can be **latent**(hard to detect, but may surface up over a period of time). Hence the effect of ESD need not be immediate. The PCB on the mother board have several components. The particular component which may have been completely damaged may not be involved in booting OR even normal operation of PC. Hence, even if PC boots and there is a permanent damage of one or two components it might go undetected for a while. Since there is no practical way of identifying the latent damage of the device, always take ESD precautions while handling boards which are not meant to be handled with out such care.
Electrostatic damage is not always immediately obvious, and when it does manifest sometimes it only effects some operations. Maybe one of the RAM slots, SATA interfaces, front panel controls, or indicators stops working, but the system still passes POST if those features aren't being used.
34,817,344
I see both of these styles for inserting the contents of an expression in a map. For example: ``` imap ,9 <c-r>=1+1<cr> imap <expr> ,9 1+1 ``` Both of these do the same thing as far as I can tell: they insert `2` if you type `,9` in insert mode. I see some scripts use the first style and others the second. Are there any differences? It seems to me that the `<expr>` style is clearer, but are there use-cases where the `<c-r>=` style can accomplish something that `<expr>` can't?
2016/01/15
[ "https://Stackoverflow.com/questions/34817344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438615/" ]
Your two examples are equivalent. You should prefer the second style as `<c-r>=` behaves differently in some case. One recent example would be [<Plug> function failing, inserting as literal "<t\_ý>S"](https://stackoverflow.com/q/34487155/1890567), where using `<c-r>=<Plug>Func()<CR>` did something different and unexpected compared to `<Plug>Func()` in an expression mapping. Most of the uses for `<c-r>=` should be when you want to insert the result of the expression in the middle of your mapping (or just using the expression register manually). A trivial example would be you want to include the contents of the `g:some_var` variable in between parentheses when you hit `,8` ``` imap ,8 (<c-r>=g:some_var<cr>) ```
My biggest issues with `:map-<expr>` are the one explained in the documentation: * We cannot modify the buffer, nor play with other buffers * We cannot use `:normal` * We cannot move the cursor around (as an observable property of the mapping) -- which I sometime do with `:normal`... Moreover, `i_CTRL-R` has been around for a much longer time. As a consequence I haven't even try to migrate my old, and intensively tested and used, mappings to `i(nore)map <expr>`.
14,604,659
Scenario -------- I have three elements in this problem. One is an array of ids in this format: (1,3,5,6,8). That array is a list of id of users I want to display. The second element is table that contains user information something simple like: *id name surname email*. The third element is a second table that contains users configuration. There are two parameters in that last table, one is **lid**, and the other is **usraction** (among others, but the important are those two). lid represent a permission type and usraction the value, if the user wants his data to be public there will be a row on that table where **lid=3** and **usraction="accepted"**, also I register the datetime of the action every time the user changes this permission, so each time he change it a new row is added, and in order to retrieve the actual state of the permission i have to retrieve the last row for the user an check the value of usraction like this: ``` SELECT * FROM legallog WHERE uid = '.$user['id'].' AND lid = 3 ORDER BY ABS(`registration` - NOW()) LIMIT 1 ``` Then in php: ``` if($queryresult && $queryresult[0]['usraction']=='accepted') //display data ``` The problem ----------- In the scenario id described how im getting the actual state of the permission set by one user at the time, the problem now is I want to sort of clean an array of ids in one or two sql calls. Lets say I want to print the user information of 4 users, one function gives me the ids in this format: (2,6,8,1), but those users may not want to display their information, using the query I showed before I can make a call to the sql server for each user and then generate a new array, if the users who authorize are 1 and 8 the result array will be (8,1). The think is whit an array of 100 users I will make 100 calls, and I dont want this, is there a way to solve this in one or two querys?
2013/01/30
[ "https://Stackoverflow.com/questions/14604659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310648/" ]
A query such as this gets you the information you want: ``` select u.*, (select usraction from configuration c where c.userid = u.userid and c.lid = 3 order by datetime limit 1 ) as lastLid3Action from users u where u.userid in (1,3,5,6,8) ``` If you only want "accepted" values, then make this a subquery: ``` select t.* from (select u.*, (select usraction from configuration c where c.userid = u.userid and c.lid = 3 order by datetime limit 1 ) as lastLid3Action from users u where u.userid in (1,3,5,6,8) ) t where LastLid3Action = 'Accepted' ```
You question is somewhat vague, but if you are asking how to select a number of records when you have a list of ids, the answer is: ``` select column, list, goes, here from tablename where id in (1,5,8,12,413); ``` That will get you the values of the columns you list for just the records that match your array of ids.
14,604,659
Scenario -------- I have three elements in this problem. One is an array of ids in this format: (1,3,5,6,8). That array is a list of id of users I want to display. The second element is table that contains user information something simple like: *id name surname email*. The third element is a second table that contains users configuration. There are two parameters in that last table, one is **lid**, and the other is **usraction** (among others, but the important are those two). lid represent a permission type and usraction the value, if the user wants his data to be public there will be a row on that table where **lid=3** and **usraction="accepted"**, also I register the datetime of the action every time the user changes this permission, so each time he change it a new row is added, and in order to retrieve the actual state of the permission i have to retrieve the last row for the user an check the value of usraction like this: ``` SELECT * FROM legallog WHERE uid = '.$user['id'].' AND lid = 3 ORDER BY ABS(`registration` - NOW()) LIMIT 1 ``` Then in php: ``` if($queryresult && $queryresult[0]['usraction']=='accepted') //display data ``` The problem ----------- In the scenario id described how im getting the actual state of the permission set by one user at the time, the problem now is I want to sort of clean an array of ids in one or two sql calls. Lets say I want to print the user information of 4 users, one function gives me the ids in this format: (2,6,8,1), but those users may not want to display their information, using the query I showed before I can make a call to the sql server for each user and then generate a new array, if the users who authorize are 1 and 8 the result array will be (8,1). The think is whit an array of 100 users I will make 100 calls, and I dont want this, is there a way to solve this in one or two querys?
2013/01/30
[ "https://Stackoverflow.com/questions/14604659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310648/" ]
As I understand you have two tables in the first table, where the user information is stored; and the second table, where the user permission is stored. And you want to get information from the first table using permission from the second table, then you need this query: ``` SELECT a.* FROM first-table-name AS a RIGHT JOIN second-table-name AS b a.uid = b.lid WHERE uid in (1,3,5,6,8) AND usraction='accepted' ORDER BY ABS) LIMIT 1 ```
You question is somewhat vague, but if you are asking how to select a number of records when you have a list of ids, the answer is: ``` select column, list, goes, here from tablename where id in (1,5,8,12,413); ``` That will get you the values of the columns you list for just the records that match your array of ids.
14,604,659
Scenario -------- I have three elements in this problem. One is an array of ids in this format: (1,3,5,6,8). That array is a list of id of users I want to display. The second element is table that contains user information something simple like: *id name surname email*. The third element is a second table that contains users configuration. There are two parameters in that last table, one is **lid**, and the other is **usraction** (among others, but the important are those two). lid represent a permission type and usraction the value, if the user wants his data to be public there will be a row on that table where **lid=3** and **usraction="accepted"**, also I register the datetime of the action every time the user changes this permission, so each time he change it a new row is added, and in order to retrieve the actual state of the permission i have to retrieve the last row for the user an check the value of usraction like this: ``` SELECT * FROM legallog WHERE uid = '.$user['id'].' AND lid = 3 ORDER BY ABS(`registration` - NOW()) LIMIT 1 ``` Then in php: ``` if($queryresult && $queryresult[0]['usraction']=='accepted') //display data ``` The problem ----------- In the scenario id described how im getting the actual state of the permission set by one user at the time, the problem now is I want to sort of clean an array of ids in one or two sql calls. Lets say I want to print the user information of 4 users, one function gives me the ids in this format: (2,6,8,1), but those users may not want to display their information, using the query I showed before I can make a call to the sql server for each user and then generate a new array, if the users who authorize are 1 and 8 the result array will be (8,1). The think is whit an array of 100 users I will make 100 calls, and I dont want this, is there a way to solve this in one or two querys?
2013/01/30
[ "https://Stackoverflow.com/questions/14604659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310648/" ]
A query such as this gets you the information you want: ``` select u.*, (select usraction from configuration c where c.userid = u.userid and c.lid = 3 order by datetime limit 1 ) as lastLid3Action from users u where u.userid in (1,3,5,6,8) ``` If you only want "accepted" values, then make this a subquery: ``` select t.* from (select u.*, (select usraction from configuration c where c.userid = u.userid and c.lid = 3 order by datetime limit 1 ) as lastLid3Action from users u where u.userid in (1,3,5,6,8) ) t where LastLid3Action = 'Accepted' ```
As I understand you have two tables in the first table, where the user information is stored; and the second table, where the user permission is stored. And you want to get information from the first table using permission from the second table, then you need this query: ``` SELECT a.* FROM first-table-name AS a RIGHT JOIN second-table-name AS b a.uid = b.lid WHERE uid in (1,3,5,6,8) AND usraction='accepted' ORDER BY ABS) LIMIT 1 ```
38,090,429
I have an STL map that has String keys and int values. I need to put the items into a new map with int keys and String values, such that the keys are sorted from lowest to greatest. For example I have a map with these values(key, value): ``` "A", 5 "B", 2 "C", 8 "D", 4 ``` I would like them to then be arranged in such a way that they look like this(key, value): ``` 2, "B" 4, "D" 5, "A" 8, "C" ``` Where the value from the original map becomes the key, and the key becomes the value. I know that I need to add the values from the original map to a new map, but I'm not sure how I would add them in a way that they're sorted from lowest to greatest.
2016/06/29
[ "https://Stackoverflow.com/questions/38090429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/926319/" ]
Something along these lines perhaps: ``` std::map<std::string, int> old_map = ...; // initialized somehow std::map<int, std::string> new_map; std::transform(old_map.begin(), old_map.end(), std::inserter(new_map, new_map.end()), [](decltype(old_map)::iterator it) { return std::make_pair(it->second, it->first); } ); ```
For each pair in the original map, reverse the pair and insert into the other map. The sorting is automatic because [`std::map`](http://en.cppreference.com/w/cpp/container/map) is sorted by key. Also, if you might have multiple keys in the original map with the same data (for example both `"A"` and `"E"` have the data `5`) then you need to be using [`std::multimap`](http://en.cppreference.com/w/cpp/container/multimap) instead.
38,090,429
I have an STL map that has String keys and int values. I need to put the items into a new map with int keys and String values, such that the keys are sorted from lowest to greatest. For example I have a map with these values(key, value): ``` "A", 5 "B", 2 "C", 8 "D", 4 ``` I would like them to then be arranged in such a way that they look like this(key, value): ``` 2, "B" 4, "D" 5, "A" 8, "C" ``` Where the value from the original map becomes the key, and the key becomes the value. I know that I need to add the values from the original map to a new map, but I'm not sure how I would add them in a way that they're sorted from lowest to greatest.
2016/06/29
[ "https://Stackoverflow.com/questions/38090429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/926319/" ]
Something along these lines perhaps: ``` std::map<std::string, int> old_map = ...; // initialized somehow std::map<int, std::string> new_map; std::transform(old_map.begin(), old_map.end(), std::inserter(new_map, new_map.end()), [](decltype(old_map)::iterator it) { return std::make_pair(it->second, it->first); } ); ```
For `std:map`, it is order by key default. ``` Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). ``` Please read the link:<http://www.cplusplus.com/reference/map/map/> ``` #include <iostream> #include <string> #include <iterator> #include <algorithm> #include <map> using namespace std; int main() { map<string, int> myMap; myMap["D"] = 4; myMap["C"] = 8; myMap["B"] = 2; myMap["A"] = 5; cout<<"before:"<<endl; for_each(myMap.begin(), myMap.end(), [](auto& element){cout<<element.first<<" "<<element.second<<endl;}); map<int, string> otherMap; cout<<"after:"<<endl; for_each(myMap.begin(), myMap.end(), [&otherMap](auto& element){otherMap[element.second] = element.first;}); for_each(otherMap.begin(), otherMap.end(), [](auto& element){cout<<element.first<<" "<<element.second<<endl;}); return 0; } ``` Here is the code exmaple: the output is: ``` before: A 5 B 2 C 8 D 4 after: 2 B 4 D 5 A 8 C ``` So you don't sort it by yourself.
71,906,782
I have a dataset of n samples and 6 attributes and two classes. I am currently using the KNeighborsClassifier from Scikit Learn in order to classify a dataset's two classes. I am looking to plot the values of the dataset (across an arbitrary two attributes/domains of the dataset) and would look the plot to show the split according to the KNeighborsClassifier that I have. In other words, to plot the values and have the background sections of the plot match what the classification would be. So for example, Class 1 would be blue and Class 2 would be red. The points in those areas would have the appropriate color and the background (containing points are not) would have the appropriate color as well. However, I can't seem to find help online on how I can achieve this. Any help would be appreciated.
2022/04/18
[ "https://Stackoverflow.com/questions/71906782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7802550/" ]
Installing Microsoft Visual C++ 2015-2019 Redistributable could help
Are running vanilla Python or some distribution?
1,899,228
On a trip, four friends want to play a card game, where $n$ cards must be dealt among the players before the game starts. However, they forgot the cards, so they HAVE TO play with imaginary cards (there is no paper etc. at hand). The game cannot be played with less than four players, so the friends cannot choose one of them as a dealer, who would randomly shuffle a deck of cards in his mind, and secretly tell each of the others, which cards he gets. How to solve their problem, i.e., how to (randomly) permute a deck of cards, so that each of the players knows only his $n/4$ cards?
2016/08/21
[ "https://math.stackexchange.com/questions/1899228", "https://math.stackexchange.com", "https://math.stackexchange.com/users/73561/" ]
One can use a slight modification of the random coin flip algorithm. As in the latter, it is essential that the cryptographic protocols used by the players are commutative, i.e. it does not matter in which order decryption/encryption with different keys is performed. (E.g. they can XOR the plaintext deck with their own private keys.) Now you do as follows. $A$ shuffles the deck, encrypts each card with his key, and passes the deck to $B$. $B$ shuffles further, encrypts with his own key, and passes the deck to $C$, etc. Once the deck is shuffled and coded by all four players, $A$ decrypts anything but his own cards, i.e. the first $n/4$ cards, then $B$ decrypts anything but the cards $n/4 +1 $ to $n/2$, etc. Finally, they end up with the deck where the cards $1$ to $n/4$ encrypted by $A$'s key; $n/4+1$ to $n/2$, by $B$'s key etc. This can be passed to all players, so everyone can identify his cards (but not the cards of other players).
Theoretically possible solution for the values of $n$ big enough, is the following: 1. Players injectively map the cards to the set of prime numbers, i.e., every card $j$ gets its own prime number $p\_j$. 2. Each player $i$ chooses his $n/4$ cards and computes the product $\Pi\_i$ of the corresponding primes and report it to the other players. 3. If the product $\Pi\_1\Pi\_2\Pi\_3\Pi\_4$ equals the product $\Pi\_{j = 1}^n p\_j$, the cards were successfully dealt. Otherwise, we go back to step $2$. Two problems: * For a human, it is hard to calculate $\Pi\_i$. * We may have to repeat step 2. many times.
4,548,887
I'm new to [jQTouch](http://jqtouch.com/) -- it's pretty awesome -- but I'm finding that I'm not able to get it to work out of the box for my HTML, even though I'm following the [getting started](https://github.com/senchalabs/jQTouch/wiki/gettingstarted) guide as well as the [markup guidelines](https://github.com/senchalabs/jQTouch/wiki/Markup,-Theming-and-Styling). Specifically, each of my screens is a `<section>` element (direct child of `<body>`) with a unique ID, and I have links to those IDs, e.g. `<a href="#screen-a">`. This seems to follow the convention of the demo code, but yet the demo code works and my code doesn't. Here is the HTML structure of my `<body>`: ``` <section id="main-menu"> <header class="toolbar"><!-- ... --></header> <nav> <ul> <li class="arrow"><a href="#screen-a">Screen A</a></li> <li class="arrow"><a href="#screen-b">Screen B</a></li> <li class="arrow"><a href="#screen-c">Screen C</a></li> </ul> </nav> <footer><!-- ... --></footer> </section> <section id="screen-a"><!-- ... --></section> <section id="screen-b"><!-- ... --></section> <section id="screen-c"><!-- ... --></section> <script src="jquery.min.js"></script> <script src="jqtouch.min.js"></script> <script src="init.js"></script> ``` And my `init.js` simply initializes jQTouch (no custom options): ``` var jQT = new $.jQTouch({}); ``` When I load my page, the UI appears fine, and I can confirm jQTouch was initialized because my `jQT` variable exists. But when I click any link, the location bar changes to the new hash (e.g. "#screen-a"), but the UI doesn't change. And the JavaScript console starts throwing repeated multiple **No pages in history** errors. (When I use the unminified jQTouch.js, these errors come from inside the jQTouch `goBack()` function, which is being called from the `dumbLoopStart()` timer.) Note that this happens for me both in desktop Safari and in Mobile Safari on the iPhone. But that's very strange, because their [demo](http://jqtouch.com/preview/demos/main/) works just fine for me on both. I've banged my head against this for hours to no avail. Does anyone have ideas or suggestions or tips for what I might be doing wrong? Thanks!
2010/12/28
[ "https://Stackoverflow.com/questions/4548887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132978/" ]
I created an test from your provided example (with the addition of the style imports). Simply removing the <nav> elements resolved the issue for me.
I believe your main elements have to be div's. Additionally, you need a class of "current" on the div that should be displayed first. I don't know if the version you are using requires this, but what I pulled via git a while back requires that all of your main elements be contained in a div with an id of "jqt". ``` <div id="jqt"> <div id="main-menu" class="current"> <ul> <li class="arrow"><a href="#screen-a">Screen A</a></li> <li class="arrow"><a href="#screen-b">Screen B</a></li> <li class="arrow"><a href="#screen-c">Screen C</a></li> </ul> </div> <div id="screen-a"><!-- ... --></div> <div id="screen-b"><!-- ... --></div> <div id="screen-c"><!-- ... --></div> </div> <script src="jquery.min.js"></script> <script src="jqtouch.min.js"></script> ```
62,188,651
My project was successfully building and all of a sudden I got the below error in Android studio. **Unable to find method 'org.gradle.api.publish.maven.internal.publication.MavenPublicationInternal.getPublishableFiles()Lorg/gradle/api/file/FileCollection;'. Possible causes for this unexpected error include: Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.) Re-download dependencies and sync project (requires network) The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem. Stop Gradle build processes (requires restart) Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project. In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.** I tried clearing the local dependency cache and rebuilding the project. But still the error persists. I am using android studio v4.0 with build tools v29.0.2. Is it because gradle can't download the dependency from maven repo? Is it because there is an error in configuring maven in my 'respositories' list? How can I get more information on this error?
2020/06/04
[ "https://Stackoverflow.com/questions/62188651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3665376/" ]
Try to update the [com.jfrog.artifactory](https://plugins.gradle.org/plugin/com.jfrog.artifactory) version.
My resolution for this was to update the artifactory version like @disha4mourya suggested - add this block to your project's `build.gradle`, directly after your buildscript block: ``` plugins { id "com.jfrog.artifactory" version "4.18.3" } ```
43,729,583
``` {map(arr, (obj,index) => <div key={index}>{obj.name}</div> </div>)} ``` What's wrong with my jsx above? couldn't get the index using map?
2017/05/02
[ "https://Stackoverflow.com/questions/43729583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7934660/" ]
Here is the proper way to use map. ``` array.map((x, index)=>{ return (<div key={index}>{x.name}</div>); }); ``` or ``` Array.prototype.map.call(arr, function(x, index) { return (<div key={index}>{x.name}</div>); }); ``` Mozilla [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=control)
You are not wrapping your JSX content within `()` . Also you need to have the `(` on the same line as `=>` and you have an extra closing `div` ``` {map(arr, (obj,index) => ( <div key={index}>{obj.name}</div> ))} ```
385
Luke 2:52 (ESV) states that "Jesus increased in wisdom and in stature and in favor with God and man." The word "favor" in this passage is translated from the Greek word "charis" (Strong's G5485), which the Strong's defines as "graciousness (as gratifying), of manner or act." In my modern, American, English-speaking context, I don't see a straight-forward connection between graciousness and favor, specifically not the kind of favor implied by the common usage of "charisma" (i.e. I don't assume a person who has charisma will necessarily be gracious). How were "graciousness" and "favor" associated in the ancient Greek context? How is it that the Greek word for "graciousness" also carried a connotation of "favor?"
2011/10/22
[ "https://hermeneutics.stackexchange.com/questions/385", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/78/" ]
You might be interested in [Moral Transformation](http://rads.stackoverflow.com/amzn/click/1456389807), page 166ff, in which Wallace and Rusk argue that "charis" did not have the technical sense many now give it, but always meant "favor" in a reciprocity system, or "favorable" as we would understand it, and that most of the passages in which we see "charis" used in a technical sense, it is referring to the favor that God did for us when he sent his son. They cite Malina and Harrison, among others--might be worth reading their sources. In other words, perhaps it meant "favor" and has come to imply "charisma" instead of the other way around.
There's no doubt that the word is primarily translated as "grace" (130 times in the King James version). However, there are a few times (6 in total) that this word is translated as "favor". [Luke 1:30](http://www.biblegateway.com/passage/?search=Luke%201:30&version=NASB), [Acts 2:47](http://www.biblegateway.com/passage/?search=Acts%202:47&version=NASB), [Acts 7:10](http://www.biblegateway.com/passage/?search=Acts%207:10&version=NASB), [Acts 7:46](http://www.biblegateway.com/passage/?search=Acts%207:46&version=NASB), and [Acts 25:3](http://www.biblegateway.com/passage/?search=Acts%2025:3&version=NASB) are the other five places (beyond the passage in question). If you look at all six passages, the idea used is having found "grace" *with* someone, "grace" *for* someone, or "grace" *towards* someone. The idea is always grace in motion. If we look at the English definition of "favor" it might help make this translation clearer: > > [Merriam Webster: favor](http://www.merriam-webster.com/dictionary/favor) > > > 1. (1): a friendly regard shown toward another especially by a superior (2): an approving consideration or attention > 2. *archaic* appearance > 3. a : gracious kindness; also : an act of such kindness > > > The first definition shows that "favor" is a regard shown `toward another`. This is the same type of concept shown in the six passages above. Furthermore, the third definition shows that the idea of favor is connected with grace: "gracious kindness". This link between "favor" and "grace" can also be seen in that [second definition of "grace"](http://www.merriam-webster.com/dictionary/grace) is *"approval, favor"*. ### Summary Ultimately, "finding grace with God and man" and "finding favor with God and man" are the same. If someone offers you grace, then they favor you. If someone finds favor with you, they will offer you grace. These two concepts are inextricably linked, to the point of being able to translate between the two.
385
Luke 2:52 (ESV) states that "Jesus increased in wisdom and in stature and in favor with God and man." The word "favor" in this passage is translated from the Greek word "charis" (Strong's G5485), which the Strong's defines as "graciousness (as gratifying), of manner or act." In my modern, American, English-speaking context, I don't see a straight-forward connection between graciousness and favor, specifically not the kind of favor implied by the common usage of "charisma" (i.e. I don't assume a person who has charisma will necessarily be gracious). How were "graciousness" and "favor" associated in the ancient Greek context? How is it that the Greek word for "graciousness" also carried a connotation of "favor?"
2011/10/22
[ "https://hermeneutics.stackexchange.com/questions/385", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/78/" ]
There's no doubt that the word is primarily translated as "grace" (130 times in the King James version). However, there are a few times (6 in total) that this word is translated as "favor". [Luke 1:30](http://www.biblegateway.com/passage/?search=Luke%201:30&version=NASB), [Acts 2:47](http://www.biblegateway.com/passage/?search=Acts%202:47&version=NASB), [Acts 7:10](http://www.biblegateway.com/passage/?search=Acts%207:10&version=NASB), [Acts 7:46](http://www.biblegateway.com/passage/?search=Acts%207:46&version=NASB), and [Acts 25:3](http://www.biblegateway.com/passage/?search=Acts%2025:3&version=NASB) are the other five places (beyond the passage in question). If you look at all six passages, the idea used is having found "grace" *with* someone, "grace" *for* someone, or "grace" *towards* someone. The idea is always grace in motion. If we look at the English definition of "favor" it might help make this translation clearer: > > [Merriam Webster: favor](http://www.merriam-webster.com/dictionary/favor) > > > 1. (1): a friendly regard shown toward another especially by a superior (2): an approving consideration or attention > 2. *archaic* appearance > 3. a : gracious kindness; also : an act of such kindness > > > The first definition shows that "favor" is a regard shown `toward another`. This is the same type of concept shown in the six passages above. Furthermore, the third definition shows that the idea of favor is connected with grace: "gracious kindness". This link between "favor" and "grace" can also be seen in that [second definition of "grace"](http://www.merriam-webster.com/dictionary/grace) is *"approval, favor"*. ### Summary Ultimately, "finding grace with God and man" and "finding favor with God and man" are the same. If someone offers you grace, then they favor you. If someone finds favor with you, they will offer you grace. These two concepts are inextricably linked, to the point of being able to translate between the two.
So, let's consider that Greek word, "charis" means "(God's) divine influence in the heart and its (subsequent) reflection in the life", as defined in Strong's Greek dictionary. Then let's consider that in the early translations into English (Geneva and King James Bibles) the language is absent of words that equate with the Greek word, "charis" and its technical meaning, thus the translators used words at their disposal, those being grace and favor which are plesionyms rather than synonyms, the result of which was that at some point the meaning of "how God operates in our 'core beings'" began to be substituted with the meaning of “our resultant standing with God”. It seems that the Bible translators would have done a greater service by simply injecting the meaning of charis rather than to use words that were (and are) mismatched to the word "charis". For after all, as Jesus stated, no one comes to Him (for salvation) except the Father draws (influences/motivates) him to do so! (See: John 6:44) Now, "charis" IS the base for the Greek word "charizomai" which does mean "to grant as a favor", but "charis" itself means that God works in our hearts to produce an effect which HE desires ... His first desire being our redemption/salvation with the ongoing desired effects of His influence towards our lives increasingly reflecting the Lord Jesus Christ (Romans 8:29), which is why God tells us to "grow in grace and in the knowledge of our Lord Jesus Christ ..." (The concluding instructive of 2 Peter 3). Interestingly, there can also be a negative reflection of God’s influence in our hearts which is human rejection and refusal to comply! Both of these are in fact reflections in life from God’s influencing efforts to draw us to Christ … so when you see a person adamantly or being confrontational in their refusing or rejecting God’s offer of salvation in Christ Jesus the Lord - you can be pretty certain that such person is reacting to God’s current operation of influencing their hearts to receive Christ Jesus! Finally, looking at just the specific, not extrapolated, meaning of “charis”, it is interesting that it does apparently include or imply “favor”, much less undeserved or unmerited favor! To further understand the confusion, the etymology of “grace” stems back to the French language in which the Old French grace means, "pardon, divine grace, mercy; favor, thanks; elegance, virtue" (12c., Modern French grâce), and from the Latin, “gratia” meaning "favor, esteem, regard; pleasing quality, good will, gratitude" (source of Italian grazia, Spanish gracia; in Church use translating Greek kharisma), from gratus "pleasing, agreeable," from PIE \*gwreto-, suffixed form of root \*gwere- (2) "to favor." {From etymonline.com} So, as stipulated earlier, what has become the traditional religious meaning in churches is the result of the absence of a word in English that equates the Greek word, “charis”.
385
Luke 2:52 (ESV) states that "Jesus increased in wisdom and in stature and in favor with God and man." The word "favor" in this passage is translated from the Greek word "charis" (Strong's G5485), which the Strong's defines as "graciousness (as gratifying), of manner or act." In my modern, American, English-speaking context, I don't see a straight-forward connection between graciousness and favor, specifically not the kind of favor implied by the common usage of "charisma" (i.e. I don't assume a person who has charisma will necessarily be gracious). How were "graciousness" and "favor" associated in the ancient Greek context? How is it that the Greek word for "graciousness" also carried a connotation of "favor?"
2011/10/22
[ "https://hermeneutics.stackexchange.com/questions/385", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/78/" ]
You might be interested in [Moral Transformation](http://rads.stackoverflow.com/amzn/click/1456389807), page 166ff, in which Wallace and Rusk argue that "charis" did not have the technical sense many now give it, but always meant "favor" in a reciprocity system, or "favorable" as we would understand it, and that most of the passages in which we see "charis" used in a technical sense, it is referring to the favor that God did for us when he sent his son. They cite Malina and Harrison, among others--might be worth reading their sources. In other words, perhaps it meant "favor" and has come to imply "charisma" instead of the other way around.
So, let's consider that Greek word, "charis" means "(God's) divine influence in the heart and its (subsequent) reflection in the life", as defined in Strong's Greek dictionary. Then let's consider that in the early translations into English (Geneva and King James Bibles) the language is absent of words that equate with the Greek word, "charis" and its technical meaning, thus the translators used words at their disposal, those being grace and favor which are plesionyms rather than synonyms, the result of which was that at some point the meaning of "how God operates in our 'core beings'" began to be substituted with the meaning of “our resultant standing with God”. It seems that the Bible translators would have done a greater service by simply injecting the meaning of charis rather than to use words that were (and are) mismatched to the word "charis". For after all, as Jesus stated, no one comes to Him (for salvation) except the Father draws (influences/motivates) him to do so! (See: John 6:44) Now, "charis" IS the base for the Greek word "charizomai" which does mean "to grant as a favor", but "charis" itself means that God works in our hearts to produce an effect which HE desires ... His first desire being our redemption/salvation with the ongoing desired effects of His influence towards our lives increasingly reflecting the Lord Jesus Christ (Romans 8:29), which is why God tells us to "grow in grace and in the knowledge of our Lord Jesus Christ ..." (The concluding instructive of 2 Peter 3). Interestingly, there can also be a negative reflection of God’s influence in our hearts which is human rejection and refusal to comply! Both of these are in fact reflections in life from God’s influencing efforts to draw us to Christ … so when you see a person adamantly or being confrontational in their refusing or rejecting God’s offer of salvation in Christ Jesus the Lord - you can be pretty certain that such person is reacting to God’s current operation of influencing their hearts to receive Christ Jesus! Finally, looking at just the specific, not extrapolated, meaning of “charis”, it is interesting that it does apparently include or imply “favor”, much less undeserved or unmerited favor! To further understand the confusion, the etymology of “grace” stems back to the French language in which the Old French grace means, "pardon, divine grace, mercy; favor, thanks; elegance, virtue" (12c., Modern French grâce), and from the Latin, “gratia” meaning "favor, esteem, regard; pleasing quality, good will, gratitude" (source of Italian grazia, Spanish gracia; in Church use translating Greek kharisma), from gratus "pleasing, agreeable," from PIE \*gwreto-, suffixed form of root \*gwere- (2) "to favor." {From etymonline.com} So, as stipulated earlier, what has become the traditional religious meaning in churches is the result of the absence of a word in English that equates the Greek word, “charis”.
31,515,562
I am trying to run a calabash script on iOS but continually getting the following errors: ``` Retrying.. Errno::ECONNREFUSED: (Connection refused - connect(2) (http://localhost:37265)) Retrying.. Errno::ECONNREFUSED: (Connection refused - connect(2) (http://localhost:37265)) Failing... Errno::ECONNREFUSED Given I am on the homepage # features/step_definitions/homepage_steps.rb:6 Connection refused - connect(2) (http://localhost:37265) (Errno::ECONNREFUSED) ./features/PageObjects/home_page.rb:12:in `initialize' ./features/step_definitions/homepage_steps.rb:7:in `new' ./features/step_definitions/homepage_steps.rb:7:in `/^I am on the homepage$/' features/general.feature:9:in `Given I am on the homepage' ``` Anyone have any suggestions on fixing this error?
2015/07/20
[ "https://Stackoverflow.com/questions/31515562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/646818/" ]
I don't know if you are running on iOS or Android. Running on Android, this can be caused by the device disconnecting from USB (unstable USB connection), or becoming invisible to ADB in some other way.
In this instance I fixed this by commenting ount 'APP\_BUNDLE\_PATH' within 01\_launch.rb file. All working now. So looks like the path to the APP\_BUNDLE\_PATH was set incorrectly. Hopefully this answer might help others.
25,051,733
In the following example the j++ both acts as a variable and a function ``` var j = 0; var arr = []; arr[j++] = "a1"; arr[j++] = "a2"; console.log(arr[0]); console.log(arr[1]); ``` is there a way to write this without using the ++ like: ``` function addx(i) { return i+1; } var j=0; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` the issue is that i can only change the space between the brackets []. I'm not allowed to declare the j variable above the function and update it within so this solution is not acceptable. ``` var j=0; function addx(i) { j = i+1; return j-1; } arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` In Pascal you can declare the function like `function addx(var i:integer) : integer;` in which case the parameter would be the variable so having `i := i+1;` inside the function would update the calling variable too.
2014/07/31
[ "https://Stackoverflow.com/questions/25051733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476796/" ]
This is the place where reference helps. Like bellow ``` function addx(i) { return i.val++; } var j={val:0}; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ```
You can do this: ``` var oldj; var j = 0; var arr = []; arr[oldj = j, j = addx(j), oldj] = "a1"; arr[oldj = j, j = addx(j), oldj] = "a2"; ``` This makes use of the rarely-used comma operator to combine a sequence of expressions into a single expression. We save the old value of `j`, update `j` with the result of `addx`, then use the old value as the index in the array to assign to. Unfortunately, Javascript doesn't have macros, so there's no way to abbreviate that verbose code.
25,051,733
In the following example the j++ both acts as a variable and a function ``` var j = 0; var arr = []; arr[j++] = "a1"; arr[j++] = "a2"; console.log(arr[0]); console.log(arr[1]); ``` is there a way to write this without using the ++ like: ``` function addx(i) { return i+1; } var j=0; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` the issue is that i can only change the space between the brackets []. I'm not allowed to declare the j variable above the function and update it within so this solution is not acceptable. ``` var j=0; function addx(i) { j = i+1; return j-1; } arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` In Pascal you can declare the function like `function addx(var i:integer) : integer;` in which case the parameter would be the variable so having `i := i+1;` inside the function would update the calling variable too.
2014/07/31
[ "https://Stackoverflow.com/questions/25051733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476796/" ]
You can do this: ``` var oldj; var j = 0; var arr = []; arr[oldj = j, j = addx(j), oldj] = "a1"; arr[oldj = j, j = addx(j), oldj] = "a2"; ``` This makes use of the rarely-used comma operator to combine a sequence of expressions into a single expression. We save the old value of `j`, update `j` with the result of `addx`, then use the old value as the index in the array to assign to. Unfortunately, Javascript doesn't have macros, so there's no way to abbreviate that verbose code.
You can add subsequent elements to an array with the push method: ``` arr.push("a1"); arr.push("a2"); ``` This makes `j` unnecessary and also avoids gaps in the array indices.
25,051,733
In the following example the j++ both acts as a variable and a function ``` var j = 0; var arr = []; arr[j++] = "a1"; arr[j++] = "a2"; console.log(arr[0]); console.log(arr[1]); ``` is there a way to write this without using the ++ like: ``` function addx(i) { return i+1; } var j=0; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` the issue is that i can only change the space between the brackets []. I'm not allowed to declare the j variable above the function and update it within so this solution is not acceptable. ``` var j=0; function addx(i) { j = i+1; return j-1; } arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` In Pascal you can declare the function like `function addx(var i:integer) : integer;` in which case the parameter would be the variable so having `i := i+1;` inside the function would update the calling variable too.
2014/07/31
[ "https://Stackoverflow.com/questions/25051733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476796/" ]
This is the place where reference helps. Like bellow ``` function addx(i) { return i.val++; } var j={val:0}; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ```
You can add subsequent elements to an array with the push method: ``` arr.push("a1"); arr.push("a2"); ``` This makes `j` unnecessary and also avoids gaps in the array indices.
25,051,733
In the following example the j++ both acts as a variable and a function ``` var j = 0; var arr = []; arr[j++] = "a1"; arr[j++] = "a2"; console.log(arr[0]); console.log(arr[1]); ``` is there a way to write this without using the ++ like: ``` function addx(i) { return i+1; } var j=0; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` the issue is that i can only change the space between the brackets []. I'm not allowed to declare the j variable above the function and update it within so this solution is not acceptable. ``` var j=0; function addx(i) { j = i+1; return j-1; } arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` In Pascal you can declare the function like `function addx(var i:integer) : integer;` in which case the parameter would be the variable so having `i := i+1;` inside the function would update the calling variable too.
2014/07/31
[ "https://Stackoverflow.com/questions/25051733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476796/" ]
This is the place where reference helps. Like bellow ``` function addx(i) { return i.val++; } var j={val:0}; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ```
I assume from the constraint that this is some sort of homework problem? Otherwise it appears to be a completely artificial constraint. One solution is to use a closure to maintain your variable state that supports a post increment function: ``` function NumberWrapper() { var value; // initially undefined return { assign: function(n) { return value = n; }, postincrement: function() { var result = ++value; ... return result; // to emulate post-increment semantics } }; }; var i = new NumberWrapper(); var arr = []; arr[i.next()] = "a1"; arr[i.next()] = "a2"; ``` The `NumberWrapper` object maintains its own state, and the only functionality it exposes is incrementing itself and returning that value (in one step). **EDIT** ok, interesting use case, hmm - the wrapper above could be extended to provide a clean implementation for other numeric operations: ``` return { postincrement: ... preincrement: function() { return ++value; } plusequals: function(n) { value += n; return value; } minusequals: function(n) { value -= n; return value; } etc... }; ```
25,051,733
In the following example the j++ both acts as a variable and a function ``` var j = 0; var arr = []; arr[j++] = "a1"; arr[j++] = "a2"; console.log(arr[0]); console.log(arr[1]); ``` is there a way to write this without using the ++ like: ``` function addx(i) { return i+1; } var j=0; arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` the issue is that i can only change the space between the brackets []. I'm not allowed to declare the j variable above the function and update it within so this solution is not acceptable. ``` var j=0; function addx(i) { j = i+1; return j-1; } arr[addx(j)] = "a1"; arr[addx(j)] = "a2"; ``` In Pascal you can declare the function like `function addx(var i:integer) : integer;` in which case the parameter would be the variable so having `i := i+1;` inside the function would update the calling variable too.
2014/07/31
[ "https://Stackoverflow.com/questions/25051733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476796/" ]
I assume from the constraint that this is some sort of homework problem? Otherwise it appears to be a completely artificial constraint. One solution is to use a closure to maintain your variable state that supports a post increment function: ``` function NumberWrapper() { var value; // initially undefined return { assign: function(n) { return value = n; }, postincrement: function() { var result = ++value; ... return result; // to emulate post-increment semantics } }; }; var i = new NumberWrapper(); var arr = []; arr[i.next()] = "a1"; arr[i.next()] = "a2"; ``` The `NumberWrapper` object maintains its own state, and the only functionality it exposes is incrementing itself and returning that value (in one step). **EDIT** ok, interesting use case, hmm - the wrapper above could be extended to provide a clean implementation for other numeric operations: ``` return { postincrement: ... preincrement: function() { return ++value; } plusequals: function(n) { value += n; return value; } minusequals: function(n) { value -= n; return value; } etc... }; ```
You can add subsequent elements to an array with the push method: ``` arr.push("a1"); arr.push("a2"); ``` This makes `j` unnecessary and also avoids gaps in the array indices.
35,064,532
``` Node0x7fd34984d728:s1 -> Node0x7fd34984d600:d0; Node0x7fd34984d850 [shape=record,shape=Mrecord,label="{Register %vreg13|0x7fd34984d850|{<d0>i32}}"]; Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; Node0x7fd34984d978:s0 -> Node0x7fd3486095f0:d0[color=blue,style=dashed]; Node0x7fd34984d978:s1 -> Node0x7fd34984d850:d0; Node0x7fd34984daa0 [shape=record,shape=Mrecord,label="{Register %vreg14|0x7fd34984daa0|{<d0>i32}}"]; ``` I'm trying to capture only Nodes with "ORD" keyword, my simple Regex pattern is: ``` Node.+?label=\"\\{\\{(?<SRC><s[0-9]+?>[a-z0-9]+?)\\}|(?<NAME>.+?)\\[ORD=(?<ORD>[0-9]+?)\\]\\|(?<ID>[A-Za-z0-9]{14})|\\{(?<DEST><d[0-9]+?>[a-z0-9]+?)\\}\\}\"\\]; ``` *It's too greedy capturing wrong groups.* The following snippet is captured as one group! ``` Node0x7fd34984d728:s1 -> Node0x7fd34984d600:d0; Node0x7fd34984d850 [shape=record,shape=Mrecord,label="{Register %vreg13|0x7fd34984d850|{<d0>i32}}"]; Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; ``` However it must only capture: ``` Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; ``` as it's the only **Node** has "**ORD**" keyword before **Semicolon**
2016/01/28
[ "https://Stackoverflow.com/questions/35064532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713777/" ]
Test code that relies on grabbing the current time is not a good idea. You'll need rewrite things so that you can mock out or inject a date. Some good examples of doing that at ([Unit Tests, How to Write Testable Code and Why it Matters](http://www.toptal.com/qa/how-to-write-testable-code-and-why-it-matters)). That article is C#-based, but the same same concept applies here.
I think you need to build in some tolerance into your tests, as some amount of time will inevitably pass between dispatching an action and receiving a response. Even if your faking it, there will still be a difference in execution time. How you actually go about doing this depends on your assertion library.
35,064,532
``` Node0x7fd34984d728:s1 -> Node0x7fd34984d600:d0; Node0x7fd34984d850 [shape=record,shape=Mrecord,label="{Register %vreg13|0x7fd34984d850|{<d0>i32}}"]; Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; Node0x7fd34984d978:s0 -> Node0x7fd3486095f0:d0[color=blue,style=dashed]; Node0x7fd34984d978:s1 -> Node0x7fd34984d850:d0; Node0x7fd34984daa0 [shape=record,shape=Mrecord,label="{Register %vreg14|0x7fd34984daa0|{<d0>i32}}"]; ``` I'm trying to capture only Nodes with "ORD" keyword, my simple Regex pattern is: ``` Node.+?label=\"\\{\\{(?<SRC><s[0-9]+?>[a-z0-9]+?)\\}|(?<NAME>.+?)\\[ORD=(?<ORD>[0-9]+?)\\]\\|(?<ID>[A-Za-z0-9]{14})|\\{(?<DEST><d[0-9]+?>[a-z0-9]+?)\\}\\}\"\\]; ``` *It's too greedy capturing wrong groups.* The following snippet is captured as one group! ``` Node0x7fd34984d728:s1 -> Node0x7fd34984d600:d0; Node0x7fd34984d850 [shape=record,shape=Mrecord,label="{Register %vreg13|0x7fd34984d850|{<d0>i32}}"]; Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; ``` However it must only capture: ``` Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; ``` as it's the only **Node** has "**ORD**" keyword before **Semicolon**
2016/01/28
[ "https://Stackoverflow.com/questions/35064532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713777/" ]
You can mock Date.now() function like this: ``` describe('>>> Test Name', () => { const literallyJustNow = Date.now(); const realDateNow = Date.now.bind(global.Date); const dateNowStub = jest.fn(() => literallyJustNow); beforeEach(() => { global.Date.now = dateNowStub; }); afterEach(() => { global.Date.now = realDateNow; }); it('... your tests ...', () => { ... }); }); ```
I think you need to build in some tolerance into your tests, as some amount of time will inevitably pass between dispatching an action and receiving a response. Even if your faking it, there will still be a difference in execution time. How you actually go about doing this depends on your assertion library.
35,064,532
``` Node0x7fd34984d728:s1 -> Node0x7fd34984d600:d0; Node0x7fd34984d850 [shape=record,shape=Mrecord,label="{Register %vreg13|0x7fd34984d850|{<d0>i32}}"]; Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; Node0x7fd34984d978:s0 -> Node0x7fd3486095f0:d0[color=blue,style=dashed]; Node0x7fd34984d978:s1 -> Node0x7fd34984d850:d0; Node0x7fd34984daa0 [shape=record,shape=Mrecord,label="{Register %vreg14|0x7fd34984daa0|{<d0>i32}}"]; ``` I'm trying to capture only Nodes with "ORD" keyword, my simple Regex pattern is: ``` Node.+?label=\"\\{\\{(?<SRC><s[0-9]+?>[a-z0-9]+?)\\}|(?<NAME>.+?)\\[ORD=(?<ORD>[0-9]+?)\\]\\|(?<ID>[A-Za-z0-9]{14})|\\{(?<DEST><d[0-9]+?>[a-z0-9]+?)\\}\\}\"\\]; ``` *It's too greedy capturing wrong groups.* The following snippet is captured as one group! ``` Node0x7fd34984d728:s1 -> Node0x7fd34984d600:d0; Node0x7fd34984d850 [shape=record,shape=Mrecord,label="{Register %vreg13|0x7fd34984d850|{<d0>i32}}"]; Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; ``` However it must only capture: ``` Node0x7fd34984d978 [shape=record,shape=Mrecord,label="{{<s0>0|<s1>1}|CopyFromReg [ORD=1]|0x7fd34984d978|{<d0>i32|<d1>ch}}"]; ``` as it's the only **Node** has "**ORD**" keyword before **Semicolon**
2016/01/28
[ "https://Stackoverflow.com/questions/35064532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713777/" ]
Test code that relies on grabbing the current time is not a good idea. You'll need rewrite things so that you can mock out or inject a date. Some good examples of doing that at ([Unit Tests, How to Write Testable Code and Why it Matters](http://www.toptal.com/qa/how-to-write-testable-code-and-why-it-matters)). That article is C#-based, but the same same concept applies here.
You can mock Date.now() function like this: ``` describe('>>> Test Name', () => { const literallyJustNow = Date.now(); const realDateNow = Date.now.bind(global.Date); const dateNowStub = jest.fn(() => literallyJustNow); beforeEach(() => { global.Date.now = dateNowStub; }); afterEach(() => { global.Date.now = realDateNow; }); it('... your tests ...', () => { ... }); }); ```
57,038,347
I am very new to databases and I'm currently working with Microsoft Access 2013. The situation is that I have a huge amount of data which I wanna fill in in an already created table (Inventory) by using an SQL-statement in a query. What I have is the following: ``` INSERT INTO Inventory (Col 1, Col 2, Col 3, Col 4) VALUES ("Val 1", "Val 2", "Val 3", "Val 4"), ("Val 5", "Val 6", "Val 7", "Val 8"), .... ("Val 9", "Val 10", "Val 11", "Val 12"); ``` And what I want is simply this table: ``` Col 1 | Col 2 | Col 3 | Col 4 | | | Val 1 | Val 2 | Val 3 | Val 4 Val 5 | Val 6 | Val 7 | Val 8 Val 9 | Val 10 | Val 11 | Val 12 ``` The problem is, that I keep getting the error **Missing semicolon at the end of sql-statement**. Therefore I suppose that I should add a semicolon after each line. If I do this tho, I get the error that access found characters after the semicolon. What is the right syntax to achieve my multiple-lined INSERT INTO-Statement?
2019/07/15
[ "https://Stackoverflow.com/questions/57038347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10765169/" ]
I think MS Access only allows you to insert one record at a time using `INSERT . . . VALUES`: ``` INSERT INTO Inventory (Col 1, Col 2, Col 3, Col 4) VALUES ("Val 1", "Val 2", "Val 3", "Val 4"); INSERT INTO Inventory (Col 1, Col 2, Col 3, Col 4) VALUES ("Val 5", "Val 6", "Val 7", "Val 8"); .... INSERT INTO Inventory (Col 1, Col 2, Col 3, Col 4) VALUES ("Val 9", "Val 10", "Val 11", "Val 12"); ```
You can bulk insert using `INSERT INTO ... SELECT` and a union query: ``` INSERT INTO Inventory (Col 1, Col 2, Col 3, Col 4) SELECT "Val 1", "Val 2", "Val 3", "Val 4" FROM (SELECT First(ID) FROM MSysObjects) dummy UNION ALL SELECT "Val 5", "Val 6", "Val 7", "Val 8" FROM (SELECT First(ID) FROM MSysObjects) dummy UNION ALL SELECT "Val 9", "Val 10", "Val 11", "Val 12" FROM (SELECT First(ID) FROM MSysObjects) dummy ``` However, the overhead might not make this construct worthwhile, and Access does have a maximum length on single queries of ~65K characters. To serialize and deserialize tables, I recommend [using ADO and persistence](https://learn.microsoft.com/en-us/sql/ado/guide/data/more-about-recordset-persistence?view=sql-server-2017). This can properly store field properties, serializing to different file formats or database formats will cause information loss.
23,591,705
I just did a clean install of Ubuntu 14.04 and also installed pycharm. Pycharm said setuptools and pip weren't installed and offered to install it. I simply clicked "Ÿes" and it seemed to install it. A bit after that I wanted to install Flask (which is awesome btw) using pip, so I did `sudo pip install flask`. To my surprise it said the following: ``` Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "build/bdist.linux-x86_64/egg/pkg_resources.py", line 2797, in <module> File "build/bdist.linux-x86_64/egg/pkg_resources.py", line 576, in resolve def resolve(self, requirements, env=None, installer=None, pkg_resources.DistributionNotFound: pip==1.4.1 ``` So I simply tried the regular way: I downloaded get-pip.py and ran that, but that says: `Requirement already up-to-date: pip in /usr/local/lib/python2.7/dist-packages` I found some other [similar](https://stackoverflow.com/questions/20282679/pkg-resources-distributionnotfound-at-pip-and-easy-install) [problems](https://stackoverflow.com/questions/19400370/easy-install-and-pip-broke-pkg-resources-distributionnotfound-distribute-0-6) here on SO, which suggested to look in `/usr/local/lib/python2.7/site-packages/`, but that folder is empty. Does anybody know what's wrong and how I can fix this? All tips are welcome!
2014/05/11
[ "https://Stackoverflow.com/questions/23591705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1650012/" ]
Had the same problem under 12.04. Did `sudo easy_install pip==1.4.1` and it worked.
Faced the same problem with ubuntu 14.04 ,python2.7 and pip 1.5.4 ``` sudo apt-get install --reinstall python2.7 sudo apt-get purge python-pip wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py sudo python get-pip.py sudo pip install package-name ``` This worked!
19,707
Is it possible to USB-tether my WiFi-only Galaxy Tab to my Galaxy S? I know how to WiFi tether but it is a huge battery hog. Is there a mini-USB version of the Galaxy Tab cable? If so, can it be used to tether?
2012/02/20
[ "https://android.stackexchange.com/questions/19707", "https://android.stackexchange.com", "https://android.stackexchange.com/users/11872/" ]
There is a bit tricky method suggested by one of the XDA members. Rooting is required. 1. Download & install a Terminal Emulator on your Android tablet. 2. Run the Emulator & enter the following commands: ``` dhcpcd usb1 setprop net.dns1 8.8.8.8 ``` The Android phone from which the internet connection is to be sourced must be connected via a USB cable, and then enable USB tethering on that phone. Now you can access the internet on your Android tablet using your Android phone as a USB modem!
Yes! First, attach an OTG cable to your tablet. Then, attach a MicroUSB and connect both devices. Now download one of the numerous apps which make tethering possible and you're done! If your devices support Bluetooth tethering, you can use it. It doesn't consume too beach battery also. :) P.S. isn't creating a WiFi hotspot a better idea?
19,707
Is it possible to USB-tether my WiFi-only Galaxy Tab to my Galaxy S? I know how to WiFi tether but it is a huge battery hog. Is there a mini-USB version of the Galaxy Tab cable? If so, can it be used to tether?
2012/02/20
[ "https://android.stackexchange.com/questions/19707", "https://android.stackexchange.com", "https://android.stackexchange.com/users/11872/" ]
There is a bit tricky method suggested by one of the XDA members. Rooting is required. 1. Download & install a Terminal Emulator on your Android tablet. 2. Run the Emulator & enter the following commands: ``` dhcpcd usb1 setprop net.dns1 8.8.8.8 ``` The Android phone from which the internet connection is to be sourced must be connected via a USB cable, and then enable USB tethering on that phone. Now you can access the internet on your Android tablet using your Android phone as a USB modem!
I did it by connecting an ethernet dongle to each device and an e-cable to the dongles. I imagine it would use less power than wireless, and I can place the hotspot device away for the best reception.
19,707
Is it possible to USB-tether my WiFi-only Galaxy Tab to my Galaxy S? I know how to WiFi tether but it is a huge battery hog. Is there a mini-USB version of the Galaxy Tab cable? If so, can it be used to tether?
2012/02/20
[ "https://android.stackexchange.com/questions/19707", "https://android.stackexchange.com", "https://android.stackexchange.com/users/11872/" ]
Yes! First, attach an OTG cable to your tablet. Then, attach a MicroUSB and connect both devices. Now download one of the numerous apps which make tethering possible and you're done! If your devices support Bluetooth tethering, you can use it. It doesn't consume too beach battery also. :) P.S. isn't creating a WiFi hotspot a better idea?
I did it by connecting an ethernet dongle to each device and an e-cable to the dongles. I imagine it would use less power than wireless, and I can place the hotspot device away for the best reception.
36,478
[Deuteronomy 24:16](http://www.mechon-mamre.org/p/pt/pt0524.htm#16) says “The fathers shall not be put to death for the children, neither shall the children be put to death for the fathers; every man shall be put to death for his own sin." Why then did the whole family of Achan have to die by stoning in [Joshua 7:24-25](http://www.mechon-mamre.org/p/pt/pt0607.htm#24), when only Achan took plunder from Jericho?
2014/03/19
[ "https://judaism.stackexchange.com/questions/36478", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/4999/" ]
According to Rashi they were not killed. In his commentary to [Joshua 7:24](http://www.chabad.org/library/bible_cdo/aid/15791#showrashi=true&v=24), Rashi writes that they were taken to see in order that they not copy his actions. Verse 25 says "וירגמו אותו" - they stoned *him*, in singular. "וישרפו אותם", they burned them, in plural, Rashi says refers to the tent and other property. "ויסלקו אותם" - they stoned *them* in plural, Rashi says refers to the animals he owned.
Gersonides (Ralbag) is puzzled by this. He offers two answers. The first is that the children were minors, and that they consequently came under the category of Achen's property, with regard to the punishment. We must then say that the verse in Deuteronomy takes apllies only once the child becomes an adult by Jewish Law. This would appear consistent with the fate of David's first child with Bathsheba, whom Nathan specifically tells David will die by Gd's will in [Samuel II 12](http://www.mechon-mamre.org/e/et/et08b12.htm):14, due to David's sin. The second answer mirrors [Rashi's](https://judaism.stackexchange.com/a/36479/4682).
4,103,623
I'm writing my first jQuery plug-in, but I've run into a couple of problems. In my first attempt I successfully implemented the basic plug-in, but now I need to expose additional methods for the client to use. After numerous articles, stackoverflow posts, and reading the documentation I thought I could create an object and store it in the element .data() cache. However, the code I've written seems to reference the same object when I call my plug-in. Admittedly I'm still in the learning phases of jQuery so my terminology is lacking and google hasn't been able to pull through for me. ``` var CONST_TEST_KEY = "test-data-key"; (function($){ var TestObject = function(e, o){ var elem = $(e); this.random = Math.floor(Math.random() * 100); this.GetRandom = function() { alert(this.random); } }; $.fn.testJQueryPlugin = function(o) { return $.each(function() { var currentElement = $(this); if(currentElement.data(CONST_TEST_KEY)) return; currentElement.data(CONST_TEST_KEY, new TestObject(currentElement, {})); }); }; })(jQuery) ``` The HTML: ``` <script type="text/javascript"> $(document).ready(function() { var object1 = $("#entry1").testJQueryPlugin(); var object2 = $("#entry2").testJQueryPlugin(); alert($(object1).data(CONST_TEST_KEY).random); alert($(object2).data(CONST_TEST_KEY).random); }); </script> </head> <body> <div id="entry1"> x </div> <div id="entry2"> y </div> </body> ``` This code displays two alerts both have the same value. I expected each alert to have a different value. I would appreciate any solutions, pointers, and even better an explanation why it works this way and/or why I should do it differently.
2010/11/05
[ "https://Stackoverflow.com/questions/4103623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115021/" ]
Moving files between different filesystems requires you to copy them. The vanilla JDK doesn't have any method to do that, you'll have to do it yourself (e.g. by using FileInputStream / FileOutputStream). Also check out [this thread](https://stackoverflow.com/questions/300559/move-copy-file-operations-in-java).
If you want to move files on different file Systems. Copy and Delete. [Apache IO FileUtils](http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#moveFile%28java.io.File,%20java.io.File%29)
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
Depends on the OS. The standard c runtime on windows and unices uses a shared heap across threads. This means locking every malloc/free. On Symbian, for example, each thread comes with its own heap, although threads can share pointers to data allocated in any heap. Symbian's design is better in my opinion since it not only eliminates the need for locking during alloc/free, but also encourages clean specification of data ownership among threads. Also in that case when a thread dies, it takes all the objects it allocated along with it - i.e. it cannot leak objects that it has allocated, which is an important property to have in mobile devices with constrained memory. Erlang also follows a similar design where a "process" acts as a unit of garbage collection. All data is communicated between processes by copying, except for binary blobs which are reference counted (I think).
It depends on what exactly you mean when saying "heap". All threads share the address space, so heap-allocated objects are accessible from all threads. Technically, stacks are shared as well in this sense, i.e. nothing prevents you from accessing other thread's stack (though it would almost never make any sense to do so). On the other hand, there are heap *structures* used to allocate memory. That is where all the bookkeeping for heap memory allocation is done. These structures are sophisticatedly organized to minimize contention between the threads - so some threads might share a heap structure (an arena), and some might use distinct arenas. See the following thread for an excellent explanation of the details: [How does malloc work in a multithreaded environment?](https://stackoverflow.com/questions/10706466/how-does-malloc-work-in-a-multithreaded-environment)
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
By default, C has only a single heap. That said, some allocators that are thread aware will partition the heap so that each thread has it's own area to allocate from. The idea is that this should make the heap scale better. One example of such a heap is [Hoard](http://www.hoard.org/).
On FreeRTOS Operating system, tasks(threads) share the same heap but each one of them has its own stack. This comes in very handy when dealing with low power low RAM architectures,because the same pool of memory can be accessed/shared by several threads, but this comes with a small catch , the developer needs to keep in mind that a mechanism for synchronizing malloc and free is needed, that is why it is necessary to use some type of process synchronization/lock when allocating or freeing memory on the heap, for example a semaphore or a mutex.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
No. All threads share a common heap. Each [thread has a private stack](http://en.wikipedia.org/wiki/Stack-based_memory_allocation), which it can quickly add and remove items from. This makes stack based memory fast, but if you use too much stack memory, as occurs in infinite recursion, you will get a stack overflow. Since all threads share the same heap, access to the allocator/deallocator must be synchronized. There are various methods and libraries for avoiding [allocator contention](https://stackoverflow.com/questions/470683/memory-allocation-deallocation-bottleneck). Some languages allow you to create private pools of memory, or individual heaps, which you can assign to a single thread.
By default, C has only a single heap. That said, some allocators that are thread aware will partition the heap so that each thread has it's own area to allocate from. The idea is that this should make the heap scale better. One example of such a heap is [Hoard](http://www.hoard.org/).
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
Depends on the OS. The standard c runtime on windows and unices uses a shared heap across threads. This means locking every malloc/free. On Symbian, for example, each thread comes with its own heap, although threads can share pointers to data allocated in any heap. Symbian's design is better in my opinion since it not only eliminates the need for locking during alloc/free, but also encourages clean specification of data ownership among threads. Also in that case when a thread dies, it takes all the objects it allocated along with it - i.e. it cannot leak objects that it has allocated, which is an important property to have in mobile devices with constrained memory. Erlang also follows a similar design where a "process" acts as a unit of garbage collection. All data is communicated between processes by copying, except for binary blobs which are reference counted (I think).
Each thread has its own stack and call stack. Each thread shares the same heap.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
By default, C has only a single heap. That said, some allocators that are thread aware will partition the heap so that each thread has it's own area to allocate from. The idea is that this should make the heap scale better. One example of such a heap is [Hoard](http://www.hoard.org/).
Generally speaking, all threads use the same address space and therefore usually have just one heap. However, it can be a bit more complicated. You might be looking for [Thread Local Storage](http://en.wikipedia.org/wiki/Thread-local_storage) (TLS), but it stores single values only. Windows-Specific: TLS-space can be allocated using [TlsAlloc](http://msdn.microsoft.com/en-us/library/ms686801%28VS.85%29.aspx) and freed using [TlsFree](http://msdn.microsoft.com/en-us/library/ms686804%28VS.85%29.aspx) (Overview [here](http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx)). Again, it's not a heap, just DWORDs. Strangely, Windows support multiple [Heaps](http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx) per process. One can store the Heap's handle in TLS. Then you would have something like a "Thread-Local Heap". However, just the handle is not known to the other threads, they still can access its memory using pointers as it's still the same address space. **EDIT**: Some memory allocators (specifically [jemalloc](http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf) on FreeBSD) use TLS to assign "arenas" to threads. This is done to optimize allocation for multiple cores by reducing synchronization overhead.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
By default, C has only a single heap. That said, some allocators that are thread aware will partition the heap so that each thread has it's own area to allocate from. The idea is that this should make the heap scale better. One example of such a heap is [Hoard](http://www.hoard.org/).
Each thread has its own stack and call stack. Each thread shares the same heap.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
Each thread has its own stack and call stack. Each thread shares the same heap.
Generally speaking, all threads use the same address space and therefore usually have just one heap. However, it can be a bit more complicated. You might be looking for [Thread Local Storage](http://en.wikipedia.org/wiki/Thread-local_storage) (TLS), but it stores single values only. Windows-Specific: TLS-space can be allocated using [TlsAlloc](http://msdn.microsoft.com/en-us/library/ms686801%28VS.85%29.aspx) and freed using [TlsFree](http://msdn.microsoft.com/en-us/library/ms686804%28VS.85%29.aspx) (Overview [here](http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx)). Again, it's not a heap, just DWORDs. Strangely, Windows support multiple [Heaps](http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx) per process. One can store the Heap's handle in TLS. Then you would have something like a "Thread-Local Heap". However, just the handle is not known to the other threads, they still can access its memory using pointers as it's still the same address space. **EDIT**: Some memory allocators (specifically [jemalloc](http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf) on FreeBSD) use TLS to assign "arenas" to threads. This is done to optimize allocation for multiple cores by reducing synchronization overhead.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
It depends on what exactly you mean when saying "heap". All threads share the address space, so heap-allocated objects are accessible from all threads. Technically, stacks are shared as well in this sense, i.e. nothing prevents you from accessing other thread's stack (though it would almost never make any sense to do so). On the other hand, there are heap *structures* used to allocate memory. That is where all the bookkeeping for heap memory allocation is done. These structures are sophisticatedly organized to minimize contention between the threads - so some threads might share a heap structure (an arena), and some might use distinct arenas. See the following thread for an excellent explanation of the details: [How does malloc work in a multithreaded environment?](https://stackoverflow.com/questions/10706466/how-does-malloc-work-in-a-multithreaded-environment)
On FreeRTOS Operating system, tasks(threads) share the same heap but each one of them has its own stack. This comes in very handy when dealing with low power low RAM architectures,because the same pool of memory can be accessed/shared by several threads, but this comes with a small catch , the developer needs to keep in mind that a mechanism for synchronizing malloc and free is needed, that is why it is necessary to use some type of process synchronization/lock when allocating or freeing memory on the heap, for example a semaphore or a mutex.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
Depends on the OS. The standard c runtime on windows and unices uses a shared heap across threads. This means locking every malloc/free. On Symbian, for example, each thread comes with its own heap, although threads can share pointers to data allocated in any heap. Symbian's design is better in my opinion since it not only eliminates the need for locking during alloc/free, but also encourages clean specification of data ownership among threads. Also in that case when a thread dies, it takes all the objects it allocated along with it - i.e. it cannot leak objects that it has allocated, which is an important property to have in mobile devices with constrained memory. Erlang also follows a similar design where a "process" acts as a unit of garbage collection. All data is communicated between processes by copying, except for binary blobs which are reference counted (I think).
Typically, threads share the heap and other resources, however there are thread-like constructions that don't. Among these thread-like constructions are Erlang's lightweight processes, and UNIX's full-on processes (created with a call to `fork()`). You might also be working on multi-machine concurrency, in which case your inter-thread communication options are considerably more limited.
1,665,425
I have 5 different infopath forms.on sharepoint site , i want to upload them in single document library. But when i am going to do this it is overwriting existing form. What i have to do. Is that possible to upload all 5 forms in single Document library ? I do not want to create 5 different Document libraries for 5 forms . please guide....
2009/11/03
[ "https://Stackoverflow.com/questions/1665425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165309/" ]
Depends on the OS. The standard c runtime on windows and unices uses a shared heap across threads. This means locking every malloc/free. On Symbian, for example, each thread comes with its own heap, although threads can share pointers to data allocated in any heap. Symbian's design is better in my opinion since it not only eliminates the need for locking during alloc/free, but also encourages clean specification of data ownership among threads. Also in that case when a thread dies, it takes all the objects it allocated along with it - i.e. it cannot leak objects that it has allocated, which is an important property to have in mobile devices with constrained memory. Erlang also follows a similar design where a "process" acts as a unit of garbage collection. All data is communicated between processes by copying, except for binary blobs which are reference counted (I think).
Generally speaking, all threads use the same address space and therefore usually have just one heap. However, it can be a bit more complicated. You might be looking for [Thread Local Storage](http://en.wikipedia.org/wiki/Thread-local_storage) (TLS), but it stores single values only. Windows-Specific: TLS-space can be allocated using [TlsAlloc](http://msdn.microsoft.com/en-us/library/ms686801%28VS.85%29.aspx) and freed using [TlsFree](http://msdn.microsoft.com/en-us/library/ms686804%28VS.85%29.aspx) (Overview [here](http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx)). Again, it's not a heap, just DWORDs. Strangely, Windows support multiple [Heaps](http://msdn.microsoft.com/en-us/library/ms686991%28VS.85%29.aspx) per process. One can store the Heap's handle in TLS. Then you would have something like a "Thread-Local Heap". However, just the handle is not known to the other threads, they still can access its memory using pointers as it's still the same address space. **EDIT**: Some memory allocators (specifically [jemalloc](http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf) on FreeBSD) use TLS to assign "arenas" to threads. This is done to optimize allocation for multiple cores by reducing synchronization overhead.
152,542
I have a video which I read in a loop frame by frame. For every frame, I want to do temporal kernel filtering, the coefficients of which come from the input variable model (a dictionary). The temporal kernel is an array that has size of 15. So, basically, for every frame we apply this function. The variables scale, clip\_size are constants. Firstly I add borders across the obtained frame. Then I start a buffer of size (15,240,320) where (240,320) is the clip size. Variable `bindex` is used to write the buffer. The buffer variable will store only last 15 modified frames, hence `bindex` needs to be updated at every function iteration. Variable `sindex` is used to traverse through the buffer and apply the buffer, hence it has to be returned too. Since the `input_frames` are coming from a video in a loop, I had to make some variables be both inputs and outputs. Is there a way to speed this up? Any better way to do this? ``` def filtered_output(input_frame,model, Buffer,bindex,sindex,scale,clip_size): # padding is required top=model['item'][0] bot=model['item1'].shape[1]-top-1 left=model['item'][1] right=model['item1'].shape[0]-left-1 # NewDepth = 15 # clip_size is [240,320] # In the external loop, bindex = 0, sindex =0 in the beginning # We now create a copy of our current frame, with appropriate padding frame2= cv2.copyMakeBorder(input_frame,top,bot,left,right,cv2.BORDER_CONSTANT,value=0.5) Buffer[bindex] = scipy.signal.convolve2d(frame2, model['item1'], boundary='symm', mode='valid') sindex = (bindex+1) % NewDepth # point to oldest image in the buffer temp=np.zeros(tuple(clip_size),dtype=float) temp = model['TempKern'][0]*Buffer[sindex] sindex = (sindex+1) % NewDepth for j in range(1, NewDepth) : # iterate from oldest to newest frame temp = temp + model['TempKern'][j]*Buffer[sindex] sindex = (sindex+1) % NewDepth bindex = (bindex+1) % NewDepth temp=np.nan_to_num(temp) output_frame = ApplyCubicSpline(model['CubicSplineCoeffs'],temp)*scale return output_frame, Buffer,bindex,sindex ``` My question is whether we can make this function faster somehow (not that it is slow)? If yes, how? Is it the best practice to use `bindex`, `sindex` as both inputs and outputs to the function? Are there any alternatives?
2017/01/13
[ "https://codereview.stackexchange.com/questions/152542", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/128120/" ]
Switched ======== Let's start with the obvious things we can improve. A `return` statement terminates the current function. Therefore, all your ``` case XY: return AB; break; ``` can be rewritten as ``` case XY: return AB; ``` However, you don't have any `default` cases in both `switch` statements. What happens if you use `conv0to19(100)`? Well, it's not obvious, because [it's undefined behaviour](//stackoverflow.com/q/2598084). For the sake of simplicity, let's use an `assert` for unhandled cases. But before we do that, let's have a closer look at your `switch`: ``` case 0:return ""; case 1:return "one "; case 2:return "two "; ... case 18:return "eighteen "; case 19:return "nineteen "; ``` Hm. You have a continuous range of integer values. So let's use that to our advantage: ``` std::string conv0to19(uint64_t a) { static char const * const numbers[20] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; assert(0 <= a && a < 20); return numbers[a]; } ``` You can do the same for `conv_dec`. Note that I've removed the suffix space from the string. More on that later. While we're at it and using an array, your `name` should: * have a better name (especially not `name`, since it's a collection of several ones) * be `const`, so that you don't change it by accident: ``` const std::string numberNames[] = {"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion"}; ``` By the way, did you notice that I've added whitespace to separate the arguments? Remember code is written for humans (and for machines). If you want to remove a word later, it should be easy to do so, and whitespace makes it a lot easier to mark text with `Ctrl`+`Shift` (or whatever your operating system/editor uses). Back to the beginning ===================== ``` int container[7]; /// every element contains a number between 0 and 999 ``` That is a code smell. It's a global variable, which isn't constant. And the description is, well, no really helpful. Just remove it. Also, the `7` seems like a magic number. Why is it `7`? Why not `10`? Either way, you should include `cstdint` instead of `stdint-gcc.h`, or — if your compiler is too old — `stdint.h`. Also, I recommend you to `typedef` your used number type, e.g.: ``` typedef uint64_t number_type; ``` That way you can replace the type easily, if you want to support even larger numbers later. And `using namespace std`… well, it's [considered bad practice](//stackoverflow.com/q/1452721) for large programs, **especially in headers**, but you're writing only a single file here. It's up to you, but I wouldn't use it. Using logic to reduce `if`-complexity ===================================== Your `convert1to999` is too complex. If we didn't enter the following block: ``` if (a>0&&a<20) return conv0to19(a)+name[i]; ``` we're guaranteed that `a` is larger then 20. Why? Because `a` isn't `0`. Since it is a non-negative number, it must be then greater than zero, so `a>0` holds, so `a < 20` must not hold. We don't need to repeat that in the next condition: ``` if(a>20&&a<100&&a%10!=0) ^^^^ ``` And again, your code is neigh unreadable, since you don't use any whitespace. What is easier to read: ``` a>=20&&a&&a<100&&a%10==0 ``` or ``` a >= 20 && a && a < 100 && a % 10 == 0 ``` I guess you now see the superfluous `a` in the condition, which will always be true at that point. Next, this function should do **one** job. It should get a number from 0-999 and return its name, not add the suffix. So let's get rid of that and fix the `if` complexity. And while we're at it, let's add another function for `0-99`: ``` std::string conv0to99(number_type a) { assert(0 <= a && a < 100); if(a == 0) { return ""; } else if (a <= 20) { return conv0to19(a); } else { return conv_dec(a / 10) + "-" + conv0to19(a % 10); } } std::string convert1to999(number_type a) { assert(0 <= a && a < 1000); if(a == 0) { return ""; } else if (a <= 100) { return conv0to99(a); } else { return conv0to19(a/100) + " hundred " + conv0to99(a % 100); } } ``` Both functions are rather simple and easy to check. The hurdles of the `<=20` are now (almost) entirely hidden in `conv0to99`, which is still easy enough to understand quickly. As I said, get rid of `fillContainer`. You use it only in `convert`, so let's only have it there. Also, handle the easy case first: ``` std::string convert(uint64_t a) { if(a == 0) { return "zero"; } std::string output; int container[7]; for(int i = 0; i < 7; ++i) { container[i] = a % 1000; a = a / 1000; } for(int i = 6; i>=0; i--) { if(container[i] != 0) { // we add the name now here instead of in convert1to999 output += convert1to999(container[i]) + " " + name[i] + " "; } } // if your compiler doesn't have `output.back()`, use your old check while(output.back() == ' ') { output.pop_back(); } return output; } ``` You can also get rid of `container` if you build the number from the back. Last words ========== Make sure to format your code. Either use an editor which supports automatic formatting, or use a program that formats your code, **especially** if you want to share your code.
Overall your solution is straightforward and clear. A few areas might be improved including * consistency of formatting, * enabling and addressing compiler warnings, * considering brevity/efficiency/constancy of your algorithm. Formatting ========== Whitespace ---------- From experience, even though whitespace does not matter to the compiler, I recommend that you apply it as consistently as possible and to help the reader see the structure. While subjective, my opinion is that your code would be cleaner if it had whitespace after the includes and before prototypes, aligned adjacent inline comments, consistently used single spaces or alignment after punctuation and around operators. I consider the readability of ``` if(a>20&&a<100&&a%10!=0) return conv_dec(a/10)+conv0to19(a%10)+name[i]; ``` to be improved as ``` if (a > 20 && a < 100 && a % 10 != 0) return conv_dec(a / 10) + conv0to19(a % 10) + name[i]; ``` Single Statement Braces ----------------------- My opinion is that the lack of braces around single-line if/for/while statement eventually causes far more pain than it saves. Take my experience for what you will. Consistency ----------- Whatever styling you choose, *please* apply it consistently. Longterm you might consider applying a code formatter to help maintain formatting consistency within your codebase. Enable Compiler Warnings ======================== Compile with warnings enabled and consider what they say. My compiler informed me that several functions had code paths that failed to return the expected value. Specifically in this case, all case-statements should have a `default` case, whether it be a return or an exception. Plus in `convert1to999` consider what happens if `a == 1000` due to some code changes or function reuse. Algorithm and Coding ==================== Eliminate code whenever possible unless it trades off on clarity. The function `convert1to999` takes an unsigned input so it will never be `< 0` so do not test for it. In fact there is also have another extraneous check of `a` in a later condition obscured by the lack of spaces. `conv0to19` handles 0 input correctly so you don't need special handling for (a % 10) == 0. (Keeping your braces formatting style even though I prefer a terser style. Using `else if` because it clearly conveys intent without needing to immediately recognize multiple return paths.) ``` string convert1to999(uint64_t a, int i) { if(a != 0) { boolean isNonMag = (a % 10 != 0); if (a < 20) { return conv0to19(a) + name[i]; } else if (a < 100) { // note conv0to19 handle 0 properly return conv_dec(a / 10) + conv0to19(a % 10) + name[i]; } else if(a < 1000) { return conv0to19(a / 100) + "hundred " + conv_dec(fmod((a / 10), 10)) + conv0to19(a % 10) + name[i]; } } return ""; } ``` The use of `case` statements in `conv1to19` and `conv_dec` is certainly reasonable but the problem maps so naturally to array indexing. Furthermore you do use array indexing for handling order of magnitude counters. There is a consistency argument for using it more widely. Of course the downside of array indexing is that it opens the prospect of array indexing errors. On option is to use a `std::vector` instead. Especially if you do use arrays I *strongly* suggest that you get in the habit of bounds checking input and in cases where you have an expected array length that you encode the array length into the declaration to help avoid hard to catch mistakes. Particularly since you do use an indexed array for the order of magnitude counters, you might consider using them elsewhere for the sake of constancy. ``` string lessThan20[20] = { "", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen " }; string conv1to19(uint64 a) { if (a < 20) { return lessThan20[a]; } return ""; } ``` Certainly maintaining the use of `case` is perfectly defensible in my mind. Generally, globals limits your ability to reuse the code. ``` int container[7]; /// every element contains a number between 0 and 999 ``` Consider passing an array to populate to fillContainer. (Also consider whether the naming could be improved, perhaps something like `convertToMagnitudeEncoding`). ``` #define ENCODED_LENGTH 7 ... { ... int magnitudeEncoded[ENCODED_LENGTH]; fillContainer(a, &decimalEncode); ... } ``` I suggest that except when the `for` loop boundary is clearer with `<=` for your array bounds, prefer `<` as an idiom. ``` void fillContainer(uint64_t a, int* decimalEncoded) { for(int i = 0; i < ENCODED_LENGTH; i++) { decimalEncoded[i] = a % 1000; a /= 1000; } } ``` Better might be to use or return a safe container or pass an array length along with the array rather than to have the length embed in physically separated parts of code. Other observations 1. No bounds checking value used when indexing into `name` 2. Avoid scattering magic numbers 6 and 7 through the code. Use constants or defines if you will reuse them. This mitigates introducing errors due to partial changes at some later date. 3. When possible avoid mixing snake and camel function naming conventions such as conv\_dec and fillContainer. 4. Usually one want to terminate console output with newlines `<< endl;`
99,742
I have seen a number of these, and hate to ask another one, but when I count my accepted answers, it seems that I should have the Tenacious badge. The fact that I haven;t means I have probably misunderstood something about it. I have 6 zero score accepted answers, and 13 scored accepted answers. This should therefore count as more than 5 and more than 20% of the total. Or does it mean less that 20%? Or exactly 20%? Or something else I have not understood?
2011/07/25
[ "https://meta.stackexchange.com/questions/99742", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/164650/" ]
We only check for answers *more than 10 days old* in this badge...so your earning it doesn't depend on luck of when the job ran (it doesn't run as often as others)...before an answer has the opportunity to get upvotes just after being posted. As it stands now, you'd get the badge in 6 days.
The [mega-list of all badges with full descriptions](https://meta.stackexchange.com/questions/67397/list-of-all-badges-with-full-descriptions) says of the **Tenacious badge:** > > * silver; awarded once; same family as Unsung Hero (gold) > * have more than five accepted answers with a score of zero, and have those zero-score accepted answers account for at least 20% of all your accepted answers > * only accepted answers at least ten days old are considered > * Community Wiki answers, deleted answers, and self-accepted answers are not included in any calculations > > > I count that you have 6 zero-score accepted answers and 20 total accepted answers. However, your [*last*](https://stackoverflow.com/questions/6777351/thread-context-switching-issue/6777412#6777412) zero-score accepted answer was posted on July 21st, which is less than 10 days ago. That means you're only working with 5 zero-score accepted answers, which doesn't meet the criteria for the badge. It requires **more than 5** zero-score accepted answers. Just wait 6 days, and you'll get the badge. :-)
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
``` System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); ``` Problem is here. You are reading some non numeric input and trying to parse it into int. Thats the exceptional case.
Maybe because readline string is like '123\n'.
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
This problem i have faced in my daytoday work. The `bf.readLine()` gives you the empty string(`""`) or character values `[A-Z]`.So do a precondition check like > > > ``` > // To allow only Integer to be parsed. > > ``` > > ``` String rawText = br.readLine().trim(); if ( isNumeric (rawText) // returns false for non numeric && rawText.matches("-?\\d+?") // Only Integers. ) ``` Updates : ``` // isNumeric implementation Due credit to CraigTP ``` Please refer for brilliant logic > > [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java) > > > ``` public static boolean isNumeric(String str) { NumberFormat formatter = NumberFormat.getInstance(); ParsePosition pos = new ParsePosition(0); formatter.parse(str, pos); return str.length() == pos.getIndex(); } ```
Maybe because readline string is like '123\n'.
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
This problem i have faced in my daytoday work. The `bf.readLine()` gives you the empty string(`""`) or character values `[A-Z]`.So do a precondition check like > > > ``` > // To allow only Integer to be parsed. > > ``` > > ``` String rawText = br.readLine().trim(); if ( isNumeric (rawText) // returns false for non numeric && rawText.matches("-?\\d+?") // Only Integers. ) ``` Updates : ``` // isNumeric implementation Due credit to CraigTP ``` Please refer for brilliant logic > > [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java) > > > ``` public static boolean isNumeric(String str) { NumberFormat formatter = NumberFormat.getInstance(); ParsePosition pos = new ParsePosition(0); formatter.parse(str, pos); return str.length() == pos.getIndex(); } ```
``` System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); ``` Problem is here. You are reading some non numeric input and trying to parse it into int. Thats the exceptional case.
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
``` System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); ``` Problem is here. You are reading some non numeric input and trying to parse it into int. Thats the exceptional case.
I replaced the inputstream with a Scanner. ``` public class Case1 { public static void main(String args[]) { char ch='y';int i=0; Scanner s=new Scanner(System.in); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ System.out.println("Enter the option"); System.out.flush(); i=s.nextInt(); System.out.println("after"+i); switch(i) { case 1:System.out.println("1"); break; case 2:System.out.println("1"); break; } System.out.println("do u want to continue(Y/N)"); ch=(char)s.next().charAt(0); System.out.println("ch after execution:::"+ch); } }} ```
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
``` System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); ``` Problem is here. You are reading some non numeric input and trying to parse it into int. Thats the exceptional case.
We can only use Explicit Type Conversion for data types which are type compatible with each other. But as you are trying to do type conversion on ``` ch=(char)bf.read(); ``` you are actually trying to cast an Integer as char(since return type of bf.read() is int). But Integer and char are not compatible, hence the error.
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
This problem i have faced in my daytoday work. The `bf.readLine()` gives you the empty string(`""`) or character values `[A-Z]`.So do a precondition check like > > > ``` > // To allow only Integer to be parsed. > > ``` > > ``` String rawText = br.readLine().trim(); if ( isNumeric (rawText) // returns false for non numeric && rawText.matches("-?\\d+?") // Only Integers. ) ``` Updates : ``` // isNumeric implementation Due credit to CraigTP ``` Please refer for brilliant logic > > [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java) > > > ``` public static boolean isNumeric(String str) { NumberFormat formatter = NumberFormat.getInstance(); ParsePosition pos = new ParsePosition(0); formatter.parse(str, pos); return str.length() == pos.getIndex(); } ```
I replaced the inputstream with a Scanner. ``` public class Case1 { public static void main(String args[]) { char ch='y';int i=0; Scanner s=new Scanner(System.in); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ System.out.println("Enter the option"); System.out.flush(); i=s.nextInt(); System.out.println("after"+i); switch(i) { case 1:System.out.println("1"); break; case 2:System.out.println("1"); break; } System.out.println("do u want to continue(Y/N)"); ch=(char)s.next().charAt(0); System.out.println("ch after execution:::"+ch); } }} ```
3,811,356
Hi When I run the following code I am getting `NumberFormatException` can anybody help me out in debugging code. ``` import java.io.*; public class Case1 { public static void main(String args[]) { char ch='y';int i=0; BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("ch before while:::"+ch); while(ch=='y'||ch=='Y'){ try{ System.out.println("Enter the option"); i=Integer.parseInt(bf.readLine()); System.out.println("after"+i); switch { case 1 ystem.out.println("1"); break; case 2 ystem.out.println("1"); break; } System.out.println("do u want to continue(Y/y"); ch=(char)bf.read(); System.out.println("ch after execution:::"+ch); } catch(NumberFormatException e){e.printStackTrace();} catch(IOException e){e.printStackTrace();} } }} ```
2010/09/28
[ "https://Stackoverflow.com/questions/3811356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240698/" ]
This problem i have faced in my daytoday work. The `bf.readLine()` gives you the empty string(`""`) or character values `[A-Z]`.So do a precondition check like > > > ``` > // To allow only Integer to be parsed. > > ``` > > ``` String rawText = br.readLine().trim(); if ( isNumeric (rawText) // returns false for non numeric && rawText.matches("-?\\d+?") // Only Integers. ) ``` Updates : ``` // isNumeric implementation Due credit to CraigTP ``` Please refer for brilliant logic > > [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java) > > > ``` public static boolean isNumeric(String str) { NumberFormat formatter = NumberFormat.getInstance(); ParsePosition pos = new ParsePosition(0); formatter.parse(str, pos); return str.length() == pos.getIndex(); } ```
We can only use Explicit Type Conversion for data types which are type compatible with each other. But as you are trying to do type conversion on ``` ch=(char)bf.read(); ``` you are actually trying to cast an Integer as char(since return type of bf.read() is int). But Integer and char are not compatible, hence the error.
13,299,195
I've been trying to test my Flask application that uses PyMongo. The application works fine, but when I execute unit tests, I constantly get an error message saying "working outside of application context". This message is thrown every time I run any unit test that requires access to the Mongo database. I've been following this guide for unit testing: <http://flask.pocoo.org/docs/testing/> My application's design is straight forward, similar to the standard Flask tutorial. Did anyone already have the same issue? ``` class BonjourlaVilleTestCase(unittest.TestCase): container = {} def register(self, nickname, password, email, agerange): """Helper function to register a user""" return self.app.post('/doregister', data={ 'nickname' : nickname, 'agerange' : agerange, 'password': password, 'email': email }, follow_redirects=True) def setUp(self): app.config.from_envvar('app_settings_unittests', silent=True) for x in app.config.iterkeys(): print "Conf Key=%s, Value=%s" % (x, app.config[x]) self.app = app.test_client() self.container["mongo"] = PyMongo(app) self.container["mailer"] = Mailer(app) self.container["mongo"].safe = True app.container = self.container def tearDown(self): self.container["mongo"].db.drop() pass def test_register(self): nickname = "test_nick" password = "test_password" email = "test@email.com" agerange = "1" rv = self.register(nickname, password, email, agerange) assert "feed" in rv.data if __name__ == '__main__': unittest.main() ```
2012/11/08
[ "https://Stackoverflow.com/questions/13299195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715321/" ]
I've finally fixed the issue, which was due to the application context. It seems that when using PyMongo, as it manages the connection for you, the connection object must be used within the same context which initialized the PyMongo instance. I had to modify the code, thus the PyMongo instance is initialized in the testable object. Later, this instance is returned via a public method. Thus, to resolve the issue, all my DB requests in the unit tests must be executed under the *with* statement. Example follows ``` with testable.app.app_context(): # within this block, current_app points to app. testable.dbinstance.find_one({"user": user}) ```
Review Context Locals and test\_request\_context(): <http://flask.pocoo.org/docs/quickstart/#context-locals>
20,380,597
(As a follow up to [this question](https://stackoverflow.com/questions/20378549/how-to-run-all-gtest-files-at-once-using-cmake)) My cmake file looks like this: ``` include(CTest) add_subdirectory(/usr/src/gtest gtest) include_directories(${GTEST_INCLUDE_DIR}) add_executable(TestA TestA.cpp) target_link_libraries(TestA gtest) add_test(NAME AllTestsInA COMMAND TestA) add_executable(TestB TestB.cpp) target_link_libraries(TestB gtest) add_test(NAME AllTestsInB COMMAND TestB) ``` I am able to run single tests from within qtcreator and all tests from command line using `ctest --output-on-failure`, but how can I execute all tests from within qtcreator? qtcreator version: 2.7.0
2013/12/04
[ "https://Stackoverflow.com/questions/20380597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408351/" ]
It might make sense to have a "default" implementation, which concrete classes can use if it's useful to them. They still need to override it, but can call the base-class version non-virtually: ``` struct B : A { void interface() { A::interface(); // call the default implementation // and maybe do some B-specific things too } }; ```
> > I can't think up a reason for this. If one virtual function is defined as pure, then what's the reason to implement it? > > > The purpose of a pure virtual function is *not* to prohibit definitions. It is to mark the class as uninstantiable. Providing a definition may be useful for deriving classes: ``` struct A { virtual void foo() = 0; }; void A::foo() { /* some common logic here */ } struct B : A { virtual void foo() overrides { bar(); A::foo(); } void bar(); }; struct C : A { virtual void foo() overrides { baz(); A::foo(); } void baz(); }; ```
20,380,597
(As a follow up to [this question](https://stackoverflow.com/questions/20378549/how-to-run-all-gtest-files-at-once-using-cmake)) My cmake file looks like this: ``` include(CTest) add_subdirectory(/usr/src/gtest gtest) include_directories(${GTEST_INCLUDE_DIR}) add_executable(TestA TestA.cpp) target_link_libraries(TestA gtest) add_test(NAME AllTestsInA COMMAND TestA) add_executable(TestB TestB.cpp) target_link_libraries(TestB gtest) add_test(NAME AllTestsInB COMMAND TestB) ``` I am able to run single tests from within qtcreator and all tests from command line using `ctest --output-on-failure`, but how can I execute all tests from within qtcreator? qtcreator version: 2.7.0
2013/12/04
[ "https://Stackoverflow.com/questions/20380597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408351/" ]
It might make sense to have a "default" implementation, which concrete classes can use if it's useful to them. They still need to override it, but can call the base-class version non-virtually: ``` struct B : A { void interface() { A::interface(); // call the default implementation // and maybe do some B-specific things too } }; ```
You apparently completely misunderstood the meaning of the term "statically" in this context. Yes, pure virtual functions can still have bodies, i.e. they can still be *defined*. And no, you cannot invoke such function "without an object instance", as you seem to incorrectly believe. A pure virtual function with a body is still a non-static member function. It still requires an object instance to be invoked. When someone says that such function can be invoked "statically", it means that it can be called directly, without using virtual dispatch mechanism. Function calls that go through virtual dispatch are sometimes called "virtual calls" or "dynamic calls", while direct function calls are sometimes called "static calls". The term "static" in this context assumes a completely different meaning, not connected in any way to static member functions. In C++ language a direct non-virtual (i.e. "static") call can be performed explicitly by specifying a qualified member name in the call. For example, if class `B` derives from your class `A`, then inside some method `B::foo()` you can use the following syntax ``` void B::foo() { A::interface(); // <- qualified method name } ``` which performs a direct call to the implementation of `A::interface()` you provided. For an object `b` of type `B` the same kind of call can be performed as ``` B b; b.A::interface(); // <- qualified method name ``` In both cases the call is performed for a specific object (`*this` in the first example, and `b` in the second). Pretty much the same thing happens implicitly when destructors of derived classes call destructors of base class, which is why you will often encounter this situation with pure virtual destructors (i.e. they are declared as pure virtual, yet have a body).
20,380,597
(As a follow up to [this question](https://stackoverflow.com/questions/20378549/how-to-run-all-gtest-files-at-once-using-cmake)) My cmake file looks like this: ``` include(CTest) add_subdirectory(/usr/src/gtest gtest) include_directories(${GTEST_INCLUDE_DIR}) add_executable(TestA TestA.cpp) target_link_libraries(TestA gtest) add_test(NAME AllTestsInA COMMAND TestA) add_executable(TestB TestB.cpp) target_link_libraries(TestB gtest) add_test(NAME AllTestsInB COMMAND TestB) ``` I am able to run single tests from within qtcreator and all tests from command line using `ctest --output-on-failure`, but how can I execute all tests from within qtcreator? qtcreator version: 2.7.0
2013/12/04
[ "https://Stackoverflow.com/questions/20380597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408351/" ]
It might make sense to have a "default" implementation, which concrete classes can use if it's useful to them. They still need to override it, but can call the base-class version non-virtually: ``` struct B : A { void interface() { A::interface(); // call the default implementation // and maybe do some B-specific things too } }; ```
A pure virtual function simply means that the function must be overidden by all derived classes it does not mean that the function cannot/should not have a implementation of its own. Two most obvious cases for such a pure virtual function having implementation are: * A Derived class implementation can call Base class implementation * Sometimes you would want a base class to be made abstract but there is no method which you can mark as pure `virtual` in such a case a destructor is most obvious choice but in such a destructor still needs a implementation.
20,380,597
(As a follow up to [this question](https://stackoverflow.com/questions/20378549/how-to-run-all-gtest-files-at-once-using-cmake)) My cmake file looks like this: ``` include(CTest) add_subdirectory(/usr/src/gtest gtest) include_directories(${GTEST_INCLUDE_DIR}) add_executable(TestA TestA.cpp) target_link_libraries(TestA gtest) add_test(NAME AllTestsInA COMMAND TestA) add_executable(TestB TestB.cpp) target_link_libraries(TestB gtest) add_test(NAME AllTestsInB COMMAND TestB) ``` I am able to run single tests from within qtcreator and all tests from command line using `ctest --output-on-failure`, but how can I execute all tests from within qtcreator? qtcreator version: 2.7.0
2013/12/04
[ "https://Stackoverflow.com/questions/20380597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408351/" ]
It might make sense to have a "default" implementation, which concrete classes can use if it's useful to them. They still need to override it, but can call the base-class version non-virtually: ``` struct B : A { void interface() { A::interface(); // call the default implementation // and maybe do some B-specific things too } }; ```
interface() = 0 means derived classes **must** provide an implementation, so the definition effects derived classes, but the base class is permitted to have an implementation of the method so that derived classes can always call base::interface().
180,012
I have been hanging around SO for a year and a bit and hugely appreciate the quality of the questions and answers, and the ethos of the site. The polite and constructive atmosphere is very welcome. One thing that I also appreciate about SO is the intention that questions should be specific *and* have more general applicability. Maybe it's just me, but I seem to have noticed an increase in the number of "debugging" or "I would like to write a program to ensure world peace - how do I do this" questions. Or maybe I'm getting more aware of what "ideal" questions are. My question is this: to help ensure that SO continues to grow, in a constructive manner, keeping quality focussed (and other management speak), should there be a more active "question review" process for people asking questions who are new or have limited reputation? For example, could review become mandatory for all questions asked by people who have less than 20 days visited the site or less than 25 reputation? *ie* the question won't appear unless it passes this review.
2013/05/13
[ "https://meta.stackexchange.com/questions/180012", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/206685/" ]
Every now and then I introduce someone new to the network. We pick a site from [the list](https://stackexchange.com/sites#questionsperday), usually the one that's closer to their professional interests, and go through the site's: * About page * FAQ * Top questions All in all, my "intro to SE" process takes about 20 minutes. That's *a lot*, when was the last time you spend 20 minutes essentially reading the manual before you used a website? Of course not everyone spends that much time (or any time at all) familiarizing themselves with the site before they ask their first question. But some do, with or without help from a veteran user. Do we really want to place yet another barrier in front of them? I can see how your feature would be (very) useful, but I also feel it would needlessly alienate the (perhaps few) new users who actually care enough to do it right. We are assuming their questions are somehow problematic before we even see them and that's... not right. That said, perhaps your feature would make sense *after* a new user has got it wrong a couple of times. If their first 2-3 questions were downvoted and closed, their next one could be placed in limbo until it's thoroughly reviewed.
No, I can't really see the benefit of doing so. The "advantage" is that the bad questions don't appear on the site at all, but you're also limiting the number of eyes on a question and potentially alienating new users who can't get their good questions answers as quickly. On a site the size of StackOverflow the bad questions are handled appropriately quickly because there's just so many people looking at them, and new questions wouldn't sit in the proposed queue for the same reason. Now consider a site with a much smaller population. There are less people to filter out the bad questions, so they might linger for a bit longer, but there are also far fewer people to review new questions before they're visible on the site. Not every new user asks bad questions, and it would be a shame for them to be put off and stop using the site (or the network entirely) because their question sat waiting and they were unable to get answers to it. I'd prefer to have bad questions get through, and be handled collectively by the community rather than just by those who use the existing review queues, rather than potentially lose users of smaller sites because of this.
41,736,481
I am stuck, we want to display value in H18 by adding cell(D18 & H17) this is the formula I tried "=IF(ISBLANK(D18),0,(SUM(D18+H17)))" once we are giving value in "D" Row then only we need to display value in H Row. including "zero" "H" Row fully taking value as "0" [![enter image description here](https://i.stack.imgur.com/YKqjm.jpg)](https://i.stack.imgur.com/YKqjm.jpg)
2017/01/19
[ "https://Stackoverflow.com/questions/41736481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627729/" ]
@ranjit ``` =IF(D18="","",SUM(D18+H17)) ``` This is working for me, give it a try.
So, as per comment in view : show zero values - can be ticked or not...
26,645,612
I need to pass both a flash value and a session value into one view in Play Framework. Is this possible?
2014/10/30
[ "https://Stackoverflow.com/questions/26645612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3145170/" ]
Both the session and the flash objects are accessible from the request. Simply pass request from a controller to a view. Usually it's done by an implicit parameter: ``` @()(implicit request: RequestHeader) @request.session.get("yourSessionKey") @request.flash.get("yourFlashKey") ```
``` @()(implicit flash : Flash, request: RequestHeader) ``` And then you can use it like this: ``` @if(request.session.get("example").toList(0) == example2){ <a href="#example>"><h5>example</h5></a> } ```
25,032,716
I have a Maven project and inside a method I want to create a path for a directory in my resources folder. This is done like this: ``` try { final URI uri = getClass().getResource("/my-folder").toURI(); Path myFolderPath = Paths.get(uri); } catch (final URISyntaxException e) { ... } ``` The generated `URI` looks like `jar:file:/C:/path/to/my/project.jar!/my-folder`. The stacktrace is as following: ``` Exception in thread "pool-4-thread-1" java.nio.file.FileSystemNotFoundException at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) at java.nio.file.Paths.get(Paths.java:143) ``` The `URI` seems to be valid. The part before `!` points to the generated jar-file and the part after it to `my-folder` in the root of the archive. I have used this instructions before to create paths to my resources. Why am I getting an exception now?
2014/07/30
[ "https://Stackoverflow.com/questions/25032716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183192/" ]
You need to create the file system before you can access the path within the zip like ``` final URI uri = getClass().getResource("/my-folder").toURI(); Map<String, String> env = new HashMap<>(); env.put("create", "true"); FileSystem zipfs = FileSystems.newFileSystem(uri, env); Path myFolderPath = Paths.get(uri); ``` This is not done automatically. See <http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html>
If you intend to read the resource file, you can directly use `getClass.getResourceAsStream`. This will set up the file system implictly. The function returns `null` if your resource could not be found, otherwise you directly have an input stream to parse your resource.
25,032,716
I have a Maven project and inside a method I want to create a path for a directory in my resources folder. This is done like this: ``` try { final URI uri = getClass().getResource("/my-folder").toURI(); Path myFolderPath = Paths.get(uri); } catch (final URISyntaxException e) { ... } ``` The generated `URI` looks like `jar:file:/C:/path/to/my/project.jar!/my-folder`. The stacktrace is as following: ``` Exception in thread "pool-4-thread-1" java.nio.file.FileSystemNotFoundException at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) at java.nio.file.Paths.get(Paths.java:143) ``` The `URI` seems to be valid. The part before `!` points to the generated jar-file and the part after it to `my-folder` in the root of the archive. I have used this instructions before to create paths to my resources. Why am I getting an exception now?
2014/07/30
[ "https://Stackoverflow.com/questions/25032716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183192/" ]
You need to create the file system before you can access the path within the zip like ``` final URI uri = getClass().getResource("/my-folder").toURI(); Map<String, String> env = new HashMap<>(); env.put("create", "true"); FileSystem zipfs = FileSystems.newFileSystem(uri, env); Path myFolderPath = Paths.get(uri); ``` This is not done automatically. See <http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html>
Expanding on @Uwe Allner 's excellent answer, a failsafe method to use is ``` private FileSystem initFileSystem(URI uri) throws IOException { try { return FileSystems.getFileSystem(uri); } catch( FileSystemNotFoundException e ) { Map<String, String> env = new HashMap<>(); env.put("create", "true"); return FileSystems.newFileSystem(uri, env); } } ``` Calling this with the URI you are about to load will ensure the filesystem is in working condition. I always call `FileSystem.close()` after using it: ``` FileSystem zipfs = initFileSystem(fileURI); filePath = Paths.get(fileURI); // Do whatever you need and then close the filesystem zipfs.close(); ```
25,032,716
I have a Maven project and inside a method I want to create a path for a directory in my resources folder. This is done like this: ``` try { final URI uri = getClass().getResource("/my-folder").toURI(); Path myFolderPath = Paths.get(uri); } catch (final URISyntaxException e) { ... } ``` The generated `URI` looks like `jar:file:/C:/path/to/my/project.jar!/my-folder`. The stacktrace is as following: ``` Exception in thread "pool-4-thread-1" java.nio.file.FileSystemNotFoundException at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) at java.nio.file.Paths.get(Paths.java:143) ``` The `URI` seems to be valid. The part before `!` points to the generated jar-file and the part after it to `my-folder` in the root of the archive. I have used this instructions before to create paths to my resources. Why am I getting an exception now?
2014/07/30
[ "https://Stackoverflow.com/questions/25032716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183192/" ]
You need to create the file system before you can access the path within the zip like ``` final URI uri = getClass().getResource("/my-folder").toURI(); Map<String, String> env = new HashMap<>(); env.put("create", "true"); FileSystem zipfs = FileSystems.newFileSystem(uri, env); Path myFolderPath = Paths.get(uri); ``` This is not done automatically. See <http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html>
In addition to @Uwe Allner and @mvreijn: Be careful with the `URI`. Sometimes the `URI` has a wrong format (e.g. `"file:/path/..."` and correct one would be `"file:///path/..."`) and you cant get a proper `FileSystem`. In this case it helps that the `URI` is created from the `Path`'s `toUri()` method. In my case I modified `initFileSystem` method a little bit and used in non exceptional cases the `FileSystems.newFileSystem(uri, Collections.emptyMap())`. In exceptional case the `FileSystems.getDefault()` is used. In my case it was also necessary to catch the `IllegalArgumentException` to handle the case with `Path component should be '/'`. On windows and linux the exception is caught but the `FileSystems.getDefault()` works. On osx no exception happens and the `newFileSystem` is created: ``` private FileSystem initFileSystem(URI uri) throws IOException { try { return FileSystems.newFileSystem(uri, Collections.emptyMap()); }catch(IllegalArgumentException e) { return FileSystems.getDefault(); } } ```
25,032,716
I have a Maven project and inside a method I want to create a path for a directory in my resources folder. This is done like this: ``` try { final URI uri = getClass().getResource("/my-folder").toURI(); Path myFolderPath = Paths.get(uri); } catch (final URISyntaxException e) { ... } ``` The generated `URI` looks like `jar:file:/C:/path/to/my/project.jar!/my-folder`. The stacktrace is as following: ``` Exception in thread "pool-4-thread-1" java.nio.file.FileSystemNotFoundException at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) at java.nio.file.Paths.get(Paths.java:143) ``` The `URI` seems to be valid. The part before `!` points to the generated jar-file and the part after it to `my-folder` in the root of the archive. I have used this instructions before to create paths to my resources. Why am I getting an exception now?
2014/07/30
[ "https://Stackoverflow.com/questions/25032716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183192/" ]
If you intend to read the resource file, you can directly use `getClass.getResourceAsStream`. This will set up the file system implictly. The function returns `null` if your resource could not be found, otherwise you directly have an input stream to parse your resource.
In addition to @Uwe Allner and @mvreijn: Be careful with the `URI`. Sometimes the `URI` has a wrong format (e.g. `"file:/path/..."` and correct one would be `"file:///path/..."`) and you cant get a proper `FileSystem`. In this case it helps that the `URI` is created from the `Path`'s `toUri()` method. In my case I modified `initFileSystem` method a little bit and used in non exceptional cases the `FileSystems.newFileSystem(uri, Collections.emptyMap())`. In exceptional case the `FileSystems.getDefault()` is used. In my case it was also necessary to catch the `IllegalArgumentException` to handle the case with `Path component should be '/'`. On windows and linux the exception is caught but the `FileSystems.getDefault()` works. On osx no exception happens and the `newFileSystem` is created: ``` private FileSystem initFileSystem(URI uri) throws IOException { try { return FileSystems.newFileSystem(uri, Collections.emptyMap()); }catch(IllegalArgumentException e) { return FileSystems.getDefault(); } } ```
25,032,716
I have a Maven project and inside a method I want to create a path for a directory in my resources folder. This is done like this: ``` try { final URI uri = getClass().getResource("/my-folder").toURI(); Path myFolderPath = Paths.get(uri); } catch (final URISyntaxException e) { ... } ``` The generated `URI` looks like `jar:file:/C:/path/to/my/project.jar!/my-folder`. The stacktrace is as following: ``` Exception in thread "pool-4-thread-1" java.nio.file.FileSystemNotFoundException at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171) at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157) at java.nio.file.Paths.get(Paths.java:143) ``` The `URI` seems to be valid. The part before `!` points to the generated jar-file and the part after it to `my-folder` in the root of the archive. I have used this instructions before to create paths to my resources. Why am I getting an exception now?
2014/07/30
[ "https://Stackoverflow.com/questions/25032716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183192/" ]
Expanding on @Uwe Allner 's excellent answer, a failsafe method to use is ``` private FileSystem initFileSystem(URI uri) throws IOException { try { return FileSystems.getFileSystem(uri); } catch( FileSystemNotFoundException e ) { Map<String, String> env = new HashMap<>(); env.put("create", "true"); return FileSystems.newFileSystem(uri, env); } } ``` Calling this with the URI you are about to load will ensure the filesystem is in working condition. I always call `FileSystem.close()` after using it: ``` FileSystem zipfs = initFileSystem(fileURI); filePath = Paths.get(fileURI); // Do whatever you need and then close the filesystem zipfs.close(); ```
In addition to @Uwe Allner and @mvreijn: Be careful with the `URI`. Sometimes the `URI` has a wrong format (e.g. `"file:/path/..."` and correct one would be `"file:///path/..."`) and you cant get a proper `FileSystem`. In this case it helps that the `URI` is created from the `Path`'s `toUri()` method. In my case I modified `initFileSystem` method a little bit and used in non exceptional cases the `FileSystems.newFileSystem(uri, Collections.emptyMap())`. In exceptional case the `FileSystems.getDefault()` is used. In my case it was also necessary to catch the `IllegalArgumentException` to handle the case with `Path component should be '/'`. On windows and linux the exception is caught but the `FileSystems.getDefault()` works. On osx no exception happens and the `newFileSystem` is created: ``` private FileSystem initFileSystem(URI uri) throws IOException { try { return FileSystems.newFileSystem(uri, Collections.emptyMap()); }catch(IllegalArgumentException e) { return FileSystems.getDefault(); } } ```
42,292,315
I was given this problem during a phone interview: > > Suppose there is a list of ranges. For example, [[1-6],[10-19],[5-8]]. > Write a function that returns the list of combined ranges > such that input [[1-6],[10-19],[5-8]] to the function returns > [[1,8],[10,19]] (only the start and end number). Note, the input list > may contain arbitrary number of > ranges. > > > My solution to this problem is: 1. Combine all range list into one list: [[1-6],[10-19],[5-8]] -> [1-6,10-19,5-8] 2. Perform sorting on the list: list = Sorted(list) -> [1,2,3,4,5,5,6,6,7,8,10...] 3. Use list = set(list) to get rid of the redundant numbers 4. Iterate through the list and find the range I know this solution is definitely what they are looking for (that's why I failed the interview terribly) as the time complexity is O(nlogn) (sorting), n is the number of distinct numbers in the range. Can you python expert gives a O(n) solution, n as the number of ranges in the original list?
2017/02/17
[ "https://Stackoverflow.com/questions/42292315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718049/" ]
First of all, the solution mentioned in the question is not O(nlgn), where n is the number of segments. This is O(Xlg(X))where, `X = length of the segment*num of segments`, which is terribly slow. An O(NlgN) solution exists where N is the number of segments. 1. Sort the segments by their starting point. 2. Sweep across the sorted list and check if the current segment overlaps with the previous one. If yes, then extend the previous segment if required. Sample code: ``` inp = [[1,6], [10,19], [5,8]] inp = sorted(inp) segments = [] for i in inp: if segments: if segments[-1][1] >= i[0]: segments[-1][1] = max(segments[-1][1], i[1]) continue segments.append(i) print segments # [[1, 8], [10, 19]] ```
You could use [`heapq`](https://docs.python.org/3.6/library/heapq.html) to create a heap from the ranges. Then pop range from a heap and if it overlaps with the top of the heap replace the top with merged range. If there's no overlap or there's no more ranges append it to result: ``` import heapq def merge(ranges): heapq.heapify(ranges) res = [] while ranges: start, end = heapq.heappop(ranges) if ranges and ranges[0][0] <= end: heapq.heapreplace(ranges, [start, max(end, ranges[0][1])]) else: res.append((start, end)) return res ranges = [[1,6],[10,19],[5,8]] print(merge(ranges)) ``` Output: ``` [(1, 8), (10, 19)] ``` Above has **O(n log n)** time complexity where **n** is the number of ranges.
42,292,315
I was given this problem during a phone interview: > > Suppose there is a list of ranges. For example, [[1-6],[10-19],[5-8]]. > Write a function that returns the list of combined ranges > such that input [[1-6],[10-19],[5-8]] to the function returns > [[1,8],[10,19]] (only the start and end number). Note, the input list > may contain arbitrary number of > ranges. > > > My solution to this problem is: 1. Combine all range list into one list: [[1-6],[10-19],[5-8]] -> [1-6,10-19,5-8] 2. Perform sorting on the list: list = Sorted(list) -> [1,2,3,4,5,5,6,6,7,8,10...] 3. Use list = set(list) to get rid of the redundant numbers 4. Iterate through the list and find the range I know this solution is definitely what they are looking for (that's why I failed the interview terribly) as the time complexity is O(nlogn) (sorting), n is the number of distinct numbers in the range. Can you python expert gives a O(n) solution, n as the number of ranges in the original list?
2017/02/17
[ "https://Stackoverflow.com/questions/42292315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718049/" ]
You could use [`heapq`](https://docs.python.org/3.6/library/heapq.html) to create a heap from the ranges. Then pop range from a heap and if it overlaps with the top of the heap replace the top with merged range. If there's no overlap or there's no more ranges append it to result: ``` import heapq def merge(ranges): heapq.heapify(ranges) res = [] while ranges: start, end = heapq.heappop(ranges) if ranges and ranges[0][0] <= end: heapq.heapreplace(ranges, [start, max(end, ranges[0][1])]) else: res.append((start, end)) return res ranges = [[1,6],[10,19],[5,8]] print(merge(ranges)) ``` Output: ``` [(1, 8), (10, 19)] ``` Above has **O(n log n)** time complexity where **n** is the number of ranges.
In case range is [x,y] and max\_x,y is less probably within a few millions you can do this The idea is that I use the technique of hashing to put them in sorted order taking advantage of lower max\_y. We then iterate and keep the current 'good' range is variables mn and mx. When a new range comes if it is entirely outside the 'good' range, we append the good range and make the new range as the good range. Otherwise we change the good range accordingly. ``` max_y = 1000000 range_sort = [None]*max_y ranges = [[1,6],[10,19],[5,8]] for r in ranges: if range_sort[r[0]] is not None and range_sort[r[0]]>=r[1]: continue ## handling the case [1,5] [1,8] range_sort[r[0]] = r[1] # in the list lower value is stored as index, higher as value mx = -1 mn = 1000000000 ans = [] for x,y in enumerate(range_sort): # The values are correct as explained in comment above if y is None: continue #To remove the null values if x<mn: mn = x # This will change the lower value of current range if x>mx and mx>0: # If lower val x higher than current upper mx ans.append([mn,mx]) # append current lower (mn) and upper(mx) mn = x mx = y # change the current upper and lower to the new one if y>mx: mx = y # This will change upper value of current range ans.append([mn,mx]) # This has to be outside as last range won't get appended print ans ``` Output: [[1,8],[10,19]] Time complexity **O(MAX\_y)**
42,292,315
I was given this problem during a phone interview: > > Suppose there is a list of ranges. For example, [[1-6],[10-19],[5-8]]. > Write a function that returns the list of combined ranges > such that input [[1-6],[10-19],[5-8]] to the function returns > [[1,8],[10,19]] (only the start and end number). Note, the input list > may contain arbitrary number of > ranges. > > > My solution to this problem is: 1. Combine all range list into one list: [[1-6],[10-19],[5-8]] -> [1-6,10-19,5-8] 2. Perform sorting on the list: list = Sorted(list) -> [1,2,3,4,5,5,6,6,7,8,10...] 3. Use list = set(list) to get rid of the redundant numbers 4. Iterate through the list and find the range I know this solution is definitely what they are looking for (that's why I failed the interview terribly) as the time complexity is O(nlogn) (sorting), n is the number of distinct numbers in the range. Can you python expert gives a O(n) solution, n as the number of ranges in the original list?
2017/02/17
[ "https://Stackoverflow.com/questions/42292315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718049/" ]
First of all, the solution mentioned in the question is not O(nlgn), where n is the number of segments. This is O(Xlg(X))where, `X = length of the segment*num of segments`, which is terribly slow. An O(NlgN) solution exists where N is the number of segments. 1. Sort the segments by their starting point. 2. Sweep across the sorted list and check if the current segment overlaps with the previous one. If yes, then extend the previous segment if required. Sample code: ``` inp = [[1,6], [10,19], [5,8]] inp = sorted(inp) segments = [] for i in inp: if segments: if segments[-1][1] >= i[0]: segments[-1][1] = max(segments[-1][1], i[1]) continue segments.append(i) print segments # [[1, 8], [10, 19]] ```
In case range is [x,y] and max\_x,y is less probably within a few millions you can do this The idea is that I use the technique of hashing to put them in sorted order taking advantage of lower max\_y. We then iterate and keep the current 'good' range is variables mn and mx. When a new range comes if it is entirely outside the 'good' range, we append the good range and make the new range as the good range. Otherwise we change the good range accordingly. ``` max_y = 1000000 range_sort = [None]*max_y ranges = [[1,6],[10,19],[5,8]] for r in ranges: if range_sort[r[0]] is not None and range_sort[r[0]]>=r[1]: continue ## handling the case [1,5] [1,8] range_sort[r[0]] = r[1] # in the list lower value is stored as index, higher as value mx = -1 mn = 1000000000 ans = [] for x,y in enumerate(range_sort): # The values are correct as explained in comment above if y is None: continue #To remove the null values if x<mn: mn = x # This will change the lower value of current range if x>mx and mx>0: # If lower val x higher than current upper mx ans.append([mn,mx]) # append current lower (mn) and upper(mx) mn = x mx = y # change the current upper and lower to the new one if y>mx: mx = y # This will change upper value of current range ans.append([mn,mx]) # This has to be outside as last range won't get appended print ans ``` Output: [[1,8],[10,19]] Time complexity **O(MAX\_y)**
622,140
I am getting stuck in a really easy problem in Statistical Mechanics that involves elastic collisions, it is really very shameful that I am getting stuck at such a simple thing, but from: $$\|\vec{v\_1}\|^2 +\|\vec{v\_2}\|^2 = \|\vec{u\_1}\|^2 +\|\vec{u\_2}\|^2$$ and $$\vec{v\_1}+\vec{v\_2} = \vec{u\_1} + \vec{u\_2}$$ How can I get $$\|\vec{v\_2}-\vec{v\_1}\|=\|\vec{u\_2}-\vec{u\_1}\|$$ I tried completing the square in the first equation like: $$\vec{v\_1}\cdot\vec{v\_1} +\vec{v\_2}\cdot\vec{v\_2} -2\vec{v\_1}\cdot\vec{v\_2}= (\vec{v\_2}-\vec{v\_1})\cdot(\vec{v\_2}-\vec{v\_1})=\|\vec{v\_2}-\vec{v\_1}\|^2= \vec{u\_1}\cdot\vec{u\_1} +\vec{u\_2}\cdot\vec{u\_2} -2\vec{v\_1}\cdot\vec{v\_2}$$ and then using the second equation to get: $$=\vec{u\_1}\cdot\vec{u\_1} +\vec{u\_2}\cdot\vec{u\_2} -2\vec{v\_1}\cdot(\vec{u\_1}+\vec{u\_2}-\vec{v\_1})$$ but I cannot seem to be able to simplify this to $$\vec{u\_1}\cdot\vec{u\_1} +\vec{u\_2}\cdot\vec{u\_2} -2\vec{u\_1}\cdot\vec{u\_2} = \|\vec{u\_2}-\vec{u\_1}\|^2$$ Can someone help me with this? I am sure it is quite simple, but since I am stuck I am losing way too much time on this.
2021/03/18
[ "https://physics.stackexchange.com/questions/622140", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/164849/" ]
You are certainly correct that the Lie algebra of $U(d)$ consists of skew-Hermitian $d \times d$ matrices. However, physicists will often implicitly complexify Lie algebras, without ever bothering to mention that they are doing it. The complexification of $u(d)$ is indeed $gl(d, \mathbb{C})$. That's because multiplying by $i$ we get Hermitian matrix, and any matrix at all can be expressed as the sum of a Hermitian and a skew-Hermitian matrix. You can find more discussions about Lie groups and algebras in mathematics vs. physics in Peter Woit's book 'Quantum Theory, Groups and Representations'.
As far as I remember, it is only a matter of definition of the term "generator". If $H$ is hermitian $$H^+=H$$ then $G=iH$ is skew hermitian: $$H^+=(iG)^+=-iG=-H$$ So after all, the parameter inside the exponential differs only by an imaginary unit, which doesn't change a lot, at least notation-wise. Instead of generating a one-parameter sub-group by $$\exp(\lambda G)$$ where $G$ is skew-hermitian, you generate it by $$\exp(i\lambda H)$$ where $H$ is hermitian.
622,140
I am getting stuck in a really easy problem in Statistical Mechanics that involves elastic collisions, it is really very shameful that I am getting stuck at such a simple thing, but from: $$\|\vec{v\_1}\|^2 +\|\vec{v\_2}\|^2 = \|\vec{u\_1}\|^2 +\|\vec{u\_2}\|^2$$ and $$\vec{v\_1}+\vec{v\_2} = \vec{u\_1} + \vec{u\_2}$$ How can I get $$\|\vec{v\_2}-\vec{v\_1}\|=\|\vec{u\_2}-\vec{u\_1}\|$$ I tried completing the square in the first equation like: $$\vec{v\_1}\cdot\vec{v\_1} +\vec{v\_2}\cdot\vec{v\_2} -2\vec{v\_1}\cdot\vec{v\_2}= (\vec{v\_2}-\vec{v\_1})\cdot(\vec{v\_2}-\vec{v\_1})=\|\vec{v\_2}-\vec{v\_1}\|^2= \vec{u\_1}\cdot\vec{u\_1} +\vec{u\_2}\cdot\vec{u\_2} -2\vec{v\_1}\cdot\vec{v\_2}$$ and then using the second equation to get: $$=\vec{u\_1}\cdot\vec{u\_1} +\vec{u\_2}\cdot\vec{u\_2} -2\vec{v\_1}\cdot(\vec{u\_1}+\vec{u\_2}-\vec{v\_1})$$ but I cannot seem to be able to simplify this to $$\vec{u\_1}\cdot\vec{u\_1} +\vec{u\_2}\cdot\vec{u\_2} -2\vec{u\_1}\cdot\vec{u\_2} = \|\vec{u\_2}-\vec{u\_1}\|^2$$ Can someone help me with this? I am sure it is quite simple, but since I am stuck I am losing way too much time on this.
2021/03/18
[ "https://physics.stackexchange.com/questions/622140", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/164849/" ]
As it is often the case the issue lies in conventions. For mathematicians the Lie Algebra generators are any basis that can span the algebra as a vector space, for physicist we usually require the generators themselves to be hermitian (e.g. think about the Pauli matrices), because of their interpretation as observables. Let us also make clear the difference between Algebra and Group. The Lie algebra is a vector space and an algebra thanks to the Lie bracket (the commutator), it is denoted with small cap fraktur letters. So for this case: $\mathfrak{u}(N)$ is the Lie Algebra of the group of unitary matrices of dimension $N\times N$. The group is denoted by $U(N)$ and is a group under usual matrix multiplication, whose elements are indeed unitary (thus complex entries) matrices. The algebra condition on the elements of the algebra is obtained by differentiating the unitarity condition, $$A A^\dagger = 1,$$ which gives $$ A + A^\dagger = 0$$ which is nothing else than the anti-hermitian condition. This means the Lie algebra is the vector space of all anti-hermitian matrices of dimension $N\times N$. So for a matrix $A\in \mathfrak{u}(N)$ the exponentiation does give you an element of $U(N)$, and it can be shown that all elements in the vicinity of the identity of $U(N)$ can be described by exponentiation of some element of $\mathfrak{u}(N)$. At this point we are free to describe the matrix $A$ as we wish. As physicist we want to pick a basis of hermitian elements (notice that if $A$ is anti-hermitian then $-iA$ is Hermitian, or vice versa if $\sigma$ is Hermitian then $i\sigma$ is anti-hermitian) so let us have a basis for $\mathfrak{u}(N)$ of hermitian elements multiplied by $i$ and voila $$A = \sum\_n c\_n i \sigma\_n \in \mathfrak{u}(N)$$ and exponentiating $$\exp(A) = \exp\left(\sum\_n c\_n i \sigma\_n \right) \in U(N)$$ For the case of $SU(N)$ it is the $\det = 1$ condition that when differentiated forces the matrices of its algebra to be traceless. So far we have spoken implicitly of Lie algebras as **real** vector spaces, that is the $c\_n$ above are real and don't change the hermitian properties of $A$. However one can also complexify the algebra (build a new algebra), so one obtains a vector space over the complex numbers, thus allowing for anti-hermitian and hermitian matrices. So we have \begin{align} \mathfrak{u}(N) &= \text{anti-hermitian matrices}\\[7pt] \mathfrak{u}\_\mathbb{C}(N) &= gl(N,\mathbb{C}) = \text{complex matrices size} N\times N \end{align}
As far as I remember, it is only a matter of definition of the term "generator". If $H$ is hermitian $$H^+=H$$ then $G=iH$ is skew hermitian: $$H^+=(iG)^+=-iG=-H$$ So after all, the parameter inside the exponential differs only by an imaginary unit, which doesn't change a lot, at least notation-wise. Instead of generating a one-parameter sub-group by $$\exp(\lambda G)$$ where $G$ is skew-hermitian, you generate it by $$\exp(i\lambda H)$$ where $H$ is hermitian.
3,823,961
I am using the following code for charater encoding of unicode charater. It is giving me the different string value of MD5EncryptedString when I use the value of the DataToEncrypt as 'abc' & 'ABC' ``` String DataToEncrypt="abc"; String MD5EncryptedString = String.Empty; MD5 md5 = new MD5CryptoServiceProvider(); Byte[] encodedBytes = ASCIIEncoding.Default.GetBytes(DataToEncrypt); // Byte[] encodedBytes = UTF8Encoding.Default.GetBytes(DataToEncrypt); encodedBytes = md5.ComputeHash(encodedBytes); MD5EncryptedString = BitConverter.ToString(encodedBytes); return MD5EncryptedString; ``` Is there any class instead of the ASCIIEncoding which will give me the case insensitive string means it will give me the value of the MD5EncryptedString same for both the 'abc' & 'ABC' for the DataToEncrypt variable ?
2010/09/29
[ "https://Stackoverflow.com/questions/3823961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265103/" ]
Your current code isn't using *either* `ASCIIEncoding` *or* `UTF8Encoding`... it's using the default encoding on the system, because it's equivalent to just `Encoding.Default`. Accessing that static property via the two subclasses makes no difference. To use ASCII or UTF-8, use `Encoding.ASCII` or `Encoding.UTF8`. Now, regarding case-sensitivity... no, that's not the job of encodings. Your question is quite confusing as it claims it *is* giving you the same result for "abc" and "ABC", which I seriously doubt. I assume you mean you *want* it to give you the same result, but it currently doesn't. I suggest you use something like this, if you want case insensitivity: ``` string lower = string.ToLowerInvariant(); byte[] data = Encoding.UTF8.GetBytes(lower); byte[] hash = md5.ComputeHash(encodedBytes); return BitConverter.ToString(hash); ``` Note that this gives case-insensitivity in a culture-insensitive way... which may not be ideal in all cases, but is at least consistent regardless of which culture you're using.
All character encodings encode upper and lower case letters using different bytes, so there is no way to get an encoding that will do that for you. You can always upper/lower case the string *before* hashing.
3,823,961
I am using the following code for charater encoding of unicode charater. It is giving me the different string value of MD5EncryptedString when I use the value of the DataToEncrypt as 'abc' & 'ABC' ``` String DataToEncrypt="abc"; String MD5EncryptedString = String.Empty; MD5 md5 = new MD5CryptoServiceProvider(); Byte[] encodedBytes = ASCIIEncoding.Default.GetBytes(DataToEncrypt); // Byte[] encodedBytes = UTF8Encoding.Default.GetBytes(DataToEncrypt); encodedBytes = md5.ComputeHash(encodedBytes); MD5EncryptedString = BitConverter.ToString(encodedBytes); return MD5EncryptedString; ``` Is there any class instead of the ASCIIEncoding which will give me the case insensitive string means it will give me the value of the MD5EncryptedString same for both the 'abc' & 'ABC' for the DataToEncrypt variable ?
2010/09/29
[ "https://Stackoverflow.com/questions/3823961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265103/" ]
Your current code isn't using *either* `ASCIIEncoding` *or* `UTF8Encoding`... it's using the default encoding on the system, because it's equivalent to just `Encoding.Default`. Accessing that static property via the two subclasses makes no difference. To use ASCII or UTF-8, use `Encoding.ASCII` or `Encoding.UTF8`. Now, regarding case-sensitivity... no, that's not the job of encodings. Your question is quite confusing as it claims it *is* giving you the same result for "abc" and "ABC", which I seriously doubt. I assume you mean you *want* it to give you the same result, but it currently doesn't. I suggest you use something like this, if you want case insensitivity: ``` string lower = string.ToLowerInvariant(); byte[] data = Encoding.UTF8.GetBytes(lower); byte[] hash = md5.ComputeHash(encodedBytes); return BitConverter.ToString(hash); ``` Note that this gives case-insensitivity in a culture-insensitive way... which may not be ideal in all cases, but is at least consistent regardless of which culture you're using.
Translating character symbols to ordinals (bytes) will ALWAYS give you a different answer when you encode uppercase vs lowercase, because those two symbols are represented by two different bytecodes in the codepage. That's true for any character encoding, whether it's ASCII, Unicode, etc. To get a case-insensitive hash, always call ToUpper() on the string before encoding it into bytes and hashing it.
3,823,961
I am using the following code for charater encoding of unicode charater. It is giving me the different string value of MD5EncryptedString when I use the value of the DataToEncrypt as 'abc' & 'ABC' ``` String DataToEncrypt="abc"; String MD5EncryptedString = String.Empty; MD5 md5 = new MD5CryptoServiceProvider(); Byte[] encodedBytes = ASCIIEncoding.Default.GetBytes(DataToEncrypt); // Byte[] encodedBytes = UTF8Encoding.Default.GetBytes(DataToEncrypt); encodedBytes = md5.ComputeHash(encodedBytes); MD5EncryptedString = BitConverter.ToString(encodedBytes); return MD5EncryptedString; ``` Is there any class instead of the ASCIIEncoding which will give me the case insensitive string means it will give me the value of the MD5EncryptedString same for both the 'abc' & 'ABC' for the DataToEncrypt variable ?
2010/09/29
[ "https://Stackoverflow.com/questions/3823961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265103/" ]
Translating character symbols to ordinals (bytes) will ALWAYS give you a different answer when you encode uppercase vs lowercase, because those two symbols are represented by two different bytecodes in the codepage. That's true for any character encoding, whether it's ASCII, Unicode, etc. To get a case-insensitive hash, always call ToUpper() on the string before encoding it into bytes and hashing it.
All character encodings encode upper and lower case letters using different bytes, so there is no way to get an encoding that will do that for you. You can always upper/lower case the string *before* hashing.
177,295
My daughter is in the process of buying her first home and she paid for an inspection. The inspector found that the joists under one of the bedrooms in the center of the house that sits on a basement foundation is sagging. We both have been told this is very easily fixed however I feel like she is getting ready to buy a problem. There are one inch holes drilled along the walls of the entire basement foundation and the ENTIRE underside of the floor system was “conveniently” covered in black plastic to where the inspector could not observe the flooring of the entire house. I have been researching and feel like it’s possible that the seller is trying to cover up at least termite damage if not something worse. Does anyone have any advice regarding this type of issue or had experience in the repair of?
2019/10/28
[ "https://diy.stackexchange.com/questions/177295", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/108535/" ]
Our lawnmower shipped with pins that look like this. [![enter image description here](https://i.stack.imgur.com/4IFvP.png)](https://i.stack.imgur.com/4IFvP.png) I took them off because I thought they were used because they were cheap (somebody at Sears was laughing all the way to the bank over the 1" less of spring steel rod they use per fastener. I switched to the *proper* kind, the ones you show in OP. They fell off at such a rate that I soon ran out of them, and was forced to go back to the original (here above) kind. They have been reliable. Hard to take off, but that appears to be the necessary compromise.
I spent some time driving tractors as a contractor and also repairing them, most of the agricultural suppliers had clips like both that you show with loops or chains to stop them getting lost. We also used to use zip ties aka cable ties to hold the free ends.
177,295
My daughter is in the process of buying her first home and she paid for an inspection. The inspector found that the joists under one of the bedrooms in the center of the house that sits on a basement foundation is sagging. We both have been told this is very easily fixed however I feel like she is getting ready to buy a problem. There are one inch holes drilled along the walls of the entire basement foundation and the ENTIRE underside of the floor system was “conveniently” covered in black plastic to where the inspector could not observe the flooring of the entire house. I have been researching and feel like it’s possible that the seller is trying to cover up at least termite damage if not something worse. Does anyone have any advice regarding this type of issue or had experience in the repair of?
2019/10/28
[ "https://diy.stackexchange.com/questions/177295", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/108535/" ]
I have a few trailers I rent out which use the pin with the snap-down ring -- the latter type pictured in the question. To avoid the pins being lost I made tethers from a length of 1/16" wire rope and crimp bands. Each tether fastens the ring part of the pin to the body of the trailer or door where the pin is used. Most are about 4-6 inches long. It's a balance between being long enough to make the pin easy to install or remove, yet short enough to keep it from being caught.
I spent some time driving tractors as a contractor and also repairing them, most of the agricultural suppliers had clips like both that you show with loops or chains to stop them getting lost. We also used to use zip ties aka cable ties to hold the free ends.
177,295
My daughter is in the process of buying her first home and she paid for an inspection. The inspector found that the joists under one of the bedrooms in the center of the house that sits on a basement foundation is sagging. We both have been told this is very easily fixed however I feel like she is getting ready to buy a problem. There are one inch holes drilled along the walls of the entire basement foundation and the ENTIRE underside of the floor system was “conveniently” covered in black plastic to where the inspector could not observe the flooring of the entire house. I have been researching and feel like it’s possible that the seller is trying to cover up at least termite damage if not something worse. Does anyone have any advice regarding this type of issue or had experience in the repair of?
2019/10/28
[ "https://diy.stackexchange.com/questions/177295", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/108535/" ]
Get some Velcro cable ties and attach them to the looped end of the R clip. When you install the R clip, turn the pin so the R clip is parallel to the cross-member and wrap the strap around.
I spent some time driving tractors as a contractor and also repairing them, most of the agricultural suppliers had clips like both that you show with loops or chains to stop them getting lost. We also used to use zip ties aka cable ties to hold the free ends.
3,312,009
Is it possible to use a XML element from other file in another XML? For instance, instead of having: ``` <document> <a><!-- huge content --></a> <b/> </document> ``` I would like to have: ``` <document> <a ref="aDef"/> <b/> </document> ``` Where is defined in its own XML and reused where needed. I would like this to be done by the parser and transparent to the application, the app would not be able to know if the element is a reference or a copy. How can i get this done?
2010/07/22
[ "https://Stackoverflow.com/questions/3312009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203801/" ]
This is what the [xinclude](http://www.w3.org/TR/xinclude/) W3C standard is for. Similar to the external entities approach (as in above answer), you can encode the content-to-be-included in a separate file, like e.g. (frag.xml): ``` <a><!-- huge content --></a> ``` In the main XML file, an xinclude instruction refers to this external content: ``` <document> <xi:include href="frag.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/> <b/> </document> ``` When processed with an (xinclude-capable) XML processor (like e.g. Xerces `http://xerces.apache.org/`), the parser will expand this xinclude instruction with the contents it points at. The inclusion target in the @href attribute is interpreted as a URI, so you can equally point to fragments using fragment identifiers (e.g. `href="frag.xml#fragment1`). Besides simple URIs in @href, the xinclude standard supports a very fine-grained vocabulary for expressing the inclusion target in a @xpointer attribute. However, support for complex XPointer expressions depends on the processor's XPointer compliance, which is generally underused. However, there's a (minimal) XSLT implementation as well: XIPr (`http://dret.net/projects/xipr/`).
This is one option: Fragment XML file (frag.xml): ``` <a><!-- huge content --></a> ``` Main XML file: ``` <!DOCTYPE document [ <!ENTITY aDef SYSTEM "frag.xml"> ]> <document> &aDef; <b/> </document> ```
1,481
Over the last days, I had a few attempts of vandalizing questions/answers in my "approve edit" queue. This morning, it was the user "gnu" for three times and I wonder what to do about this. Just rejecting the edit helps the immediate problem of course, but I feel this shouldn't be all. Edit: With Iain's help I got them back, so here are a few examples: * <https://serverfault.com/suggested-edits/1463> * <https://serverfault.com/suggested-edits/1464> * <https://serverfault.com/suggested-edits/1465>
2011/05/06
[ "https://meta.serverfault.com/questions/1481", "https://meta.serverfault.com", "https://meta.serverfault.com/users/8897/" ]
The edit > > sdfsfsdfsfsfsfsfsffsdfsfs df sf sf s f asf s fs df asf > > > convinced me that these edits were pretty intentional. So, in this case the user will be suspended for at least one day. Also, he'll receive a warning email. If there are similar cases, please just flag them and add a short explanation. Moderators will take care of them. *Thank you!*
Remember that if you get enough edit suggestion rejections, you cannot suggest edits for 7 days. This is enforced both by account and by IP address.
11,828,045
let's say I have a interface IPerson that expose a collection of another interface ICar. ICar is implemented by the Car class, and the IPerson is implemented by the Person class. I would like that Person could expose a collection of Car, and not of ICar, but this does not seem possible without changing the IPerson interface. Is there any other solution ? I would like to have the IPerson expose a collection of ICar, but I would also need a class implementing IPerson and exposind a collection of Car. Thanks
2012/08/06
[ "https://Stackoverflow.com/questions/11828045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1472131/" ]
I don't know if this solution will fit your needs, however depending on what language you are using, you could use a generic solution to achieve this kind of behavior. For example in java ``` interface IPerson<T extends ICar> { public T[] getCars(); // ... } ``` This will insure that the generic type `T` must implement `ICar`, then in your implementation of `Person` you can have ``` Class Person implements IPerson<Car> { Car[] cars; public Car[] getCars() { return cars; } // ... } ``` This will unfortunately not allow you to look at a collection of different `IPersons` together, since this is no longer an `IPerson` but an `IPerson<Car>`.
If I understood correctly you can just add a collection of type ICar to your Person class. Because a collection of ICar or Car are (ALMOST) the same thing.