qid
int64 1
74.7M
| question
stringlengths 15
55.4k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 2
32.4k
| response_k
stringlengths 9
40.5k
|
---|---|---|---|---|---|
6,590,117 | ```
Array
(
[n] => Unover
[i] => 250
)
Array
(
[n] => Un
[i] => 195
)
Array
(
[n] => Iliad
[i] => 110
)
```
They are in the form of $arr['Unover']['i'].
I'd like to sort them based on the i smallest to largest, can't figure how to do it without completely wrecking the array and no idea where to start.
Need to be able to get it into another array that I can just foreach through in orde | 2011/07/05 | [
"https://Stackoverflow.com/questions/6590117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/586712/"
] | I kept having the same problem, and none of the solutions I found above or anywhere else would work in the general case.
For example, the first answer above works only because the array is an array of strings. If it's an array of anything else, that solution breaks, and Write-Debug will output the object type, and not its value as one would expect.
Finally I found a general solution: The key point is to first convert the input object to a string using the Out-String command. Once everything is a string, the above solution works. Using "Out-String -stream" improves the output alignment.
Example:
```
PS C:\> gwmi win32_bios
SMBIOSBIOSVersion : 786F3 v01.34
Manufacturer : Hewlett-Packard
Name : Default System BIOS
SerialNumber : CZC8196Q8S
Version : HPQOEM - 20120709
PS C:\> gwmi win32_bios | ft -auto
SMBIOSBIOSVersion Manufacturer Name SerialNumber Version
----------------- ------------ ---- ------------ -------
786F3 v01.34 Hewlett-Packard Default System BIOS CZC8196Q8S HPQOEM - ...
PS C:\> $DebugPreference = "Continue"
PS C:\> gwmi win32_bios | ft -auto | Write-Debug
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.GroupEndData
PS C:\> gwmi win32_bios | ft -auto | Out-String | Write-Debug
DEBUG: SMBIOSBIOSVersion Manufacturer Name SerialNumber Version
----------------- ------------ ---- ------------ -------
786F3 v01.34 Hewlett-Packard Default System BIOS CZC8196Q8S HPQOEM - ...
PS C:\> gwmi win32_bios | ft | Out-String -stream | Write-Debug
DEBUG:
DEBUG: SMBIOSBIOSVersi Manufacturer Name SerialNumber Version
DEBUG: on
DEBUG: --------------- ------------ ---- ------------ -------
DEBUG: 786F3 v01.34 Hewlett-Packard Default Syst... CZC8196Q8S HPQOEM - 201...
DEBUG:
DEBUG:PS C:\>
``` | [`Write-Debug`](http://technet.microsoft.com/en-us/library/dd347714.aspx) is designed for outputting simple messages when debug preferences are set in a particular [way](http://ss64.com/ps/write-debug.html). It takes only a string, not just anything like `Write-Host` does (and magically formats). You will have to format your output yourself into a single string.
You could combine `Write-Host` and `Write-Debug` if you have extra info to output before prompting the user:
```
if ($DebugPreference -ne 'SilentlyContinue') {
Write-Host 'such-and-such array:' $array
}
Write-Debug 'such-and-such array dumped'
```
`Write-Host` is used because it will always write to the console host, rather than to the script's output, as `Write-Output` does. If you where redirecting standard output of the script to a file, `Write-Output` would end up in the file, while `Write-Host` would still be seen in the console.
You could also try doing something like this if your array is of simply enough types that an automatic call to `ToString()` on them (if they're not strings already) gets you what you want:
```
$array = 'Alice','Bob','Charlie'
Write-Debug ([String]::Join("`n", $array))
``` |
6,590,117 | ```
Array
(
[n] => Unover
[i] => 250
)
Array
(
[n] => Un
[i] => 195
)
Array
(
[n] => Iliad
[i] => 110
)
```
They are in the form of $arr['Unover']['i'].
I'd like to sort them based on the i smallest to largest, can't figure how to do it without completely wrecking the array and no idea where to start.
Need to be able to get it into another array that I can just foreach through in orde | 2011/07/05 | [
"https://Stackoverflow.com/questions/6590117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/586712/"
] | If you want write-debug to handle each one separately:
```
[string[]]$test = @("test1", "test2", "test3")
Write-Output $test
test1
test2
test3
$DebugPreference = "Inquire"
$test | Write-Debug
DEBUG: test1
DEBUG: test2
DEBUG: test3
``` | Write-Debug:
```
Write-Debug [-Message] <string> [<CommonParameters>]
```
It expects a string. It is unable to convert a string array to a string as the error says. The reason why it expects a string is because it `writes debug messages to the console from a script or command.`
Note that Write-Output and Write-Host take an object:
```
Write-Output [-InputObject] <PSObject[]> [<CommonParameters>]
```
and
```
Write-Host [[-Object] <Object>] ...
``` |
6,590,117 | ```
Array
(
[n] => Unover
[i] => 250
)
Array
(
[n] => Un
[i] => 195
)
Array
(
[n] => Iliad
[i] => 110
)
```
They are in the form of $arr['Unover']['i'].
I'd like to sort them based on the i smallest to largest, can't figure how to do it without completely wrecking the array and no idea where to start.
Need to be able to get it into another array that I can just foreach through in orde | 2011/07/05 | [
"https://Stackoverflow.com/questions/6590117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/586712/"
] | I kept having the same problem, and none of the solutions I found above or anywhere else would work in the general case.
For example, the first answer above works only because the array is an array of strings. If it's an array of anything else, that solution breaks, and Write-Debug will output the object type, and not its value as one would expect.
Finally I found a general solution: The key point is to first convert the input object to a string using the Out-String command. Once everything is a string, the above solution works. Using "Out-String -stream" improves the output alignment.
Example:
```
PS C:\> gwmi win32_bios
SMBIOSBIOSVersion : 786F3 v01.34
Manufacturer : Hewlett-Packard
Name : Default System BIOS
SerialNumber : CZC8196Q8S
Version : HPQOEM - 20120709
PS C:\> gwmi win32_bios | ft -auto
SMBIOSBIOSVersion Manufacturer Name SerialNumber Version
----------------- ------------ ---- ------------ -------
786F3 v01.34 Hewlett-Packard Default System BIOS CZC8196Q8S HPQOEM - ...
PS C:\> $DebugPreference = "Continue"
PS C:\> gwmi win32_bios | ft -auto | Write-Debug
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.GroupEndData
PS C:\> gwmi win32_bios | ft -auto | Out-String | Write-Debug
DEBUG: SMBIOSBIOSVersion Manufacturer Name SerialNumber Version
----------------- ------------ ---- ------------ -------
786F3 v01.34 Hewlett-Packard Default System BIOS CZC8196Q8S HPQOEM - ...
PS C:\> gwmi win32_bios | ft | Out-String -stream | Write-Debug
DEBUG:
DEBUG: SMBIOSBIOSVersi Manufacturer Name SerialNumber Version
DEBUG: on
DEBUG: --------------- ------------ ---- ------------ -------
DEBUG: 786F3 v01.34 Hewlett-Packard Default Syst... CZC8196Q8S HPQOEM - 201...
DEBUG:
DEBUG:PS C:\>
``` | Write-Debug:
```
Write-Debug [-Message] <string> [<CommonParameters>]
```
It expects a string. It is unable to convert a string array to a string as the error says. The reason why it expects a string is because it `writes debug messages to the console from a script or command.`
Note that Write-Output and Write-Host take an object:
```
Write-Output [-InputObject] <PSObject[]> [<CommonParameters>]
```
and
```
Write-Host [[-Object] <Object>] ...
``` |
6,590,117 | ```
Array
(
[n] => Unover
[i] => 250
)
Array
(
[n] => Un
[i] => 195
)
Array
(
[n] => Iliad
[i] => 110
)
```
They are in the form of $arr['Unover']['i'].
I'd like to sort them based on the i smallest to largest, can't figure how to do it without completely wrecking the array and no idea where to start.
Need to be able to get it into another array that I can just foreach through in orde | 2011/07/05 | [
"https://Stackoverflow.com/questions/6590117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/586712/"
] | I kept having the same problem, and none of the solutions I found above or anywhere else would work in the general case.
For example, the first answer above works only because the array is an array of strings. If it's an array of anything else, that solution breaks, and Write-Debug will output the object type, and not its value as one would expect.
Finally I found a general solution: The key point is to first convert the input object to a string using the Out-String command. Once everything is a string, the above solution works. Using "Out-String -stream" improves the output alignment.
Example:
```
PS C:\> gwmi win32_bios
SMBIOSBIOSVersion : 786F3 v01.34
Manufacturer : Hewlett-Packard
Name : Default System BIOS
SerialNumber : CZC8196Q8S
Version : HPQOEM - 20120709
PS C:\> gwmi win32_bios | ft -auto
SMBIOSBIOSVersion Manufacturer Name SerialNumber Version
----------------- ------------ ---- ------------ -------
786F3 v01.34 Hewlett-Packard Default System BIOS CZC8196Q8S HPQOEM - ...
PS C:\> $DebugPreference = "Continue"
PS C:\> gwmi win32_bios | ft -auto | Write-Debug
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.GroupStartData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
DEBUG: Microsoft.PowerShell.Commands.Internal.Format.GroupEndData
PS C:\> gwmi win32_bios | ft -auto | Out-String | Write-Debug
DEBUG: SMBIOSBIOSVersion Manufacturer Name SerialNumber Version
----------------- ------------ ---- ------------ -------
786F3 v01.34 Hewlett-Packard Default System BIOS CZC8196Q8S HPQOEM - ...
PS C:\> gwmi win32_bios | ft | Out-String -stream | Write-Debug
DEBUG:
DEBUG: SMBIOSBIOSVersi Manufacturer Name SerialNumber Version
DEBUG: on
DEBUG: --------------- ------------ ---- ------------ -------
DEBUG: 786F3 v01.34 Hewlett-Packard Default Syst... CZC8196Q8S HPQOEM - 201...
DEBUG:
DEBUG:PS C:\>
``` | If you want write-debug to handle each one separately:
```
[string[]]$test = @("test1", "test2", "test3")
Write-Output $test
test1
test2
test3
$DebugPreference = "Inquire"
$test | Write-Debug
DEBUG: test1
DEBUG: test2
DEBUG: test3
``` |
65,105,209 | ![Else is executed](https://i.stack.imgur.com/Px5Xg.png)
the if else statement is not working for me | 2020/12/02 | [
"https://Stackoverflow.com/questions/65105209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14747792/"
] | ```
print('Hello There')
number=int(input('please provide a number'))
if number%2==0:
print ('even')
else:
print('odd')
```
Just read about the `modulus %` | `/` is the division operator. If you want to check for evenness vs oddness, you should be looking at the remainder, and using the module (`%`) operator:
```py
if number % 2 == 0:
print("even")
else:
print("odd")
``` |
44,868,612 | I'm doing a project in MapReduce using Amazon Web Services and I'm having this error:
>
> FATAL [main] org.apache.hadoop.mapred.YarnChild: Error running child :
> java.lang.StackOverflowError at
> java.util.regex.Pattern$GroupHead.match(Pattern.java:4658)
>
>
>
I read a few other questions to understand why this happened and it seems my regex has repetitive alternative paths. This is the regex:
```
\\s+(?=(?:(?<=[a-zA-Z])\"(?=[A-Za-z])|\"[^\"]*\"|[^\"])*$)
```
What it does is that it splits by space except when they are inside these symbols `< >` or these `" "`. So basically takes strings that are inside those 2 types of symbol. I have tried many other versions but none works, so I am far away from an optimal one. I am kind of lost and it's the first time Im using these complicated regexs. Can someone please give a better option for my regex?
I would truly appreciate every feedback regarding this!
EDIT:
This string with URLs inside <> and text inside "" and spaces:
<\janhaeussler.com/?sioc\_type=user&sioc\_id=1/> "HEY" <.org/1999/02/22-rdf-syntax-ns#type/>
should produce these 3 Strings:
1. <\janhaeussler.com/?sioc\_type=user&sioc\_id=1/> (with or without <>)
2. "HEY"
3. <.org/1999/02/22-rdf-syntax-ns#type/>
EDIT 2:
I think the symbols <> are confusing. I am trying to find a regex that splits by one or more spaces without taking into consideration the spaces inside " ", since the urls do not have spaces. | 2017/07/02 | [
"https://Stackoverflow.com/questions/44868612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182830/"
] | Try this:
```
\s+(?=(?:(?:[^"]*"){2})*[^"]*$)
```
[Demo](https://regex101.com/r/fn1IoR/2/)
```
String string = "abc d<\\janhaeussler.com/?sioc_type=user &sioc_id=1/> \"HEY 1\" 2 3 <.org/1999/02/22-rdf-syntax-ns#type/> \"tra la\" <asdfadsf sadfasdf/> 4 \"sdf sdf\" 5 6";
String[] res=string.split("\\s+(?=(?:(?:[^\"]*\"){2})*[^\"]*$)");
System.out.println(Arrays.toString(res));
```
Will output:
```
[abc, d<\janhaeussler.com/?sioc_type=user, &sioc_id=1/>, "HEY 1", 2, 3, <.org/1999/02/22-rdf-syntax-ns#type/>, "tra la", <asdfadsf, sadfasdf/>, 4, "sdf sdf", 5, 6]
``` | Don't use `split()`. Use a `find()` loop instead, with this regex:
```none
(?:<[^<]*>
|
"[^"]*"
|
\S
)+
```
Example:
```
String input = "<\\janhaeussler.com/?sioc_type=user&sioc_id=1/> \"HEY\" <.org/1999/02/22-rdf-syntax-ns#type/>";
Pattern p = Pattern.compile("(?:<[^<]*>|\"[^\"]*\"|\\S)+");
for (Matcher m = p.matcher(input); m.find(); ) {
System.out.println(m.group());
}
```
*Output*
```none
<\janhaeussler.com/?sioc_type=user&sioc_id=1/>
"HEY"
<.org/1999/02/22-rdf-syntax-ns#type/>
``` |
44,868,612 | I'm doing a project in MapReduce using Amazon Web Services and I'm having this error:
>
> FATAL [main] org.apache.hadoop.mapred.YarnChild: Error running child :
> java.lang.StackOverflowError at
> java.util.regex.Pattern$GroupHead.match(Pattern.java:4658)
>
>
>
I read a few other questions to understand why this happened and it seems my regex has repetitive alternative paths. This is the regex:
```
\\s+(?=(?:(?<=[a-zA-Z])\"(?=[A-Za-z])|\"[^\"]*\"|[^\"])*$)
```
What it does is that it splits by space except when they are inside these symbols `< >` or these `" "`. So basically takes strings that are inside those 2 types of symbol. I have tried many other versions but none works, so I am far away from an optimal one. I am kind of lost and it's the first time Im using these complicated regexs. Can someone please give a better option for my regex?
I would truly appreciate every feedback regarding this!
EDIT:
This string with URLs inside <> and text inside "" and spaces:
<\janhaeussler.com/?sioc\_type=user&sioc\_id=1/> "HEY" <.org/1999/02/22-rdf-syntax-ns#type/>
should produce these 3 Strings:
1. <\janhaeussler.com/?sioc\_type=user&sioc\_id=1/> (with or without <>)
2. "HEY"
3. <.org/1999/02/22-rdf-syntax-ns#type/>
EDIT 2:
I think the symbols <> are confusing. I am trying to find a regex that splits by one or more spaces without taking into consideration the spaces inside " ", since the urls do not have spaces. | 2017/07/02 | [
"https://Stackoverflow.com/questions/44868612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182830/"
] | Try this:
```
\s+(?=(?:(?:[^"]*"){2})*[^"]*$)
```
[Demo](https://regex101.com/r/fn1IoR/2/)
```
String string = "abc d<\\janhaeussler.com/?sioc_type=user &sioc_id=1/> \"HEY 1\" 2 3 <.org/1999/02/22-rdf-syntax-ns#type/> \"tra la\" <asdfadsf sadfasdf/> 4 \"sdf sdf\" 5 6";
String[] res=string.split("\\s+(?=(?:(?:[^\"]*\"){2})*[^\"]*$)");
System.out.println(Arrays.toString(res));
```
Will output:
```
[abc, d<\janhaeussler.com/?sioc_type=user, &sioc_id=1/>, "HEY 1", 2, 3, <.org/1999/02/22-rdf-syntax-ns#type/>, "tra la", <asdfadsf, sadfasdf/>, 4, "sdf sdf", 5, 6]
``` | You could try to match: tags OR what's between the double quotes OR the remaining non-whitespaces.
```
<[^>]+>|"[^"]+"|\S+
```
For example:
```
String str = "<\\janhaeussler.com/?sioc_type=user&sioc_id=1/> \"HEY\" YOU! \"How Are You?\" <.org/1999/02/22-rdf-syntax-ns#type/>";
final java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("<[^>]+>|\"[^\"]+\"|\\S+");
java.util.regex.Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("match: " + matcher.group(0));
}
```
Prints:
```
match: <\janhaeussler.com/?sioc_type=user&sioc_id=1/>
match: "HEY"
match: YOU!
match: "How Are You?"
match: <.org/1999/02/22-rdf-syntax-ns#type/>
``` |
25,866,078 | I am trying to read txt file using `RandomAccessFile` and `FileChannel` which contains large number of float / integer values, but at after the all conversations using `ByteBuffer` the values which I get as a result are not the same with the ones in txt file. Here is how I am doing it :
```
RandomAccessFile mRandomFile = new RandomAccessFile(Environment.getExternalStorageDirectory() + "/Models/vertices.txt", "rw");
FileChannel mInChannel = mRandomFile.getChannel();
ByteBuffer mBuffer = ByteBuffer.allocate(181017 * 4);
mBuffer.clear();
mInChannel.read(mBuffer);
mBuffer.rewind();
FloatBuffer mFloatBUffer = mBuffer.asFloatBuffer();
mFloatBUffer.get(VERTS);
mInChannel.close();
for (int i = 0; i < 20; i++) {
Log.d("", "VALUE: " + VERTS[i]);
}
```
The values in txt file are presented in this way (they are separated with a new line):
```
-36.122300
-6.356030
-46.876744
-36.122303
-7.448818
-46.876756
-36.122303
-7.448818
81.123221
-36.122300
-6.356030
81.123209
36.817676
-6.356030
-46.876779
36.817676
-7.448818
-46.876779
-36.122303
-7.448818
```
and the values which I am getting in `for` are:
```
VALUE: 1.0187002E-11
VALUE: 2.5930944E-9
VALUE: 6.404289E-10
VALUE: 2.5957827E-6
VALUE: 2.6255839E-6
VALUE: 8.339467E-33
VALUE: 4.1885793E-11
VALUE: 1.0740952E-5
VALUE: 1.0187002E-11
VALUE: 2.5930944E-9
VALUE: 6.513428E-10
VALUE: 1.0383363E-5
VALUE: 4.3914857E-5
VALUE: 8.339467E-33
VALUE: 4.1885793E-11
VALUE: 1.0801023E-5
VALUE: 1.0187002E-11
VALUE: 2.5930944E-9
VALUE: 6.513428E-10
VALUE: 1.0383363E-5
```
Any ideas, suggestions what I am missing here? | 2014/09/16 | [
"https://Stackoverflow.com/questions/25866078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1511776/"
] | It is a text file, not a random access file. You should be reading with a `BufferedReader`. It´s got a `readLine()` that returns a String, and then you can just go with `Double.valueOf(String)`.
There´s more code here [How to use Buffered Reader in Java](https://stackoverflow.com/questions/16265693/how-to-use-buffered-reader-in-java) | Android-Developer again, i see you try the binary-file-approach... to do this you must convert your data
Create a **new** Java-Project and use your original methods there to load the the values from a xml/text-file and convert it into floats... (yes, it will take some time then, but it provided valid data...) once you have the data inside your application store your floats into a file named floats.bin (using a FileWriter).
Go then and copy the file floats.bin into your Android Project and try to load it there with your code from above (looks good in my opinion)...
(referring to [Android fastest way of reading big arrays of variables](https://stackoverflow.com/questions/25845929/android-fastest-way-of-reading-big-arrays-of-variables/25846974#25846974))
after sleeping one night over your problem i think you can
* either distract the user and load the data before you show your models...
* or you can show the model while you are loading - and let the user see your progress and see the model growing with each second....
* or you can split your data into seperate chunks from coarse to fine and load first the coarse data and show it - then you load into background the finer and finer data and add it piece by piece into your model... |
51,886,330 | In my project I have included a third-party bundle via composer containing multiple forms like:
```
namespace acme\ContactBundle\Form\Type;
class PersonType extends AbstractType {
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('firstname', TextType::class, array(
'label' => 'person.firstname'
))
->add('lastname', TextType::class, array(
'label' => 'person.lastname'
));
}
}
```
Now I would like to add an additional field *before* `firstname` called `title`.
Is there a way to do this without touching the original code? Probably, I also need to alter the entity to add the additional database field.
Alternatively: Since I have write access to the third-party bundle, maybe there's a way to allow fields to be injected? | 2018/08/16 | [
"https://Stackoverflow.com/questions/51886330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That's is because you are using : `Dart version 2.1.0-dev.0.0.flutter-be6309690f` and the plugin named `flutter_circular_chart` has a `constraint`
<https://github.com/xqwzts/flutter_circular_chart/blob/master/pubspec.yaml>
```
environment:
sdk: '>=1.19.0 <2.0.0'
```
You can fork the project and update the sdk constraint and ref to your repository:
Like this:
```
flutter_circular_chart:
git: https://github.com/your_repo/flutter_circular_chart.git
```
**Note**
Also would be fine if you open an issue in their repo to notify the devs about the issue that you have. | Use devendency\_override with same version witch need for same for other dependency.
Like google\_maps\_flutter: ^0.5.28+1 needs intl to be 0.16.0
then craete dependency\_overrides:
intl: ^0.16.0
below of dev\_dependencies:
flutter\_test:
sdk: flutter
run project until it not run on device.
Enjoy. Thanks.. |
12,015,139 | I'm having some cookie/oauth issues. What I'm trying to achieve is have a new tab open up, have the user go through google's oauth flow, and upon returning to the app they should be able to make requests to our api with the cookie they receive, but.. I have no idea how to save that cookie. If I go into chrome's inspect tool I can see the cookie in the resources tab, but anything done with forge or angularjs (the js framework I'm using) doesn't include the cookie, and due to browser security I can't set it manually. Any help? | 2012/08/18 | [
"https://Stackoverflow.com/questions/12015139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434445/"
] | Why do you have to save it as a cookie? You have localStorage (or [forge.prefs](http://docs.trigger.io/en/v1.4/modules/prefs.html?highlight=prefs#prefs.set), but not sure how those work exactly).
You're in a mobile app, so the security of localStorage isn't a worry. | I use angular-storage. It is perfect for storing the token.
<https://github.com/auth0/angular-storage>
To save your token after login:
```
store.set('jwt', data.token);
store.set('user', jwtHelper.decodeToken(store.get('jwt')));
```
Then to check if your token is valid:
```
.run(function($rootScope, $state, store, jwtHelper) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (toState.data && toState.data.requiresLogin) {
store.set('redirect', {state: toState.name, stateParams: toParams});
//TODO This is never passing but still redirecting?
if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
event.preventDefault();
$state.go('login');
}
}
});
})
``` |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | As much as I love the shell, it’s unforgiving with wildcards and spaces in general and worse if your script gets to folders you didn’t expect. Your case of all within one folder and no recursion limits your risk to [script this cleanly](https://apple.stackexchange.com/a/448509/5472).
To prepare, empty trash (so you can easily see / reverse this if needed) and consider making a backup - great advice any time you are about to automate destruction of thousands of files right next to ones you hope to retain.
In finder, search for space 2.ext with quotes. Select search in your folder to ensure you’re not searching everywhere and count the results.
**“ 2.ext”**
* `Command` + `A`
* `Command` + `Delete` | In Terminal, `rm *\ 2.ext` should work.
PS: To be sure that the correct files get deleted, run `ls *\ 2.ext` first, or use `rm -i *\ 2.ext` to be prompted for each file. |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | [nohillside's answer](https://apple.stackexchange.com/a/448509) to use `rm *\ 2.ext` will work just fine, but if you want extra confidence it's doing the right thing, you can instead use
```
mkdir to_be_deleted
mv -- *\ 2.ext to_be_deleted
```
That'll put all the files you want deleted in a separate folder - you can then use finder (or whatever) to check which files are still in the original folder, and which ones have been moved. When you're happy it looks good, delete the `to_be_deleted` folder.
*Thanks to fd0 for suggesting the initial `--` argument.* | In Terminal, `rm *\ 2.ext` should work.
PS: To be sure that the correct files get deleted, run `ls *\ 2.ext` first, or use `rm -i *\ 2.ext` to be prompted for each file. |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | In Terminal, `rm *\ 2.ext` should work.
PS: To be sure that the correct files get deleted, run `ls *\ 2.ext` first, or use `rm -i *\ 2.ext` to be prompted for each file. | As noted by others, there might be issues here with shell scripting depending on how the duplicates were made. You could theoretically avoid those by copying the folder and trying it first, but the only way to totally verify is if you went through them by hand which somewhat defeats the purpose.
This is a Python file I use for similar deduplication that I might have. It scans the folder for files by using their sha256, retains the highest file name alphabetically (which should generally keep the cleaner file names) and deletes the others. You can change the dry\_run variable on the 3rd to last line to true like this:
```
if __name__ == '__main__':
d = Deduplicator(path, dry_run=True)
d.deduplicate()
```
To verify that the files you want to delete are actually what are going to be deleted. And, of course, change line 4 from /path/to/your/files to the actual directory where the files are.
To run, on a mac you should simply be able to run:
```
python /path/to/your/deduplicate.py
```
Where /path/to/your/script is wherever you save this .py file. Basically, put the following in a text file and name it deduplicate.py:
```
import os
import hashlib
path = '/path/to/your/files'
class Deduplicator:
def __init__(self, path, dry_run=True):
self.path = path
self.file_dict = dict()
self.dry_run = dry_run
def deduplicate(self):
self.get_files()
self.clean_files()
def get_file_hash(self, file_path):
with open(file_path, 'rb') as f:
file = f.read()
hash = hashlib.sha256(file).hexdigest()
return hash
def get_files(self):
# Loop through the directory
for file in os.listdir(path):
# Get the file hash
hash = self.get_file_hash(os.path.join(self.path, file))
# If we haven't seen the hash yet, go ahead and initiate the list
if not self.file_dict.get(hash):
self.file_dict[hash] = list()
# Then add this filename to that hashed value
self.file_dict[hash].append(file)
def clean_files(self):
for hash, file_names in self.file_dict.items():
file_names.sort(reverse=True)
files_to_delete = file_names[:-1]
print(f"File to keep: {file_names[0]}")
print(f'Files to delete: {files_to_delete}')
print('-'*50)
if not self.dry_run:
for file in files_to_delete:
full_path = os.path.join(path,file)
print(f"...deleting: {full_path}")
os.remove(full_path)
if __name__ == '__main__':
d = Deduplicator(path, dry_run=False)
d.deduplicate()
``` |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | In Terminal, `rm *\ 2.ext` should work.
PS: To be sure that the correct files get deleted, run `ls *\ 2.ext` first, or use `rm -i *\ 2.ext` to be prompted for each file. | A very unpopular opinion is to use a dedicated duplicate removal software rather than trying to mess up with terminal. Even if you are pro-terminal user you might end up deleting important files.
There are few reasons.
1. Softwares are developed after succeeding a lot of cases.
2. They compare file content rather than relying on file name only.
3. They provide an interface that draw attention to important details. |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | As much as I love the shell, it’s unforgiving with wildcards and spaces in general and worse if your script gets to folders you didn’t expect. Your case of all within one folder and no recursion limits your risk to [script this cleanly](https://apple.stackexchange.com/a/448509/5472).
To prepare, empty trash (so you can easily see / reverse this if needed) and consider making a backup - great advice any time you are about to automate destruction of thousands of files right next to ones you hope to retain.
In finder, search for space 2.ext with quotes. Select search in your folder to ensure you’re not searching everywhere and count the results.
**“ 2.ext”**
* `Command` + `A`
* `Command` + `Delete` | [nohillside's answer](https://apple.stackexchange.com/a/448509) to use `rm *\ 2.ext` will work just fine, but if you want extra confidence it's doing the right thing, you can instead use
```
mkdir to_be_deleted
mv -- *\ 2.ext to_be_deleted
```
That'll put all the files you want deleted in a separate folder - you can then use finder (or whatever) to check which files are still in the original folder, and which ones have been moved. When you're happy it looks good, delete the `to_be_deleted` folder.
*Thanks to fd0 for suggesting the initial `--` argument.* |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | As much as I love the shell, it’s unforgiving with wildcards and spaces in general and worse if your script gets to folders you didn’t expect. Your case of all within one folder and no recursion limits your risk to [script this cleanly](https://apple.stackexchange.com/a/448509/5472).
To prepare, empty trash (so you can easily see / reverse this if needed) and consider making a backup - great advice any time you are about to automate destruction of thousands of files right next to ones you hope to retain.
In finder, search for space 2.ext with quotes. Select search in your folder to ensure you’re not searching everywhere and count the results.
**“ 2.ext”**
* `Command` + `A`
* `Command` + `Delete` | As noted by others, there might be issues here with shell scripting depending on how the duplicates were made. You could theoretically avoid those by copying the folder and trying it first, but the only way to totally verify is if you went through them by hand which somewhat defeats the purpose.
This is a Python file I use for similar deduplication that I might have. It scans the folder for files by using their sha256, retains the highest file name alphabetically (which should generally keep the cleaner file names) and deletes the others. You can change the dry\_run variable on the 3rd to last line to true like this:
```
if __name__ == '__main__':
d = Deduplicator(path, dry_run=True)
d.deduplicate()
```
To verify that the files you want to delete are actually what are going to be deleted. And, of course, change line 4 from /path/to/your/files to the actual directory where the files are.
To run, on a mac you should simply be able to run:
```
python /path/to/your/deduplicate.py
```
Where /path/to/your/script is wherever you save this .py file. Basically, put the following in a text file and name it deduplicate.py:
```
import os
import hashlib
path = '/path/to/your/files'
class Deduplicator:
def __init__(self, path, dry_run=True):
self.path = path
self.file_dict = dict()
self.dry_run = dry_run
def deduplicate(self):
self.get_files()
self.clean_files()
def get_file_hash(self, file_path):
with open(file_path, 'rb') as f:
file = f.read()
hash = hashlib.sha256(file).hexdigest()
return hash
def get_files(self):
# Loop through the directory
for file in os.listdir(path):
# Get the file hash
hash = self.get_file_hash(os.path.join(self.path, file))
# If we haven't seen the hash yet, go ahead and initiate the list
if not self.file_dict.get(hash):
self.file_dict[hash] = list()
# Then add this filename to that hashed value
self.file_dict[hash].append(file)
def clean_files(self):
for hash, file_names in self.file_dict.items():
file_names.sort(reverse=True)
files_to_delete = file_names[:-1]
print(f"File to keep: {file_names[0]}")
print(f'Files to delete: {files_to_delete}')
print('-'*50)
if not self.dry_run:
for file in files_to_delete:
full_path = os.path.join(path,file)
print(f"...deleting: {full_path}")
os.remove(full_path)
if __name__ == '__main__':
d = Deduplicator(path, dry_run=False)
d.deduplicate()
``` |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | As much as I love the shell, it’s unforgiving with wildcards and spaces in general and worse if your script gets to folders you didn’t expect. Your case of all within one folder and no recursion limits your risk to [script this cleanly](https://apple.stackexchange.com/a/448509/5472).
To prepare, empty trash (so you can easily see / reverse this if needed) and consider making a backup - great advice any time you are about to automate destruction of thousands of files right next to ones you hope to retain.
In finder, search for space 2.ext with quotes. Select search in your folder to ensure you’re not searching everywhere and count the results.
**“ 2.ext”**
* `Command` + `A`
* `Command` + `Delete` | A very unpopular opinion is to use a dedicated duplicate removal software rather than trying to mess up with terminal. Even if you are pro-terminal user you might end up deleting important files.
There are few reasons.
1. Softwares are developed after succeeding a lot of cases.
2. They compare file content rather than relying on file name only.
3. They provide an interface that draw attention to important details. |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | [nohillside's answer](https://apple.stackexchange.com/a/448509) to use `rm *\ 2.ext` will work just fine, but if you want extra confidence it's doing the right thing, you can instead use
```
mkdir to_be_deleted
mv -- *\ 2.ext to_be_deleted
```
That'll put all the files you want deleted in a separate folder - you can then use finder (or whatever) to check which files are still in the original folder, and which ones have been moved. When you're happy it looks good, delete the `to_be_deleted` folder.
*Thanks to fd0 for suggesting the initial `--` argument.* | As noted by others, there might be issues here with shell scripting depending on how the duplicates were made. You could theoretically avoid those by copying the folder and trying it first, but the only way to totally verify is if you went through them by hand which somewhat defeats the purpose.
This is a Python file I use for similar deduplication that I might have. It scans the folder for files by using their sha256, retains the highest file name alphabetically (which should generally keep the cleaner file names) and deletes the others. You can change the dry\_run variable on the 3rd to last line to true like this:
```
if __name__ == '__main__':
d = Deduplicator(path, dry_run=True)
d.deduplicate()
```
To verify that the files you want to delete are actually what are going to be deleted. And, of course, change line 4 from /path/to/your/files to the actual directory where the files are.
To run, on a mac you should simply be able to run:
```
python /path/to/your/deduplicate.py
```
Where /path/to/your/script is wherever you save this .py file. Basically, put the following in a text file and name it deduplicate.py:
```
import os
import hashlib
path = '/path/to/your/files'
class Deduplicator:
def __init__(self, path, dry_run=True):
self.path = path
self.file_dict = dict()
self.dry_run = dry_run
def deduplicate(self):
self.get_files()
self.clean_files()
def get_file_hash(self, file_path):
with open(file_path, 'rb') as f:
file = f.read()
hash = hashlib.sha256(file).hexdigest()
return hash
def get_files(self):
# Loop through the directory
for file in os.listdir(path):
# Get the file hash
hash = self.get_file_hash(os.path.join(self.path, file))
# If we haven't seen the hash yet, go ahead and initiate the list
if not self.file_dict.get(hash):
self.file_dict[hash] = list()
# Then add this filename to that hashed value
self.file_dict[hash].append(file)
def clean_files(self):
for hash, file_names in self.file_dict.items():
file_names.sort(reverse=True)
files_to_delete = file_names[:-1]
print(f"File to keep: {file_names[0]}")
print(f'Files to delete: {files_to_delete}')
print('-'*50)
if not self.dry_run:
for file in files_to_delete:
full_path = os.path.join(path,file)
print(f"...deleting: {full_path}")
os.remove(full_path)
if __name__ == '__main__':
d = Deduplicator(path, dry_run=False)
d.deduplicate()
``` |
448,554 | I use my AirPods Pro 2 for both my MacBook but also on another device. What I notice is that when my MacBook is asleep, but I take out my AirPods, it will cause my MacBook to wake up.
I looked through the settings in my MacBook but I only see the basic bluetooth options for the AirPods. I can't seem to find a setting to ensure my MacBook doesn't auto-wake up from AirPods or any Bluetooth item. | 2022/10/03 | [
"https://apple.stackexchange.com/questions/448554",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/473526/"
] | [nohillside's answer](https://apple.stackexchange.com/a/448509) to use `rm *\ 2.ext` will work just fine, but if you want extra confidence it's doing the right thing, you can instead use
```
mkdir to_be_deleted
mv -- *\ 2.ext to_be_deleted
```
That'll put all the files you want deleted in a separate folder - you can then use finder (or whatever) to check which files are still in the original folder, and which ones have been moved. When you're happy it looks good, delete the `to_be_deleted` folder.
*Thanks to fd0 for suggesting the initial `--` argument.* | A very unpopular opinion is to use a dedicated duplicate removal software rather than trying to mess up with terminal. Even if you are pro-terminal user you might end up deleting important files.
There are few reasons.
1. Softwares are developed after succeeding a lot of cases.
2. They compare file content rather than relying on file name only.
3. They provide an interface that draw attention to important details. |
30,742,889 | Can't figure out how to get this work:
```
//Have a tiny CustomServiceLoader implementation
public class MyServiceLoader {
static private Map<Class<?>, Class<?>> CONTENTS = new HashMap<>();
static public <S, T extends S> void registerClassForInterface(Class<T> c, Class<S> i) {
if (c == null) {
CONTENTS.remove(i);
} else {
CONTENTS.put(c, i);
}
}
static public <S, T extends S> Class<T> getClassForInterface(Class<S> i) {
return (Class<T>)CONTENTS.get(i);
}
}
```
Usage:
```
// classes registration works perfect event check for interface conformance (e.g. T extends S really works here!):
MyServiceLoader.registerClassForInterface(Model.class, APIAsyncLoaderTask.class);
// but I can't figure out how to instantiate a class returned from my service loader:
Class c = GiftdServiceLoader.getClassForInterface(APIAsyncLoaderTask.class);
mLoaderTask = c.newInstance(); // 'new c();' also couldn't work
```
And compiler error:
![incompatible types compiler error](https://i.stack.imgur.com/7234z.png)
also I have a strange tip for that method which is
```
public final Class<T> extends Object implements Serializable, AnnotatedElement, GenericDeclaration, Type
```
But I cannot see my interface there. I'm getting same when using both: **abstract class + class** and **interface + class**
**How do I make it work properly? I'm wondering is it at least possible?** | 2015/06/09 | [
"https://Stackoverflow.com/questions/30742889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1823351/"
] | You're using the raw type `Class`.
```
Class c = GiftdServiceLoader.getClassForInterface(APIAsyncLoaderTask.class);
```
All generatic types and generic type parameters in any method invoked on such a reference are erased.
Parameterize it correctly
```
Class<APIAsyncLoaderTask> c = MyServiceLoader.getClassForInterface(APIAsyncLoaderTask.class);
```
Note that you should use only the interface type if you aren't sure of what you'll be receiving from the call to `getClassForInterface`.
For example, I can do
```
MyServiceLoader.registerClassForInterface(NotModel.class, APIAsyncLoaderTask.class);
// but I can't figure out how to instantiate a class returned from my service loader:
Class<Model> c = MyServiceLoader.getClassForInterface(APIAsyncLoaderTask.class);
Model mLoaderTask = c.newInstance(); // 'new c();' also couldn't work
```
and it will fail with a `ClassCastException`.
Generics are not powerful enough to prevent this.
---
I believe you meant to have
```
CONTENTS.put(i, c);
```
in your `registerClassForInterface` method. | You have the raw form of the `Class` class in the preceding line:
```
Class c = GiftdServiceLoader.getClassForInterface(APIAsyncLoaderTask.class);
```
Therefore, the `newInstance()` method returns an `Object`, which can't be assigned to an `APIAsyncLoaderTask`.
But coming out of a `Map<Class<?>, Class<?>>`, the best you can do with generics is `Class<?> c = ...`, and `newInstance` still returns an `Object`. You don't have the information at compile time to determine if the `Class` `c` represents an `APIAsyncLoaderTask`.
However, you can enforce an upper bound on the value of the `HashMap`.
```
static private Map<Class<?>, Class<? extends APIAsyncLoaderTask>> CONTENTS = new HashMap<>();
```
Your `registerClassForInterface` method will need that upper bound also.
```
static public <S extends APIAsyncLoaderTask, T extends S> void registerClassForInterface(
Class<T> c, Class<S> i) {
```
Then you can `get` a `Class<? extends APIAsyncLoaderTask>` out of the `HashMap`, and `newInstance()` will return the erasure of the upper bound -- an `APIAsyncLoaderTask`. |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You have not allocated any memory to `str`. So you are trying to essentially write to a pointer which cannot hold the string. Essentially this leads to an Undefined Behavior and a seg fault.
The solution is:
You should use **[std::string](http://www.google.co.in/url?sa=t&rct=j&q=std::string&source=web&cd=1&ved=0CCUQFjAA&url=http://www.cplusplus.com/reference/string/string/&ei=Nr26Tt-9AYXMhAeKuf27Bw&usg=AFQjCNHYSO65lBUum_PPFu0nJcwzb0EW9w)** instead of pointer.
```
std::string str;
std::cout<<"please enter string : ";
std::cin >>str;
```
Also, try not to mix C and C++.
Use `streams` in C++ not `printf`
---
Alternatively, there are 2 other approaches:
**Not so good other Approach 1:**
You can allocate memory to `str` by making it an fixed size array:
```
#define MAX_INPUT 256
char str[MAX_INPUT]={0};
```
**Drawback:**
This would require that you need to know the length of the maximum input that user can enter at compile time, Since **[Variable Length Arrays](https://stackoverflow.com/questions/1887097/variable-length-arrays-in-c)** are not allowed in C++.
**Not so good other Approach 2:**
You could allocate memory dynamically to `str` using `new []`.`str` will be a pointer in this case.
```
#define MAX_INPUT 256
char *str = new char[MAX_INPUT];
```
**Drawback:**
Again this approach has the drawback of knowing how much memory to allocate at compile time in this case,since user inputs the string. Also, You need to remember to deallocate by calling `delete[]` or you leak memory.
Also, try to avoid using `new` as much as possible in C++.
**Conclusion:**
Best solution here is to use `std::string` because it saves you from all above problems. | Segmentation faults occur when a program accesses memory that doesn't belong to it. The pointer `str` is not initialized. It doesn't point at any memory. The stream-extraction operator `>>` doesn't allocate new memory for the string it reads; it expects the pointer to already point to a buffer that it can fill. It doesn't know that `str` is garbage, though. It assumes it's a valid pointer and attempts to write into that memory. Since the memory at that garbage address doesn't belong to your program, the OS halts it with a segmentation fault.
Read into a `std::string` instead. Better yet, use `std::getline` so the user can enter a string with spaces; the `>>` operator will only read up to the first whitespace character.
```
std::string str;
std::getline(cin, str);
``` |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You should use `std::string` instead.
Your declaration:
```
char * str;
```
declares only a pointer, but does not allocate a memory region for the string to be stored. The solutions could have been
```
char str[256];
```
or
```
char * str = new char[256];
```
However, they are *very* bad style because you would then have to check and control the size of input each time you want to write to it.
C++ provides `std::string` to store strings. Use it. | Use `std::string`.
Or, if you just want to use char \* (discouraged):
```
char * str = new char[256];
cin >> str;
``` |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You should use `std::string` instead.
Your declaration:
```
char * str;
```
declares only a pointer, but does not allocate a memory region for the string to be stored. The solutions could have been
```
char str[256];
```
or
```
char * str = new char[256];
```
However, they are *very* bad style because you would then have to check and control the size of input each time you want to write to it.
C++ provides `std::string` to store strings. Use it. | You need to allocate memory first for `str`. You declared only a pointer
```
char* str = (char*)malloc(MAX_SIZE_OF_BUFFER);
``` |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You have not allocated any memory to `str`. So you are trying to essentially write to a pointer which cannot hold the string. Essentially this leads to an Undefined Behavior and a seg fault.
The solution is:
You should use **[std::string](http://www.google.co.in/url?sa=t&rct=j&q=std::string&source=web&cd=1&ved=0CCUQFjAA&url=http://www.cplusplus.com/reference/string/string/&ei=Nr26Tt-9AYXMhAeKuf27Bw&usg=AFQjCNHYSO65lBUum_PPFu0nJcwzb0EW9w)** instead of pointer.
```
std::string str;
std::cout<<"please enter string : ";
std::cin >>str;
```
Also, try not to mix C and C++.
Use `streams` in C++ not `printf`
---
Alternatively, there are 2 other approaches:
**Not so good other Approach 1:**
You can allocate memory to `str` by making it an fixed size array:
```
#define MAX_INPUT 256
char str[MAX_INPUT]={0};
```
**Drawback:**
This would require that you need to know the length of the maximum input that user can enter at compile time, Since **[Variable Length Arrays](https://stackoverflow.com/questions/1887097/variable-length-arrays-in-c)** are not allowed in C++.
**Not so good other Approach 2:**
You could allocate memory dynamically to `str` using `new []`.`str` will be a pointer in this case.
```
#define MAX_INPUT 256
char *str = new char[MAX_INPUT];
```
**Drawback:**
Again this approach has the drawback of knowing how much memory to allocate at compile time in this case,since user inputs the string. Also, You need to remember to deallocate by calling `delete[]` or you leak memory.
Also, try to avoid using `new` as much as possible in C++.
**Conclusion:**
Best solution here is to use `std::string` because it saves you from all above problems. | You should use `std::string` instead.
Your declaration:
```
char * str;
```
declares only a pointer, but does not allocate a memory region for the string to be stored. The solutions could have been
```
char str[256];
```
or
```
char * str = new char[256];
```
However, they are *very* bad style because you would then have to check and control the size of input each time you want to write to it.
C++ provides `std::string` to store strings. Use it. |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You have not allocated any memory to `str`. So you are trying to essentially write to a pointer which cannot hold the string. Essentially this leads to an Undefined Behavior and a seg fault.
The solution is:
You should use **[std::string](http://www.google.co.in/url?sa=t&rct=j&q=std::string&source=web&cd=1&ved=0CCUQFjAA&url=http://www.cplusplus.com/reference/string/string/&ei=Nr26Tt-9AYXMhAeKuf27Bw&usg=AFQjCNHYSO65lBUum_PPFu0nJcwzb0EW9w)** instead of pointer.
```
std::string str;
std::cout<<"please enter string : ";
std::cin >>str;
```
Also, try not to mix C and C++.
Use `streams` in C++ not `printf`
---
Alternatively, there are 2 other approaches:
**Not so good other Approach 1:**
You can allocate memory to `str` by making it an fixed size array:
```
#define MAX_INPUT 256
char str[MAX_INPUT]={0};
```
**Drawback:**
This would require that you need to know the length of the maximum input that user can enter at compile time, Since **[Variable Length Arrays](https://stackoverflow.com/questions/1887097/variable-length-arrays-in-c)** are not allowed in C++.
**Not so good other Approach 2:**
You could allocate memory dynamically to `str` using `new []`.`str` will be a pointer in this case.
```
#define MAX_INPUT 256
char *str = new char[MAX_INPUT];
```
**Drawback:**
Again this approach has the drawback of knowing how much memory to allocate at compile time in this case,since user inputs the string. Also, You need to remember to deallocate by calling `delete[]` or you leak memory.
Also, try to avoid using `new` as much as possible in C++.
**Conclusion:**
Best solution here is to use `std::string` because it saves you from all above problems. | You need to allocate memory first for `str`. You declared only a pointer
```
char* str = (char*)malloc(MAX_SIZE_OF_BUFFER);
``` |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You have not allocated any memory to `str`. So you are trying to essentially write to a pointer which cannot hold the string. Essentially this leads to an Undefined Behavior and a seg fault.
The solution is:
You should use **[std::string](http://www.google.co.in/url?sa=t&rct=j&q=std::string&source=web&cd=1&ved=0CCUQFjAA&url=http://www.cplusplus.com/reference/string/string/&ei=Nr26Tt-9AYXMhAeKuf27Bw&usg=AFQjCNHYSO65lBUum_PPFu0nJcwzb0EW9w)** instead of pointer.
```
std::string str;
std::cout<<"please enter string : ";
std::cin >>str;
```
Also, try not to mix C and C++.
Use `streams` in C++ not `printf`
---
Alternatively, there are 2 other approaches:
**Not so good other Approach 1:**
You can allocate memory to `str` by making it an fixed size array:
```
#define MAX_INPUT 256
char str[MAX_INPUT]={0};
```
**Drawback:**
This would require that you need to know the length of the maximum input that user can enter at compile time, Since **[Variable Length Arrays](https://stackoverflow.com/questions/1887097/variable-length-arrays-in-c)** are not allowed in C++.
**Not so good other Approach 2:**
You could allocate memory dynamically to `str` using `new []`.`str` will be a pointer in this case.
```
#define MAX_INPUT 256
char *str = new char[MAX_INPUT];
```
**Drawback:**
Again this approach has the drawback of knowing how much memory to allocate at compile time in this case,since user inputs the string. Also, You need to remember to deallocate by calling `delete[]` or you leak memory.
Also, try to avoid using `new` as much as possible in C++.
**Conclusion:**
Best solution here is to use `std::string` because it saves you from all above problems. | Use `std::string`.
Or, if you just want to use char \* (discouraged):
```
char * str = new char[256];
cin >> str;
``` |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | `str` doesn't point to anything sensible. You need to have a memory to write to.
```
std::string str;
std::cout << "please enter string: ";
std::cin >> str;
``` | Your first line, `char * str` declares a raw pointer and doesn't initialize it or allocate any memory. That means it could point anywhere, and most likely not somewhere valid or useful. You most likely segfault when you try to use it on the 3rd line. Can you use `std::string` instead? It'll be much easier and safer than raw C-strings. |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You should use `std::string` instead.
Your declaration:
```
char * str;
```
declares only a pointer, but does not allocate a memory region for the string to be stored. The solutions could have been
```
char str[256];
```
or
```
char * str = new char[256];
```
However, they are *very* bad style because you would then have to check and control the size of input each time you want to write to it.
C++ provides `std::string` to store strings. Use it. | Your first line, `char * str` declares a raw pointer and doesn't initialize it or allocate any memory. That means it could point anywhere, and most likely not somewhere valid or useful. You most likely segfault when you try to use it on the 3rd line. Can you use `std::string` instead? It'll be much easier and safer than raw C-strings. |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | You should use `std::string` instead.
Your declaration:
```
char * str;
```
declares only a pointer, but does not allocate a memory region for the string to be stored. The solutions could have been
```
char str[256];
```
or
```
char * str = new char[256];
```
However, they are *very* bad style because you would then have to check and control the size of input each time you want to write to it.
C++ provides `std::string` to store strings. Use it. | Segmentation faults occur when a program accesses memory that doesn't belong to it. The pointer `str` is not initialized. It doesn't point at any memory. The stream-extraction operator `>>` doesn't allocate new memory for the string it reads; it expects the pointer to already point to a buffer that it can fill. It doesn't know that `str` is garbage, though. It assumes it's a valid pointer and attempts to write into that memory. Since the memory at that garbage address doesn't belong to your program, the OS halts it with a segmentation fault.
Read into a `std::string` instead. Better yet, use `std::getline` so the user can enter a string with spaces; the `>>` operator will only read up to the first whitespace character.
```
std::string str;
std::getline(cin, str);
``` |
8,069,236 | This gives me seg fault 11 when I input the string.
Why am i getting the seg fault?
It's so simple... where is the seg fault coming from?
```
int main(){
char * str;
printf ("please enter string : ");
cin >> str;
// reverse_str(str);
}
``` | 2011/11/09 | [
"https://Stackoverflow.com/questions/8069236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038203/"
] | Your first line, `char * str` declares a raw pointer and doesn't initialize it or allocate any memory. That means it could point anywhere, and most likely not somewhere valid or useful. You most likely segfault when you try to use it on the 3rd line. Can you use `std::string` instead? It'll be much easier and safer than raw C-strings. | You need to allocate memory first for `str`. You declared only a pointer
```
char* str = (char*)malloc(MAX_SIZE_OF_BUFFER);
``` |
67,104,574 | I'm creating an `aws_subnet` and referencing it in another resource.
Example:
```
resource "aws_subnet" "mango" {
vpc_id = aws_vpc.mango.id
cidr_block = "${var.subnet_cidr}"
}
```
The reference
```
network_configuration {
subnets = "${aws_subnet.mango.id}"
}
```
When planning it I get
`aws_subnet.mango.id is a string, known only after apply`
error. I'm new to Terraform. Is there something similar to Cloudformation's `DependsOn` or `Export/Import`? | 2021/04/15 | [
"https://Stackoverflow.com/questions/67104574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17450994/"
] | This is a case of [explicit dependency](https://learn.hashicorp.com/tutorials/terraform/dependencies#manage-explicit-dependencies).
The argument `depends_on` similar to CloudFormation's `DependsOn` solves such dependencies.
Note: *"Since Terraform will wait to create the dependent resource until after the specified resource is created, adding explicit dependencies can increase the length of time it takes for Terraform to create your infrastructure."*
Example:
```
depends_on = [aws_subnet.mango]
``` | The information like `ID` or other such information which will be generated by AWS, cannot be predicted by `terraform plan` as this step only does a dry run and doesn't apply any changes.
The fields which have `known only after apply` is not an error, but just informs the user that these fields only get populated in terraform state after its applied. The dependency order is handled by Terraform and hence referring values (even those which have `known only after apply`) will be resolved at run time. |
67,104,574 | I'm creating an `aws_subnet` and referencing it in another resource.
Example:
```
resource "aws_subnet" "mango" {
vpc_id = aws_vpc.mango.id
cidr_block = "${var.subnet_cidr}"
}
```
The reference
```
network_configuration {
subnets = "${aws_subnet.mango.id}"
}
```
When planning it I get
`aws_subnet.mango.id is a string, known only after apply`
error. I'm new to Terraform. Is there something similar to Cloudformation's `DependsOn` or `Export/Import`? | 2021/04/15 | [
"https://Stackoverflow.com/questions/67104574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17450994/"
] | This is a case of [explicit dependency](https://learn.hashicorp.com/tutorials/terraform/dependencies#manage-explicit-dependencies).
The argument `depends_on` similar to CloudFormation's `DependsOn` solves such dependencies.
Note: *"Since Terraform will wait to create the dependent resource until after the specified resource is created, adding explicit dependencies can increase the length of time it takes for Terraform to create your infrastructure."*
Example:
```
depends_on = [aws_subnet.mango]
``` | This line:
```
cidr_block = "${var.subnet_cidr}"
```
should look like
```
cidr_block = var.subnet_cidr
```
And this line:
```
subnets = "${aws_subnet.mango.id}"
```
should look like
```
subnets = aws_subnet.mango.id
```
Terraform gives a warning when a string value only has a template in it. The reason is that for cases like yours, it's able to make a graph with the bare value and resolve it on apply, but it's unable to make the string without creating the resource first. |
67,104,574 | I'm creating an `aws_subnet` and referencing it in another resource.
Example:
```
resource "aws_subnet" "mango" {
vpc_id = aws_vpc.mango.id
cidr_block = "${var.subnet_cidr}"
}
```
The reference
```
network_configuration {
subnets = "${aws_subnet.mango.id}"
}
```
When planning it I get
`aws_subnet.mango.id is a string, known only after apply`
error. I'm new to Terraform. Is there something similar to Cloudformation's `DependsOn` or `Export/Import`? | 2021/04/15 | [
"https://Stackoverflow.com/questions/67104574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17450994/"
] | This is a case of [explicit dependency](https://learn.hashicorp.com/tutorials/terraform/dependencies#manage-explicit-dependencies).
The argument `depends_on` similar to CloudFormation's `DependsOn` solves such dependencies.
Note: *"Since Terraform will wait to create the dependent resource until after the specified resource is created, adding explicit dependencies can increase the length of time it takes for Terraform to create your infrastructure."*
Example:
```
depends_on = [aws_subnet.mango]
``` | The error in this case is not the string "known only after apply" but the message "Incorrect attribute value type".
`subnets` (plural) requires a *list* of strings but you gave only one string.
```
network_configuration {
subnets = ["${aws_subnet.mango.id}"]
}
```
The `depends_on` is not necessary in this case, tf resolves this dependency by itself. `depends_on` is only important if tf can't get this by itself.
writing `"${foo.bar}"` instead of `foo.bar` is also no problem but doesn't follow tf's code-style-rules. |
26,002,958 | This HTML / JS code :
```
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
```
**overrides** the browser CTRL+PLUS 's ZOOM keyboard shortcut.
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the `alert("hello")` is launched, but the browser's zooming is also changed !
This means that `event.preventDefault();` hasn't worked like it should have worked.
**How to use `event.preventDefault()` with Safari ?**
*Note: I already tried as well with StopPropagation, but it doesn't solve the problem.* | 2014/09/23 | [
"https://Stackoverflow.com/questions/26002958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | Seems like this is problem with `ctrlKey`. Assuming you use Mac OS X system you need to check for `metaKey` too, so your code should be:
```
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 61 || event.keyCode == 187))
``` | We probably have different keyboard layouts or something, but my `+` and `-` signs on my numpad have the key code values 107 and 109. (<http://www.asquare.net/javascript/tests/KeyCode.html>)
The code snippet below works in safari for me.
```js
window.onkeydown = function (event) {
if (event.ctrlKey && (event.keyCode == 107 || event.keyCode == 109)) {
event.preventDefault();
alert("hello");
}
}
``` |
26,002,958 | This HTML / JS code :
```
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
```
**overrides** the browser CTRL+PLUS 's ZOOM keyboard shortcut.
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the `alert("hello")` is launched, but the browser's zooming is also changed !
This means that `event.preventDefault();` hasn't worked like it should have worked.
**How to use `event.preventDefault()` with Safari ?**
*Note: I already tried as well with StopPropagation, but it doesn't solve the problem.* | 2014/09/23 | [
"https://Stackoverflow.com/questions/26002958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | Seems like this is problem with `ctrlKey`. Assuming you use Mac OS X system you need to check for `metaKey` too, so your code should be:
```
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 61 || event.keyCode == 187))
``` | You can try this:
```
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
if (event.preventDefault){
event.preventDefault();
}
else {
event.returnValue = false;
}
alert("hello");
return false;
}
}
}
``` |
26,002,958 | This HTML / JS code :
```
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
```
**overrides** the browser CTRL+PLUS 's ZOOM keyboard shortcut.
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the `alert("hello")` is launched, but the browser's zooming is also changed !
This means that `event.preventDefault();` hasn't worked like it should have worked.
**How to use `event.preventDefault()` with Safari ?**
*Note: I already tried as well with StopPropagation, but it doesn't solve the problem.* | 2014/09/23 | [
"https://Stackoverflow.com/questions/26002958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | Seems like this is problem with `ctrlKey`. Assuming you use Mac OS X system you need to check for `metaKey` too, so your code should be:
```
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 61 || event.keyCode == 187))
``` | The key codes for zoom are different across browsers:
```
Opera MSIE Firefox Safari Chrome
61 187 107 187 187 = +
109 189 109 189 189 - _
```
Also try :
```
event.stopImmediatePropagation();
```
To prevent other handlers from executing. |
26,002,958 | This HTML / JS code :
```
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
```
**overrides** the browser CTRL+PLUS 's ZOOM keyboard shortcut.
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the `alert("hello")` is launched, but the browser's zooming is also changed !
This means that `event.preventDefault();` hasn't worked like it should have worked.
**How to use `event.preventDefault()` with Safari ?**
*Note: I already tried as well with StopPropagation, but it doesn't solve the problem.* | 2014/09/23 | [
"https://Stackoverflow.com/questions/26002958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | We probably have different keyboard layouts or something, but my `+` and `-` signs on my numpad have the key code values 107 and 109. (<http://www.asquare.net/javascript/tests/KeyCode.html>)
The code snippet below works in safari for me.
```js
window.onkeydown = function (event) {
if (event.ctrlKey && (event.keyCode == 107 || event.keyCode == 109)) {
event.preventDefault();
alert("hello");
}
}
``` | You can try this:
```
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
if (event.preventDefault){
event.preventDefault();
}
else {
event.returnValue = false;
}
alert("hello");
return false;
}
}
}
``` |
26,002,958 | This HTML / JS code :
```
<script>
window.onload = function(e) {
window.onkeydown = function(event) {
if (event.ctrlKey && (event.keyCode == 61 || event.keyCode == 187))
{
event.preventDefault();
alert("hello");
return false;
}
}
}
</script>
<p>Blah</p>
```
**overrides** the browser CTRL+PLUS 's ZOOM keyboard shortcut.
It works on Firefox, Chrome, but not with Safari : with Safari, if you do CTRL+PLUS on this page, the `alert("hello")` is launched, but the browser's zooming is also changed !
This means that `event.preventDefault();` hasn't worked like it should have worked.
**How to use `event.preventDefault()` with Safari ?**
*Note: I already tried as well with StopPropagation, but it doesn't solve the problem.* | 2014/09/23 | [
"https://Stackoverflow.com/questions/26002958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | We probably have different keyboard layouts or something, but my `+` and `-` signs on my numpad have the key code values 107 and 109. (<http://www.asquare.net/javascript/tests/KeyCode.html>)
The code snippet below works in safari for me.
```js
window.onkeydown = function (event) {
if (event.ctrlKey && (event.keyCode == 107 || event.keyCode == 109)) {
event.preventDefault();
alert("hello");
}
}
``` | The key codes for zoom are different across browsers:
```
Opera MSIE Firefox Safari Chrome
61 187 107 187 187 = +
109 189 109 189 189 - _
```
Also try :
```
event.stopImmediatePropagation();
```
To prevent other handlers from executing. |
845,426 | `/etc/hosts` lets you set system-wide hostname lookups. Is there a place in OS X to set per-user hostnames?
I use two user accounts on my laptop and I'd like to override IP addresses for just one of those accounts. Is that possible? | 2014/11/26 | [
"https://superuser.com/questions/845426",
"https://superuser.com",
"https://superuser.com/users/39309/"
] | No, DNS is global.
You don't mention any details.
You could redefine:
thissite.com 0.0.0.0
mythissite.com 122.122.122.122 <-- with the IP address of the real site.
Then only people who know that thissite.com is broken and to use mythissinte.com instead would be able to access thissite.com | There is no such thing in any operating system, but you can swap `/etc/hosts` file by some script when user is logging in.
I don't know much about OS X, you may have to restart one or more network services after that file swap.
You also might want to change permissions or owner on `/etc/hosts` file, if your script will be running from non-administrator account. |
45,794,275 | In my application I am using authentication with Google account. When the user logs in for the first time list of google accounts used on the device is displayed and user can log in by picking one of available accounts. But when the user logs out and then try to log in again the list is no longer displayed and he is automatically logged with previously picked account. How can I prevent my app from remembering that account and force it to display account list on every log in try? | 2017/08/21 | [
"https://Stackoverflow.com/questions/45794275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8404031/"
] | Try this :
```
htmlCanvas.onclick= function(evt) {
img.src = images[count];
img.width = 80/100* htmlCanvas.width;
img.height = 80/100* htmlCanvas.height;
var x = evt.offsetX - img.width/2,
y = evt.offsetY - img.height/2;
// context.drawImage(img, x, y);
context.drawImage(img, x, y, img.width, img.height);
count++;
if (count == images.length) {
count = 0;
}
}
``` | ```
context.drawImage(img, 0, 0,img.width,img.height,0,0,htmlCanvas.width,htmlCanvas.height);
```
you also can use `background-size:cover;` |
45,794,275 | In my application I am using authentication with Google account. When the user logs in for the first time list of google accounts used on the device is displayed and user can log in by picking one of available accounts. But when the user logs out and then try to log in again the list is no longer displayed and he is automatically logged with previously picked account. How can I prevent my app from remembering that account and force it to display account list on every log in try? | 2017/08/21 | [
"https://Stackoverflow.com/questions/45794275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8404031/"
] | Try this :
```
htmlCanvas.onclick= function(evt) {
img.src = images[count];
img.width = 80/100* htmlCanvas.width;
img.height = 80/100* htmlCanvas.height;
var x = evt.offsetX - img.width/2,
y = evt.offsetY - img.height/2;
// context.drawImage(img, x, y);
context.drawImage(img, x, y, img.width, img.height);
count++;
if (count == images.length) {
count = 0;
}
}
``` | The max-height/width doesn't work because everything within the canvas is independent from your css.
If you want to set the image to 80% use `htmlCanvas.width` and `htmlCanvas.height` to calculate the new size and use `context.drawImage(img, x, y, w, h)` to set the image size when drawing.
Maybe [this post](https://stackoverflow.com/questions/21961839/simulation-background-size-cover-in-canvas/21961894#21961894) could be helpful. |
3,591,833 | >
> Let $F(x)=x^{3}+2 x-2,$ let $\alpha \in \mathbb{C}$ be a root of $F,$ and let $K=\mathbb{Q}(\alpha)$
>
>
> Find $a, b, c \in \mathbb{Q}$ such that $\alpha^{4}=a \alpha^{2}+b \alpha+c$
>
>
>
We have that [$K:\mathbb{Q}]=3$.
I know that such a thing is possible, but do not know in what manner to proceed. Please leave a hint only as this is a homework assignment. | 2020/03/23 | [
"https://math.stackexchange.com/questions/3591833",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/716605/"
] | $\alpha$ is a root of $F$, so $\alpha^3 + 2\alpha - 2 = ?$ And you should be able to solve that for $\alpha^4$ (by multiplying by one thing, then moving all non-$\alpha^4$ terms to the right-hand side). | Since $\alpha$ is a root of
$f(x) = x^3 + 2x - 2, \tag 1$
we have
$\alpha^3 + 2\alpha - 2 = 0, \tag 2$
or
$\alpha^3 = -2\alpha + 2; \tag 3$
thus,
$\alpha^4 = -2\alpha^2 + 2\alpha; \tag 4$
therefore,
$a = -2, \tag 5$
$b = 2, \tag 6$
and
$c = 0. \tag 7$
In order to show uniqueness, suppose there are
$q, r, s \in \Bbb Q \tag 8$
with
$\alpha^4 = q\alpha^2 + r\alpha + s; \tag 9$
we subract (4) from (9):
$0 = (q + 2)\alpha^2 + (r - 2)\alpha + s; \tag{10}$
thus $\alpha$ must satisfy the polynomial
$g(x) = (q + 2)x^2 + (r - 2)x + s \in \Bbb Q[x]; \tag{11}$
we observe that $f(x)$ is irreducible over $\Bbb Q$ *via* [the Eisenstein criterion](https://en.wikipedia.org/wiki/Eisenstein%27s_criterion) with prime $p = 2$; therefore it is minimal for $\alpha$ over $\Bbb Q$; but this contradicts
$g(\alpha) = 0 \tag{12}$
unless
$g(x) = 0; \tag{13}$
therefore (13) binds and thus
$q = -2 = a, \tag{14}$
$r = 2 = b, \tag{15}$
and
$s = c = 0, \tag{16}$
and we conclude the expression (4) for $\alpha^4$ is unique. |
42,950,167 | For me it is not clear what the difference is between a WebSphere Message Broker and the WebSphere MQ .
According to wikipedia the message broker translates and routes the message. Which would lead me to believe the WebSphere MQ is the queue, but it is not clear from all of the marketing information what the core task of the WebSphere MQ is. Wikipedia says MQ is composed of messages, queues, and queue managers.
Does that mean WebSphere Message Broker is a component of MQ? | 2017/03/22 | [
"https://Stackoverflow.com/questions/42950167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273096/"
] | WebSphere Message Broker is not a component of WebSphere MQ Series (moreover, starting from v10 of Message Broker you don't need to have WebSphere MQ installed at all on your system in order to run message broker).
Think about WebSphere MQ as of a transport layer - you can send a message and receive it on another end (and all other particularities like persistence, fail-over, JMS, etc.)
Think about WebSphere Message Broker as of a set of transformations you can apply on your message (which **may** be transported via WebSphere MQ layer) | If an analogy helps, MQ is like an HTTP client and HTTP server, whereas MB/IIB is more of a gateway (proxy). Usually they emphasize **disparate systems** and **transformations** in the MB/IIB context. |
42,950,167 | For me it is not clear what the difference is between a WebSphere Message Broker and the WebSphere MQ .
According to wikipedia the message broker translates and routes the message. Which would lead me to believe the WebSphere MQ is the queue, but it is not clear from all of the marketing information what the core task of the WebSphere MQ is. Wikipedia says MQ is composed of messages, queues, and queue managers.
Does that mean WebSphere Message Broker is a component of MQ? | 2017/03/22 | [
"https://Stackoverflow.com/questions/42950167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273096/"
] | If an analogy helps, MQ is like an HTTP client and HTTP server, whereas MB/IIB is more of a gateway (proxy). Usually they emphasize **disparate systems** and **transformations** in the MB/IIB context. | WebSpher MQ is an implementation of JSM plus a bit more, Message Broker or IIB as its called now is an ESB, It enables communication between separate system by transforming message from one definition to another.
MQ is one of the many transport channels that WMB can use to send and receive messages. |
42,950,167 | For me it is not clear what the difference is between a WebSphere Message Broker and the WebSphere MQ .
According to wikipedia the message broker translates and routes the message. Which would lead me to believe the WebSphere MQ is the queue, but it is not clear from all of the marketing information what the core task of the WebSphere MQ is. Wikipedia says MQ is composed of messages, queues, and queue managers.
Does that mean WebSphere Message Broker is a component of MQ? | 2017/03/22 | [
"https://Stackoverflow.com/questions/42950167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273096/"
] | WebSphere Message Broker is not a component of WebSphere MQ Series (moreover, starting from v10 of Message Broker you don't need to have WebSphere MQ installed at all on your system in order to run message broker).
Think about WebSphere MQ as of a transport layer - you can send a message and receive it on another end (and all other particularities like persistence, fail-over, JMS, etc.)
Think about WebSphere Message Broker as of a set of transformations you can apply on your message (which **may** be transported via WebSphere MQ layer) | WebSpher MQ is an implementation of JSM plus a bit more, Message Broker or IIB as its called now is an ESB, It enables communication between separate system by transforming message from one definition to another.
MQ is one of the many transport channels that WMB can use to send and receive messages. |
2,341,335 | **Preamble**
I know from linear algebra that any vector in a vector space can be written as a linear combination of basis vectors. However, in physics, unit vectors are used as basis vectors, which brings me to my question. **Note**: I do not have the math tools to formally prove any of this... I just need an explanation
**The question**
Which is correct (and why):
* Are all unit vectors basis vectors?
* Are all basis vector unit vectors?
* Are unit vectors a subset of basis vectors?
* Are basis vectors a subset of unit vectors?
In a nutshell if the set of all basis vectors was **b** and the set of all unit vectors was **u**, what is the relation between the two sets? (i.e. b \_\_\_ u) | 2017/06/29 | [
"https://math.stackexchange.com/questions/2341335",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/458997/"
] | The term *unit vector* is well-defined: a vector of length one. The term *basis vector* is taken out of context, and doesn't make sense on its own.
A *basis* of a vector space $V$ is a set of vectors $\left\{v\_1,\dots, v\_n\right\}$ such each vector $v\in V$ can be written uniquely as a linear combination of $v\_1,\dots, v\_n$. So if you read “basis vector”, it means “member of the aforementioned basis,” and which basis is being referenced comes from the context.
* **Are all unit vectors basis vectors?** No. The vector $e\_1 = (1,0,0)$ in $\mathbb{R}^3$ is a unit vector. But on its own it's not a “basis vector.” There is a basis of $\mathbb{R}^3$ which contains $e\_1$—for instance $\left\{e\_1, e\_2, e\_3\right\}$. In general, for any unit vector $v$ we can find a basis of $V$ that has $v$ as a member.
* **Are all basis vectors unit vectors?** The best way to interpret this question is: *Does every basis consist of unit vectors?* The answer is no. For instance $\left\{e\_1, e\_2, e\_1+e\_3\right\}$ is a basis of $\mathbb{R}^3$ too, and not all of its elements are unit vectors.
* **Are unit vectors a subset of basis vectors?** No. However, there is an additional property of vectors that's related. Vectors $v$ and $w$ are *orthogonal* if their inner (dot) product $v\cdot w= 0$. A set of vectors is *orthonormal* if every single vector in the set is a unit vector, and any pair of vectors in the set are orthogonal. An orthonormal set of $n$ vectors in an $n$-dimensional vector space is automatically a basis.
* **Are basis vectors a subset of unit vectors**? No. However, if you start with a basis $v\_1, \dots, v\_n$, there exists an orthonormal basis $u\_1, \dots, u\_n$ such that for each $k$ between $1$ and $n$, the span of $u\_1, \dots, u\_k$ is the same as the span of $v\_1, \dots, v\_k$. The algorithm which constructs $u\_1, \dots, u\_n$ is called the *Gram-Schmidt process.* Because of this property, the physicists might assume that any given basis is orthonormal.
I hope that clarifies some of these terms.
**Edit** You asked for some more explanation on the third point. The standard basis $\hat{\mathbf x}, \hat{\mathbf y}, \hat{\mathbf z}$ (using your notation) of $\mathbb{R}^n$ is orthonormal. Put your hand in the right-hand-rule position with these three vectors, and rotate your hand. The vectors change, but not the property that each of them is unit length, and that each pair are perpendicular/orthogonal.
Now let $\mathbf{v}$ be any vector. If $\mathbf{v}$ can be written as a linear combination $a \hat{\mathbf x} + b \hat{\mathbf y} + c \hat{\mathbf z}$, then what are $a$, $b$, and $c$? Use the orthonormality property:
\begin{align\*}
\mathbf{v}\cdot\hat{\mathbf x}
&= (a \hat{\mathbf x} + b \hat{\mathbf y} + c \hat{\mathbf z})\hat{\mathbf x}\\
&= a \hat{\mathbf x}\cdot \hat{\mathbf x} + b \hat{\mathbf y}\cdot \hat{\mathbf x} + c \hat{\mathbf z}\cdot \hat{\mathbf x} \\
&= a (1) + b(0) + c(0) = a
\end{align\*}
[Since $\hat{\mathbf x}$ is a unit vector, $\hat{\mathbf x}\cdot\hat{\mathbf x} = \left\Vert\hat{\mathbf x}\right\Vert^2 = 1$.] You can do the same for $\hat{\mathbf y}$ and $\hat{\mathbf z$}$. Therefore the coefficients of $\mathbf{v}$ can be recovered by the dot products:
$$
\mathbf{v} = (\mathbf{v}\cdot\hat{\mathbf x})\hat{\mathbf x} + (\mathbf{v}\cdot\hat{\mathbf y})\hat{\mathbf x} + (\mathbf{v}\cdot\hat{\mathbf z})\hat{\mathbf x}
$$ | Being a "basis vector" is not a property of vectors on their own, so your questions have no clear answer.
Take, for instance, the real plane. One basis here would be $\{(1,0),(1,1)\}$. So in this case, those two would be basis vectors.
On the other hand, if you take $\{(2,2),(1,1)\}$, then this set of vectors forms no basis, and thus there's no reason to call either a "basis vector".
In general, a basis is something that you can chose for any given vector space - any set of vectors that is both linearly independant (no linear combination of them except with all zero coefficients adds to 0) and spans the vector space (any vector can be expressed as linear combination). |
32,046,116 | I have sql Upgrade script which has many sql statements(DDL,DML). When i ran this upgrade script in SQL developer, it runs successufully.I also provide in my script at the bottom commit. I can see all the changes in the database after running this upgrade script except the unique index constraints. When i insert few duplicate records it says unique constraint violated. It means the table has unique constraints. But i dont know why i cant view this constraints in oracle sql developer. The other DDL changes made i can view.I dont know is there any settings to view it in oracle sql developer.
```
CREATE UNIQUE INDEX "RATOR_MONITORING"."CAPTURING_UK1" ON "RATOR_MONITORING"."CAPTURING" ("DB_TABLE");
CREATE UNIQUE INDEX "RATOR_MONITORING_CONFIGURATION"."BRAND_UK1" ON "RATOR_MONITORING_CONFIGURATION"."BRAND" ("NAME");
CREATE UNIQUE INDEX "RATOR_MONITORING_CONFIGURATION"."BRAND_BUSINESS_PROCESS_UK1" ON "RATOR_MONITORING_CONFIGURATION"."BRAND_BUSINESS_PROCESS" ("BRAND_ID", "BP_ID");
CREATE UNIQUE INDEX "RATOR_MONITORING_CONFIGURATION"."BRAND_ENGINE_UK1" ON "RATOR_MONITORING_CONFIGURATION"."BRAND_ENGINE" ("BRAND_ID", "ENGINE_ID");
``` | 2015/08/17 | [
"https://Stackoverflow.com/questions/32046116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4508605/"
] | As A Hocevar noted, if you create an index
```
create unique index test_ux on test(id);
```
you see it in the Indexes tab of the table properties (not in the Constraints tab).
Please note that COMMIT is not required here, it is done implicitely in each DDL statement. More usual source of problems are stale metadata in SQL Developer, i.e. missing REFRESH (ctrl R on user or table node).
If you want to define the constraint, **add** following statement, that will reuse the index defined previously
```
alter table test add constraint test_unique unique(id) using index test_ux;
```
See further discussion about the option in [Documentation](http://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF52179) | I am assuming you are trying to look for index on a table in the correct tab in sql developer. If you are not able to see the index there, one reason could be that your user (the one with which you are logged in) doesn't have proper rights to see the Index. |
32,046,116 | I have sql Upgrade script which has many sql statements(DDL,DML). When i ran this upgrade script in SQL developer, it runs successufully.I also provide in my script at the bottom commit. I can see all the changes in the database after running this upgrade script except the unique index constraints. When i insert few duplicate records it says unique constraint violated. It means the table has unique constraints. But i dont know why i cant view this constraints in oracle sql developer. The other DDL changes made i can view.I dont know is there any settings to view it in oracle sql developer.
```
CREATE UNIQUE INDEX "RATOR_MONITORING"."CAPTURING_UK1" ON "RATOR_MONITORING"."CAPTURING" ("DB_TABLE");
CREATE UNIQUE INDEX "RATOR_MONITORING_CONFIGURATION"."BRAND_UK1" ON "RATOR_MONITORING_CONFIGURATION"."BRAND" ("NAME");
CREATE UNIQUE INDEX "RATOR_MONITORING_CONFIGURATION"."BRAND_BUSINESS_PROCESS_UK1" ON "RATOR_MONITORING_CONFIGURATION"."BRAND_BUSINESS_PROCESS" ("BRAND_ID", "BP_ID");
CREATE UNIQUE INDEX "RATOR_MONITORING_CONFIGURATION"."BRAND_ENGINE_UK1" ON "RATOR_MONITORING_CONFIGURATION"."BRAND_ENGINE" ("BRAND_ID", "ENGINE_ID");
``` | 2015/08/17 | [
"https://Stackoverflow.com/questions/32046116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4508605/"
] | As A Hocevar noted, if you create an index
```
create unique index test_ux on test(id);
```
you see it in the Indexes tab of the table properties (not in the Constraints tab).
Please note that COMMIT is not required here, it is done implicitely in each DDL statement. More usual source of problems are stale metadata in SQL Developer, i.e. missing REFRESH (ctrl R on user or table node).
If you want to define the constraint, **add** following statement, that will reuse the index defined previously
```
alter table test add constraint test_unique unique(id) using index test_ux;
```
See further discussion about the option in [Documentation](http://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF52179) | If you not obtain any error, the solution is very simple and tedious. SQL Developer doesn't refresh his fetched structures. Kindly push Refresh blue icon (or use Ctrl-R) in Connections view or disconnect and connect again (or restart SQL Developer) to see your changes in structures. |
14,156,007 | I was evaluating the outlook redemption for conversion of .eml to .msg file and subsequently purchase of the software.
what I found was it uses current user login to connect to outlook and convert a .eml file to .msg.
but I would like to know is that if we deploy this on the server we would use a service account for the conversion.
now the question is whether this service account that is used to perform the .eml to .msg conversion is required to have valid email id on the exchange server. | 2013/01/04 | [
"https://Stackoverflow.com/questions/14156007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948304/"
] | You can use
LogonExchangeMailbox(User, ServerName) or
LogonPstStore(Path, Format, DisplayName, Password, Encryption)
<http://www.dimastr.com/redemption/rdo/rdosession.htm> | Keep in mind you do not need to log in to convert an EML file to MSG: call RDOSession.CreateMessageFroMMsgFIle (returns RDOMail object), call RDOMail.IMport(..., olRfc822) to import the EML file, then RDOMail.Save. |
18,138,150 | I'm trying to make an `HTTPGET` request to a REST server, the URL i need to send contains many parameters:
This is the URI :
`http://darate.free.fr/rest/api.php?rquest=addUser&&login=samuel&&password=0757bed3d74ccc8fc8e67a13983fc95dca209407&&firstname=samuel&&lastname=barbier`
I need to get the Login,password,first, name and last name that the user types, then produce an URI like the once above.
Is there any easy way to create the URI, without concatenate the first part of the URI `http://darate.free.fr/rest/api.php?rquest=addUser` with every `&¶meter:value` | 2013/08/08 | [
"https://Stackoverflow.com/questions/18138150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2302854/"
] | I prefer to use [`Uri.Builder`](http://developer.android.com/reference/android/net/Uri.Builder.html) for building `Uri`s. It makes sure everything is escaped properly.
My typical code:
```
Uri.Builder builder = Uri.parse(BASE_URI).buildUpon();
builder.appendPath(REQUEST_PATH);
builder.builder.appendQueryParameter("param1", value);
Uri builtUri = builder.build();
``` | I hope you can use webview.posturl shown below
```
webview.postUrl("http://5.39.186.164/SEBC.php?user="+username));
```
It also worked fine for me to get the username from the database. I hope it will help you. |
11,248,235 | I am reading Code Complete. In that book, Steve McConnell warns that "Developer tests tend to be 'clean tests.' Developers tend to test for whether the code works (clean test) rather than test for all the ways the code breaks (dirty tests)."
How do I write a test for the way the code breaks? I mean, I can write tests for bad input and make sure that it is blocked correctly. But aside from that, what sorts of things should I be thinking about? What does McConnell mean here? I am comfortable with basic unit testing but trying to master it. | 2012/06/28 | [
"https://Stackoverflow.com/questions/11248235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/821742/"
] | I think you are on the right path here. Tests to prove that the code works would call a method with sensible, meaningful and expected inputs, with the program in normal state. While tests to break the code try to think "out of the box" regarding that piece of code, thus use any sort of senseless or unexpected input.
What is IMHO important though is to understand that the two thought processes are very different. When a developer writes code in TDD fashion, (s)he tends to focus on the various bits of functionality to implement in the code, and the tests to prove that this and that bit of functionality or use case works as specified. Tests created this way are what McConnell calls "clean tests".
Thinking about how a piece of code could be broken requires a very different thought process and different experience too. It requires looking at your methods and APIs from a different angle, e.g. temporarily putting aside what you know about the *aim* of these methods and parameters, and focusing only what is *technically possible* to do with them. Also to think about all the - often implied - preconditions or dependencies required for this method to work correctly. Does it depend on a configuration parameter read from DB? Does it write to the file system? Does it call another component, expecting it to having been initialized properly beforehand? Does it use large amounts of memory? Does it display a message on a GUI?... And what if one or more of these doesn't hold?
All this leads to important questions: **how should your method handle such dirty cases?** Should it crash? Throw an exception? Continue as best as it can? Return an error code? Log an error report?... All these little or bigger decisions are actually quite important for defining the contract of a method or an API correctly and consistently.
Kent Beck talks about switching between wearing "developer hat" and "tester hat" in the same sense. Fluently switching viewpoints and thought processes this way requires practice and experience. | What author most likely meant by *clean test* is test that verifies only [*happy path*](http://en.wikipedia.org/wiki/Happy_path) of method execution.
Testing happy path is usually easiest and people might tend to think that since *it works*, their job with writing tests is done. This rarely is the case. Consider:
```
public void SaveLog(string entry)
{
var outputFile = this.outputFileProvider.GetLogFile();
var isValid = this.logValidator.IsValid(outputFile);
if (isValid)
{
this.logWriter.Write(outputFile, entry);
}
}
```
Happy path testing would be simply assuming all the dependencies (`outputFileProvider`, `logValidator`, `logWriter`) worked and write is indeed taking place. However, there's high chance something *might break* along the way, and those *paths* should be tested too. Like:
* `outputFileProvider` fails to acquire output file
* `outputFile` turns out to be invalid
* `logValidator` fails with its own exception
* `logWriter` fails to write
Just to name a few! There's lot more to unit testing than simply checking happy path, but unfortunately this is often the case. |
11,248,235 | I am reading Code Complete. In that book, Steve McConnell warns that "Developer tests tend to be 'clean tests.' Developers tend to test for whether the code works (clean test) rather than test for all the ways the code breaks (dirty tests)."
How do I write a test for the way the code breaks? I mean, I can write tests for bad input and make sure that it is blocked correctly. But aside from that, what sorts of things should I be thinking about? What does McConnell mean here? I am comfortable with basic unit testing but trying to master it. | 2012/06/28 | [
"https://Stackoverflow.com/questions/11248235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/821742/"
] | I think you are on the right path here. Tests to prove that the code works would call a method with sensible, meaningful and expected inputs, with the program in normal state. While tests to break the code try to think "out of the box" regarding that piece of code, thus use any sort of senseless or unexpected input.
What is IMHO important though is to understand that the two thought processes are very different. When a developer writes code in TDD fashion, (s)he tends to focus on the various bits of functionality to implement in the code, and the tests to prove that this and that bit of functionality or use case works as specified. Tests created this way are what McConnell calls "clean tests".
Thinking about how a piece of code could be broken requires a very different thought process and different experience too. It requires looking at your methods and APIs from a different angle, e.g. temporarily putting aside what you know about the *aim* of these methods and parameters, and focusing only what is *technically possible* to do with them. Also to think about all the - often implied - preconditions or dependencies required for this method to work correctly. Does it depend on a configuration parameter read from DB? Does it write to the file system? Does it call another component, expecting it to having been initialized properly beforehand? Does it use large amounts of memory? Does it display a message on a GUI?... And what if one or more of these doesn't hold?
All this leads to important questions: **how should your method handle such dirty cases?** Should it crash? Throw an exception? Continue as best as it can? Return an error code? Log an error report?... All these little or bigger decisions are actually quite important for defining the contract of a method or an API correctly and consistently.
Kent Beck talks about switching between wearing "developer hat" and "tester hat" in the same sense. Fluently switching viewpoints and thought processes this way requires practice and experience. | Elisabeth Hendrickson, of [Test Obsessed](http://testobsessed.com/blog/2007/02/19/test-heuristics-cheat-sheet/), has a [Test Heuristics Cheat Sheet](http://testobsessed.com/wp-content/uploads/2011/04/testheuristicscheatsheetv1.pdf) in which she lists *all sorts* of testing approaches. The document is broadly about testing, but the section called "Data Type Attacks" has lots of specific examples that "unhappy path" unit tests could look at.
For example, here are her ideas about ways to test paths and files:
>
> Long Name (>255 chars)
>
> Special Characters in Name (space \* ? / \ | < > , . ( ) [ ] { } ; : ‘ “ !
> @ # $ % ^ &)
> Non-Existent
> Already Exists
> No Space
> Minimal Space
> Write-Protected
> Unavailable
> Locked
> On Remote Machine
> Corrupted
>
>
> |
15,206,166 | I am using storyboards. I have used auto layout but its not working with ios5 and give crashes so I want to remove it. However, How can I uncheck the auto layout. But if I uncheck auto layout, How can i set my screens for both iPhone 4 and 5
Regards | 2013/03/04 | [
"https://Stackoverflow.com/questions/15206166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1921872/"
] | You can disable autolayout in IB but set the constraints programatically in the view controller, based on whether the iOS version on the device supports it or not by, for example, checking if the NSLayoutConstraint class can be found:
```
if (NSClassFromString(@"NSLayoutConstraint")) {
//create constraints
}
```
More info on creating the actual constraints can be found here: <http://www.techotopia.com/index.php/Implementing_iOS_6_Auto_Layout_Constraints_in_Code> | You can uncheck auto layout from the Storyboard Utilities tab. If you aren't using auto layout you can use strings and structs or make adjustments programatically.
![enter image description here](https://i.stack.imgur.com/wFxGJ.jpg) |
15,206,166 | I am using storyboards. I have used auto layout but its not working with ios5 and give crashes so I want to remove it. However, How can I uncheck the auto layout. But if I uncheck auto layout, How can i set my screens for both iPhone 4 and 5
Regards | 2013/03/04 | [
"https://Stackoverflow.com/questions/15206166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1921872/"
] | You can uncheck auto layout from the Storyboard Utilities tab. If you aren't using auto layout you can use strings and structs or make adjustments programatically.
![enter image description here](https://i.stack.imgur.com/wFxGJ.jpg) | For the use the Auto Layout use the springs in the story board for each view depending on how you want to resize them! Naturally you will need
```
view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth
```
In the StoryBoard when you set a string or strut that means you are fixing that distance eg: if you select the bottom spring the distance of the view from the bottom is fixed which is same as the above UIViewAutoresizingFlexibleTopMargin. |
15,206,166 | I am using storyboards. I have used auto layout but its not working with ios5 and give crashes so I want to remove it. However, How can I uncheck the auto layout. But if I uncheck auto layout, How can i set my screens for both iPhone 4 and 5
Regards | 2013/03/04 | [
"https://Stackoverflow.com/questions/15206166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1921872/"
] | You can disable autolayout in IB but set the constraints programatically in the view controller, based on whether the iOS version on the device supports it or not by, for example, checking if the NSLayoutConstraint class can be found:
```
if (NSClassFromString(@"NSLayoutConstraint")) {
//create constraints
}
```
More info on creating the actual constraints can be found here: <http://www.techotopia.com/index.php/Implementing_iOS_6_Auto_Layout_Constraints_in_Code> | For the use the Auto Layout use the springs in the story board for each view depending on how you want to resize them! Naturally you will need
```
view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth
```
In the StoryBoard when you set a string or strut that means you are fixing that distance eg: if you select the bottom spring the distance of the view from the bottom is fixed which is same as the above UIViewAutoresizingFlexibleTopMargin. |
7,035,049 | How can I join these 2 queries together.
```
SELECT *
FROM tbl_person
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +';
SELECT *
FROM tbl_settings
WHERE tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
I tried this but doesn't seem to work.
```
SELECT *
FROM tbl_person, tbl_settings
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'
OR tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
Here's a bit more information about what I'm trying to do.
In both tables (tbl\_person, tbl\_settings) status\_id is a foreign key. In my application a user has the ability to create and delete statuses. So this query I'm trying to write is for when a status is being deleted. Before the status is deleted I need to check both tbl\_person and tbl\_settings to see if the status being deleted exists in either table. If either of the tables have a match to the status being deleted I need to promote the user.
Hope this helps. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7035049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258594/"
] | Do not know what you need probably union?
```
SELECT *
FROM tbl_person
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'
union
SELECT *
FROM tbl_status
WHERE tbl_status.status_id = '+ status_dg.selectedItem.status_id +'
```
1.You should AVOID using "\*" to select all records. You should specify set of columns you want to retrieve.
2. This line: `WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'` looks like you're doing something totally wrong. You should avoid putting business logic in SQL
and yes, provide more info | Without more information on your table schema, try:
```
SELECT *
FROM tbl_person, tbl_settings
WHERE tbl_person.status_id = tbl_settings.status_id
AND tbl_person.status_id = '+status_dg.selectedItem.status_id+'
```
This will join the 2 tables, `tbl_person` and `tbl_status`, on `status_id`, and only retrieve rows where `status_id = '+status_dg.selectedItem.status_id+'`. |
7,035,049 | How can I join these 2 queries together.
```
SELECT *
FROM tbl_person
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +';
SELECT *
FROM tbl_settings
WHERE tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
I tried this but doesn't seem to work.
```
SELECT *
FROM tbl_person, tbl_settings
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'
OR tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
Here's a bit more information about what I'm trying to do.
In both tables (tbl\_person, tbl\_settings) status\_id is a foreign key. In my application a user has the ability to create and delete statuses. So this query I'm trying to write is for when a status is being deleted. Before the status is deleted I need to check both tbl\_person and tbl\_settings to see if the status being deleted exists in either table. If either of the tables have a match to the status being deleted I need to promote the user.
Hope this helps. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7035049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258594/"
] | I am a little confused with your question because you used tbl\_person and tbl\_status firstly, then you tried to test by joining tbl\_person and tbl\_settings.
Which two tables do you want to join?
If you want to join tbl\_person and tbl\_settings, how about this.
```
SELECT *
FROM tbl_person JOIN tbl_setting
ON tbl_person.status_id = tbl_settings.status_id
WHERE tbl_person.status_id = '+status_dg.selectedItem.status_id+'
``` | Without more information on your table schema, try:
```
SELECT *
FROM tbl_person, tbl_settings
WHERE tbl_person.status_id = tbl_settings.status_id
AND tbl_person.status_id = '+status_dg.selectedItem.status_id+'
```
This will join the 2 tables, `tbl_person` and `tbl_status`, on `status_id`, and only retrieve rows where `status_id = '+status_dg.selectedItem.status_id+'`. |
7,035,049 | How can I join these 2 queries together.
```
SELECT *
FROM tbl_person
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +';
SELECT *
FROM tbl_settings
WHERE tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
I tried this but doesn't seem to work.
```
SELECT *
FROM tbl_person, tbl_settings
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'
OR tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
Here's a bit more information about what I'm trying to do.
In both tables (tbl\_person, tbl\_settings) status\_id is a foreign key. In my application a user has the ability to create and delete statuses. So this query I'm trying to write is for when a status is being deleted. Before the status is deleted I need to check both tbl\_person and tbl\_settings to see if the status being deleted exists in either table. If either of the tables have a match to the status being deleted I need to promote the user.
Hope this helps. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7035049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258594/"
] | Do not know what you need probably union?
```
SELECT *
FROM tbl_person
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'
union
SELECT *
FROM tbl_status
WHERE tbl_status.status_id = '+ status_dg.selectedItem.status_id +'
```
1.You should AVOID using "\*" to select all records. You should specify set of columns you want to retrieve.
2. This line: `WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'` looks like you're doing something totally wrong. You should avoid putting business logic in SQL
and yes, provide more info | To join the tables, you need to define the joining fields, which in your case seems to be the status\_id fields.
This might not work correctly, but if you look at the last line you'll need that in your query:
```
SELECT *
FROM tbl_person, tbl_settings
WHERE
( tbl_person.status_id='+status_dg.selectedItem.status_id+'
OR tbl_settings.status_id='+status_dg.selectedItem.status_id+' )
AND tbl_person.status_id = tbl_settings.status_id;
``` |
7,035,049 | How can I join these 2 queries together.
```
SELECT *
FROM tbl_person
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +';
SELECT *
FROM tbl_settings
WHERE tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
I tried this but doesn't seem to work.
```
SELECT *
FROM tbl_person, tbl_settings
WHERE tbl_person.status_id = '+ status_dg.selectedItem.status_id +'
OR tbl_settings.status_id = '+ status_dg.selectedItem.status_id +';
```
Here's a bit more information about what I'm trying to do.
In both tables (tbl\_person, tbl\_settings) status\_id is a foreign key. In my application a user has the ability to create and delete statuses. So this query I'm trying to write is for when a status is being deleted. Before the status is deleted I need to check both tbl\_person and tbl\_settings to see if the status being deleted exists in either table. If either of the tables have a match to the status being deleted I need to promote the user.
Hope this helps. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7035049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258594/"
] | I am a little confused with your question because you used tbl\_person and tbl\_status firstly, then you tried to test by joining tbl\_person and tbl\_settings.
Which two tables do you want to join?
If you want to join tbl\_person and tbl\_settings, how about this.
```
SELECT *
FROM tbl_person JOIN tbl_setting
ON tbl_person.status_id = tbl_settings.status_id
WHERE tbl_person.status_id = '+status_dg.selectedItem.status_id+'
``` | To join the tables, you need to define the joining fields, which in your case seems to be the status\_id fields.
This might not work correctly, but if you look at the last line you'll need that in your query:
```
SELECT *
FROM tbl_person, tbl_settings
WHERE
( tbl_person.status_id='+status_dg.selectedItem.status_id+'
OR tbl_settings.status_id='+status_dg.selectedItem.status_id+' )
AND tbl_person.status_id = tbl_settings.status_id;
``` |
47,912,642 | Let say I have a `Map<Date, List<Integer>>`, where list of integers is just a list of numbers thrown in lottery draw. It may look like this:
```
Wed Nov 15 13:31:45 EST 2017=[1, 2, 3, 4, 5, 6],
Wed Nov 22 13:31:45 EST 2017=[7, 8, 9, 10, 11, 12],
Wed Nov 29 13:31:45 EST 2017=[13, 14, 15, 16, 17, 18],
Wed Dec 13 13:31:45 EST 2017=[1, 19, 20, 21, 22, 23],
Wed Dec 20 13:31:45 EST 2017=[24, 25, 26, 27, 28, 29]
```
I need to convert that map into the map, where key is the lottery number, and the value is the last date when the number was thrown. Something like:
1=Wed Dec 13 13:31:45 EST 2017
2=Wed Nov 15 13:31:45 EST 2017
etc till 49.
So, the question is: is it possible to make it with the Java 8 streams and if yes, then how.
Thanks in advance. | 2017/12/20 | [
"https://Stackoverflow.com/questions/47912642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1712442/"
] | If I am not mistaken you are looking for something like this (assuming `Date` is `Comparable`):
```
map.entrySet()
.stream()
.flatMap(x -> x.getValue().stream().map(y -> new AbstractMap.SimpleEntry<>(x.getKey(), y)))
.collect(Collectors.groupingBy(
Entry::getValue,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Entry::getKey)),
x -> x.get().getKey())));
``` | Here's a succint way to do it (without streams, though):
```
Map<Integer, Date> result = new HashMap<>();
map.forEach((date, list) -> list.forEach(n -> result.merge(n, date,
(oldDate, newDate) -> newDate.after(oldDate) ? newDate : oldDate)));
```
This iterates the `map` map and for each one of its `(date, list)` pairs, it iterates the `list` list of numbers. Then it uses the [`Map.merge`](https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-) and [`Date.after`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html#after-java.util.Date-) methods to put entries into the `result` map in such a way that only the last date is mapped to a given number. |
27,842,921 | ```
#include<stdio.h>
int main() {
int i;
goto l;
for(i = 0; i < 5; i++) {
l:printf("Hi\n");
}
return 0;
}
```
The above code gives output three times Hi . I don't have any idea how it happens, please expalin it. If i reducde value of 5 to 3 then only once the Hi printed. | 2015/01/08 | [
"https://Stackoverflow.com/questions/27842921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671587/"
] | iCloud doesn't support a pretty wide range of calendar-query requests. You may be stuck downloading the entire collection first. | The url you are using to post request must contain ics file link along with the UID in request. |
4,214,815 | I have a simple webservice running in Visual Studio. If I attempt to view the metadata it is missing information about the operation and so svcutil generates client code without any methods. Is there anything wrong with my setup?
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="FCRPublishSOAP" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
<message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Test.Publish.FCRPublish" behaviorConfiguration="SimpleServiceBehavior">
<endpoint address="FCRPublish" behaviorConfiguration="" binding="basicHttpBinding" bindingConfiguration="FCRPublishSOAP" contract="IFCRPublish"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SimpleServiceBehavior">
<serviceMetadata httpGetEnabled="True" policyVersion="Policy15" />
</behavior>
</serviceBehaviors>
</behaviors>
```
Interface:
```
[System.ServiceModel.ServiceContractAttribute(Namespace="http://Test/Publish", ConfigurationName="IFCRPublish")]
public interface IFCRPublish
{
// CODEGEN: Generating message contract since the operation PublishNotification is neither RPC nor document wrapped.
[System.ServiceModel.OperationContractAttribute(Action="http://Test/PublishNotification", ReplyAction="*")]
PublishNotificationResponse1 PublishNotification(PublishNotificationRequest1 request);
}
```
Response:
```
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class PublishNotificationResponse1
{
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://Test/PublishTypes", Order=0)]
public PublishNotificationResponse PublishNotificationResponse;
public PublishNotificationResponse1()
{
}
public PublishNotificationResponse1(PublishNotificationResponse PublishNotificationResponse)
{
this.PublishNotificationResponse = PublishNotificationResponse;
}
}
```
Request:
```
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial class PublishNotificationRequest1
{
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://Test/PublishTypes", Order=0)]
public PublishNotification PublishNotification;
public PublishNotificationRequest1()
{
}
public PublishNotificationRequest1(PublishNotification PublishNotification)
{
this.PublishNotification = PublishNotification;
}
}
```
This is the metadata I receive:
```
<wsdl:import namespace="http://Test/Publish" location="http://localhost:3992/FCRPublish.svc?wsdl=wsdl0"/>
<wsdl:types/>
<wsdl:binding name="BasicHttpBinding_IFCRPublish" type="i0:IFCRPublish">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
</wsdl:binding>
<wsdl:service name="FCRPublish">
<wsdl:port name="BasicHttpBinding_IFCRPublish" binding="tns:BasicHttpBinding_IFCRPublish">
<soap:address location="http://localhost:3992/FCRPublish.svc"/>
</wsdl:port>
</wsdl:service>
```
Where has my operation gone? | 2010/11/18 | [
"https://Stackoverflow.com/questions/4214815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236733/"
] | Worked it out. Setting ReplyAction="\*" for an OperationContract means the WsdlExporter (which publishes the metadata) will ignore that Operation. Setting any other value fixes it.
What bothers me about this is that svcutil will by default set replyaction to \* which means svcutil by default creates services for which the metadata is effectively broken. | try removing `FCRPublish` from the address of your enpoint... your mex endpoint is there and seems ok, so I believe it should work |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | ```
SELECT B.userID from TableA A
LEFT JOIN TableB B on A.IntroCode=B.IntroCode
``` | use this query
```
SELECT * FROM tblA INNER JOIN tblB ON tblA.IntroCode = tblB.IntroCode where tblB.userid = value
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | Use this query.
```
SELECT TableA.Username FROM TableA JOIN TableB ON (TableA.IntroCode = TableB.IntroCode);
``` | use this query
```
SELECT * FROM tblA INNER JOIN tblB ON tblA.IntroCode = tblB.IntroCode where tblB.userid = value
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | ```
SELECT column_name(s)
FROM TableA
LEFT JOIN TableB
ON TableA.UserID=TableB.UserID
``` | use this query
```
SELECT * FROM tblA INNER JOIN tblB ON tblA.IntroCode = tblB.IntroCode where tblB.userid = value
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | This is just a simple join.
```
SELECT a.*, b.* -- select your desired columns here
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
WHERE b.userid = valueHere
```
**UPDATE 1**
```
SELECT a.UserID,
a.`Username` OrigUserName,
a.`Status`,
c.`Username` IntroUserName
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
INNER JOIN tableA c
ON b.userID = c.userID
-- WHERE b.UserID = valueHere -- extra condition here
``` | ```
SELECT B.userID from TableA A
LEFT JOIN TableB B on A.IntroCode=B.IntroCode
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | ```
select a.*,b.IntroCode from TableA a left join TableB b
on a.IntroCode = b.IntroCode
``` | use this query
```
SELECT * FROM tblA INNER JOIN tblB ON tblA.IntroCode = tblB.IntroCode where tblB.userid = value
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | This is just a simple join.
```
SELECT a.*, b.* -- select your desired columns here
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
WHERE b.userid = valueHere
```
**UPDATE 1**
```
SELECT a.UserID,
a.`Username` OrigUserName,
a.`Status`,
c.`Username` IntroUserName
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
INNER JOIN tableA c
ON b.userID = c.userID
-- WHERE b.UserID = valueHere -- extra condition here
``` | you have to give the columns with same name an unique value:
```
SELECT a.UserID as uid_a, b.UserID as uid_b
FROM tableA a
INNER JOIN tableB b ON a.IntroCode = b.IntroCode
WHERE b.UserID = 1
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | This is just a simple join.
```
SELECT a.*, b.* -- select your desired columns here
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
WHERE b.userid = valueHere
```
**UPDATE 1**
```
SELECT a.UserID,
a.`Username` OrigUserName,
a.`Status`,
c.`Username` IntroUserName
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
INNER JOIN tableA c
ON b.userID = c.userID
-- WHERE b.UserID = valueHere -- extra condition here
``` | ```
SELECT column_name(s)
FROM TableA
LEFT JOIN TableB
ON TableA.UserID=TableB.UserID
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | This is just a simple join.
```
SELECT a.*, b.* -- select your desired columns here
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
WHERE b.userid = valueHere
```
**UPDATE 1**
```
SELECT a.UserID,
a.`Username` OrigUserName,
a.`Status`,
c.`Username` IntroUserName
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
INNER JOIN tableA c
ON b.userID = c.userID
-- WHERE b.UserID = valueHere -- extra condition here
``` | use this query
```
SELECT * FROM tblA INNER JOIN tblB ON tblA.IntroCode = tblB.IntroCode where tblB.userid = value
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | This is just a simple join.
```
SELECT a.*, b.* -- select your desired columns here
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
WHERE b.userid = valueHere
```
**UPDATE 1**
```
SELECT a.UserID,
a.`Username` OrigUserName,
a.`Status`,
c.`Username` IntroUserName
FROM tableA a
INNER JOIN tableB b
ON a.IntroCode = b.IntroCode
INNER JOIN tableA c
ON b.userID = c.userID
-- WHERE b.UserID = valueHere -- extra condition here
``` | Use this query.
```
SELECT TableA.Username FROM TableA JOIN TableB ON (TableA.IntroCode = TableB.IntroCode);
``` |
12,598,223 | I need to get both table and here is the table structure
Table A
-------
* UserID
* Username
* Status
* IntroCode
Table B
-------
* IntroCode
* UserID
I want to get the table a data and join with table b on tblA.IntroCode = tblB.IntroCode, then get the username of tblB.userID. How can i do such join ?
I tried half way and stuck in the middle, please help. Thanks for reply | 2012/09/26 | [
"https://Stackoverflow.com/questions/12598223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235119/"
] | you have to give the columns with same name an unique value:
```
SELECT a.UserID as uid_a, b.UserID as uid_b
FROM tableA a
INNER JOIN tableB b ON a.IntroCode = b.IntroCode
WHERE b.UserID = 1
``` | use this query
```
SELECT * FROM tblA INNER JOIN tblB ON tblA.IntroCode = tblB.IntroCode where tblB.userid = value
``` |
4,507,009 | Why does this test fail?
```
private class TestClass
{
public string Property { get; set; }
}
[Test]
public void Test()
{
var testClasses = new[] { "a", "b", "c", "d" }
.Select(x => new TestClass());
foreach(var testClass in testClasses)
{
testClass.Property = "test";
}
foreach(var testClass in testClasses)
{
Assert.That(!string.IsNullOrEmpty(testClass.Property));
}
}
```
The problem is obviously to do with lazy yielding in the Select statement, because if I add a .ToList() call after the Select() method, the test passes. | 2010/12/22 | [
"https://Stackoverflow.com/questions/4507009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21966/"
] | Every time you iterate over the `testClasses` variable, you will run the code in the `.Select()` lambda expression. The effect in your case is that the different foreach loops gets different instances of `TestClass` objects.
As you noticed yourself, sticking a `.ToList()` at the end of the query will make sure the ot is only executed once. | It's because LINQ extension methods such as Select return `IEnumerable<T>` which are lazy. Try to be more eager:
```
var testClasses = new[] { "a", "b", "c", "d" }
.Select(x => new TestClass())
.ToArray();
``` |
4,507,009 | Why does this test fail?
```
private class TestClass
{
public string Property { get; set; }
}
[Test]
public void Test()
{
var testClasses = new[] { "a", "b", "c", "d" }
.Select(x => new TestClass());
foreach(var testClass in testClasses)
{
testClass.Property = "test";
}
foreach(var testClass in testClasses)
{
Assert.That(!string.IsNullOrEmpty(testClass.Property));
}
}
```
The problem is obviously to do with lazy yielding in the Select statement, because if I add a .ToList() call after the Select() method, the test passes. | 2010/12/22 | [
"https://Stackoverflow.com/questions/4507009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21966/"
] | Because of how LINQ works, you are actually creating **8** different versions of `TestClass` - one set of 4 per `foreach`. Essentially the same as if you had:
```
var testClasses = new[] { "a", "b", "c", "d" };
foreach(var testClass in testClasses.Select(x => new TestClass()))
{
testClass.Property = "test";
}
foreach(var testClass in testClasses.Select(x => new TestClass()))
{
Assert.That(!string.IsNullOrEmpty(testClass.Property));
}
```
The first set (discarded) have the property set.
By calling `ToList()` at the end of `testClasses`, you force it to store and re-use the same 4 `TestClass` instances, hence it passes. | Every time you iterate over the `testClasses` variable, you will run the code in the `.Select()` lambda expression. The effect in your case is that the different foreach loops gets different instances of `TestClass` objects.
As you noticed yourself, sticking a `.ToList()` at the end of the query will make sure the ot is only executed once. |
4,507,009 | Why does this test fail?
```
private class TestClass
{
public string Property { get; set; }
}
[Test]
public void Test()
{
var testClasses = new[] { "a", "b", "c", "d" }
.Select(x => new TestClass());
foreach(var testClass in testClasses)
{
testClass.Property = "test";
}
foreach(var testClass in testClasses)
{
Assert.That(!string.IsNullOrEmpty(testClass.Property));
}
}
```
The problem is obviously to do with lazy yielding in the Select statement, because if I add a .ToList() call after the Select() method, the test passes. | 2010/12/22 | [
"https://Stackoverflow.com/questions/4507009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21966/"
] | Because of how LINQ works, you are actually creating **8** different versions of `TestClass` - one set of 4 per `foreach`. Essentially the same as if you had:
```
var testClasses = new[] { "a", "b", "c", "d" };
foreach(var testClass in testClasses.Select(x => new TestClass()))
{
testClass.Property = "test";
}
foreach(var testClass in testClasses.Select(x => new TestClass()))
{
Assert.That(!string.IsNullOrEmpty(testClass.Property));
}
```
The first set (discarded) have the property set.
By calling `ToList()` at the end of `testClasses`, you force it to store and re-use the same 4 `TestClass` instances, hence it passes. | It's because LINQ extension methods such as Select return `IEnumerable<T>` which are lazy. Try to be more eager:
```
var testClasses = new[] { "a", "b", "c", "d" }
.Select(x => new TestClass())
.ToArray();
``` |
8,787 | I use discrete Fourier transform for digital image processing purposes , but I don't understand basic concept behind it. For example :
1. What information exists in frequency domain?
2. What is difference between spatial domain and frequency domain? | 2013/04/22 | [
"https://dsp.stackexchange.com/questions/8787",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/4408/"
] | >
> What information exists in frequency domain?
>
>
>
As JasonR says in the comment, ***The frequency domain
is a different view of the same data.***
No new information is created, it just takes the "spatial" domain data (the image pixel values and their locations) and re-presents it as the coefficients of complex exponentials (sines and cosines).
>
> What is difference between spatial domain and frequency domain?
>
>
>
The spatial domain is the domain of the image: the pixel values are located at particular positions in the image --- they are spatially distributed, usually in a regular grid.
The frequency domain takes this same data and finds any underlying periodicities (sine waves and cosine waves) in the spatial data, and their amplitudes and phases (spatial offsets).
For example, suppose I have the following image (Scialab, not matlab):
```
N = 100;
x = [1:N];
y = [1:N];
phi = 2*%pi*0.0987298374*ones(N,1)*x + 2*%pi*0.033102974*y'*ones(1,N);
im1 = sin(phi);
```
Which looks like (appropriately scaled to the grey scale values):
![Periodic image (scaled)](https://i.stack.imgur.com/vNmzL.png)
Then the FFT of this is:
![FFT of periodic image (scaled)](https://i.stack.imgur.com/rjd48.png)
(again, with appropriate scaling).
The frequency domain version shows up the periodicities of the spatial domain as a small number of large coefficients. | Fourier transform approximates a function to a sum of sine and cosine signals of varying frequency.
The Fourier transform is an extension of the Fourier series that results when the period of the represented function is lengthened and allowed to approach infinity.
Due to the properties of sine and cosine, it is possible to recover the amplitude of each wave in a Fourier series using an integral. |
8,787 | I use discrete Fourier transform for digital image processing purposes , but I don't understand basic concept behind it. For example :
1. What information exists in frequency domain?
2. What is difference between spatial domain and frequency domain? | 2013/04/22 | [
"https://dsp.stackexchange.com/questions/8787",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/4408/"
] | Fourier transform approximates a function to a sum of sine and cosine signals of varying frequency.
The Fourier transform is an extension of the Fourier series that results when the period of the represented function is lengthened and allowed to approach infinity.
Due to the properties of sine and cosine, it is possible to recover the amplitude of each wave in a Fourier series using an integral. | Spatial domain in image looks like time domain in signals. Any signal (image,data...everything) can be composed of sine signals of varying frequencies (cosine signals are sine signals too, with just some lag or lead). So a definite signal can be decomposed to the sum of lots of sine signals with different frequencies. In more easy terms, any signal has a lot of components having multiple frequencies.
This is the basic underlying principle of fourier transform.
So what it basically tells is what is the strength of the signal at a definite frequency. "What frequency, What strength". So fourier transform mainly converts the signal from spatial domain to frequency domain.
So, in spatial domain, you are concerned about finding the value of the pixel at a definite location, right? Like if I go this location, what value of pixel would I find there, what color would I see there.
But in frequency domain, you can find the strength of the signal occurring at a definite frequency. Remember, any signal contains of components of multiple frequencies. So any signal can be thought of having a lot of frequencies. So in frequency domain, you get to know how strong the signal would be at this particular frequency. |
8,787 | I use discrete Fourier transform for digital image processing purposes , but I don't understand basic concept behind it. For example :
1. What information exists in frequency domain?
2. What is difference between spatial domain and frequency domain? | 2013/04/22 | [
"https://dsp.stackexchange.com/questions/8787",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/4408/"
] | >
> What information exists in frequency domain?
>
>
>
As JasonR says in the comment, ***The frequency domain
is a different view of the same data.***
No new information is created, it just takes the "spatial" domain data (the image pixel values and their locations) and re-presents it as the coefficients of complex exponentials (sines and cosines).
>
> What is difference between spatial domain and frequency domain?
>
>
>
The spatial domain is the domain of the image: the pixel values are located at particular positions in the image --- they are spatially distributed, usually in a regular grid.
The frequency domain takes this same data and finds any underlying periodicities (sine waves and cosine waves) in the spatial data, and their amplitudes and phases (spatial offsets).
For example, suppose I have the following image (Scialab, not matlab):
```
N = 100;
x = [1:N];
y = [1:N];
phi = 2*%pi*0.0987298374*ones(N,1)*x + 2*%pi*0.033102974*y'*ones(1,N);
im1 = sin(phi);
```
Which looks like (appropriately scaled to the grey scale values):
![Periodic image (scaled)](https://i.stack.imgur.com/vNmzL.png)
Then the FFT of this is:
![FFT of periodic image (scaled)](https://i.stack.imgur.com/rjd48.png)
(again, with appropriate scaling).
The frequency domain version shows up the periodicities of the spatial domain as a small number of large coefficients. | Spatial domain in image looks like time domain in signals. Any signal (image,data...everything) can be composed of sine signals of varying frequencies (cosine signals are sine signals too, with just some lag or lead). So a definite signal can be decomposed to the sum of lots of sine signals with different frequencies. In more easy terms, any signal has a lot of components having multiple frequencies.
This is the basic underlying principle of fourier transform.
So what it basically tells is what is the strength of the signal at a definite frequency. "What frequency, What strength". So fourier transform mainly converts the signal from spatial domain to frequency domain.
So, in spatial domain, you are concerned about finding the value of the pixel at a definite location, right? Like if I go this location, what value of pixel would I find there, what color would I see there.
But in frequency domain, you can find the strength of the signal occurring at a definite frequency. Remember, any signal contains of components of multiple frequencies. So any signal can be thought of having a lot of frequencies. So in frequency domain, you get to know how strong the signal would be at this particular frequency. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | I use C professionally, nearly every day. In fact, C is the *highest* level language in which I regularly program.
**Where I use C:** I write low-level library code that has a requirement to be as efficient as possible. My glue code is written in C, inner computational loops are written in assembly.
**Why I use C:** It's much simpler to handle complex argument structures and error conditions than it is in assembly, and the performance overhead for that sort of condition checking before starting the real computation is often negligible. Because C is a simple, well-specified language, I have an easy time working with the compiler team at work to improve the code generation whenever I see compiled code with unacceptable performance hazards.
Portability is another great virtue of C. My glue code is shared across multiple hardware-specific implementations of the libraries I work on, which really simplifies bringing up support for new platforms. Most platforms don't have a virtual machine or interpreter for the language flavor of the month. Some platforms don't have a good C++ compiler. There are very few platforms that lack a usable C compiler (and, since I have a good working relationship with our compiler team, I usually don't have a hard time getting the support I need). | Yes, I do it all the time.
If you don't call any libraries, code generated from C requires no OS support. It also gives you fine control over the generated machine language. So it's great for writing drivers or other code that lives in kernel spaces, and other constrained situations like many kinds of embedded systems work. It's also the primary language for open-source projects I work with like X Windows, GTK+, and Clutter.
While you can do everything in C you can in C++, often C++'s mechanisms make it quicker and easier to write code. I love OOP and the way C++ classes encapsulate functionality, and I love RAII. Careful use of automatic destructor invocation when an object goes out of scope eliminates most of the memory and resource leaks that are the bane of C programming. The STL is basically a giant library of highly optimized algorithms and data structures; if you wanted to use them from C, you'd have to write them yourself or buy them someplace.
Unfortunately, for reasons I don't understand, the runtime system on Linux requires a special shared object library (equivalent to DLL on Windows, dylib on Mac) to run any C++, and it's not found when you run a C program. So I can't do one of my favorite Mac and Windows tricks, which is to write a C++-based shared object with a C-based API, and call it from a C program.
So here's my decision-making process:
1. Am I working in a constrained situation like a device driver? Use C.
2. Am I writing a Linux library anybody else will have to use? Use C.
3. Am I working inside code that's already written in C? Use C.
4. Am I writing a Mac or Windows library, or a Linux library only I will use? Write the internals in C++, but only expose a C interface to avoid the fragile binary interface problem.
5. Use C++.
One nice thing is that because C++ can compile C, if you really need fine-grained control over the code generated for a particular situation, you can just write C for that, and C++ for the rest, and compile it all with the C++ compiler. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | Every single language out there has a decent niche of use. I frequently find myself implementing things in higher-level languages, and then gradually bringing them down to C-land if I need them to be higher-performance or even simply just more portable. There are C compilers for nearly everything in existence, and if you write to an API that is universally available (such as POSIX), then it can be very useful.
What I often tell people who are interested in learning programming today is to make sure that at *some* point, they learn C and become comfortable with it. You might find yourself in circumstances where you need it. On more than one occasion, I've had to compile a tiny, statically-linked "fast reboot" program, and use scp to put it on a RAM disk on a server where the disk subsystem went away entirely. (Cheap, cheap servers, no online redundancy, and only the ability to load a small program? C is the way to go.)
Also, learning how to work in C without shooting yourself in the foot can contribute significantly to one's ability to write efficiently in other languages and environment. At least, that has been my experience.
While I certainly don't use it for everything, or even most things, it has its place and it's pretty much universal: so yes, I've used it in the past and will use it in the future (though I don't know when at the moment). | **C++** is portable across platforms and embedded devices like microcontrollers.
(C++ can be compiled to C, therefore microcontrollers.)
**C** is even portable (as foreign functions) to other languages. Therefore, iff I program low-level libraries, then I want more compatibility than C++.
**Haskell** is portable across platforms (ARM is coming soon) but NOT embedded devices like microcontrollers. Its speed is comparable to C and C++; but because it is functional, it uses a garbage-collector instead of an runtime-stack, therefore it can be faster and slower than C at different times (garbage-collecting) and in different situations (continuations instead of sub-routine calls).
---
I choose the most abstract language possible, because the program speed does not differ but the development time and bug-rate. C and C++ differ much, but not from the point of view of Haskell.
I do not prefer other languages, even though I know one or two hand full.
…except in a few cases, well, **bash**. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | I work mostly with the Xen hypervisor, the assorted libraries it features and the Linux kernel. On occasion, I have to write a device driver (or re-write one so that nxx virtual machines can share a single device such as a HRNG). C is my primary language and I am quite happy with that.
Would I try to write a spreadsheet program using it? No way. Each tool has its applications, and I'm happy that I have many tools.
I love C, but I don't try to pound screws with a hammer.
If C is a sensible choice for a new project, sure. If not, I'll use something else. | if it has to be both
* fast, and
* portable
then I use C. Maybe C++. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | Every single language out there has a decent niche of use. I frequently find myself implementing things in higher-level languages, and then gradually bringing them down to C-land if I need them to be higher-performance or even simply just more portable. There are C compilers for nearly everything in existence, and if you write to an API that is universally available (such as POSIX), then it can be very useful.
What I often tell people who are interested in learning programming today is to make sure that at *some* point, they learn C and become comfortable with it. You might find yourself in circumstances where you need it. On more than one occasion, I've had to compile a tiny, statically-linked "fast reboot" program, and use scp to put it on a RAM disk on a server where the disk subsystem went away entirely. (Cheap, cheap servers, no online redundancy, and only the ability to load a small program? C is the way to go.)
Also, learning how to work in C without shooting yourself in the foot can contribute significantly to one's ability to write efficiently in other languages and environment. At least, that has been my experience.
While I certainly don't use it for everything, or even most things, it has its place and it's pretty much universal: so yes, I've used it in the past and will use it in the future (though I don't know when at the moment). | Embedded systems frequently have no more than a few kilobytes of RAM and perhaps a couple dozen kilobytes of flash, with a processor clock rate of a few MHz. C is the only option that makes any sense in such a bare-metal environment. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | if it has to be both
* fast, and
* portable
then I use C. Maybe C++. | I would use C if I was writing an operating system. Since that is not going to happen in the next twenty years, unless I hit lotto and have nothing else to do but make my own awesome Linux distro, I'll probably just stick to C#, Java, Python, etc, etc. I haven't used C in a very long time but I always enjoyed using it; I think though, these days my head is so wrapped around OO if I have to go back to it it'd take me a bit to get rolling again. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | Yes, I do it all the time.
If you don't call any libraries, code generated from C requires no OS support. It also gives you fine control over the generated machine language. So it's great for writing drivers or other code that lives in kernel spaces, and other constrained situations like many kinds of embedded systems work. It's also the primary language for open-source projects I work with like X Windows, GTK+, and Clutter.
While you can do everything in C you can in C++, often C++'s mechanisms make it quicker and easier to write code. I love OOP and the way C++ classes encapsulate functionality, and I love RAII. Careful use of automatic destructor invocation when an object goes out of scope eliminates most of the memory and resource leaks that are the bane of C programming. The STL is basically a giant library of highly optimized algorithms and data structures; if you wanted to use them from C, you'd have to write them yourself or buy them someplace.
Unfortunately, for reasons I don't understand, the runtime system on Linux requires a special shared object library (equivalent to DLL on Windows, dylib on Mac) to run any C++, and it's not found when you run a C program. So I can't do one of my favorite Mac and Windows tricks, which is to write a C++-based shared object with a C-based API, and call it from a C program.
So here's my decision-making process:
1. Am I working in a constrained situation like a device driver? Use C.
2. Am I writing a Linux library anybody else will have to use? Use C.
3. Am I working inside code that's already written in C? Use C.
4. Am I writing a Mac or Windows library, or a Linux library only I will use? Write the internals in C++, but only expose a C interface to avoid the fragile binary interface problem.
5. Use C++.
One nice thing is that because C++ can compile C, if you really need fine-grained control over the code generated for a particular situation, you can just write C for that, and C++ for the rest, and compile it all with the C++ compiler. | Embedded systems frequently have no more than a few kilobytes of RAM and perhaps a couple dozen kilobytes of flash, with a processor clock rate of a few MHz. C is the only option that makes any sense in such a bare-metal environment. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | C is a great language for System programming
--------------------------------------------
I would use C if I implemented some harware drivers. And I would use C if I implement my own Operating System kernel or my own Virtual Machine.
It is a very good language to do low-level things if you have to deal with hardware or low-level OS APIs for Windows API, Linux, Mac OS X, Solaris and so on... Embedded systems has usually good support for C with a compiler + development kit. | **Yes, in fact I have recently!**
I like programming in C. I do most my programming in python, but there are times when I need fast code and I really enjoy the elegance that come from the simplicity of the language.
The project I'm working on now is a database, which, as you can imagine, is performance critical. At the moment I'm using C and some python, but it will eventually be predominantly, if not entirely C. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | I work mostly with the Xen hypervisor, the assorted libraries it features and the Linux kernel. On occasion, I have to write a device driver (or re-write one so that nxx virtual machines can share a single device such as a HRNG). C is my primary language and I am quite happy with that.
Would I try to write a spreadsheet program using it? No way. Each tool has its applications, and I'm happy that I have many tools.
I love C, but I don't try to pound screws with a hammer.
If C is a sensible choice for a new project, sure. If not, I'll use something else. | Every single language out there has a decent niche of use. I frequently find myself implementing things in higher-level languages, and then gradually bringing them down to C-land if I need them to be higher-performance or even simply just more portable. There are C compilers for nearly everything in existence, and if you write to an API that is universally available (such as POSIX), then it can be very useful.
What I often tell people who are interested in learning programming today is to make sure that at *some* point, they learn C and become comfortable with it. You might find yourself in circumstances where you need it. On more than one occasion, I've had to compile a tiny, statically-linked "fast reboot" program, and use scp to put it on a RAM disk on a server where the disk subsystem went away entirely. (Cheap, cheap servers, no online redundancy, and only the ability to load a small program? C is the way to go.)
Also, learning how to work in C without shooting yourself in the foot can contribute significantly to one's ability to write efficiently in other languages and environment. At least, that has been my experience.
While I certainly don't use it for everything, or even most things, it has its place and it's pretty much universal: so yes, I've used it in the past and will use it in the future (though I don't know when at the moment). |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | **Yes, in fact I have recently!**
I like programming in C. I do most my programming in python, but there are times when I need fast code and I really enjoy the elegance that come from the simplicity of the language.
The project I'm working on now is a database, which, as you can imagine, is performance critical. At the moment I'm using C and some python, but it will eventually be predominantly, if not entirely C. | I would use C if I was writing an operating system. Since that is not going to happen in the next twenty years, unless I hit lotto and have nothing else to do but make my own awesome Linux distro, I'll probably just stick to C#, Java, Python, etc, etc. I haven't used C in a very long time but I always enjoyed using it; I think though, these days my head is so wrapped around OO if I have to go back to it it'd take me a bit to get rolling again. |
26,301 | If yes, where and why would you use it?
If no, please provide an explanation to why C is not acceptable to you. | 2010/12/14 | [
"https://softwareengineering.stackexchange.com/questions/26301",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3306/"
] | C is a great language for System programming
--------------------------------------------
I would use C if I implemented some harware drivers. And I would use C if I implement my own Operating System kernel or my own Virtual Machine.
It is a very good language to do low-level things if you have to deal with hardware or low-level OS APIs for Windows API, Linux, Mac OS X, Solaris and so on... Embedded systems has usually good support for C with a compiler + development kit. | **C++** is portable across platforms and embedded devices like microcontrollers.
(C++ can be compiled to C, therefore microcontrollers.)
**C** is even portable (as foreign functions) to other languages. Therefore, iff I program low-level libraries, then I want more compatibility than C++.
**Haskell** is portable across platforms (ARM is coming soon) but NOT embedded devices like microcontrollers. Its speed is comparable to C and C++; but because it is functional, it uses a garbage-collector instead of an runtime-stack, therefore it can be faster and slower than C at different times (garbage-collecting) and in different situations (continuations instead of sub-routine calls).
---
I choose the most abstract language possible, because the program speed does not differ but the development time and bug-rate. C and C++ differ much, but not from the point of view of Haskell.
I do not prefer other languages, even though I know one or two hand full.
…except in a few cases, well, **bash**. |
62,256,834 | I keep getting this error while writing a spring boot application using REST API.
>
> {
> "status": 415,
> "error": "Unsupported Media Type",
> "message": "Content type 'text/plain' not supported" }
>
>
>
How do I get rid of the error?
My Post Request code is as follows, in my
```
StudentController.java,
@RequestMapping(value = "/students/{studentId}/courses", method = RequestMethod.POST,
consumes = "application/json",
produces = {"application/json"})
public ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody course newCourse)
{
course course1 = studentService.addCourse(studentId, newCourse);
if (course1 == null)
return ResponseEntity.noContent().build();
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(course1.getId()).toUri();
return ResponseEntity.created(location).build();
}
```
And my postman input for the requestBody is as follows, to add a new course to student . The code is in json
```
{
"name":"Microservices",
"description"="10 Steps",
"steps":
[
"Learn How to Break Things up ",
"Automate the hell out of everything ",
"Have fun"
]
}
```
`My addcourse()` method is as follows :
```
SecureRandom random = new SecureRandom();
public course addCourse(String studentId, course cour)
{
Student student = retrieveStudent(studentId);
if(student==null)
{
return null;
}
String randomId = new BigInteger(130,random).toString(32);
cour.setId(randomId);
student.getCourses().add(cour);
return cour;
}
``` | 2020/06/08 | [
"https://Stackoverflow.com/questions/62256834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13704420/"
] | As each Pod of Statefulset is created, it gets a matching DNS subdomain, taking the form: `$(podname).$(governing service domain)`.
For your case,
* podname = `report-mysqlha-0`
* governing service domain = `report-mysqlha.middleware.svc.cluster.local`
Pod's subdomain will be, `report-mysqlha-0.report-mysqlha.middleware.svc.cluster.local`
* [Reference](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#stable-network-id) | `report-mysqlha-0` is the name of the pod and not the name of the service. Hence you can't access it via `report-mysqlha-0.middleware.svc.cluster.local` |
42,298,694 | * History: I'm making a Powershell script in order to create user from a defined table containing list of users and put them in a defined OrganizationalUnit.
* Problem: At the end of the script, I'd like to have a report in order to list whether or not there is one or many user account disabled amoung newly created account
In my script, I have to input a password for each user, but I may enter a password that won't meet the password policy defined in Active Directory; in this case, the account will be created but disabled.
To proceed, I tried :
```
dsquery user "ou=sp,dc=mydomain,dc=local" -disabled
```
and it print me this :
```
"CN=user1,OU=SP,DC=mydomain,DC=local"
"CN=user2,OU=SP,DC=mydomain,DC=local"
"CN=user3,OU=SP,DC=mydomain,DC=local"
```
* My goal : I'd like to extract in a variable the values in "CN" field in order to compare them to the inital user table in my script.
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.CN -ne $null}
```
or
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.Common-Name -ne $null}
```
But it didn't help (doesn't work). How can I proceed please? | 2017/02/17 | [
"https://Stackoverflow.com/questions/42298694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572709/"
] | You need to check if `firstNode` is `null` before you try to access it in the line with the error, since you initialize it with `null`. | In
```
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
```
`firstNode` is null and you are not initializing the memory to the node and accessing it afterwards.That's the reason you are getting null pointer exception because you are accessing null. Change it to.
```
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = new Node();
} // end Constructor
```
To check if empty
```
public boolean isEmpty() {
return firstNode==null;
} // end isEmpty()
```
Node Class
```
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
next= new Node();
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
```
Main
```
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.isEmpty());
}
}
``` |
42,298,694 | * History: I'm making a Powershell script in order to create user from a defined table containing list of users and put them in a defined OrganizationalUnit.
* Problem: At the end of the script, I'd like to have a report in order to list whether or not there is one or many user account disabled amoung newly created account
In my script, I have to input a password for each user, but I may enter a password that won't meet the password policy defined in Active Directory; in this case, the account will be created but disabled.
To proceed, I tried :
```
dsquery user "ou=sp,dc=mydomain,dc=local" -disabled
```
and it print me this :
```
"CN=user1,OU=SP,DC=mydomain,DC=local"
"CN=user2,OU=SP,DC=mydomain,DC=local"
"CN=user3,OU=SP,DC=mydomain,DC=local"
```
* My goal : I'd like to extract in a variable the values in "CN" field in order to compare them to the inital user table in my script.
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.CN -ne $null}
```
or
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.Common-Name -ne $null}
```
But it didn't help (doesn't work). How can I proceed please? | 2017/02/17 | [
"https://Stackoverflow.com/questions/42298694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572709/"
] | Your set is empty if it has no nodes. Therefore your `isEmpty()` implementation is your problem, since it assumes you always have a `firstNode` even though you explicitly set it to `null` in the constructor.
Try this:
```
public boolean isEmpty() {
return firstNode == null;
}
```
*Edit after the first problem was edited away:*
You still access null (which causes the `NullPointerException`) since you set `current` to `firstNode` which in turn has never been set to anything but null. | In
```
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
```
`firstNode` is null and you are not initializing the memory to the node and accessing it afterwards.That's the reason you are getting null pointer exception because you are accessing null. Change it to.
```
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = new Node();
} // end Constructor
```
To check if empty
```
public boolean isEmpty() {
return firstNode==null;
} // end isEmpty()
```
Node Class
```
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
next= new Node();
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
```
Main
```
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.isEmpty());
}
}
``` |
42,298,694 | * History: I'm making a Powershell script in order to create user from a defined table containing list of users and put them in a defined OrganizationalUnit.
* Problem: At the end of the script, I'd like to have a report in order to list whether or not there is one or many user account disabled amoung newly created account
In my script, I have to input a password for each user, but I may enter a password that won't meet the password policy defined in Active Directory; in this case, the account will be created but disabled.
To proceed, I tried :
```
dsquery user "ou=sp,dc=mydomain,dc=local" -disabled
```
and it print me this :
```
"CN=user1,OU=SP,DC=mydomain,DC=local"
"CN=user2,OU=SP,DC=mydomain,DC=local"
"CN=user3,OU=SP,DC=mydomain,DC=local"
```
* My goal : I'd like to extract in a variable the values in "CN" field in order to compare them to the inital user table in my script.
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.CN -ne $null}
```
or
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.Common-Name -ne $null}
```
But it didn't help (doesn't work). How can I proceed please? | 2017/02/17 | [
"https://Stackoverflow.com/questions/42298694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572709/"
] | ```
public boolean isEmpty() {
Node next = firstNode.next; //Get error here
if (next.equals(null)) {
return true;
}
return false;
} // end isEmpty()
```
This line gives you NullPointerException, I hope:
```
Node next = firstNode.next; //Get error here
```
Because `firstNode` is probably `null` and not pointing anywhere so far. It's also best practice to handle `NullPointerException`. So, what you should do is:
```
public boolean isEmpty() {
if (firstNode == null) { return true;}
return false;
} // end isEmpty()
```
Also, do not check null as:
`next.equals(null)`
Always check it as:
`null == next` or `next == null` | In
```
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = null;
} // end Constructor
```
`firstNode` is null and you are not initializing the memory to the node and accessing it afterwards.That's the reason you are getting null pointer exception because you are accessing null. Change it to.
```
public class LinkedSet<T> implements Set<T> {
private Node firstNode;
public LinkedSet() {
firstNode = new Node();
} // end Constructor
```
To check if empty
```
public boolean isEmpty() {
return firstNode==null;
} // end isEmpty()
```
Node Class
```
private class Node {
private T data;
private Node next; //Get Error here
private Node(T data, Node next) {
next= new Node();
this.data = data;
this.next = next;
} // end Node constructor
private Node(T data) {
this(data, null);
}// end Node constructor
} // end Node inner Class
```
Main
```
public class SetTester {
public static void main(String[] args) {
LinkedSet<String> set = new LinkedSet<String>();
System.out.println(set.isEmpty());
}
}
``` |
42,298,694 | * History: I'm making a Powershell script in order to create user from a defined table containing list of users and put them in a defined OrganizationalUnit.
* Problem: At the end of the script, I'd like to have a report in order to list whether or not there is one or many user account disabled amoung newly created account
In my script, I have to input a password for each user, but I may enter a password that won't meet the password policy defined in Active Directory; in this case, the account will be created but disabled.
To proceed, I tried :
```
dsquery user "ou=sp,dc=mydomain,dc=local" -disabled
```
and it print me this :
```
"CN=user1,OU=SP,DC=mydomain,DC=local"
"CN=user2,OU=SP,DC=mydomain,DC=local"
"CN=user3,OU=SP,DC=mydomain,DC=local"
```
* My goal : I'd like to extract in a variable the values in "CN" field in order to compare them to the inital user table in my script.
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.CN -ne $null}
```
or
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.Common-Name -ne $null}
```
But it didn't help (doesn't work). How can I proceed please? | 2017/02/17 | [
"https://Stackoverflow.com/questions/42298694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572709/"
] | Your set is empty if it has no nodes. Therefore your `isEmpty()` implementation is your problem, since it assumes you always have a `firstNode` even though you explicitly set it to `null` in the constructor.
Try this:
```
public boolean isEmpty() {
return firstNode == null;
}
```
*Edit after the first problem was edited away:*
You still access null (which causes the `NullPointerException`) since you set `current` to `firstNode` which in turn has never been set to anything but null. | You need to check if `firstNode` is `null` before you try to access it in the line with the error, since you initialize it with `null`. |
42,298,694 | * History: I'm making a Powershell script in order to create user from a defined table containing list of users and put them in a defined OrganizationalUnit.
* Problem: At the end of the script, I'd like to have a report in order to list whether or not there is one or many user account disabled amoung newly created account
In my script, I have to input a password for each user, but I may enter a password that won't meet the password policy defined in Active Directory; in this case, the account will be created but disabled.
To proceed, I tried :
```
dsquery user "ou=sp,dc=mydomain,dc=local" -disabled
```
and it print me this :
```
"CN=user1,OU=SP,DC=mydomain,DC=local"
"CN=user2,OU=SP,DC=mydomain,DC=local"
"CN=user3,OU=SP,DC=mydomain,DC=local"
```
* My goal : I'd like to extract in a variable the values in "CN" field in order to compare them to the inital user table in my script.
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.CN -ne $null}
```
or
```
dsquery user "dc=mydomain,dc=local" -disabled | where-object {$_.Common-Name -ne $null}
```
But it didn't help (doesn't work). How can I proceed please? | 2017/02/17 | [
"https://Stackoverflow.com/questions/42298694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572709/"
] | ```
public boolean isEmpty() {
Node next = firstNode.next; //Get error here
if (next.equals(null)) {
return true;
}
return false;
} // end isEmpty()
```
This line gives you NullPointerException, I hope:
```
Node next = firstNode.next; //Get error here
```
Because `firstNode` is probably `null` and not pointing anywhere so far. It's also best practice to handle `NullPointerException`. So, what you should do is:
```
public boolean isEmpty() {
if (firstNode == null) { return true;}
return false;
} // end isEmpty()
```
Also, do not check null as:
`next.equals(null)`
Always check it as:
`null == next` or `next == null` | You need to check if `firstNode` is `null` before you try to access it in the line with the error, since you initialize it with `null`. |
27,216,349 | I want a quick way to burn a ZIP file into an ISO file so I use NeroCmd.exe which is the command-line tool for Nero. When I'm using the following command:
```
NeroCmd --write --drivename "Image Recorder" --real --iso isoName rarFile.rar
```
The problem is that it prompts for the image name and I don't know if it's possible to specify it in the parameters and which parameter should I include, supposing the image name is "Image.iso".
**EDIT:**
I tried using `--output_image test.iso`, so my final code is:
```
NeroCmd --write --no_error_log --drivename "Image Recorder" --real --iso Drive --enable_abort --underrun_prot --output_image Image.iso --verify rarFile.rar
```
But no file was created, here's the console output:
```
PHASE: Unspecified
[i] Generation of disc structures started
Creating directories
[i] Creating directories
PHASE: Unspecified
[i] Generation of disc structures completed
Checking discs
[i] Checking discs
Enter file name to save image to (RETURN to abort): GameSetup.iso
There is not enough space available to burn the image.
Enter file name to save image to (RETURN to abort): Not enough space available in the given location.
[!] Canceled by user
ERROR: The operation cannot be performed without user interaction!
User aborted!
```
The command works perfectly without that parameter, but the problem is it prompts. | 2014/11/30 | [
"https://Stackoverflow.com/questions/27216349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133866/"
] | In the first example, some variation of the below may happen:
1. `even()` acquires the lock
2. `even()` prints `count` (which is 0) and signals the condition (though `odd()` can't wake until `even()` releases the lock)
3. `even()` increments `count` to 1
4. `even()` releases the lock, and `odd()` wakes.
5. `odd()` increments `count` to 2
6. `odd()` releases the lock (but hasn't signalled the condition)
7. `odd()` acquires the lock
8. `odd()` waits, because `count` is even (== 2)... now both threads are waiting and neither can signal the condition.
Things may happen slightly differently depending on which thread goes first, but both threads still get stuck in a way similar to the above.
Both examples are unreliable, though, because they don't account for spurious wakeups when waiting for the condition. Normally a loop should be used to retry the wait if the desired wakeup conditions aren't met, holding the lock the whole time so a signal won't be missed:
```
pthread_mutex_lock(&lock);
/* ...stuff... */
/* Use a loop to restart the wait if it was interrupted early */
while(count % 2 != 0)
pthread_cond_wait(&cond,&lock);
/* ...stuff... */
pthread_mutex_unlock(&lock);
``` | In the first example, in `even()`, then if count is odd, you `pthread_cond_signal` `odd()` to run if `count` is even. `count` will be incremented, and the mutex dropped. At this point `odd()` may run and signal `even()` before `even()` ever reaches the `pthread_cond_wait()`. Now `odd()` will never again signal `even()` (because `count` is now even), and the `even()`'s `pthread_cond_wait()` will never exit.
But both of your examples are buggy. You are (last full line) reading `count` outside the mutex that protects it. |
27,216,349 | I want a quick way to burn a ZIP file into an ISO file so I use NeroCmd.exe which is the command-line tool for Nero. When I'm using the following command:
```
NeroCmd --write --drivename "Image Recorder" --real --iso isoName rarFile.rar
```
The problem is that it prompts for the image name and I don't know if it's possible to specify it in the parameters and which parameter should I include, supposing the image name is "Image.iso".
**EDIT:**
I tried using `--output_image test.iso`, so my final code is:
```
NeroCmd --write --no_error_log --drivename "Image Recorder" --real --iso Drive --enable_abort --underrun_prot --output_image Image.iso --verify rarFile.rar
```
But no file was created, here's the console output:
```
PHASE: Unspecified
[i] Generation of disc structures started
Creating directories
[i] Creating directories
PHASE: Unspecified
[i] Generation of disc structures completed
Checking discs
[i] Checking discs
Enter file name to save image to (RETURN to abort): GameSetup.iso
There is not enough space available to burn the image.
Enter file name to save image to (RETURN to abort): Not enough space available in the given location.
[!] Canceled by user
ERROR: The operation cannot be performed without user interaction!
User aborted!
```
The command works perfectly without that parameter, but the problem is it prompts. | 2014/11/30 | [
"https://Stackoverflow.com/questions/27216349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133866/"
] | In the first example, in `even()`, then if count is odd, you `pthread_cond_signal` `odd()` to run if `count` is even. `count` will be incremented, and the mutex dropped. At this point `odd()` may run and signal `even()` before `even()` ever reaches the `pthread_cond_wait()`. Now `odd()` will never again signal `even()` (because `count` is now even), and the `even()`'s `pthread_cond_wait()` will never exit.
But both of your examples are buggy. You are (last full line) reading `count` outside the mutex that protects it. | ```
#include <stdio.h>
#include <pthread.h>
#include<iostream>
void *odd(void* data);
void *even(void* data);
static int count=0;
pthread_mutex_t mutex;
pthread_cond_t cond;
int main()
{
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,&even,0);
pthread_create(&thread2,NULL,&odd,0);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
void *even(void* data)
{
pthread_mutex_lock(&mutex);
while(count< 10)
{
while(count%2!=0)
{
pthread_cond_wait(&cond,&mutex);
}
std::cout<<count;
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
void *odd(void* data)
{
pthread_mutex_lock(&mutex);
while(count<10)
{
while(count%2!=1)
{
pthread_cond_wait(&cond,&mutex);
}
std::cout<<count;
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
``` |
27,216,349 | I want a quick way to burn a ZIP file into an ISO file so I use NeroCmd.exe which is the command-line tool for Nero. When I'm using the following command:
```
NeroCmd --write --drivename "Image Recorder" --real --iso isoName rarFile.rar
```
The problem is that it prompts for the image name and I don't know if it's possible to specify it in the parameters and which parameter should I include, supposing the image name is "Image.iso".
**EDIT:**
I tried using `--output_image test.iso`, so my final code is:
```
NeroCmd --write --no_error_log --drivename "Image Recorder" --real --iso Drive --enable_abort --underrun_prot --output_image Image.iso --verify rarFile.rar
```
But no file was created, here's the console output:
```
PHASE: Unspecified
[i] Generation of disc structures started
Creating directories
[i] Creating directories
PHASE: Unspecified
[i] Generation of disc structures completed
Checking discs
[i] Checking discs
Enter file name to save image to (RETURN to abort): GameSetup.iso
There is not enough space available to burn the image.
Enter file name to save image to (RETURN to abort): Not enough space available in the given location.
[!] Canceled by user
ERROR: The operation cannot be performed without user interaction!
User aborted!
```
The command works perfectly without that parameter, but the problem is it prompts. | 2014/11/30 | [
"https://Stackoverflow.com/questions/27216349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133866/"
] | In the first example, some variation of the below may happen:
1. `even()` acquires the lock
2. `even()` prints `count` (which is 0) and signals the condition (though `odd()` can't wake until `even()` releases the lock)
3. `even()` increments `count` to 1
4. `even()` releases the lock, and `odd()` wakes.
5. `odd()` increments `count` to 2
6. `odd()` releases the lock (but hasn't signalled the condition)
7. `odd()` acquires the lock
8. `odd()` waits, because `count` is even (== 2)... now both threads are waiting and neither can signal the condition.
Things may happen slightly differently depending on which thread goes first, but both threads still get stuck in a way similar to the above.
Both examples are unreliable, though, because they don't account for spurious wakeups when waiting for the condition. Normally a loop should be used to retry the wait if the desired wakeup conditions aren't met, holding the lock the whole time so a signal won't be missed:
```
pthread_mutex_lock(&lock);
/* ...stuff... */
/* Use a loop to restart the wait if it was interrupted early */
while(count % 2 != 0)
pthread_cond_wait(&cond,&lock);
/* ...stuff... */
pthread_mutex_unlock(&lock);
``` | ```
#include <stdio.h>
#include <pthread.h>
#include<iostream>
void *odd(void* data);
void *even(void* data);
static int count=0;
pthread_mutex_t mutex;
pthread_cond_t cond;
int main()
{
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,&even,0);
pthread_create(&thread2,NULL,&odd,0);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
void *even(void* data)
{
pthread_mutex_lock(&mutex);
while(count< 10)
{
while(count%2!=0)
{
pthread_cond_wait(&cond,&mutex);
}
std::cout<<count;
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
void *odd(void* data)
{
pthread_mutex_lock(&mutex);
while(count<10)
{
while(count%2!=1)
{
pthread_cond_wait(&cond,&mutex);
}
std::cout<<count;
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
``` |
16,892,869 | I am using JSP and Servlets to first display a Form in a JSP page then inserting all the parameters to a table in the servlet. Here is some of the code which I am using:
```
<form action="ClassServlet" method="post">
<fieldset>
<label for="year">Year</label>
<input type="text" name="year" id="year" class="text ui-widget-content ui-corner-all" />
<label for="subject">Subject</label> <input type="text" name="subject" id="subject" value="" class="text ui-widget-content ui-corner-all" />
<label for="name">Name of your class</label> <input type="text" name="name1" id="name1" value="" class="text ui-widget-content ui-corner-all" />
<input type="hidden" name="teacher" id="teacher"
<%
out.println("value=\""+TeacherId+"\"");
%>
class="text ui-widget-content ui-corner-all" />
<input type="submit" value="Add">
</fieldset>
</form>
```
And for servlets:
```
PreparedStatement ps = null;
ps = con.prepareStatement("insert into TB_classes( CLASS_ID , CLASS_TEACHER_ID , CLASS_NAME , CLASS_YEAR , CLASS_SUBJECT) values (? , ? , ? , ? ,?) ");
ps.setString(1, "3");
ps.setString(2, request.getParameter("teacher"));
ps.setString(3, request.getParameter("name1"));
ps.setString(4, request.getParameter("year"));
ps.setString(5, request.getParameter("subject"));
ps.executeUpdate();
```
The code is working totally fine But being new to this I wanted to know is there any possible way to do same task on one page. If yes then how ? Please help? | 2013/06/03 | [
"https://Stackoverflow.com/questions/16892869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994926/"
] | What you're looking for is a process called ajax.
Rather than going to a new page, you want to send a message to the server to do the insert but without making the page change.
Take a look at using jquery with a servlet, so the flow would be something like the following in javascript.
```
$.post('/servlet');
```
Then in that servlet, just do the insert SQL statement.
Take a look at the short example [here](http://nareshkumarh.wordpress.com/2012/10/11/jquery-ajax-json-servlet-example/) for further clarification. | you can have both input and output on the same page with the use of XmlHttpRequest in java script.
The following code snippet should work out for you...
```
var xhReq = new XMLHttpRequest();
xhReq.open("post", "ClassServlet", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
```
use this code on the click event of your submit button... then it will send the request to 'ClassServelet' and display the output in an alert box. |
16,892,869 | I am using JSP and Servlets to first display a Form in a JSP page then inserting all the parameters to a table in the servlet. Here is some of the code which I am using:
```
<form action="ClassServlet" method="post">
<fieldset>
<label for="year">Year</label>
<input type="text" name="year" id="year" class="text ui-widget-content ui-corner-all" />
<label for="subject">Subject</label> <input type="text" name="subject" id="subject" value="" class="text ui-widget-content ui-corner-all" />
<label for="name">Name of your class</label> <input type="text" name="name1" id="name1" value="" class="text ui-widget-content ui-corner-all" />
<input type="hidden" name="teacher" id="teacher"
<%
out.println("value=\""+TeacherId+"\"");
%>
class="text ui-widget-content ui-corner-all" />
<input type="submit" value="Add">
</fieldset>
</form>
```
And for servlets:
```
PreparedStatement ps = null;
ps = con.prepareStatement("insert into TB_classes( CLASS_ID , CLASS_TEACHER_ID , CLASS_NAME , CLASS_YEAR , CLASS_SUBJECT) values (? , ? , ? , ? ,?) ");
ps.setString(1, "3");
ps.setString(2, request.getParameter("teacher"));
ps.setString(3, request.getParameter("name1"));
ps.setString(4, request.getParameter("year"));
ps.setString(5, request.getParameter("subject"));
ps.executeUpdate();
```
The code is working totally fine But being new to this I wanted to know is there any possible way to do same task on one page. If yes then how ? Please help? | 2013/06/03 | [
"https://Stackoverflow.com/questions/16892869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994926/"
] | There are several technologies, which I only can recommend.
You could do it all in one servlet as follows:
* On HTTP GET (normal page call) fill the data *model* = do `request.setAttribute("TeacherId", teacherId);` and forward to the JSP with the form, the *view*.
* On HTTP POST (coming back from the form), do the SQL INSERT, and for the new case, call the doGet.
In the form use `${TeacherId}`.
To derive a new record ID from the database itself. In MySQL that would be an INT AUTO\_INCR field. And the generated primary key could be retrieved as follows:
```
ps = con.prepareStatement("insert into TB_classes"
+ "( CLASS_TEACHER_ID , CLASS_NAME , CLASS_YEAR , CLASS_SUBJECT) "
+ "values (? , ? , ? ,?)");
ps.setString(1, request.getParameter("teacher"));
ps.setString(2, request.getParameter("name1"));
ps.setString(3, request.getParameter("year"));
ps.setString(4, request.getParameter("subject"));
ps.executeUpdate();
ResultSet primaryKeysRS = ps.getGeneratedKeys();
if (primaryKeyRS.next()) {
int classId = primaryKeyRS.getInt(1);
...
}
primaryKeysRS.close();
``` | you can have both input and output on the same page with the use of XmlHttpRequest in java script.
The following code snippet should work out for you...
```
var xhReq = new XMLHttpRequest();
xhReq.open("post", "ClassServlet", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
```
use this code on the click event of your submit button... then it will send the request to 'ClassServelet' and display the output in an alert box. |
59,514,022 | I wanted to ask if there is a way in Java where I can read in, basically any file format (N3, JSON, RDF-XML) etc and then convert it into turtle(.ttl). I have searched on Google to get some idea, but they mainly just explain for specific file types and how a file type can be converted to RDF whereas I want it the other way.
EDIT (following the code example given in the answer):
```
if(FilePath.getText().equals("")){
FilePath.setText("Cannot be empty");
}else{
try {
// get the inputFile from file chooser and setting a text field with
// the path (FilePath is the variable name fo the textField in which the
// path to the selected file from file chooser is done earlier)
FileInputStream fis = new FileInputStream(FilePath.getText());
// guess the format of the input file (default set to RDF/XML)
// when clicking on the error I get take to this line.
RDFFormat inputFormat = Rio.getParserFormatForFileName(fis.toString()).orElse(RDFFormat.RDFXML);
//create a parser for the input file and a writer for Turtle
RDFParser rdfParser = Rio.createParser(inputFormat);
RDFWriter rdfWriter = Rio.createWriter(RDFFormat.TURTLE,
new FileOutputStream("./" + fileName + ".ttl"));
//link parser to the writer
rdfParser.setRDFHandler(rdfWriter);
//start the conversion
InputStream inputStream = fis;
rdfParser.parse(inputStream, fis.toString());
//exception handling
} catch (FileNotFoundException ex) {
Logger.getLogger(FileConverter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileConverter.class.getName()).log(Level.SEVERE, null, ex);
}
}
```
I have added "eclipse-rdf4j-3.0.3-onejar.jar" to the Libraries folder in NetBeans and now when I run the program I keep getting this error:
>
> Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
> at org.eclipse.rdf4j.common.lang.service.ServiceRegistry.(ServiceRegistry.java:31)
>
>
>
Any help or advice would be highly appreciated. Thank you. | 2019/12/28 | [
"https://Stackoverflow.com/questions/59514022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12615393/"
] | Yes, this is possible. One option is to use [Eclipse RDF4J](https://rdf4j.org/) for this purpose, or more specifically, its [Rio parser/writer toolkit](https://rdf4j.org/documentation/programming/rio/).
Here's a code example using RDF4J Rio. It detects the syntax format of the input file based on the file extension, and directly writes the data to a new file, in Turtle syntax:
```java
// the input file
java.net.URL url = new URL(“http://example.org/example.rdf”);
// guess the format of the input file (default to RDF/XML)
RDFFormat inputFormat = Rio.getParserFormatForFileName(url.toString()).orElse(RDFFormat.RDFXML);
// create a parser for the input file and a writer for Turtle format
RDFParser rdfParser = Rio.createParser(inputFormat);
RDFWriter rdfWriter = Rio.createWriter(RDFFormat.TURTLE,
new FileOutputStream("/path/to/example-output.ttl"));
// link the parser to the writer
rdfParser.setRDFHandler(rdfWriter);
// start the conversion
try(InputStream inputStream = url.openStream()) {
rdfParser.parse(inputStream, url.toString());
}
catch (IOException | RDFParseException | RDFHandlerException e) { ... }
```
For more examples, see the [RDF4J documentation](https://rdf4j.org/documentation/).
*edit* Regarding your `NoClassDefFoundError`: you're missing a necessary third party library on your classpath (in this particular case, a logging library).
Instead of using the onejar, it's probably better to use Maven (or Gradle) to set up your project. See the [development environment setup](https://rdf4j.org/documentation/programming/setup/) notes, or for a more step by step guide, see [this tutorial](https://rdf4j.org/documentation/maven-eclipse-project/) (the tutorial uses Eclipse rather than Netbeans, but the points about how to set up your maven project will be very similar in Netbeans).
If you really don't want to use Maven, what you can also do is just [download the RDF4J SDK](https://rdf4j.org/download/), which is a ZIP file. Unpack it, and just add all jar files in the `lib/` directory to Netbeans. | An other option would be to use [Apache Jena](https://jena.apache.org/tutorials/rdf_api.html). |