qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
If you just want to compute (column a) % (column b), you don't need `apply`, just do it directly: ``` In [7]: df['a'] % df['c'] Out[7]: 0 -1.132022 1 -0.939493 2 0.201931 3 0.511374 4 -0.694647 5 -0.023486 Name: a ```
I have given the comparison of all three discussed above. **Using values** ``` %timeit df['value'] = df['a'].values % df['c'].values ``` 139 µs ± 1.91 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) **Without values** ``` %timeit df['value'] = df['a']%df['c'] ``` 216 µs ± 1.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) **Apply function** ``` %timeit df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1) ``` 474 µs ± 5.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
Seems you forgot the `''` of your string. ``` In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) In [44]: df Out[44]: a b c Value 0 -1.674308 foo 0.343801 0.044698 1 -2.163236 bar -2.046438 -0.116798 2 -0.199115 foo -0.458050 -0.199115 3 0.918646 bar -0.007185 -0.001006 4 1.336830 foo 0.534292 0.268245 5 0.976844 bar -0.773630 -0.570417 ``` BTW, in my opinion, following way is more elegant: ``` In [53]: def my_test2(row): ....: return row['a'] % row['c'] ....: In [54]: df['Value'] = df.apply(my_test2, axis=1) ```
Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df ``` def add5(x): return x+5 df[['a', 'b']].apply(add5) ```
16,353,729
I have some problems with the Pandas apply function, when using multiple columns with the following dataframe ``` df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, 'c' : np.random.randn(6)}) ``` and the following function ``` def my_test(a, b): return a % b ``` When I try to apply this function with : ``` df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1) ``` I get the error message: ``` NameError: ("global name 'a' is not defined", u'occurred at index 0') ``` I do not understand this message, I defined the name properly. I would highly appreciate any help on this issue Update Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ''. However I still get the same issue using a more complex function such as: ``` def my_test(a): cum_diff = 0 for ix in df.index(): cum_diff = cum_diff + (a - df['a'][ix]) return cum_diff ```
2013/05/03
[ "https://Stackoverflow.com/questions/16353729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331506/" ]
Seems you forgot the `''` of your string. ``` In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) In [44]: df Out[44]: a b c Value 0 -1.674308 foo 0.343801 0.044698 1 -2.163236 bar -2.046438 -0.116798 2 -0.199115 foo -0.458050 -0.199115 3 0.918646 bar -0.007185 -0.001006 4 1.336830 foo 0.534292 0.268245 5 0.976844 bar -0.773630 -0.570417 ``` BTW, in my opinion, following way is more elegant: ``` In [53]: def my_test2(row): ....: return row['a'] % row['c'] ....: In [54]: df['Value'] = df.apply(my_test2, axis=1) ```
If you just want to compute (column a) % (column b), you don't need `apply`, just do it directly: ``` In [7]: df['a'] % df['c'] Out[7]: 0 -1.132022 1 -0.939493 2 0.201931 3 0.511374 4 -0.694647 5 -0.023486 Name: a ```
44,137,998
Auto slash(/) with leading and trailing space in a date value is working fine. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```html <input type="text" id="date" /> ``` But when I tried to remove the space before and after slash(/). But when I deleting each character using backspace key, slash is not deleting. Below is what I tried. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" /> ``` Please suggest me to rectify this.
2017/05/23
[ "https://Stackoverflow.com/questions/44137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000103/" ]
```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```css input { word-spacing:-3px; } ``` ```html <input type="text" id="date" /> ``` You can 'cheat' and use some CSS: ``` word-spacing:-3px; ``` This moves the `/` closer to the text. The reason it doesn't work when you remove the spaces from the JavaScript is because your code is looking for a string length of `2`, but the string length goes to `3` when you add the `/` with no spaces.
Here's a alternate answer even though [Albzi's answer](https://stackoverflow.com/a/44138117/4760460) works perfectly fine. You can use the `keydown` event and check if backspace or delete is being pressed and `return false` in your event. I also added a `maxlength` of 10 to your `input` element so it does not exceed 10 characters. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('keydown', function(e) { this.type = 'text'; var input = this.value; var key = e.keyCode || e.charCode; if (key == 8 || key == 46) // here's where it checks if backspace or delete is being pressed return false; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" maxlength="10" /> ```
44,137,998
Auto slash(/) with leading and trailing space in a date value is working fine. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```html <input type="text" id="date" /> ``` But when I tried to remove the space before and after slash(/). But when I deleting each character using backspace key, slash is not deleting. Below is what I tried. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" /> ``` Please suggest me to rectify this.
2017/05/23
[ "https://Stackoverflow.com/questions/44137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000103/" ]
```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```css input { word-spacing:-3px; } ``` ```html <input type="text" id="date" /> ``` You can 'cheat' and use some CSS: ``` word-spacing:-3px; ``` This moves the `/` closer to the text. The reason it doesn't work when you remove the spaces from the JavaScript is because your code is looking for a string length of `2`, but the string length goes to `3` when you add the `/` with no spaces.
I also had this come up as a requirement for an application that I am building and I implemented my solution like this. ```js $(document).ready(function () { Date.prototype.toShortDateString = function() { return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear(); } //#region CUSTOM FUNCTIONS FOR DATEPICKERS function isTextSelected(input) { if (typeof input.selectionStart == "number" && input.selectionStart != input.value.length && input.selectionStart != input.selectionEnd) { return true; } else if (typeof document.selection != "undefined") { input.focus(); return document.selection.createRange().text == input.value; } return false; } function isNumber(e) { var allowedKeys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105]; if ($.inArray(e.keyCode, allowedKeys) != -1 && !e.originalEvent.shiftKey) { return true; } return false; } function isBackspace(keyCode) { var allowedKeys = [8]; if ($.inArray(keyCode, allowedKeys) != -1) { return true; } return false; } function isAllowedKey(keyCode) { var allowedKeys = [9, 13, 16, 37, 38, 39, 40];//191,111]; if ($.inArray(keyCode, allowedKeys) != -1) { return true; } return false; } //#endregion $.fn.extend({ allowMMDDYYYY: function (validate) { $(this).keydown(function (e) { var that = this; if (!isNumber(e) && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) { e.preventDefault(); } else if ($(that).val().length == 10 && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) {// && !isTextSelected(e.target) && isNumber(e.keyCode)) { if(!isTextSelected(e.target) && isNumber(e)) e.preventDefault(); } }); $(this).keyup(function (e) { var that = this; var value = $(that).val(); if (e.keyCode != 8 && !isAllowedKey(e.keyCode)) { switch (value.length) { case 2: $(that).val(value + "/"); break; case 3: if (value.indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2, 1)); } break; case 4: if (value.substr(0,3).indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2, 2)); } break; case 5: if (e.target.selectionStart == value.length) { if (e.target.selectionStart != 1) { $(that).val(value + "/"); } } break; case 6: if (e.target.selectionStart == value.length) { if (value.substr(5).indexOf("/") == -1) { $(that).val(value.substr(0, 5) + "/" + value.substr(5, 1)); } } else if (e.target.selectionStart == 2) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)) e.target.selectionStart = 3; e.target.selectionEnd = 3; } break; case 7: if (e.target.selectionStart == value.length) { if (value.substr(5).indexOf("/") == -1) { $(that).val(value.substr(0, 6) + "/" + value.substr(5, 2)); } } else if (e.target.selectionStart == 2) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)); e.target.selectionStart = 3; e.target.selectionEnd = 3; } break; case 9: if (value.substr(3, 5).indexOf("/") == -1) { $(that).val(value.substr(0,5) + "/" + value.substr(5)) } else if (value.substr(0, 3).indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)) } break; //IF THE LENGTH IS 10 (ONKEYUP) THEN CALL VALIDATION ON OTHER DATEPICKER ELEMENTS. case 10: if (!isTextSelected(e.target)) { validate(); } break; } } }); } }); //#endregion $("input[data-role='datepicker']").each(function (i, o) { var jqueryElement = $(o); jqueryElement.allowMMDDYYYY(function () { //THIS IS MY CALLBACK FUNCTION TO ALLOW VALIDATION ON OTHER ELEMENTS console.log("validating"); }); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" data-role="datepicker"/> ``` My requirements we to be able to enter MMddyyyy format without slashes and it would auto populate the slashes as they typed. Solution does not allow any characters but numbers,backspace, arrow keys, ctrl, and shift key. This extension also has a callback function so that you can validate other elements after a date has been entered (since i was using jquery validator).
44,137,998
Auto slash(/) with leading and trailing space in a date value is working fine. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```html <input type="text" id="date" /> ``` But when I tried to remove the space before and after slash(/). But when I deleting each character using backspace key, slash is not deleting. Below is what I tried. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" /> ``` Please suggest me to rectify this.
2017/05/23
[ "https://Stackoverflow.com/questions/44137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000103/" ]
```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```css input { word-spacing:-3px; } ``` ```html <input type="text" id="date" /> ``` You can 'cheat' and use some CSS: ``` word-spacing:-3px; ``` This moves the `/` closer to the text. The reason it doesn't work when you remove the spaces from the JavaScript is because your code is looking for a string length of `2`, but the string length goes to `3` when you add the `/` with no spaces.
This is my regex solution for React: ``` // add auto "/" for date, i.e. MM/YY handleExpInput(e) { // ignore invalid input if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) { return; } let input = e.target.value; if (/^\d{3,}$/.test(input)) { input = input.match(new RegExp('.{1,2}', 'g')).join('/'); } this.setState({ expDateShow: input, }); } ```
44,137,998
Auto slash(/) with leading and trailing space in a date value is working fine. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```html <input type="text" id="date" /> ``` But when I tried to remove the space before and after slash(/). But when I deleting each character using backspace key, slash is not deleting. Below is what I tried. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" /> ``` Please suggest me to rectify this.
2017/05/23
[ "https://Stackoverflow.com/questions/44137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000103/" ]
Here's a alternate answer even though [Albzi's answer](https://stackoverflow.com/a/44138117/4760460) works perfectly fine. You can use the `keydown` event and check if backspace or delete is being pressed and `return false` in your event. I also added a `maxlength` of 10 to your `input` element so it does not exceed 10 characters. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('keydown', function(e) { this.type = 'text'; var input = this.value; var key = e.keyCode || e.charCode; if (key == 8 || key == 46) // here's where it checks if backspace or delete is being pressed return false; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" maxlength="10" /> ```
I also had this come up as a requirement for an application that I am building and I implemented my solution like this. ```js $(document).ready(function () { Date.prototype.toShortDateString = function() { return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear(); } //#region CUSTOM FUNCTIONS FOR DATEPICKERS function isTextSelected(input) { if (typeof input.selectionStart == "number" && input.selectionStart != input.value.length && input.selectionStart != input.selectionEnd) { return true; } else if (typeof document.selection != "undefined") { input.focus(); return document.selection.createRange().text == input.value; } return false; } function isNumber(e) { var allowedKeys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105]; if ($.inArray(e.keyCode, allowedKeys) != -1 && !e.originalEvent.shiftKey) { return true; } return false; } function isBackspace(keyCode) { var allowedKeys = [8]; if ($.inArray(keyCode, allowedKeys) != -1) { return true; } return false; } function isAllowedKey(keyCode) { var allowedKeys = [9, 13, 16, 37, 38, 39, 40];//191,111]; if ($.inArray(keyCode, allowedKeys) != -1) { return true; } return false; } //#endregion $.fn.extend({ allowMMDDYYYY: function (validate) { $(this).keydown(function (e) { var that = this; if (!isNumber(e) && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) { e.preventDefault(); } else if ($(that).val().length == 10 && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) {// && !isTextSelected(e.target) && isNumber(e.keyCode)) { if(!isTextSelected(e.target) && isNumber(e)) e.preventDefault(); } }); $(this).keyup(function (e) { var that = this; var value = $(that).val(); if (e.keyCode != 8 && !isAllowedKey(e.keyCode)) { switch (value.length) { case 2: $(that).val(value + "/"); break; case 3: if (value.indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2, 1)); } break; case 4: if (value.substr(0,3).indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2, 2)); } break; case 5: if (e.target.selectionStart == value.length) { if (e.target.selectionStart != 1) { $(that).val(value + "/"); } } break; case 6: if (e.target.selectionStart == value.length) { if (value.substr(5).indexOf("/") == -1) { $(that).val(value.substr(0, 5) + "/" + value.substr(5, 1)); } } else if (e.target.selectionStart == 2) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)) e.target.selectionStart = 3; e.target.selectionEnd = 3; } break; case 7: if (e.target.selectionStart == value.length) { if (value.substr(5).indexOf("/") == -1) { $(that).val(value.substr(0, 6) + "/" + value.substr(5, 2)); } } else if (e.target.selectionStart == 2) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)); e.target.selectionStart = 3; e.target.selectionEnd = 3; } break; case 9: if (value.substr(3, 5).indexOf("/") == -1) { $(that).val(value.substr(0,5) + "/" + value.substr(5)) } else if (value.substr(0, 3).indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)) } break; //IF THE LENGTH IS 10 (ONKEYUP) THEN CALL VALIDATION ON OTHER DATEPICKER ELEMENTS. case 10: if (!isTextSelected(e.target)) { validate(); } break; } } }); } }); //#endregion $("input[data-role='datepicker']").each(function (i, o) { var jqueryElement = $(o); jqueryElement.allowMMDDYYYY(function () { //THIS IS MY CALLBACK FUNCTION TO ALLOW VALIDATION ON OTHER ELEMENTS console.log("validating"); }); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" data-role="datepicker"/> ``` My requirements we to be able to enter MMddyyyy format without slashes and it would auto populate the slashes as they typed. Solution does not allow any characters but numbers,backspace, arrow keys, ctrl, and shift key. This extension also has a callback function so that you can validate other elements after a date has been entered (since i was using jquery validator).
44,137,998
Auto slash(/) with leading and trailing space in a date value is working fine. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```html <input type="text" id="date" /> ``` But when I tried to remove the space before and after slash(/). But when I deleting each character using backspace key, slash is not deleting. Below is what I tried. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" /> ``` Please suggest me to rectify this.
2017/05/23
[ "https://Stackoverflow.com/questions/44137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000103/" ]
Here's a alternate answer even though [Albzi's answer](https://stackoverflow.com/a/44138117/4760460) works perfectly fine. You can use the `keydown` event and check if backspace or delete is being pressed and `return false` in your event. I also added a `maxlength` of 10 to your `input` element so it does not exceed 10 characters. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('keydown', function(e) { this.type = 'text'; var input = this.value; var key = e.keyCode || e.charCode; if (key == 8 || key == 46) // here's where it checks if backspace or delete is being pressed return false; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" maxlength="10" /> ```
This is my regex solution for React: ``` // add auto "/" for date, i.e. MM/YY handleExpInput(e) { // ignore invalid input if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) { return; } let input = e.target.value; if (/^\d{3,}$/.test(input)) { input = input.match(new RegExp('.{1,2}', 'g')).join('/'); } this.setState({ expDateShow: input, }); } ```
44,137,998
Auto slash(/) with leading and trailing space in a date value is working fine. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + ' / ' : v; }); this.value = output.join('').substr(0, 14); }); ``` ```html <input type="text" id="date" /> ``` But when I tried to remove the space before and after slash(/). But when I deleting each character using backspace key, slash is not deleting. Below is what I tried. ```js var date = document.getElementById('date'); function checkValue(str, max) { if (str.charAt(0) !== '0' || str == '00') { var num = parseInt(str); if (isNaN(num) || num <= 0 || num > max) num = 1; str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString(); }; return str; }; date.addEventListener('input', function(e) { this.type = 'text'; var input = this.value; if (/\D\/$/.test(input)) input = input.substr(0, input.length - 1); var values = input.split('/').map(function(v) { return v.replace(/\D/g, '') }); if (values[0]) values[0] = checkValue(values[0], 12); if (values[1]) values[1] = checkValue(values[1], 31); var output = values.map(function(v, i) { return v.length == 2 && i < 2 ? v + '/' : v; }); this.value = output.join('').substr(0, 10); }); ``` ```html <input type="text" id="date" /> ``` Please suggest me to rectify this.
2017/05/23
[ "https://Stackoverflow.com/questions/44137998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000103/" ]
I also had this come up as a requirement for an application that I am building and I implemented my solution like this. ```js $(document).ready(function () { Date.prototype.toShortDateString = function() { return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear(); } //#region CUSTOM FUNCTIONS FOR DATEPICKERS function isTextSelected(input) { if (typeof input.selectionStart == "number" && input.selectionStart != input.value.length && input.selectionStart != input.selectionEnd) { return true; } else if (typeof document.selection != "undefined") { input.focus(); return document.selection.createRange().text == input.value; } return false; } function isNumber(e) { var allowedKeys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105]; if ($.inArray(e.keyCode, allowedKeys) != -1 && !e.originalEvent.shiftKey) { return true; } return false; } function isBackspace(keyCode) { var allowedKeys = [8]; if ($.inArray(keyCode, allowedKeys) != -1) { return true; } return false; } function isAllowedKey(keyCode) { var allowedKeys = [9, 13, 16, 37, 38, 39, 40];//191,111]; if ($.inArray(keyCode, allowedKeys) != -1) { return true; } return false; } //#endregion $.fn.extend({ allowMMDDYYYY: function (validate) { $(this).keydown(function (e) { var that = this; if (!isNumber(e) && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) { e.preventDefault(); } else if ($(that).val().length == 10 && !isBackspace(e.keyCode) && !isAllowedKey(e.keyCode)) {// && !isTextSelected(e.target) && isNumber(e.keyCode)) { if(!isTextSelected(e.target) && isNumber(e)) e.preventDefault(); } }); $(this).keyup(function (e) { var that = this; var value = $(that).val(); if (e.keyCode != 8 && !isAllowedKey(e.keyCode)) { switch (value.length) { case 2: $(that).val(value + "/"); break; case 3: if (value.indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2, 1)); } break; case 4: if (value.substr(0,3).indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2, 2)); } break; case 5: if (e.target.selectionStart == value.length) { if (e.target.selectionStart != 1) { $(that).val(value + "/"); } } break; case 6: if (e.target.selectionStart == value.length) { if (value.substr(5).indexOf("/") == -1) { $(that).val(value.substr(0, 5) + "/" + value.substr(5, 1)); } } else if (e.target.selectionStart == 2) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)) e.target.selectionStart = 3; e.target.selectionEnd = 3; } break; case 7: if (e.target.selectionStart == value.length) { if (value.substr(5).indexOf("/") == -1) { $(that).val(value.substr(0, 6) + "/" + value.substr(5, 2)); } } else if (e.target.selectionStart == 2) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)); e.target.selectionStart = 3; e.target.selectionEnd = 3; } break; case 9: if (value.substr(3, 5).indexOf("/") == -1) { $(that).val(value.substr(0,5) + "/" + value.substr(5)) } else if (value.substr(0, 3).indexOf("/") == -1) { $(that).val(value.substr(0, 2) + "/" + value.substr(2)) } break; //IF THE LENGTH IS 10 (ONKEYUP) THEN CALL VALIDATION ON OTHER DATEPICKER ELEMENTS. case 10: if (!isTextSelected(e.target)) { validate(); } break; } } }); } }); //#endregion $("input[data-role='datepicker']").each(function (i, o) { var jqueryElement = $(o); jqueryElement.allowMMDDYYYY(function () { //THIS IS MY CALLBACK FUNCTION TO ALLOW VALIDATION ON OTHER ELEMENTS console.log("validating"); }); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" data-role="datepicker"/> ``` My requirements we to be able to enter MMddyyyy format without slashes and it would auto populate the slashes as they typed. Solution does not allow any characters but numbers,backspace, arrow keys, ctrl, and shift key. This extension also has a callback function so that you can validate other elements after a date has been entered (since i was using jquery validator).
This is my regex solution for React: ``` // add auto "/" for date, i.e. MM/YY handleExpInput(e) { // ignore invalid input if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) { return; } let input = e.target.value; if (/^\d{3,}$/.test(input)) { input = input.match(new RegExp('.{1,2}', 'g')).join('/'); } this.setState({ expDateShow: input, }); } ```
62,003,452
How do I revert/remove the changes done in an older multi-file commit, but only do it in a single file? I.e. something like `git revert <commit-specifier> <file>` except `git revert` does not accept `<file>` argument. None of the following answers addresses this problem: [Git: Revert old commit on single file](https://stackoverflow.com/questions/31493383/git-revert-old-commit-on-single-file) is rather about how to debug conflicts. [Undo a particular commit in Git that's been pushed to remote repos](https://stackoverflow.com/questions/2318777/undo-a-particular-commit-in-git-thats-been-pushed-to-remote-repos) does not address my single file issue. [Git: revert on older commit](https://stackoverflow.com/questions/35879142/git-revert-on-older-commit) also does not address single file issue.
2020/05/25
[ "https://Stackoverflow.com/questions/62003452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155425/" ]
Git is a tool-set, not a solution, so there are multiple solutions. However, one relatively straightforward way is to start with `git revert -n`, which starts the revert but does not *finish* it: ``` git revert -n <commit-specifier> ``` This tries to back out *all* changes to *all* files, of course. You only want to back out changes to *one* file. But now that `git revert` has made this attempt *without committing* you merely need to restore each file that you *didn't* want changed. Get a list of such files, and then use `git checkout` or `git restore`—using the commands exactly as `git status` advises—to make those files match the current commit. Now `git status` will show only the one file as *changes to be committed*, and you can now `git commit` that one file. Another relatively straightforward way is to use: ``` git show <commit-specifier> -- <pathspec> | git apply -R ``` You can add `-3` to the `git apply` command if you'd like Git to use a three-way merge on the base version of the file; in this case it may help to add `--full-index` to the `git show` command options. (As with the cherry-pick `-n` method you will have to commit the result yourself.)
You can revert it first: ``` git revert <commit-specifier> ``` then reset HEAD~1: ``` git reset --soft HEAD~1 ``` and git add only the file that you want to do the revert: ``` git add -- <revert_file> ``` Now you can commit again ``` git commit --amend ``` remove all the other changes: ``` git checkout -- . ```
62,003,452
How do I revert/remove the changes done in an older multi-file commit, but only do it in a single file? I.e. something like `git revert <commit-specifier> <file>` except `git revert` does not accept `<file>` argument. None of the following answers addresses this problem: [Git: Revert old commit on single file](https://stackoverflow.com/questions/31493383/git-revert-old-commit-on-single-file) is rather about how to debug conflicts. [Undo a particular commit in Git that's been pushed to remote repos](https://stackoverflow.com/questions/2318777/undo-a-particular-commit-in-git-thats-been-pushed-to-remote-repos) does not address my single file issue. [Git: revert on older commit](https://stackoverflow.com/questions/35879142/git-revert-on-older-commit) also does not address single file issue.
2020/05/25
[ "https://Stackoverflow.com/questions/62003452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155425/" ]
Git is a tool-set, not a solution, so there are multiple solutions. However, one relatively straightforward way is to start with `git revert -n`, which starts the revert but does not *finish* it: ``` git revert -n <commit-specifier> ``` This tries to back out *all* changes to *all* files, of course. You only want to back out changes to *one* file. But now that `git revert` has made this attempt *without committing* you merely need to restore each file that you *didn't* want changed. Get a list of such files, and then use `git checkout` or `git restore`—using the commands exactly as `git status` advises—to make those files match the current commit. Now `git status` will show only the one file as *changes to be committed*, and you can now `git commit` that one file. Another relatively straightforward way is to use: ``` git show <commit-specifier> -- <pathspec> | git apply -R ``` You can add `-3` to the `git apply` command if you'd like Git to use a three-way merge on the base version of the file; in this case it may help to add `--full-index` to the `git show` command options. (As with the cherry-pick `-n` method you will have to commit the result yourself.)
I accidentally committed a file with a couple of lines of changes and realized after 10 or so commits later. That file should have never been part of any commit. Reverting using any of the suggested answers in this post or any other SO answers was horrible in my case. Ran into lots of merge conflict hell and numerous git errors. I gave up and manually opened the local file and copied/pasted the text from master and made the commit. Viola! PR didn't show that file at all as changed - luckily I'm the only one working on that repo for now. It literally took me 10 seconds. If I followed the answers in SO, I would probably spend 15 or more minutes and introduced more problems trying to fix the conflicts. Why in the world git has to make things super complicated for trivial use cases?! So if you run into issues like I had, see if you can revert the changes directly on the file itself and commit. I realize what I did may not apply to everyone's situation but still simple things are so unnecessarily complicated in git! Just look at the number of error prone git commands you need to monkey around with to accomplish what I did in 10 seconds.
62,003,452
How do I revert/remove the changes done in an older multi-file commit, but only do it in a single file? I.e. something like `git revert <commit-specifier> <file>` except `git revert` does not accept `<file>` argument. None of the following answers addresses this problem: [Git: Revert old commit on single file](https://stackoverflow.com/questions/31493383/git-revert-old-commit-on-single-file) is rather about how to debug conflicts. [Undo a particular commit in Git that's been pushed to remote repos](https://stackoverflow.com/questions/2318777/undo-a-particular-commit-in-git-thats-been-pushed-to-remote-repos) does not address my single file issue. [Git: revert on older commit](https://stackoverflow.com/questions/35879142/git-revert-on-older-commit) also does not address single file issue.
2020/05/25
[ "https://Stackoverflow.com/questions/62003452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155425/" ]
You can revert it first: ``` git revert <commit-specifier> ``` then reset HEAD~1: ``` git reset --soft HEAD~1 ``` and git add only the file that you want to do the revert: ``` git add -- <revert_file> ``` Now you can commit again ``` git commit --amend ``` remove all the other changes: ``` git checkout -- . ```
I accidentally committed a file with a couple of lines of changes and realized after 10 or so commits later. That file should have never been part of any commit. Reverting using any of the suggested answers in this post or any other SO answers was horrible in my case. Ran into lots of merge conflict hell and numerous git errors. I gave up and manually opened the local file and copied/pasted the text from master and made the commit. Viola! PR didn't show that file at all as changed - luckily I'm the only one working on that repo for now. It literally took me 10 seconds. If I followed the answers in SO, I would probably spend 15 or more minutes and introduced more problems trying to fix the conflicts. Why in the world git has to make things super complicated for trivial use cases?! So if you run into issues like I had, see if you can revert the changes directly on the file itself and commit. I realize what I did may not apply to everyone's situation but still simple things are so unnecessarily complicated in git! Just look at the number of error prone git commands you need to monkey around with to accomplish what I did in 10 seconds.
26,108
In the start of my adventure the PCs will not be together. I plan to have all them fight 1-3 encounters alone before finally meeting up. I read in the book about setting encounters but the minimum I saw was a party of three, nothing about being alone. They are of course all lvl 1. Their classes are Figher, Ranger, Sorcerer and a Cleric. All the encounters will take place in a not so dense forest covered in fog. Some more char info. The Cleric has 13STR 10DEX 15CON 13INT 15WIS 18CHA Feat is Quicken Spell The Fighter has 18STR 12DEX 15CON 13INT 13WIS 10CHA Feat is Power Attack, Cleave The Ranger has 11STR 15DEX 16CON 10INT 15WIS 10CHA Feat is Alertness The Sorcerer has 13STR 15DEX 16CON 14INT 14WIS 19CHA Feat is Spell Focus I want them to fight animals, undead and maybe even demons if possible. The theme is mostly dark and dreary foes.
2013/06/04
[ "https://rpg.stackexchange.com/questions/26108", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/8433/" ]
The results are going to be highly variable, and depend on the situation, and depend a lot on the critters facing each PC, along with the way the PCs are built. Any PC built to depend on someone else (for instance, the Sorcerer, depending on his spells, or the Ranger, if he is built for ranged combat) will struggle more, and should probably be allocated less opponents than the others. The basic way to do this, though, is to take the XP allowance for a typical party at this encounter level, and divide by 5 (since encounters are based on 5 PCs normally). If you want an average encounter for level 1 PCs, this would be 80xp. A single raven or lizard are worth 65xp. Working the other way, a single Kobold (100xp) looks to be between CR 1 and 2 for a single level 1 PC, and a single Goblin is just over a CR2. A Hard encounter at level 1 is a CR4 encounter, which would translate to 240xp for a single character, which would be slightly more than a pair of Kobolds.
Apart from [YogoZuno's excellent answer](https://rpg.stackexchange.com/a/26109/5746), I've found that in practice the challenge a single PC can face safely varies a lot. With only one person fighting, a few unlucky rolls can be all it takes for a player to die. However, sometimes the player will do a lot better than expected and simply plough through the challenge. I would suggest giving them one or two NPCs to temporarily help out. If they are commoners with sickles and staves, they aren't going to majorly boost your player's power, but they can drag him away and bandage his wounds if he is bleeding out. Also, this is an opportunity for each player to shine. It can be a good idea to set encounters up to play to your PC's strengths - if you let the Cleric fight some low-HD skeletons instead of Kobolds, he'll have an easier time of it by turning them/using *Cure Light Wounds* to damage them and it will help teach him tactics for when he's in the party later on. If you let the fighter go up against a bunch of weak mooks (maybe animated piles of branches with a 1/2HD each who are clustered together) instead of a single, stronger foe, his cleave will come in very handy and he will start to learn to group his foes. This can teach valuable lessons to your players as well as characters.
26,108
In the start of my adventure the PCs will not be together. I plan to have all them fight 1-3 encounters alone before finally meeting up. I read in the book about setting encounters but the minimum I saw was a party of three, nothing about being alone. They are of course all lvl 1. Their classes are Figher, Ranger, Sorcerer and a Cleric. All the encounters will take place in a not so dense forest covered in fog. Some more char info. The Cleric has 13STR 10DEX 15CON 13INT 15WIS 18CHA Feat is Quicken Spell The Fighter has 18STR 12DEX 15CON 13INT 13WIS 10CHA Feat is Power Attack, Cleave The Ranger has 11STR 15DEX 16CON 10INT 15WIS 10CHA Feat is Alertness The Sorcerer has 13STR 15DEX 16CON 14INT 14WIS 19CHA Feat is Spell Focus I want them to fight animals, undead and maybe even demons if possible. The theme is mostly dark and dreary foes.
2013/06/04
[ "https://rpg.stackexchange.com/questions/26108", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/8433/" ]
The results are going to be highly variable, and depend on the situation, and depend a lot on the critters facing each PC, along with the way the PCs are built. Any PC built to depend on someone else (for instance, the Sorcerer, depending on his spells, or the Ranger, if he is built for ranged combat) will struggle more, and should probably be allocated less opponents than the others. The basic way to do this, though, is to take the XP allowance for a typical party at this encounter level, and divide by 5 (since encounters are based on 5 PCs normally). If you want an average encounter for level 1 PCs, this would be 80xp. A single raven or lizard are worth 65xp. Working the other way, a single Kobold (100xp) looks to be between CR 1 and 2 for a single level 1 PC, and a single Goblin is just over a CR2. A Hard encounter at level 1 is a CR4 encounter, which would translate to 240xp for a single character, which would be slightly more than a pair of Kobolds.
At level 1, on their own, they can basically die to anything. Simple example: take [4 kobolds](http://www.d20pfsrd.com/bestiary/monster-listings/humanoids/kobold) (total CR ~= 1). * Your sorcerer has 8hp, they deal ~3 pts. damage per successful attack. They have a 50% chance of hitting, so two hit each round. Well that sorcerer is dead in 2 rounds. At best he goes first, gets a color spray and runs. Of course, one critical by any Kobold is bad news. Each attack only has a 2.5% chance of being a critical, but you have 4 guys. So there is a 10% chance that round 1 is a crit on the sorcerer and a 5% chance of 2 crits. * Your cleric has about 10hp, but dramatically better armor. Your cleric gets hit 20-25% of the time, but has limited attack spells and only hits about 30-40% of the time. That's definitely an edge, but if the kobolds maneuver into flanking position, that edge disappears. The cleric *does* have the ability to heal and channel, but the channel also heals the kobolds and is generally a net loss. So the problem you'll find with these first level fights is that things are very random. Unless the characters can work the terrain to their advantage, **they are two unlucky rolls away from death**. BTW, Cleric with Quicken Spell at level 1 is basically useless. Quicken is completely unusable until level 9. Given the Cleric's high CHA, they should consider [Selective Channeling](http://www.d20pfsrd.com/feats/general-feats/selective-channeling---final). Which is dramatically more useful.
26,108
In the start of my adventure the PCs will not be together. I plan to have all them fight 1-3 encounters alone before finally meeting up. I read in the book about setting encounters but the minimum I saw was a party of three, nothing about being alone. They are of course all lvl 1. Their classes are Figher, Ranger, Sorcerer and a Cleric. All the encounters will take place in a not so dense forest covered in fog. Some more char info. The Cleric has 13STR 10DEX 15CON 13INT 15WIS 18CHA Feat is Quicken Spell The Fighter has 18STR 12DEX 15CON 13INT 13WIS 10CHA Feat is Power Attack, Cleave The Ranger has 11STR 15DEX 16CON 10INT 15WIS 10CHA Feat is Alertness The Sorcerer has 13STR 15DEX 16CON 14INT 14WIS 19CHA Feat is Spell Focus I want them to fight animals, undead and maybe even demons if possible. The theme is mostly dark and dreary foes.
2013/06/04
[ "https://rpg.stackexchange.com/questions/26108", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/8433/" ]
> > I want them to fight animals, undead and maybe even demons if possible. > The theme is mostly dark and dreary foes. > > > Are just the foes dark or is it a theme in your whole world? If that is the case then kidnapping might be common and the rangers encounter could be with some peasants whose child has gone missing. It needs to be tracked down though a wilderness. Add a few brave people to help (e.g. the boys father and his brother, armed with pitchforks) and you have an instant mini goal with some NPCs as a buffer. For the cleric you may be able to do something similar pacifying a graveyard. The local priest or some of the family of the people who are burried there can help the their loved ones find eternal rest. This might involve turning them, or just keeping them at a distance while some rites are performed to clean the source of evil. This makes a great way to have an encounter without a fight. The fighter on the other hand is build for fighting. I think that [YogoZuno 's answer](https://rpg.stackexchange.com/questions/26108/how-many-enemies-can-one-lvl-1-pc-handle/26109#26109) is quite good. Give the fighter something to easy kill. Adding an NPC or two or making the enemies quite slow will help. (Slow in case you have bad rolls and need to run away). A nice tactical map might also help (e.g. one narrow point though which a few monsters must pass, and which can be blocked by the fighter. This will teach him that it is not just about hitting enemies, but also about placement on the map). As for the sorcerer: Charisma 19. That will come in handy with a nice political mission (e.g. convince the major of a neighbouring town to aid another town or to convince a group of NPCs that they really want to do something else. Which, unless bungled, is yet another safe no-combat encounter. No risk of dying.
Apart from [YogoZuno's excellent answer](https://rpg.stackexchange.com/a/26109/5746), I've found that in practice the challenge a single PC can face safely varies a lot. With only one person fighting, a few unlucky rolls can be all it takes for a player to die. However, sometimes the player will do a lot better than expected and simply plough through the challenge. I would suggest giving them one or two NPCs to temporarily help out. If they are commoners with sickles and staves, they aren't going to majorly boost your player's power, but they can drag him away and bandage his wounds if he is bleeding out. Also, this is an opportunity for each player to shine. It can be a good idea to set encounters up to play to your PC's strengths - if you let the Cleric fight some low-HD skeletons instead of Kobolds, he'll have an easier time of it by turning them/using *Cure Light Wounds* to damage them and it will help teach him tactics for when he's in the party later on. If you let the fighter go up against a bunch of weak mooks (maybe animated piles of branches with a 1/2HD each who are clustered together) instead of a single, stronger foe, his cleave will come in very handy and he will start to learn to group his foes. This can teach valuable lessons to your players as well as characters.
26,108
In the start of my adventure the PCs will not be together. I plan to have all them fight 1-3 encounters alone before finally meeting up. I read in the book about setting encounters but the minimum I saw was a party of three, nothing about being alone. They are of course all lvl 1. Their classes are Figher, Ranger, Sorcerer and a Cleric. All the encounters will take place in a not so dense forest covered in fog. Some more char info. The Cleric has 13STR 10DEX 15CON 13INT 15WIS 18CHA Feat is Quicken Spell The Fighter has 18STR 12DEX 15CON 13INT 13WIS 10CHA Feat is Power Attack, Cleave The Ranger has 11STR 15DEX 16CON 10INT 15WIS 10CHA Feat is Alertness The Sorcerer has 13STR 15DEX 16CON 14INT 14WIS 19CHA Feat is Spell Focus I want them to fight animals, undead and maybe even demons if possible. The theme is mostly dark and dreary foes.
2013/06/04
[ "https://rpg.stackexchange.com/questions/26108", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/8433/" ]
> > I want them to fight animals, undead and maybe even demons if possible. > The theme is mostly dark and dreary foes. > > > Are just the foes dark or is it a theme in your whole world? If that is the case then kidnapping might be common and the rangers encounter could be with some peasants whose child has gone missing. It needs to be tracked down though a wilderness. Add a few brave people to help (e.g. the boys father and his brother, armed with pitchforks) and you have an instant mini goal with some NPCs as a buffer. For the cleric you may be able to do something similar pacifying a graveyard. The local priest or some of the family of the people who are burried there can help the their loved ones find eternal rest. This might involve turning them, or just keeping them at a distance while some rites are performed to clean the source of evil. This makes a great way to have an encounter without a fight. The fighter on the other hand is build for fighting. I think that [YogoZuno 's answer](https://rpg.stackexchange.com/questions/26108/how-many-enemies-can-one-lvl-1-pc-handle/26109#26109) is quite good. Give the fighter something to easy kill. Adding an NPC or two or making the enemies quite slow will help. (Slow in case you have bad rolls and need to run away). A nice tactical map might also help (e.g. one narrow point though which a few monsters must pass, and which can be blocked by the fighter. This will teach him that it is not just about hitting enemies, but also about placement on the map). As for the sorcerer: Charisma 19. That will come in handy with a nice political mission (e.g. convince the major of a neighbouring town to aid another town or to convince a group of NPCs that they really want to do something else. Which, unless bungled, is yet another safe no-combat encounter. No risk of dying.
At level 1, on their own, they can basically die to anything. Simple example: take [4 kobolds](http://www.d20pfsrd.com/bestiary/monster-listings/humanoids/kobold) (total CR ~= 1). * Your sorcerer has 8hp, they deal ~3 pts. damage per successful attack. They have a 50% chance of hitting, so two hit each round. Well that sorcerer is dead in 2 rounds. At best he goes first, gets a color spray and runs. Of course, one critical by any Kobold is bad news. Each attack only has a 2.5% chance of being a critical, but you have 4 guys. So there is a 10% chance that round 1 is a crit on the sorcerer and a 5% chance of 2 crits. * Your cleric has about 10hp, but dramatically better armor. Your cleric gets hit 20-25% of the time, but has limited attack spells and only hits about 30-40% of the time. That's definitely an edge, but if the kobolds maneuver into flanking position, that edge disappears. The cleric *does* have the ability to heal and channel, but the channel also heals the kobolds and is generally a net loss. So the problem you'll find with these first level fights is that things are very random. Unless the characters can work the terrain to their advantage, **they are two unlucky rolls away from death**. BTW, Cleric with Quicken Spell at level 1 is basically useless. Quicken is completely unusable until level 9. Given the Cleric's high CHA, they should consider [Selective Channeling](http://www.d20pfsrd.com/feats/general-feats/selective-channeling---final). Which is dramatically more useful.
3,510,884
The harmonic-geometric mean inequality is defined as follows $$ \frac{n}{\sum\_{i=1}^n \frac{1}{x\_i}} \leq (\Pi\_{i=1}^{n}x\_i)^{\frac{1}{n}}\tag{1} $$ Given the following linear programming problem $$ \min \sum\_{i=1}^n \frac{1}{x\_i}\\ \begin{align} \text{s.t} \,\,\,\,\,\,\,& \Pi\_{i=1}^{n}x\_i=1\\ &x\geq0 \end{align} $$ where $x \in \mathbb{R}^n$. If we set up KKT conditions, we end up with $x =[1, \cdots, 1]^{\top}$ as the optimal point of the optimization. Hence the minimum value is $n$. **Question:** using the above result how we can prove $(1)$?
2020/01/16
[ "https://math.stackexchange.com/questions/3510884", "https://math.stackexchange.com", "https://math.stackexchange.com/users/494522/" ]
Suppose we have $y\_1, \ldots, y\_n > 0.$ Define $P = \prod\_{i=1}^n y\_i$ and $x\_i = y\_i \cdot P^{-1/n}.$ Then $x\_i \geq 0$ and $\prod\_{i=1}^n x\_i = 1$ so by the result of the optimization problem we have $$ \sum\_{i=1}^n \frac{1}{x\_i} \geq n$$ Since $x\_i = y\_i \cdot P^{-1/n}$ we have $$\sum\_{i=1}^n \frac{P^{1/n}}{y\_i} \geq n$$ which rearranges to $$\frac{n}{\sum\_{i=1}^n \frac{1}{y\_i}} \leq P^{1/n}$$ as required.
Because by AM-GM: $$\left(\prod\_{i=1}^nx\_i\right)^{\frac{1}{n}}\sum\_{i=1}^n\frac{1}{x\_i}\geq\left(\prod\_{i=1}^nx\_i\right)^{\frac{1}{n}}\cdot n\left(\prod\_{i=1}^n\frac{1}{x\_i}\right)^{\frac{1}{n}}=\frac{n\left(\prod\limits\_{i=1}^nx\_i\right)^{\frac{1}{n}}}{\left(\prod\limits\_{i=1}^nx\_i\right)^{\frac{1}{n}}}=n.$$
3,510,884
The harmonic-geometric mean inequality is defined as follows $$ \frac{n}{\sum\_{i=1}^n \frac{1}{x\_i}} \leq (\Pi\_{i=1}^{n}x\_i)^{\frac{1}{n}}\tag{1} $$ Given the following linear programming problem $$ \min \sum\_{i=1}^n \frac{1}{x\_i}\\ \begin{align} \text{s.t} \,\,\,\,\,\,\,& \Pi\_{i=1}^{n}x\_i=1\\ &x\geq0 \end{align} $$ where $x \in \mathbb{R}^n$. If we set up KKT conditions, we end up with $x =[1, \cdots, 1]^{\top}$ as the optimal point of the optimization. Hence the minimum value is $n$. **Question:** using the above result how we can prove $(1)$?
2020/01/16
[ "https://math.stackexchange.com/questions/3510884", "https://math.stackexchange.com", "https://math.stackexchange.com/users/494522/" ]
Suppose we have $y\_1, \ldots, y\_n > 0.$ Define $P = \prod\_{i=1}^n y\_i$ and $x\_i = y\_i \cdot P^{-1/n}.$ Then $x\_i \geq 0$ and $\prod\_{i=1}^n x\_i = 1$ so by the result of the optimization problem we have $$ \sum\_{i=1}^n \frac{1}{x\_i} \geq n$$ Since $x\_i = y\_i \cdot P^{-1/n}$ we have $$\sum\_{i=1}^n \frac{P^{1/n}}{y\_i} \geq n$$ which rearranges to $$\frac{n}{\sum\_{i=1}^n \frac{1}{y\_i}} \leq P^{1/n}$$ as required.
We can use also the TL method: Since our inequality is homogeneous, we can assume $\prod\limits\_{i=1}^nx\_i=1.$ Thus, we need to prove that: $$\sum\_{i=1}^n\frac{1}{x\_i}\geq n.$$ Indeed, $$\sum\_{i=1}^n\frac{1}{x\_i}-n=\sum\_{i=1}^n\left(\frac{1}{x\_i}-1+\ln{x\_i}\right)\geq0$$ because easy to show that for any positive $x$ the following inequality is true. $$\frac{1}{x}-1+\ln{x}\geq0.$$ Indeed, let $f(x)=\frac{1}{x}-1+\ln{x}.$ Thus, $$f'(x)=-\frac{1}{x^2}+\frac{1}{x}=\frac{x-1}{x^2},$$ which says that $x\_{min}=1$ and $$f(x)\geq f(1)=0.$$
1,641,591
I find myself writing the same argument checking code all the time for number-crunching: ``` def myfun(a, b): if a < 0: raise ValueError('a cannot be < 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b ``` Is there a better way? I was told not to use 'assert' for these things (though I don't see the problem, apart from not knowing the value of the variable that caused the error). edit: To clarify, the arguments are usually just numbers and the error checking conditions can be complex, non-trivial and will not necessarily lead to an exception later, but simply to a wrong result. (unstable algorithms, meaningless solutions etc)
2009/10/29
[ "https://Stackoverflow.com/questions/1641591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198637/" ]
`assert` gets optimized away if you run with `python -O` (modest optimizations, but sometimes nice to have). One preferable alternative if you have patterns that often repeat may be to use decorators -- great way to factor out repetition. E.g., say you have a zillion functions that must be called with arguments by-position (not by-keyword) and must have their first arguments positive; then...: ``` def firstargpos(f): def wrapper(first, *args): if first < 0: raise ValueError(whateveryouwish) return f(first, *args) return wrapper ``` then you say something like: @firstargpos def myfun(a, b): ... and the checks are performed in the decorators (or rather the wrapper closure it returns) once and for all. So, the only tricky part is figuring out exactly what checks your functions need and how best to call the decorator(s) to express those (hard to say, without seeing the set of functions you're defining and the set of checks each needs!-). Remember, DRY ("Don't Repeat Yourself") is close to the top spot among guiding principles in software development, and Python has reasonable support to allow you to implement DRY and avoid boilerplatey, repetitious code!-)
You don't want to use assert because your code can be run (and is by default on some systems) in such a way that assert lines are not checked and do not raise errors (`-O` command line flag). If you're using a lot of variables that are all supposed to have those same properties, why not subclass whatever type you're using and add that check to the class itself? Then when you use your new class, you know you never have an invalid value, and don't have to go checking for it all over the place.
1,641,591
I find myself writing the same argument checking code all the time for number-crunching: ``` def myfun(a, b): if a < 0: raise ValueError('a cannot be < 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b ``` Is there a better way? I was told not to use 'assert' for these things (though I don't see the problem, apart from not knowing the value of the variable that caused the error). edit: To clarify, the arguments are usually just numbers and the error checking conditions can be complex, non-trivial and will not necessarily lead to an exception later, but simply to a wrong result. (unstable algorithms, meaningless solutions etc)
2009/10/29
[ "https://Stackoverflow.com/questions/1641591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198637/" ]
You don't want to use assert because your code can be run (and is by default on some systems) in such a way that assert lines are not checked and do not raise errors (`-O` command line flag). If you're using a lot of variables that are all supposed to have those same properties, why not subclass whatever type you're using and add that check to the class itself? Then when you use your new class, you know you never have an invalid value, and don't have to go checking for it all over the place.
I'm not sure if this will answer your question, but it strikes me that checking a lot of arguments at the start of a function isn't very *pythonic*. What I mean by this is that it is the assumption of most pythonistas that we are all consenting adults, and we trust each other not to do something stupid. Here's how I'd write your example: ``` def myfun(a, b): '''a cannot be < 0''' return a + b ``` This has three distinct advantages. First off, it's concise, there's really no extra code doing anything unrelated to what you're actually trying to get done. Second, it puts the information exactly where it belongs, in `help(myfun)`, where pythonistas are expected to look for usage notes. Finally, is a non-positive value for `a` really an error? Although you might think so, unless something definitely will break if a is zero (here it probably wont), then maybe letting it slip through and cause an error up the call stream is wiser. after all, if `a + b` is in error, it raises an exception which gets passed up the call stack and behavior is still pretty much the same.
1,641,591
I find myself writing the same argument checking code all the time for number-crunching: ``` def myfun(a, b): if a < 0: raise ValueError('a cannot be < 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b ``` Is there a better way? I was told not to use 'assert' for these things (though I don't see the problem, apart from not knowing the value of the variable that caused the error). edit: To clarify, the arguments are usually just numbers and the error checking conditions can be complex, non-trivial and will not necessarily lead to an exception later, but simply to a wrong result. (unstable algorithms, meaningless solutions etc)
2009/10/29
[ "https://Stackoverflow.com/questions/1641591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198637/" ]
`assert` gets optimized away if you run with `python -O` (modest optimizations, but sometimes nice to have). One preferable alternative if you have patterns that often repeat may be to use decorators -- great way to factor out repetition. E.g., say you have a zillion functions that must be called with arguments by-position (not by-keyword) and must have their first arguments positive; then...: ``` def firstargpos(f): def wrapper(first, *args): if first < 0: raise ValueError(whateveryouwish) return f(first, *args) return wrapper ``` then you say something like: @firstargpos def myfun(a, b): ... and the checks are performed in the decorators (or rather the wrapper closure it returns) once and for all. So, the only tricky part is figuring out exactly what checks your functions need and how best to call the decorator(s) to express those (hard to say, without seeing the set of functions you're defining and the set of checks each needs!-). Remember, DRY ("Don't Repeat Yourself") is close to the top spot among guiding principles in software development, and Python has reasonable support to allow you to implement DRY and avoid boilerplatey, repetitious code!-)
I'm not sure if this will answer your question, but it strikes me that checking a lot of arguments at the start of a function isn't very *pythonic*. What I mean by this is that it is the assumption of most pythonistas that we are all consenting adults, and we trust each other not to do something stupid. Here's how I'd write your example: ``` def myfun(a, b): '''a cannot be < 0''' return a + b ``` This has three distinct advantages. First off, it's concise, there's really no extra code doing anything unrelated to what you're actually trying to get done. Second, it puts the information exactly where it belongs, in `help(myfun)`, where pythonistas are expected to look for usage notes. Finally, is a non-positive value for `a` really an error? Although you might think so, unless something definitely will break if a is zero (here it probably wont), then maybe letting it slip through and cause an error up the call stream is wiser. after all, if `a + b` is in error, it raises an exception which gets passed up the call stack and behavior is still pretty much the same.
13,672,482
Let a module to abstract `Area` operations (bad definition) ``` class Area someShapeType where area :: someShapeType -> Float -- module utilities sumAreas :: Area someShapeType => [someShapeType] sumAreas = sum . map area ``` Let a **posteriori** explicit shape type modules (good or acceptable definition) ``` data Point = Point Float Float data Circle = Circle Point Float instance Surface Circle where surface (Circle _ r) = 2 * pi * r data Rectangle = Rectangle Point Point instance Surface Rectangle where surface (Rectangle (Point x1 y1) (Point x2 y2)) = abs $ (x2 - x1) * (y2 - y1) ``` Let some data ``` c1 = Circle (Point 0 0) 1 r1 = Rectangle (Point 0 0) (Point 1 1) ``` Then, trying to use ``` totalArea = sumAreas [c1, r1] ``` the `[c1, r1]` type must be expanded to `[Circle]` or `[Rectangle]`! (and is not valid) I can do using `forall` **and** a extra `data` type like this ``` data Shape = forall a . Surface a => Shape a sumSurfaces :: [Shape] -> Float sumSurfaces = sum . map (\(Shape x) -> surface x) ``` then, next code run successfully ``` sumSurfaces [Shape c1, Shape r1] ``` but I think, the use of `data Shape` and `Shape` constructor (on `[Shape c1, ...]` and lambda argument) is ugly (my first [and bad] way is pretty). What is the correct way to do *"Heterogeneous polymorphism in Haskell"*? Thank you very much for your time!
2012/12/02
[ "https://Stackoverflow.com/questions/13672482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1540749/" ]
Your existential solution is okay. It might be "prettier" to instead use a `GADT`, as in: ``` {-# LANGUAGE GADTs #-} data Shape where Shape :: (Surface a) => a -> Shape ``` ...and as leftaraoundabout suggests, you may be able to structure your code differently. But I think you've basically hit up against the [Expression Problem](http://en.wikipedia.org/wiki/Expression_problem) here; or perhaps, more accurately: by trying to structure your code cleverly (separate type for each shape with classes) in anticipation of the EP you've introduced new difficulties for yourself. Check out the fun [Data Types a la Carte](http://lambda-the-ultimate.org/node/2700) by Wouter Swierstra for an elegant solution to what I hope is related to your problem. Maybe someone can comment with good packages on hackage to look at that are inspired by that paper.
Your first (and bad) way is not pretty, it's Lispy. This is just not possible in a statically typed language; even when you do such a thing in e.g. Java you're actually introducing a seperate quantification step by using base class pointers, which is analoguous to the `data Shape = forall a. Surface a`. There is dispute about whether existential quantification is nice, I think most Haskellers don't like it very much. It's certainly not the right thing to use here: `sum [ area c1, area c2 ]` is much easier and works just as well. But there sure are more complex problems where it looks differently; when you "need" heterogeneous polymorphism then existentials are the way to go. Just remember that you can always get around this: since Haskell is lazy, you can just apply all possible operations (in this example it's only `area`) "pre-emptively", store all the results in some record, and output a list of these records instead of a list of polymorphic objects. This way you keep all the information. Or, and that's more idiomatic, don't produce a list of such objects at all. You want to do something with the objects, so why not just pass these *actions* into the function where you produce different `Shape`s, and apply them right in place! This reversal exchanges existential quantification for universal quantification, which is rather more widely accepted.
13,672,482
Let a module to abstract `Area` operations (bad definition) ``` class Area someShapeType where area :: someShapeType -> Float -- module utilities sumAreas :: Area someShapeType => [someShapeType] sumAreas = sum . map area ``` Let a **posteriori** explicit shape type modules (good or acceptable definition) ``` data Point = Point Float Float data Circle = Circle Point Float instance Surface Circle where surface (Circle _ r) = 2 * pi * r data Rectangle = Rectangle Point Point instance Surface Rectangle where surface (Rectangle (Point x1 y1) (Point x2 y2)) = abs $ (x2 - x1) * (y2 - y1) ``` Let some data ``` c1 = Circle (Point 0 0) 1 r1 = Rectangle (Point 0 0) (Point 1 1) ``` Then, trying to use ``` totalArea = sumAreas [c1, r1] ``` the `[c1, r1]` type must be expanded to `[Circle]` or `[Rectangle]`! (and is not valid) I can do using `forall` **and** a extra `data` type like this ``` data Shape = forall a . Surface a => Shape a sumSurfaces :: [Shape] -> Float sumSurfaces = sum . map (\(Shape x) -> surface x) ``` then, next code run successfully ``` sumSurfaces [Shape c1, Shape r1] ``` but I think, the use of `data Shape` and `Shape` constructor (on `[Shape c1, ...]` and lambda argument) is ugly (my first [and bad] way is pretty). What is the correct way to do *"Heterogeneous polymorphism in Haskell"*? Thank you very much for your time!
2012/12/02
[ "https://Stackoverflow.com/questions/13672482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1540749/" ]
Your existential solution is okay. It might be "prettier" to instead use a `GADT`, as in: ``` {-# LANGUAGE GADTs #-} data Shape where Shape :: (Surface a) => a -> Shape ``` ...and as leftaraoundabout suggests, you may be able to structure your code differently. But I think you've basically hit up against the [Expression Problem](http://en.wikipedia.org/wiki/Expression_problem) here; or perhaps, more accurately: by trying to structure your code cleverly (separate type for each shape with classes) in anticipation of the EP you've introduced new difficulties for yourself. Check out the fun [Data Types a la Carte](http://lambda-the-ultimate.org/node/2700) by Wouter Swierstra for an elegant solution to what I hope is related to your problem. Maybe someone can comment with good packages on hackage to look at that are inspired by that paper.
What you originally did is hit the existential antipattern. Why use classes here anyways? ``` data Shape = Shape { area :: Double } data Point = Point Double Double circle :: Point -> Double -> Shape circle p r = Shape $ 2 * pi * r rectangle :: Point -> Point -> Shape rectangle (Point x1 y1) (Point x2 y2) = Shape $ abs $ (x2 - x1) * (y2 - y1) ``` And now you easily get what you want (a list of shapes): ``` *Main> map area [circle (Point 2 0) 5, rectangle (Point 0 0) (Point 2 10)] [31.41592653589793,20.0] ```
15,380,739
I am using the following code reference from Adobe Edge Commons example MixitBaby but I keep getting this error on Chrome & IE10, this works fine on Firefox though. "Uncaught ReferenceError: EC is not defined" ``` function soundSetup() { var assetsPath = "sound/"; EC.Sound.setup( [ {src: assetsPath + "introsound.mp3|" + assetsPath + "introsound.ogg", id: "intro"} ], function(){ EC.info("Sound setup finished", "DEMO"); } ); } yepnope({ load: "js/EdgeCommons-0.7.1.min.js", complete: function() { if(EC == undefined) yepnope({load: "js/EdgeCommons-0.7.1.min.js", complete: soundSetup}); else soundSetup(); } //complete }); ``` -Thanks
2013/03/13
[ "https://Stackoverflow.com/questions/15380739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079089/" ]
In string literals, a backslash `\` is used as a prefix for special characters. I'm sure you know about newline (`"\n"`) for example. If the special character after the backslash is an `x` then it means that the next two characters are hexadecimal digits, and those two digits are the translated by the compiler into a character. In your example the `sprintf` call adds a string, and then two separate characters based on the hexadecimal numbers `0xc2` and `0xb0`, which is UTF-8 for a degree character (see e.g. [this reference](http://www.utf8-chartable.de/unicode-utf8-table.pl?start=176&htmlent=1)).
That's a degree sign, encoded as UTF-8 unicode. You can have a look at a more complete list of characters and what they look like in UTF-8 [here](http://www.utf8-chartable.de/unicode-utf8-table.pl?start=128&number=128&utf8=string-literal&unicodeinhtml=hex).
15,380,739
I am using the following code reference from Adobe Edge Commons example MixitBaby but I keep getting this error on Chrome & IE10, this works fine on Firefox though. "Uncaught ReferenceError: EC is not defined" ``` function soundSetup() { var assetsPath = "sound/"; EC.Sound.setup( [ {src: assetsPath + "introsound.mp3|" + assetsPath + "introsound.ogg", id: "intro"} ], function(){ EC.info("Sound setup finished", "DEMO"); } ); } yepnope({ load: "js/EdgeCommons-0.7.1.min.js", complete: function() { if(EC == undefined) yepnope({load: "js/EdgeCommons-0.7.1.min.js", complete: soundSetup}); else soundSetup(); } //complete }); ``` -Thanks
2013/03/13
[ "https://Stackoverflow.com/questions/15380739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079089/" ]
That's a degree sign, encoded as UTF-8 unicode. You can have a look at a more complete list of characters and what they look like in UTF-8 [here](http://www.utf8-chartable.de/unicode-utf8-table.pl?start=128&number=128&utf8=string-literal&unicodeinhtml=hex).
In C, something in the format `\x???` in a string literal, where `???` are numbers, is a *Unicode escape*. It is a way of entering Unicode characters which cannot be entered with a keyboard. In this case, if you look at [this table](http://www.utf8-chartable.de/), you will see that the escape sequence `c2 b0` (written `\xC2\xB0` in your code encodes a **degree sign** - so that is what this means.
15,380,739
I am using the following code reference from Adobe Edge Commons example MixitBaby but I keep getting this error on Chrome & IE10, this works fine on Firefox though. "Uncaught ReferenceError: EC is not defined" ``` function soundSetup() { var assetsPath = "sound/"; EC.Sound.setup( [ {src: assetsPath + "introsound.mp3|" + assetsPath + "introsound.ogg", id: "intro"} ], function(){ EC.info("Sound setup finished", "DEMO"); } ); } yepnope({ load: "js/EdgeCommons-0.7.1.min.js", complete: function() { if(EC == undefined) yepnope({load: "js/EdgeCommons-0.7.1.min.js", complete: soundSetup}); else soundSetup(); } //complete }); ``` -Thanks
2013/03/13
[ "https://Stackoverflow.com/questions/15380739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1079089/" ]
In string literals, a backslash `\` is used as a prefix for special characters. I'm sure you know about newline (`"\n"`) for example. If the special character after the backslash is an `x` then it means that the next two characters are hexadecimal digits, and those two digits are the translated by the compiler into a character. In your example the `sprintf` call adds a string, and then two separate characters based on the hexadecimal numbers `0xc2` and `0xb0`, which is UTF-8 for a degree character (see e.g. [this reference](http://www.utf8-chartable.de/unicode-utf8-table.pl?start=176&htmlent=1)).
In C, something in the format `\x???` in a string literal, where `???` are numbers, is a *Unicode escape*. It is a way of entering Unicode characters which cannot be entered with a keyboard. In this case, if you look at [this table](http://www.utf8-chartable.de/), you will see that the escape sequence `c2 b0` (written `\xC2\xB0` in your code encodes a **degree sign** - so that is what this means.
62,515,551
I'm trying to add one more index value to the path: `$.data.library.category[2].book` using `jayway jsonpath` in following Json, ``` "data":{ "library":{ "class":"CRED", "category":[{ "book":"java 2.0" }, { "book":"java 3.0" }] } ``` but i'm not getting updated response in result json. My java code: ``` Configuration conf = Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL).addOptions(Option.SUPPRESS_EXCEPTIONS); DocumentContext documentContext = JsonPath.using(conf).parse(sampleJson); documentContext.set(JsonPath.compile("$.data.library.category[2].book"), "java 3.0"); ``` I have checked also with `documentContext.add`. Nothing works out. Since the array has 0 and 1 index, i can update the value there by JsonPath. But it dont have 2nd index, so not updating. But I need to insert new index in the last of given json as per jsonpath.
2020/06/22
[ "https://Stackoverflow.com/questions/62515551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13792129/" ]
Path `$.data.library.category[2].book` means that you want to update `3-rd` element in array. But there is no `3-rd` element yet. You need to create it first. You can add new element to array using `$.data.library.category` path. By providing a `Map` object you can define all required keys and values. See below example: ``` import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.Option; import java.io.File; import java.util.Collections; public class JsonPathApp { public static void main(String[] args) throws Exception { File jsonFile = new File("./resource/test.json").getAbsoluteFile(); Configuration conf = Configuration.defaultConfiguration() .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL) .addOptions(Option.SUPPRESS_EXCEPTIONS); DocumentContext document = JsonPath.using(conf).parse(jsonFile); JsonPath pathToArray = JsonPath.compile("$.data.library.category"); document.add(pathToArray, Collections.singletonMap("book", "java 3.1")); document.add(pathToArray, Collections.singletonMap("book", "java 3.2")); System.out.println(document.jsonString()); } } ``` Above code prints below `JSON`: ``` { "data":{ "library":{ "class":"CRED", "category":[ { "book":"java 2.0" }, { "book":"java 3.0" }, { "book":"java 3.1" }, { "book":"java 3.2" } ] } } } ```
I believe that `Json` class from <https://github.com/karatelabs/karate> can work for you. Given ``` String json = { "data": { "library": { "class": "CRED", "category": [ { "book": "java 2.0" }, { "book": "java 3.0" } ] } } } ``` What you need to do is ``` Json.of(json).set("$.data.library.category[2].book", "java 3.1") ``` And your output will be ``` { "data": { "library": { "class": "CRED", "category": [ { "book": "java 2.0" }, { "book": "java 3.0" }, { "book": "java 3.1" } ] } } } ```
3,852,758
What calls best emulate [pread/pwrite](http://manpages.ubuntu.com/manpages/lucid/en/man2/pwrite.2.html) in MSVC 10?
2010/10/04
[ "https://Stackoverflow.com/questions/3852758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149482/" ]
At the C runtime library level, look at [fread](http://msdn.microsoft.com/en-US/library/kt0etdcs%28v=VS.80%29.aspx), [fwrite](http://msdn.microsoft.com/en-US/library/h9t88zwz%28v=VS.80%29.aspx) and [fseek](http://msdn.microsoft.com/en-US/library/75yw9bf3%28v=VS.80%29.aspx). At the Win32 API level, have a look at [ReadFile](http://msdn.microsoft.com/en-us/library/aa365467%28v=VS.85%29.aspx), [WriteFile](http://msdn.microsoft.com/en-us/library/aa365747%28v=VS.85%29.aspx), and [SetFilePointer](http://msdn.microsoft.com/en-us/library/aa365541%28v=VS.85%29.aspx). MSDN has extensive coverage of [file I/O API's](http://msdn.microsoft.com/en-us/library/aa364232%28v=VS.85%29.aspx). Note that both ReadFile and WriteFile take an [OVERLAPPED](http://msdn.microsoft.com/en-us/library/ms684342%28v=VS.85%29.aspx) struct argument, which lets you specify a file offset. The offset is respected for all files that support byte offsets, even when opened for synchronous (i.e. non 'overlapped') I/O. Depending on the problem you are trying to solve, [file mapping](http://msdn.microsoft.com/en-us/library/aa366556%28v=VS.85%29.aspx) may be a better design choice.
It looks like you just use the **lpOverlapped** parameter to [**ReadFile**](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx)/[**WriteFile**](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365747%28v=vs.85%29.aspx) to pass a pointer to an [**OVERLAPPED**](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684342%28v=vs.85%29.aspx) structure with the offset specified in **Offset** and **OffsetHigh**. (Note: You don't actually get overlapping IO unless the handle was opened with **FILE\_FLAG\_OVERLAPPED**.)
3,852,758
What calls best emulate [pread/pwrite](http://manpages.ubuntu.com/manpages/lucid/en/man2/pwrite.2.html) in MSVC 10?
2010/10/04
[ "https://Stackoverflow.com/questions/3852758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149482/" ]
At the C runtime library level, look at [fread](http://msdn.microsoft.com/en-US/library/kt0etdcs%28v=VS.80%29.aspx), [fwrite](http://msdn.microsoft.com/en-US/library/h9t88zwz%28v=VS.80%29.aspx) and [fseek](http://msdn.microsoft.com/en-US/library/75yw9bf3%28v=VS.80%29.aspx). At the Win32 API level, have a look at [ReadFile](http://msdn.microsoft.com/en-us/library/aa365467%28v=VS.85%29.aspx), [WriteFile](http://msdn.microsoft.com/en-us/library/aa365747%28v=VS.85%29.aspx), and [SetFilePointer](http://msdn.microsoft.com/en-us/library/aa365541%28v=VS.85%29.aspx). MSDN has extensive coverage of [file I/O API's](http://msdn.microsoft.com/en-us/library/aa364232%28v=VS.85%29.aspx). Note that both ReadFile and WriteFile take an [OVERLAPPED](http://msdn.microsoft.com/en-us/library/ms684342%28v=VS.85%29.aspx) struct argument, which lets you specify a file offset. The offset is respected for all files that support byte offsets, even when opened for synchronous (i.e. non 'overlapped') I/O. Depending on the problem you are trying to solve, [file mapping](http://msdn.microsoft.com/en-us/library/aa366556%28v=VS.85%29.aspx) may be a better design choice.
The answer provided by Oren seems correct but doesn't seem to meet the needs. Actually, I too was here for searching the answer but couldn't find it. So, I will update a bit here. As said, At the C runtime library level, there are [fread](http://msdn.microsoft.com/en-US/library/kt0etdcs(v=VS.80).aspx), [fwrite](http://msdn.microsoft.com/en-US/library/h9t88zwz(v=VS.80).aspx) and [fseek](http://msdn.microsoft.com/en-US/library/75yw9bf3(v=VS.80).aspx). At the Win32 API level, we can have two level of abstractions. One at the lower level which works with **file descriptors** and other at higher level which works with Windows' defined data structures such as **File and Handle**. If you wish to work with Files and Handles, you have [ReadFile](http://msdn.microsoft.com/en-us/library/aa365467(v=VS.85).aspx), [WriteFile](http://msdn.microsoft.com/en-us/library/aa365747(v=VS.85).aspx), and [SetFilePointer](http://msdn.microsoft.com/en-us/library/aa365541(v=VS.85).aspx). But most the time, C++ developers prefer working with File Descriptors. For that, you have [\_read](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/read?view=vs-2019), [\_write](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/write?view=vs-2019) and [\_lseek](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/lseek-lseeki64?view=vs-2019).
3,852,758
What calls best emulate [pread/pwrite](http://manpages.ubuntu.com/manpages/lucid/en/man2/pwrite.2.html) in MSVC 10?
2010/10/04
[ "https://Stackoverflow.com/questions/3852758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149482/" ]
It looks like you just use the **lpOverlapped** parameter to [**ReadFile**](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx)/[**WriteFile**](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365747%28v=vs.85%29.aspx) to pass a pointer to an [**OVERLAPPED**](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684342%28v=vs.85%29.aspx) structure with the offset specified in **Offset** and **OffsetHigh**. (Note: You don't actually get overlapping IO unless the handle was opened with **FILE\_FLAG\_OVERLAPPED**.)
The answer provided by Oren seems correct but doesn't seem to meet the needs. Actually, I too was here for searching the answer but couldn't find it. So, I will update a bit here. As said, At the C runtime library level, there are [fread](http://msdn.microsoft.com/en-US/library/kt0etdcs(v=VS.80).aspx), [fwrite](http://msdn.microsoft.com/en-US/library/h9t88zwz(v=VS.80).aspx) and [fseek](http://msdn.microsoft.com/en-US/library/75yw9bf3(v=VS.80).aspx). At the Win32 API level, we can have two level of abstractions. One at the lower level which works with **file descriptors** and other at higher level which works with Windows' defined data structures such as **File and Handle**. If you wish to work with Files and Handles, you have [ReadFile](http://msdn.microsoft.com/en-us/library/aa365467(v=VS.85).aspx), [WriteFile](http://msdn.microsoft.com/en-us/library/aa365747(v=VS.85).aspx), and [SetFilePointer](http://msdn.microsoft.com/en-us/library/aa365541(v=VS.85).aspx). But most the time, C++ developers prefer working with File Descriptors. For that, you have [\_read](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/read?view=vs-2019), [\_write](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/write?view=vs-2019) and [\_lseek](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/lseek-lseeki64?view=vs-2019).
65,602,683
I have a valid HereMaps API Key and I am using python `requests` lib to execute a GET request to a link that is returned after an async call is made. I am trying to execute it like this: [https://aws-ap-southeast-1.matrix.router.hereapi.com/v8/matrix/01187ff8-7888-4ed6-af88-c8f9be9242d7/status?apiKey={my-api-key}](https://aws-ap-southeast-1.matrix.router.hereapi.com/v8/matrix/01187ff8-7888-4ed6-af88-c8f9be9242d7/status?apiKey=%7Bmy-api-key%7D) Even though I have provided the proper key before to generate this link above, the result of this request above returns: ``` { "error": "Unauthorized", "error_description": "No credentials found" } ``` How should we authenticate to check the status result for an async request on the Matrix Routing v8 API?
2021/01/06
[ "https://Stackoverflow.com/questions/65602683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8745534/" ]
There are two authentication methods [available to you for using HERE APIs](https://developer.here.com/documentation/identity-access-management/dev_guide/index.html): API key and OAuth token. Because of the way credentials are being handled, when you make an asynchronous request, you'll need to disable automatic client redirects when using API key, as the client will not add the `apiKey` parameter again to the URL it has been redirected to. There are many solutions to this problem when using Python and `requests`, and here's a complete example that might help: ```python import requests, time api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # "Profile mode (car fastest)" example request request = { "origins": [{"lat": 52.5309, "lng": 13.3849}, {"lat": 54.0924, "lng": 12.0991}], "destinations": [ {"lat": 51.3397, "lng": 12.3731}, {"lat": 51.0504, "lng": 13.7373}, ], "regionDefinition": {"type": "world"}, "profile": "carFast", } # Using a Session object allows you to persist certain parameters accross requests # see: https://requests.readthedocs.io/en/master/user/advanced/ session = requests.Session() # Add `?apiKey=xxxxxx` to all requests session.params = {"apiKey": api_key} # Raise an exception for any non 2xx or 3xx HTTP return codes session.hooks = {"response": lambda r, *args, **kwargs: r.raise_for_status()} # Send an asynchronous request, see: https://developer.here.com/documentation/matrix-routing-api/8.3.0/dev_guide/topics/get-started/asynchronous-request.html status_response = session.post( "https://matrix.router.hereapi.com/v8/matrix", json=request ).json() # Polling for the job status for 100 times # You might want to use exponential back-off instead of time.sleep for _ in range(0, 100): # do not follow the redirect here status_response = session.get( status_response["statusUrl"], allow_redirects=False ).json() if status_response["status"] == "completed": # download the result matrix_response = session.get(status_response["resultUrl"]).json() print(matrix_response) break elif status_response["accepted"] or status_response["inProgress"]: continue else: print(f"An error occured: {status_response}") break time.sleep(0.5) # sleep for 500 ms ``` Disclaimer: I work at HERE Technologies on Matrix Routing.
Please check the [documentation for the domain name to use for HERE services](https://developer.here.com/documentation/identity-access-management/dev_guide/topics/hosts-mapping.html). For Matrix Routing you should be using `matrix.route.ls.hereapi.com`. Disclosure: I'm a product manager at HERE Technologies
32,995,667
I need to select (count) rows with a specific date formatted by YEAR-MONTH-DAY. i try ``` $date = $_GET['date']; // requete qui recupere les evenements $result = "SELECT COUNT(*) FROM evenement WHERE STR_TO_DATE(start, '%Y-%m-%d') = $date"; // connexion a la base de donnees try { $bdd = new PDO('mysql:host=;dbname=', '', ''); } catch(Exception $e) { exit('Impossible de se connecter a la base de donnees.'); } $sth = $bdd->query($result); echo json_encode($sth->fetchColumn()); ``` where date variable is a date with that format. i want to count rows and return the number of rows with that date. i also try ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(start, '%Y-%m-%d') = $date"; ``` and ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(DATE(start), '%Y-%m-%d') = $date"; ``` but nothing works any ideas? Thanks
2015/10/07
[ "https://Stackoverflow.com/questions/32995667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3602203/" ]
You should convert your constant to a date, not the column. So, my first attempt would be: ``` SELECT COUNT(*) FROM evenement WHERE start = DATE('$date'); ``` However, that might not work. You might need to use `str_to_date()` with the appropriate format. The reason this method is better is because the optimizer can take advantage of an index on `evenement(start)`.
Change like this ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(start, '%Y-%m-%d') = '".$date."'"; ``` You need to enclose $date in '' quotes, else it will perform subtraction like(2014-10-01 = 2003)
32,995,667
I need to select (count) rows with a specific date formatted by YEAR-MONTH-DAY. i try ``` $date = $_GET['date']; // requete qui recupere les evenements $result = "SELECT COUNT(*) FROM evenement WHERE STR_TO_DATE(start, '%Y-%m-%d') = $date"; // connexion a la base de donnees try { $bdd = new PDO('mysql:host=;dbname=', '', ''); } catch(Exception $e) { exit('Impossible de se connecter a la base de donnees.'); } $sth = $bdd->query($result); echo json_encode($sth->fetchColumn()); ``` where date variable is a date with that format. i want to count rows and return the number of rows with that date. i also try ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(start, '%Y-%m-%d') = $date"; ``` and ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(DATE(start), '%Y-%m-%d') = $date"; ``` but nothing works any ideas? Thanks
2015/10/07
[ "https://Stackoverflow.com/questions/32995667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3602203/" ]
The responses and comments all led to this answer ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(DATE(start), '%Y-%m-%d') = DATE('".$date."')" ``` the problem was that the $date variable need DATE($date) and in SELECT need quotes.
Change like this ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(start, '%Y-%m-%d') = '".$date."'"; ``` You need to enclose $date in '' quotes, else it will perform subtraction like(2014-10-01 = 2003)
32,995,667
I need to select (count) rows with a specific date formatted by YEAR-MONTH-DAY. i try ``` $date = $_GET['date']; // requete qui recupere les evenements $result = "SELECT COUNT(*) FROM evenement WHERE STR_TO_DATE(start, '%Y-%m-%d') = $date"; // connexion a la base de donnees try { $bdd = new PDO('mysql:host=;dbname=', '', ''); } catch(Exception $e) { exit('Impossible de se connecter a la base de donnees.'); } $sth = $bdd->query($result); echo json_encode($sth->fetchColumn()); ``` where date variable is a date with that format. i want to count rows and return the number of rows with that date. i also try ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(start, '%Y-%m-%d') = $date"; ``` and ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(DATE(start), '%Y-%m-%d') = $date"; ``` but nothing works any ideas? Thanks
2015/10/07
[ "https://Stackoverflow.com/questions/32995667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3602203/" ]
The responses and comments all led to this answer ``` $result = "SELECT COUNT(*) FROM evenement WHERE DATE_FORMAT(DATE(start), '%Y-%m-%d') = DATE('".$date."')" ``` the problem was that the $date variable need DATE($date) and in SELECT need quotes.
You should convert your constant to a date, not the column. So, my first attempt would be: ``` SELECT COUNT(*) FROM evenement WHERE start = DATE('$date'); ``` However, that might not work. You might need to use `str_to_date()` with the appropriate format. The reason this method is better is because the optimizer can take advantage of an index on `evenement(start)`.
45,275,379
i'm learning nodejs and some issues appeared, that emit() and on() is not a function.. here's my emitter.js fie ```js function Emitter(){ this.events = {}; } Emitter.prototype.on = function(type, listener){ this.events[type]=this.events[type]||[]; this.events[type].push(listener); } Emitter.prototype.emit = function(type){ if (this.events[type]) { this.events[type].forEach(function(listener){ listener(); }); } } ``` and here's my app.js file ```js //Emitter var Emitter = require('./emitter'); Emitter.on('greet', function(){ console.log('a greeting occured!`'); }); console.log('hello'); Emitter.emit('greet'); ``` and here's the error `TypeError: Emitter.on is not a function` when i instantiated the Emitter: `var emitter = new Emitter();` and this the error: `TypeError: Emitter is not a constructor` then, i export the modules using this literal syntax: `module.exports= {emit: Emit}` the error still appeared that `the new Emitter() is not a constructor` so, i export it with this: `module.exports = Emitter;` instead with this pattern `module.exports = {emit: Emitter}` and i still don't know why i can't export it with literal, any idea?
2017/07/24
[ "https://Stackoverflow.com/questions/45275379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698574/" ]
You've created a class. Create an instance of it using `new Emitter()`. Also, you have to export and import the `Emitter` class: ```js // emitter.js function Emitter(){ this.events = {}; } Emitter.prototype.on = function(type, listener){ this.events[type]=this.events[type]||[]; this.events[type].push(listener); } Emitter.prototype.emit = function(type){ if (this.events[type]) { this.events[type].forEach(function(listener){ listener(); }); } } // Export the Emitter class: module.exports = Emitter; // app.js // Import the emitter class: var Emitter = require('./emitter'); var emitter = new Emitter(); emitter.on('greet', function(){ console.log('a greeting occured!`'); }); console.log('hello'); emitter.emit('greet'); ``` Whenever you use the `new` operator with a constructor function, a new object is created. The prototype of that object will the `prototype` property of the constructor function. Then, the constructor is called with the new object (`this` in the constructor is the new object).
There are two issues that should be addressed, firstly you need to export the `Emitter` function from the file that it was defined in to be able to `require` it in another file, you can do this simply like this: ``` module.exports = function Emitter() { this.events = {} } // ... etc ``` You also need to use the `new` operator on your `Emitter` function to instantiate a new copy of the object to allow you to then use the functions `on` and `emit` that you defined. This is because the methods are part of the [objects prototype](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype). You can do this like this: ``` const emitter = new Emitter() emitter.on("greet", function () { // ... etc }) ``` > > It might be worth noting that Node.js already has an inbuilt Events module that covers what you are trying to achieve, and you can find documentation in their [API docs](https://nodejs.org/api/events.html). > > >
21,992,204
I am following tutorials from [youtube](http://youtu.be/vz1O9nRyZaY). It seems I have encountered an error I can't resolve by myself. The goal is to create a class called BMI, which takes users weight name and height and prints them out.. I'm trying to compile it using g++, and I suspect I'm not doing it right. Usually I just do g++ filename.cpp, as I should in this case? The tutorial is originally in that Microsoft ....thing, I don't know it's name. Sorry Thank you, the code is attached below. The error ``` /tmp/ccRcewk3.o: In function `main': Main.cpp:(.text+0x7d): undefined reference to `BMI::BMI()' Main.cpp:(.text+0x89): undefined reference to `BMI::getWeight() const' Main.cpp:(.text+0x9a): undefined reference to `BMI::getHeight() const' Main.cpp:(.text+0xaf): undefined reference to `BMI::getName() const' Main.cpp:(.text+0x14f): undefined reference to `BMI::~BMI()' Main.cpp:(.text+0x184): undefined reference to `BMI::~BMI()' collect2: ld returned 1 exit status ``` Main.cpp ``` #include <iostream> #include <string> #include "BMI.h" using namespace std; /**************************************************/ int main() { string name; int height; double weight; cout << "Enter your name: "; cin >> name; cout << "Enter your height (cm): "; cin >> height; cout << "Enter your weight (kg): "; cin >> weight; BMI Student_1; cout << endl << "Patient name: " << Student_1.getName() << endl << "Height: " << Student_1.getHeight() << endl << "Weight: " << Student_1.getWeight() << endl; return 0; } /**************************************************/ ``` BMI.h ``` // Header ==> Function Declarations #include <iostream> #include <string> using namespace std; // tu ide klasa #ifndef BMI_H #define BMI_H class BMI { public: //Default Constructor BMI(); //Overload Constructor BMI(string, int, double); //Destructor ~BMI(); // Accessor functions string getName() const; // // // returns name of patient int getHeight() const; // // // returns height of patient double getWeight() const; // // // returns weight of patient private: // member variables string newName; int newHeight; double newWeight; }; #endif ``` BMI.cpp: ``` //Function definitions #include "BMI.h" // to access function inside a class BMI::BMI() { newHeight = 0; newWeight = 0.0; } BMI::BMI(string name, int height, double weight) { newName = name; newHeight = height; newWeight = weight; } BMI::~BMI() { } string BMI::getName() const { return newName; } int BMI::getHeight() const { return newHeight; } int BMI::getWeight() const { return newWeight; } ``` edit: OK, thanks everyone, I got part of the problem solved. However, you got me a little confused with editing, so I will do over. It seems that the original code is not working, and I feel it should. Anyway, the edited code from the question doesn't work either. So, I will try to do it again. But thank you, now I know how to compile. :) edit2: Everything is working now, thank you very much.
2014/02/24
[ "https://Stackoverflow.com/questions/21992204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to compile the main.cpp into Main.o and BMI.cpp into BMI.o. ``` g++ -c Main.cpp g++ -c BMI.cpp ``` Then you need to link both object files into one executable (and link to the Standard C++ lib) ``` g++ -o myprog Main.o BMI.o -lstdc++ ``` Run the example with ``` ./myprog ``` There seem to be more bugs, I have no time to fix, please continue yourself. :-) ``` [marc@quadfork ~/test]$./myprog Enter your name: foo Enter your height (cm): 23 Enter your weight (kg): 2 Patient name: Height: 0 Weight: 0 ```
your function return noting in your BMI.cpp try with this. ``` string BMI::getName() const { return newName; } int BMI::getHeight() const { return newHeight; } double BMI::getWeight() const { return newWeight; } ```
5,416,594
From Time to time my visual studio 2010 occupies the executable program in Debug subdirectory. Thus I have to unload the solution and reload it. Then ReBuild it and then run it. The all situatuation becomes upseen I really can't work like that. I have already unclick in Debug section the `Enable the Virtual Studio hosting process` Is there any one to help me on this situation?
2011/03/24
[ "https://Stackoverflow.com/questions/5416594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230348/" ]
Well this is a bit of a workaround but works for me most of the time. This doesn't solve the root cause but the symptoms (the file locking): Add this as a pre-build event: ``` if exist "$(TargetPath).locked" del "$(TargetPath).locked" if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked" ``` (Source of the solution: <http://nayyeri.net/file-lock-issue-in-visual-studio-when-building-a-project>) Also here there is a similar problem and a liberal solution: [Visual Studio 2010 build file lock issues](https://stackoverflow.com/questions/3095573/visual-studio-2010-build-file-lock-issues)
It may also not be Visual Studio locking your executable, check the locks on it with "Unlocker": <http://www.emptyloop.com/unlocker/>
5,416,594
From Time to time my visual studio 2010 occupies the executable program in Debug subdirectory. Thus I have to unload the solution and reload it. Then ReBuild it and then run it. The all situatuation becomes upseen I really can't work like that. I have already unclick in Debug section the `Enable the Virtual Studio hosting process` Is there any one to help me on this situation?
2011/03/24
[ "https://Stackoverflow.com/questions/5416594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230348/" ]
Well this is a bit of a workaround but works for me most of the time. This doesn't solve the root cause but the symptoms (the file locking): Add this as a pre-build event: ``` if exist "$(TargetPath).locked" del "$(TargetPath).locked" if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked" ``` (Source of the solution: <http://nayyeri.net/file-lock-issue-in-visual-studio-when-building-a-project>) Also here there is a similar problem and a liberal solution: [Visual Studio 2010 build file lock issues](https://stackoverflow.com/questions/3095573/visual-studio-2010-build-file-lock-issues)
When this happens I open [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653) and use the Find - Find Handle or Dll menu to find the process which has the file still open. From there I can jump the the handle in the process and close it from within Process Explorer. That works although it is a bit hacky. Yours, Alois Kraus
608,721
Suppose $f:[0,1]\to\mathbb{R}$ is continuous,define $$g:[0,1]\to\mathbb{R},\quad g(x):=\int\_0^1|f(t)-x|dt$$ Show that $g$ attains maximum at $0$ or $1$. I don't know how to approach, any hints?
2013/12/16
[ "https://math.stackexchange.com/questions/608721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/116072/" ]
Essentially we need to use convexity of g(x). For any $x,t\in(0,1)$, we have $$ |f(t)-x|\le x|f(t)-1|+(1-x)|f(t)| $$ Integrate on both sides form $0$ to $1$ with respect to $t$, we obtain $$ g(x)\le x\cdot g(1)+(1-x)\cdot g(0) $$. Now suppose the contrary, if there exists $x\_0\in(0,1)$ such that $g(x\_0)>g(0)$ and $g(x\_0)>g(1)$, then $$ x\_0\cdot g(1)+(1-x\_0)\cdot g(0)<g(x\_0)\le x\_0\cdot g(1)+(1-x\_0)\cdot g(0) $$ which is a contradiction.
Show that $g$ is convex. This follows since $x \mapsto |x-c|$ is convex. Now to show is that $g$ is non-constant. There are two possibilities. 1. Either $f([0,1]) \subset (-\infty, 0]$, or $f([0,1]) \subset [1,\infty)$. And in either of these cases, $g$ is linear with slope $-1$ or $1$. 2. Or, since $f$ is continuous, there exists $\epsilon,\delta>0$, $t\_0\in (\epsilon,1-\epsilon)$ such that $f([t\_0-\epsilon,t\_0+\epsilon]) \subset [\delta,1-\delta]$. Then for $t \in [t\_0-\epsilon,t\_0+\epsilon]$ we have that $$\tfrac12|f(t)| + \tfrac12|f(t)-1| = \tfrac12 f(t) + \tfrac12(1-f(t)) = \tfrac12 \ge |f(t)-\tfrac12| + \delta $$ Since for all $t \in [0,1]$ we also have $$\tfrac12|f(t)| + \tfrac12|f(t)-1| \ge |f(t)-\tfrac12| $$ then integrating we get $$ \tfrac12 g(0) + \tfrac12 g(1) \ge g(\tfrac12) + 2\epsilon\delta ,$$ and hence $g$ is non-constant. Since $g$ is convex and non-constant, it cannot attain its maximum on $(0,1)$.
64,031,727
In an Android studio activity I want to use the EditText input to go to a second activity, my code works, but I have to press twice for this to work, how can I correct this to only press once ``` editText.setInputType(InputType.TYPE_NULL); editText.setShowSoftInputOnFocus(false); public void addListenerOnButton() { editText.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String text = editText.getText().toString(); Intent myIntent = new Intent(view.getContext(),Calculated.class); myIntent.putExtra("mytext",text); startActivity(myIntent); } }); } ```
2020/09/23
[ "https://Stackoverflow.com/questions/64031727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10548326/" ]
The only difference between `println` and `print` method is that `println` throws the cursor to the next line after printing the desired result whereas `print` method keeps the cursor on the same line. [More information](https://www.tutorialslink.com/Code-Snippet/Difference-between-Systemoutprintln()-and-Systemoutprint()/1121#:%7E:text=out.-,print(),cursor%20on%20the%20same%20line.)
I wrote about it and have some examples at the following link: <https://creatingcoder.com/2020/08/07/println-vs-print/> Basically, the print method doesn't move the cursor, whereas the println creates a new line.
29,256,427
I often use two related collections and want to access the corresponding elements in a foreach loop. But, there is no ".Index" property, is there a direct way of doing this, WITHOUT incrementing a counter? ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.Index]+' '+value } } ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439497/" ]
You could use [Enumerable.Zip](https://msdn.microsoft.com/en-us/library/vstudio/dd267698%28v=vs.100%29.aspx) and an anonymous type: ``` string[] names={"Rod", "Jane", "Freddy"} int[] ages={28,32,26;}; var pairs=names.Zip(ages, (name,age) => new{Name=name, Age=age}); foreach(var pair in pairs) { string name=pair.Name; string age=pair.Age; } ```
I'm thinking you want a [`.Zip`](https://msdn.microsoft.com/en-us/library/vstudio/dd267698%28v=vs.100%29.aspx). ``` var pairs = headers.Zip(values, (header, value) => new Tuple<string, string>(header, value)); ```
29,256,427
I often use two related collections and want to access the corresponding elements in a foreach loop. But, there is no ".Index" property, is there a direct way of doing this, WITHOUT incrementing a counter? ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.Index]+' '+value } } ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439497/" ]
I'm thinking you want a [`.Zip`](https://msdn.microsoft.com/en-us/library/vstudio/dd267698%28v=vs.100%29.aspx). ``` var pairs = headers.Zip(values, (header, value) => new Tuple<string, string>(header, value)); ```
Do it with IndexOf ``` var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: " + headers[Array.IndexOf(values, value)] + ' ' + value; } ``` or maybe with iterators : ``` var lines = System.IO.File.ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); var e1 = headers.GetEnumerator(); var e2 = values.GetEnumerator(); while(e1.MoveNext() && e2.MoveNext()) { string message = "Data: " + e1.Current.ToString() + ' ' + e2.Current.ToString(); } ```
29,256,427
I often use two related collections and want to access the corresponding elements in a foreach loop. But, there is no ".Index" property, is there a direct way of doing this, WITHOUT incrementing a counter? ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.Index]+' '+value } } ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439497/" ]
Yet another variant, use [Select](https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx) overloading with index like ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(',').Select((el,index)=>new {value=el, index=index}); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.index]+' '+value.value } } ``` depends on data in headers and values, better variant can be ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var item in values.Skip(1).Select((el,index)=>new {value=el, index=index})) { string message = "Data: "+headers[item.index]+' '+item.value } } ```
I'm thinking you want a [`.Zip`](https://msdn.microsoft.com/en-us/library/vstudio/dd267698%28v=vs.100%29.aspx). ``` var pairs = headers.Zip(values, (header, value) => new Tuple<string, string>(header, value)); ```
29,256,427
I often use two related collections and want to access the corresponding elements in a foreach loop. But, there is no ".Index" property, is there a direct way of doing this, WITHOUT incrementing a counter? ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.Index]+' '+value } } ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439497/" ]
You could use [Enumerable.Zip](https://msdn.microsoft.com/en-us/library/vstudio/dd267698%28v=vs.100%29.aspx) and an anonymous type: ``` string[] names={"Rod", "Jane", "Freddy"} int[] ages={28,32,26;}; var pairs=names.Zip(ages, (name,age) => new{Name=name, Age=age}); foreach(var pair in pairs) { string name=pair.Name; string age=pair.Age; } ```
Do it with IndexOf ``` var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: " + headers[Array.IndexOf(values, value)] + ' ' + value; } ``` or maybe with iterators : ``` var lines = System.IO.File.ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); var e1 = headers.GetEnumerator(); var e2 = values.GetEnumerator(); while(e1.MoveNext() && e2.MoveNext()) { string message = "Data: " + e1.Current.ToString() + ' ' + e2.Current.ToString(); } ```
29,256,427
I often use two related collections and want to access the corresponding elements in a foreach loop. But, there is no ".Index" property, is there a direct way of doing this, WITHOUT incrementing a counter? ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.Index]+' '+value } } ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439497/" ]
You could use [Enumerable.Zip](https://msdn.microsoft.com/en-us/library/vstudio/dd267698%28v=vs.100%29.aspx) and an anonymous type: ``` string[] names={"Rod", "Jane", "Freddy"} int[] ages={28,32,26;}; var pairs=names.Zip(ages, (name,age) => new{Name=name, Age=age}); foreach(var pair in pairs) { string name=pair.Name; string age=pair.Age; } ```
Yet another variant, use [Select](https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx) overloading with index like ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(',').Select((el,index)=>new {value=el, index=index}); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.index]+' '+value.value } } ``` depends on data in headers and values, better variant can be ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var item in values.Skip(1).Select((el,index)=>new {value=el, index=index})) { string message = "Data: "+headers[item.index]+' '+item.value } } ```
29,256,427
I often use two related collections and want to access the corresponding elements in a foreach loop. But, there is no ".Index" property, is there a direct way of doing this, WITHOUT incrementing a counter? ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.Index]+' '+value } } ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439497/" ]
Yet another variant, use [Select](https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx) overloading with index like ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(',').Select((el,index)=>new {value=el, index=index}); foreach(var value in values.Skip(1)) { string message = "Data: "+headers[value.index]+' '+value.value } } ``` depends on data in headers and values, better variant can be ``` public void PrepareData() { var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var item in values.Skip(1).Select((el,index)=>new {value=el, index=index})) { string message = "Data: "+headers[item.index]+' '+item.value } } ```
Do it with IndexOf ``` var lines = ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); foreach(var value in values.Skip(1)) { string message = "Data: " + headers[Array.IndexOf(values, value)] + ' ' + value; } ``` or maybe with iterators : ``` var lines = System.IO.File.ReadAllLines(@"\\tsclient\T\Bbtra\wapData.txt"); var headers = lines[0].Split(','); var values = lines.Last().Split(','); var e1 = headers.GetEnumerator(); var e2 = values.GetEnumerator(); while(e1.MoveNext() && e2.MoveNext()) { string message = "Data: " + e1.Current.ToString() + ' ' + e2.Current.ToString(); } ```
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
If you really need them, add the dependency in your pom.xml : ``` <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations --> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>16.0.1</version> </dependency> ``` ( <https://mvnrepository.com/artifact/org.jetbrains/annotations/16.0.1> )
I had the same issue and arrived here looking for solutions, but I couldn't find the aforementioned pom.xml. Maybe because I'm not using Maven in my project. But I solved it by editing the *MyProject.iml* file. I've added the following code inside the `<component>` tags. ``` <orderEntry type="module-library"> <library> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/20.1.0/annotations-20.1.0.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </orderEntry> ``` Now I can use the annotations in my project.
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
If you really need them, add the dependency in your pom.xml : ``` <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations --> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>16.0.1</version> </dependency> ``` ( <https://mvnrepository.com/artifact/org.jetbrains/annotations/16.0.1> )
For me adding `jetbrains` dependency worked fine. Provide dependency something like this. For Gradle: ``` implementation 'org.jetbrains:annotations:16.0.2' ```
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
If you really need them, add the dependency in your pom.xml : ``` <!-- https://mvnrepository.com/artifact/org.jetbrains/annotations --> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>16.0.1</version> </dependency> ``` ( <https://mvnrepository.com/artifact/org.jetbrains/annotations/16.0.1> )
just put this code in the build gradle and it will work. **implementation 'org.jetbrains:annotations:16.0.2'**
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
For me adding `jetbrains` dependency worked fine. Provide dependency something like this. For Gradle: ``` implementation 'org.jetbrains:annotations:16.0.2' ```
I had the same issue and arrived here looking for solutions, but I couldn't find the aforementioned pom.xml. Maybe because I'm not using Maven in my project. But I solved it by editing the *MyProject.iml* file. I've added the following code inside the `<component>` tags. ``` <orderEntry type="module-library"> <library> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/20.1.0/annotations-20.1.0.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </orderEntry> ``` Now I can use the annotations in my project.
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
just put this code in the build gradle and it will work. **implementation 'org.jetbrains:annotations:16.0.2'**
I had the same issue and arrived here looking for solutions, but I couldn't find the aforementioned pom.xml. Maybe because I'm not using Maven in my project. But I solved it by editing the *MyProject.iml* file. I've added the following code inside the `<component>` tags. ``` <orderEntry type="module-library"> <library> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/20.1.0/annotations-20.1.0.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </orderEntry> ``` Now I can use the annotations in my project.
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
If anyone is using a plain `Kotlin` project (without any build tool such as maven or gradle) in IntelliJ IDEA, then you can add the jetbrain's `jetbrains.annotations` library by following the steps given below: 1. Right click on the module in the `Project` panel on your left hand side, and select the `Open module settings` 2. Select `Libraries` under `Project settings` 3. Click the `+` symbol on the top of the library area and select the `From Maven...` 4. Enter `org.jetbrains:annotations`, and hit the search icon at the end of it. Then, wait for the dropdown to list the available versions of it. 5. Select the latest or appropriate version you need and also enable the `Download to:` option. 6. Then, click `OK` and you are done.
I had the same issue and arrived here looking for solutions, but I couldn't find the aforementioned pom.xml. Maybe because I'm not using Maven in my project. But I solved it by editing the *MyProject.iml* file. I've added the following code inside the `<component>` tags. ``` <orderEntry type="module-library"> <library> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/20.1.0/annotations-20.1.0.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </orderEntry> ``` Now I can use the annotations in my project.
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
If anyone is using a plain `Kotlin` project (without any build tool such as maven or gradle) in IntelliJ IDEA, then you can add the jetbrain's `jetbrains.annotations` library by following the steps given below: 1. Right click on the module in the `Project` panel on your left hand side, and select the `Open module settings` 2. Select `Libraries` under `Project settings` 3. Click the `+` symbol on the top of the library area and select the `From Maven...` 4. Enter `org.jetbrains:annotations`, and hit the search icon at the end of it. Then, wait for the dropdown to list the available versions of it. 5. Select the latest or appropriate version you need and also enable the `Download to:` option. 6. Then, click `OK` and you are done.
For me adding `jetbrains` dependency worked fine. Provide dependency something like this. For Gradle: ``` implementation 'org.jetbrains:annotations:16.0.2' ```
64,205,627
I am facing an issue in IntelliJ when I tried to build my project through maven using ``` mvn clean install ``` I have tried different ways like changing the path of my JDK but nothing worked. Can someone help me out with this issue?
2020/10/05
[ "https://Stackoverflow.com/questions/64205627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7688591/" ]
If anyone is using a plain `Kotlin` project (without any build tool such as maven or gradle) in IntelliJ IDEA, then you can add the jetbrain's `jetbrains.annotations` library by following the steps given below: 1. Right click on the module in the `Project` panel on your left hand side, and select the `Open module settings` 2. Select `Libraries` under `Project settings` 3. Click the `+` symbol on the top of the library area and select the `From Maven...` 4. Enter `org.jetbrains:annotations`, and hit the search icon at the end of it. Then, wait for the dropdown to list the available versions of it. 5. Select the latest or appropriate version you need and also enable the `Download to:` option. 6. Then, click `OK` and you are done.
just put this code in the build gradle and it will work. **implementation 'org.jetbrains:annotations:16.0.2'**
280,645
Having come across a link on stack overflow, I have found the writings of [Miško Hevery](http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/) very engaging reading. So good that I am seeing a new approach to what I previously thought I was doing quite well. He talks mainly about Dependency Injection, Automated Unit Testing and Good Design. A number of the good practices he advocates are things that can be programatically detected. And so there is a program to detect them [Google Testability Explorer](http://code.google.com/p/testability-explorer/). My questions is: * Is there a C# equivalent to the Java based Google Testability Explorer out there? * If so, which is the best?
2008/11/11
[ "https://Stackoverflow.com/questions/280645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6023/" ]
It doesn't provide the information in quite the same way as the Google Testability Explorer, but [NDepend](http://www.ndepend.com/) (non-free) provides a lot of code analysis for .Net assemblies.
You can also use [FXCop](http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx). > > FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. Many of the issues concern violations of the programming and design rules set forth in the Design Guidelines for Class Library Developers, which are the Microsoft guidelines for writing robust and easily maintainable code by using the .NET Framework. > > > Hope it helps, Bruno Figueiredo
280,645
Having come across a link on stack overflow, I have found the writings of [Miško Hevery](http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/) very engaging reading. So good that I am seeing a new approach to what I previously thought I was doing quite well. He talks mainly about Dependency Injection, Automated Unit Testing and Good Design. A number of the good practices he advocates are things that can be programatically detected. And so there is a program to detect them [Google Testability Explorer](http://code.google.com/p/testability-explorer/). My questions is: * Is there a C# equivalent to the Java based Google Testability Explorer out there? * If so, which is the best?
2008/11/11
[ "https://Stackoverflow.com/questions/280645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6023/" ]
[Pex](http://research.microsoft.com/Pex/default.aspx) is an interesting entry. It has the potential to take testing to a new level, especially when combined with [Code Contracts](http://research.microsoft.com/contracts/).
You can also use [FXCop](http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx). > > FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements. Many of the issues concern violations of the programming and design rules set forth in the Design Guidelines for Class Library Developers, which are the Microsoft guidelines for writing robust and easily maintainable code by using the .NET Framework. > > > Hope it helps, Bruno Figueiredo
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Both MinGW & Cygwin give you the gcc compiler but if you use MinGW you don't need to install Cygwin because it uses native Windows libraries rather than Cygwin libraries Cygwin is more than just compilers, it tries to provide a UNIX programming environment by building a lot of UNIX libraries on top of Windows SDK.
You can use vc express for concole apps if you wish, or really any compiler for win platform.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That clarifies things. I'm not particularly interested in a \*nix-like environment. I was more interested in getting a GNU C compiler that conforms closely with C99 (which I believe the latest GCC compiler does) and using it as a C learning exercise (hence console rather than GUI apps) It appears to me that NetBeans IDE/Cygwin option installs an earlier version of the compiler. So, it appears that MinGW is what I am looking for if I want to use GNU C. Incidentally, the free Pelles C compiler/IDE has a very full C99 implementation.
You can use vc express for concole apps if you wish, or really any compiler for win platform.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could install CodeBlocks IDE oder DevCPP ide. If you do not require special posix api's then you do not need to install cygwin.
That clarifies things. I'm not particularly interested in a \*nix-like environment. I was more interested in getting a GNU C compiler that conforms closely with C99 (which I believe the latest GCC compiler does) and using it as a C learning exercise (hence console rather than GUI apps) It appears to me that NetBeans IDE/Cygwin option installs an earlier version of the compiler. So, it appears that MinGW is what I am looking for if I want to use GNU C. Incidentally, the free Pelles C compiler/IDE has a very full C99 implementation.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Both MinGW & Cygwin give you the gcc compiler but if you use MinGW you don't need to install Cygwin because it uses native Windows libraries rather than Cygwin libraries Cygwin is more than just compilers, it tries to provide a UNIX programming environment by building a lot of UNIX libraries on top of Windows SDK.
MinGW can support many languages as well as GNU C Compiler. It also comes with msys package that you can simulate UNIX environment. Cygwin does the same thing as msys does. I'd advice you to install MinGW with full msys support.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That clarifies things. I'm not particularly interested in a \*nix-like environment. I was more interested in getting a GNU C compiler that conforms closely with C99 (which I believe the latest GCC compiler does) and using it as a C learning exercise (hence console rather than GUI apps) It appears to me that NetBeans IDE/Cygwin option installs an earlier version of the compiler. So, it appears that MinGW is what I am looking for if I want to use GNU C. Incidentally, the free Pelles C compiler/IDE has a very full C99 implementation.
MinGW can support many languages as well as GNU C Compiler. It also comes with msys package that you can simulate UNIX environment. Cygwin does the same thing as msys does. I'd advice you to install MinGW with full msys support.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Both MinGW & Cygwin give you the gcc compiler but if you use MinGW you don't need to install Cygwin because it uses native Windows libraries rather than Cygwin libraries Cygwin is more than just compilers, it tries to provide a UNIX programming environment by building a lot of UNIX libraries on top of Windows SDK.
You really really should check out Visual C++ Express. It makes developing on windows A LOT easier. I it is free and the Visual C++ is the preferred way to develop windows apps. ANd yes, you can make console applications too.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Both MinGW & Cygwin give you the gcc compiler but if you use MinGW you don't need to install Cygwin because it uses native Windows libraries rather than Cygwin libraries Cygwin is more than just compilers, it tries to provide a UNIX programming environment by building a lot of UNIX libraries on top of Windows SDK.
That clarifies things. I'm not particularly interested in a \*nix-like environment. I was more interested in getting a GNU C compiler that conforms closely with C99 (which I believe the latest GCC compiler does) and using it as a C learning exercise (hence console rather than GUI apps) It appears to me that NetBeans IDE/Cygwin option installs an earlier version of the compiler. So, it appears that MinGW is what I am looking for if I want to use GNU C. Incidentally, the free Pelles C compiler/IDE has a very full C99 implementation.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could install CodeBlocks IDE oder DevCPP ide. If you do not require special posix api's then you do not need to install cygwin.
You really really should check out Visual C++ Express. It makes developing on windows A LOT easier. I it is free and the Visual C++ is the preferred way to develop windows apps. ANd yes, you can make console applications too.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could install CodeBlocks IDE oder DevCPP ide. If you do not require special posix api's then you do not need to install cygwin.
You can use vc express for concole apps if you wish, or really any compiler for win platform.
1,015,270
I'm a bit confused about the options for using GNU CC on Windows. If I want to primarily develop console applications (as opposed to GUI apps) what do I need? Where do Cygwin and MinGW figure? For example, if I use the NetBeans IDE C/C++ option, that requires installation of Cygwin. Are there any options which would allow Console application development without Cygwin?
2009/06/18
[ "https://Stackoverflow.com/questions/1015270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You really really should check out Visual C++ Express. It makes developing on windows A LOT easier. I it is free and the Visual C++ is the preferred way to develop windows apps. ANd yes, you can make console applications too.
MinGW can support many languages as well as GNU C Compiler. It also comes with msys package that you can simulate UNIX environment. Cygwin does the same thing as msys does. I'd advice you to install MinGW with full msys support.
14,138,066
I'm all for REST webservices and my company has a policy in place to prefer REST over SOAP. However, I need to expose a webservice that does not fit into the resource paradigm. It is essentially a calculation, where I need to send a large number of parameters (about 20 fields) and retrieve a number. I thought about using HTTP POST and send a JSON object in the request body. Problem here is, my webservice supports SOAP-WS and REST and this approach won't fall in any of these categories. My question is, what are the options here ? Can I make this fit into a RESTful WS ?
2013/01/03
[ "https://Stackoverflow.com/questions/14138066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492936/" ]
As you mention, REST makes sense when you're exposing [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) operations on resources. Usually these resources are persisted in some database or storage mechanism. In your case I guess there is no storage or resources (you provide a bunch of numbers and get a result back, nothing gets stored, is that true?). So you won't be able to really call such a WS as "RESTful". That being said REST is more of a "philosophy". You can take the pieces you like and use them. Your idea of implementing a POST, taking in a JSON structure with your input and returning a JSON with the result sounds good. You can also POST "[application/x-www-form-urlencoded](http://en.wikipedia.org/wiki/POST_%28HTTP%29)" content (a regular form submit and return the result as "text/plain" if that makes sense. The idea is to build a WS that is simple to understand and easy to operate. The exact opposite of SOAP-WS. ;)
After some research, I found this article that is really relevant to this discussion: <http://info.apigee.com/Portals/62317/docs/web%20api.pdf>
14,138,066
I'm all for REST webservices and my company has a policy in place to prefer REST over SOAP. However, I need to expose a webservice that does not fit into the resource paradigm. It is essentially a calculation, where I need to send a large number of parameters (about 20 fields) and retrieve a number. I thought about using HTTP POST and send a JSON object in the request body. Problem here is, my webservice supports SOAP-WS and REST and this approach won't fall in any of these categories. My question is, what are the options here ? Can I make this fit into a RESTful WS ?
2013/01/03
[ "https://Stackoverflow.com/questions/14138066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492936/" ]
As you mention, REST makes sense when you're exposing [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) operations on resources. Usually these resources are persisted in some database or storage mechanism. In your case I guess there is no storage or resources (you provide a bunch of numbers and get a result back, nothing gets stored, is that true?). So you won't be able to really call such a WS as "RESTful". That being said REST is more of a "philosophy". You can take the pieces you like and use them. Your idea of implementing a POST, taking in a JSON structure with your input and returning a JSON with the result sounds good. You can also POST "[application/x-www-form-urlencoded](http://en.wikipedia.org/wiki/POST_%28HTTP%29)" content (a regular form submit and return the result as "text/plain" if that makes sense. The idea is to build a WS that is simple to understand and easy to operate. The exact opposite of SOAP-WS. ;)
I see no reason why that couldn't be RESTful. Consider a particular calculation run to be a resource with its own identity (`/calculation/ID123`); you can then do a POST to `/calculation` to make a new one, GET/PUT on `/calculation/ID123/paramA` to work with a particular parameter, and GET on `/calculation/ID123/result` to retrieve the results of the calculation (or a description that says the calculation results are not available for some reason). Of course, GET on `/calculation` would be a retrieve of the list of saved calculations that you're allowed to see, GET on `/calculation/ID123` would retrieve a description of the sub-resources outlined above (plus whatever other info you want to provide), and purging a particular calculation is a DELETE. There's nothing wrong with having lots of sub-resources and highly transient resources. The important thing to remember is that the client shouldn't ever be minting URLs. (I don't know whether content negotiation is so useful in this situation; that really depends on the particular calculation I suppose.)
2,803
I have gunstock oak flooring and would like to match a piece of pine furniture to it. Any ideas how to achieve this? I'm open to liquid or gel stains, but would like to avoid veneers as it's pretty large. Where possible, I'd like to avoid buying lots of different stains and mixing them by trial and error. Related: [How can I match a finish on furniture when re-finishing?](https://woodworking.stackexchange.com/questions/1256/how-can-i-match-a-finish-on-furniture-when-re-finishing)
2015/11/17
[ "https://woodworking.stackexchange.com/questions/2803", "https://woodworking.stackexchange.com", "https://woodworking.stackexchange.com/users/1154/" ]
As bowlturner said, good luck! There are a number of challenges here. > > Where possible, I'd like to avoid buying lots of different stains and mixing them by trial and error. > > > I'm afraid with this sort of thing generally it's *not* possible without some experimentation. Even if you were matching a fairly commonplace wood there's no guarantee a product of the right name will give the colour you want. Real-world example here: trying to match some vintage English oak it's clear a commercial English Oak stain is completely the wrong sort of colour (too red), but with a little experimentation it is discovered that an initial coat of Pine followed by two coats of Old Oak, the first wiped off after application, worked perfectly. So, this kind of thing will usually require buying a few different stains and then trying various combos, *along with your final finish*; these are called "test boards" or "test strips". As you can see from the image below you must test with the final finish as there can be a significant deepening of tone after the clear finish goes on, and with oil-based varnishes also a slight yellowing, both of which obviously need to be factored in to the final colour. Or to put it another way, if you got a dead-on colour match with stains alone it would no longer match after applying most finishes (exceptions would be some waterbased polys and a light application of lacquer). [![Stain and varnish test strips](https://i.stack.imgur.com/cP3AX.jpg)](https://i.stack.imgur.com/cP3AX.jpg) There are additional challenges here, trying to match a softwood with hardwoods. **Softwood v. hardwood** Pine is a softwood, so has very characteristic light and dark banding which hardwoods don't have. The lighter parts (the earlywood or springwood) is soft and absorbent, while the darker wood (the latewood or winterwood) is much harder and non-absorbent. What this means in practical terms is that the light wood gets much darker than the dark wood when a stain goes on, at worst giving an effect called *grain reversal*, where what was the darker grain ends up lighter. **Blotching** Pine is a blotch-prone wood, and as such you need to treat the wood prior to stain going on to help achieve a smoother colouring, a process called sizing in the old days. [![Blotching and grain reversal on pine](https://i.stack.imgur.com/CGKOp.jpg)](https://i.stack.imgur.com/CGKOp.jpg) The usual recommended solution for blotching these days is to use a commercial "pre-stain conditioner", but diluted shellac or thinned varnish do the job as well or better for far less money. An additional advantages of using thinned varnish is that you can use the same product that you've already bought to use as your final finish, so no need to buy yet one more thing. Much more useful information here on Popular Woodworking: [Staining Pine - Make this inexpensive wood look like a million bucks](http://www.popularwoodworking.com/techniques/aw-extra-101013-staining-pine).
Good luck. However, since pine takes stain fairly well, you can try to match the overall color, but it will still look like stained pine. Your best bet, would be to bring a sample of the color you are trying to match into a store then make it just a little darker. Since Oak tends to start a little darker than pine. You might also bring in a sample piece of pine with you, so if you have them making the color, you can start light and try a little on a piece of the board, and slowly darken it until you get close. Then you should only have to buy one can of paint. I've done similar things at Ace Hardware (though I was matching something else entirely.)
2,803
I have gunstock oak flooring and would like to match a piece of pine furniture to it. Any ideas how to achieve this? I'm open to liquid or gel stains, but would like to avoid veneers as it's pretty large. Where possible, I'd like to avoid buying lots of different stains and mixing them by trial and error. Related: [How can I match a finish on furniture when re-finishing?](https://woodworking.stackexchange.com/questions/1256/how-can-i-match-a-finish-on-furniture-when-re-finishing)
2015/11/17
[ "https://woodworking.stackexchange.com/questions/2803", "https://woodworking.stackexchange.com", "https://woodworking.stackexchange.com/users/1154/" ]
Good luck. However, since pine takes stain fairly well, you can try to match the overall color, but it will still look like stained pine. Your best bet, would be to bring a sample of the color you are trying to match into a store then make it just a little darker. Since Oak tends to start a little darker than pine. You might also bring in a sample piece of pine with you, so if you have them making the color, you can start light and try a little on a piece of the board, and slowly darken it until you get close. Then you should only have to buy one can of paint. I've done similar things at Ace Hardware (though I was matching something else entirely.)
50:50 Varathane Early American and Colonial Maple. It is almost an exact match on pine. Made a ton of blends and bought a ton of stain. There’s nothing off the shelf that’s a good match
2,803
I have gunstock oak flooring and would like to match a piece of pine furniture to it. Any ideas how to achieve this? I'm open to liquid or gel stains, but would like to avoid veneers as it's pretty large. Where possible, I'd like to avoid buying lots of different stains and mixing them by trial and error. Related: [How can I match a finish on furniture when re-finishing?](https://woodworking.stackexchange.com/questions/1256/how-can-i-match-a-finish-on-furniture-when-re-finishing)
2015/11/17
[ "https://woodworking.stackexchange.com/questions/2803", "https://woodworking.stackexchange.com", "https://woodworking.stackexchange.com/users/1154/" ]
As bowlturner said, good luck! There are a number of challenges here. > > Where possible, I'd like to avoid buying lots of different stains and mixing them by trial and error. > > > I'm afraid with this sort of thing generally it's *not* possible without some experimentation. Even if you were matching a fairly commonplace wood there's no guarantee a product of the right name will give the colour you want. Real-world example here: trying to match some vintage English oak it's clear a commercial English Oak stain is completely the wrong sort of colour (too red), but with a little experimentation it is discovered that an initial coat of Pine followed by two coats of Old Oak, the first wiped off after application, worked perfectly. So, this kind of thing will usually require buying a few different stains and then trying various combos, *along with your final finish*; these are called "test boards" or "test strips". As you can see from the image below you must test with the final finish as there can be a significant deepening of tone after the clear finish goes on, and with oil-based varnishes also a slight yellowing, both of which obviously need to be factored in to the final colour. Or to put it another way, if you got a dead-on colour match with stains alone it would no longer match after applying most finishes (exceptions would be some waterbased polys and a light application of lacquer). [![Stain and varnish test strips](https://i.stack.imgur.com/cP3AX.jpg)](https://i.stack.imgur.com/cP3AX.jpg) There are additional challenges here, trying to match a softwood with hardwoods. **Softwood v. hardwood** Pine is a softwood, so has very characteristic light and dark banding which hardwoods don't have. The lighter parts (the earlywood or springwood) is soft and absorbent, while the darker wood (the latewood or winterwood) is much harder and non-absorbent. What this means in practical terms is that the light wood gets much darker than the dark wood when a stain goes on, at worst giving an effect called *grain reversal*, where what was the darker grain ends up lighter. **Blotching** Pine is a blotch-prone wood, and as such you need to treat the wood prior to stain going on to help achieve a smoother colouring, a process called sizing in the old days. [![Blotching and grain reversal on pine](https://i.stack.imgur.com/CGKOp.jpg)](https://i.stack.imgur.com/CGKOp.jpg) The usual recommended solution for blotching these days is to use a commercial "pre-stain conditioner", but diluted shellac or thinned varnish do the job as well or better for far less money. An additional advantages of using thinned varnish is that you can use the same product that you've already bought to use as your final finish, so no need to buy yet one more thing. Much more useful information here on Popular Woodworking: [Staining Pine - Make this inexpensive wood look like a million bucks](http://www.popularwoodworking.com/techniques/aw-extra-101013-staining-pine).
50:50 Varathane Early American and Colonial Maple. It is almost an exact match on pine. Made a ton of blends and bought a ton of stain. There’s nothing off the shelf that’s a good match
22,613,134
I am using SaveFileDialog to save a pdf file.But at the creation of pdf file i am getting this error. ``` The process cannot access the file it is being used by another process c# ``` Here is my code in c#.. ``` SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"; saveFileDialog1.FilterIndex = 0; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { // Code to write the stream goes here. PdfWriter.GetInstance(pdfDoc, myStream); //myStream.Close(); using (FileStream file = new FileStream(saveFileDialog1.FileName, FileMode.Create, System.IO.FileAccess.Write, FileShare.ReadWrite)) { byte[] bytes = new byte[myStream.Length]; myStream.Read(bytes, 0, (int)myStream.Length); file.Write(bytes, 0, bytes.Length); myStream.Close(); } } ``` I am getting this error at this line.. ``` using (FileStream file = new FileStream(saveFileDialog1.FileName, FileMode.Create, System.IO.FileAccess.Write, FileShare.ReadWrite)) ``` Here is my pdf file code ``` Stream myStream; Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); using (MemoryStream stream = new MemoryStream()) { pdfDoc.Open(); pieChart.SaveImage(stream, ChartImageFormat.Png); iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer()); chartImage.ScalePercent(75f); pdfDoc.Add(chartImage); } pdfDoc.Close(); ``` Please help me. Thanks in advance.
2014/03/24
[ "https://Stackoverflow.com/questions/22613134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3382246/" ]
In webkit based browsers, I remember a timing issue, try using a setInterval like: ``` var tim = setInterval(function(){ $.mobile.loading("show", { text: "Working...", textVisible: true }); clearInterval(tim); },1); ```
Did you also add the right CSS? ``` http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css ``` I've added JQM 1.4.0 and the CSS (1.4.0) as an external resource to your JSFiddle and it seems to be working - [Updated JSFiddle](http://jsfiddle.net/YL9PP/2/).
54,498,140
I mounted target device's (Beaglebone Black, ARM arch) root with sshfs, to a folder on host, and trying to cross compile using `--sysroot` option of GCC. But there's a problem - some include header files are located on target device not just at /usr/include folder, but in its subfolder `arm-linux-gnueabihf`. The same there's /usr/lib/arm-linux-gnueabihf folder too. "Hello world" sample fails to compile ``` [gmixaz:/work] $ $CC --sysroot=/work/sysroot h.c In file included from /work/sysroot/usr/include/stdio.h:27:0, from h.c:1: /work/sysroot/usr/include/features.h:364:25: fatal error: sys/cdefs.h: No such file or directory # include <sys/cdefs.h> ``` because `sys/cdefs.h` is located in /usr/include/arm-linux-gnueabihf, while compiler expects it in /usr/include My question is why do I have that subfolder `arm-linux-gnueabihf` in /usr/include? What was the rationale to put part of include files (and .so files in /usr/lib/arm-linux-gnueabihf) to that subfolder? And how shall I address this issue when cross compiling with --sysroot option - do I need to specify the subfolder with -I and -L compiler options, or there's some better solution? I though only --sysroot should be enough but it isn't. Is that 'by design'? After adding the folders to command line I got another problem: ``` [gmixaz:/work] 1 $ $CC --sysroot /work/sysroot3 -I /work/sysroot3/usr/include/arm-linux-gnueabihf -L /work/sysroot3/usr/lib/arm-linux-gnueabihf h.c /usr/xcc/arm-cortexa9_neon-linux-gnueabihf/lib/gcc/arm-cortexa9_neon-linux-gnueabihf/6.3.1/../../../../arm-cortexa9_neon-linux-gnueabihf/bin/ld.bfd: cannot find crt1.o: No such file or directory /usr/xcc/arm-cortexa9_neon-linux-gnueabihf/lib/gcc/arm-cortexa9_neon-linux-gnueabihf/6.3.1/../../../../arm-cortexa9_neon-linux-gnueabihf/bin/ld.bfd: cannot find crti.o: No such file or directory collect2: error: ld returned 1 exit status ``` What's going on? When building crosstool-NG I tried to match target arch info. Cross-compiling GCC on host: ``` [gmixaz:/work] 1 $ $CC -v Using built-in specs. COLLECT_GCC=/usr/xcc/arm-cortexa9_neon-linux-gnueabihf/bin/arm-cortexa9_neon-linux-gnueabihf-gcc COLLECT_LTO_WRAPPER=/usr/xcc/arm-cortexa9_neon-linux-gnueabihf/libexec/gcc/arm-cortexa9_neon-linux-gnueabihf/6.3.1/lto-wrapper Target: arm-cortexa9_neon-linux-gnueabihf Configured with: /dockcross/crosstool/toolchain/.build/src/gcc-linaro-6.3-2017.02/configure --build=x86_64-build_pc-linux-gnu --host=x86_64-build_pc-linux-gnu --target=arm-cortexa9_neon-linux-gnueabihf --prefix=/usr/xcc/arm-cortexa9_neon-linux-gnueabihf --with-sysroot=/usr/xcc/arm-cortexa9_neon-linux-gnueabihf/arm-cortexa9_neon-linux-gnueabihf/sysroot --enable-languages=c,c++ --with-cpu=cortex-a8 --with-fpu=neon --with-float=hard --with-pkgversion='crosstool-NG ' --enable-__cxa_atexit --disable-libmudflap --disable-libgomp --disable-libssp --disable-libquadmath --disable-libquadmath-support --disable-libsanitizer --disable-libmpx --with-gmp=/dockcross/crosstool/toolchain/.build/arm-cortexa9_neon-linux-gnueabihf/buildtools --with-mpfr=/dockcross/crosstool/toolchain/.build/arm-cortexa9_neon-linux-gnueabihf/buildtools --with-mpc=/dockcross/crosstool/toolchain/.build/arm-cortexa9_neon-linux-gnueabihf/buildtools --with-isl=/dockcross/crosstool/toolchain/.build/arm-cortexa9_neon-linux-gnueabihf/buildtools --enable-lto --with-host-libstdcxx='-static-libgcc -Wl,-Bstatic,-lstdc++,-Bdynamic -lm' --enable-threads=posix --enable-plugin --enable-gold --with-libintl-prefix=/dockcross/crosstool/toolchain/.build/arm-cortexa9_neon-linux-gnueabihf/buildtools --disable-multilib --with-local-prefix=/usr/xcc/arm-cortexa9_neon-linux-gnueabihf/arm-cortexa9_neon-linux-gnueabihf/sysroot --enable-long-long Thread model: posix gcc version 6.3.1 20170109 (crosstool-NG ) ``` GCC on target: ``` debian@beaglebone:~$ cc -v Using built-in specs. COLLECT_GCC=cc COLLECT_LTO_WRAPPER=/usr/lib/gcc/arm-linux-gnueabihf/6/lto-wrapper Target: arm-linux-gnueabihf Configured with: ../src/configure -v --with-pkgversion='Debian 6.3.0-18+deb9u1' --with-bugurl=file:///usr/share/doc/gcc-6/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-6 --program-prefix=arm-linux-gnueabihf- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-libitm --disable-libquadmath --enable-plugin --enable-default-pie --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-6-armhf/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-6-armhf --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-6-armhf --with-arch-directory=arm --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-sjlj-exceptions --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --enable-checking=release --build=arm-linux-gnueabihf --host=arm-linux-gnueabihf --target=arm-linux-gnueabihf Thread model: posix gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ``` What I'm missing in the toolchain configuration? **ADDED:** I have found that following file is responsible for libraries being placed to that subfolder on target: ``` debian@beaglebone:~$ cat /etc/ld.so.conf.d/arm-linux-gnueabihf.conf # Multiarch support /lib/arm-linux-gnueabihf /usr/lib/arm-linux-gnueabihf ``` Now I'm trying to understand what is correct way to attach that folders to cross compiler toolchain. Also, I guess that something similar is set for include header files, just interesting where's that setting for GCC on target? **ADDED:** Similar issue discussed for RPi cross compilation: <https://github.com/raspberrypi/tools/issues/42>
2019/02/02
[ "https://Stackoverflow.com/questions/54498140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1028256/" ]
I'm posting results of my investigation as an answer, but will accept if it solves the problem - I haven't got a solution yet ) It appears that the target's GCC was configured with --enable-multiarch, and it adds `arm-linux-gnueabihf` subfolder for that target name. Good reading about the subject is <https://wiki.debian.org/Multiarch/LibraryPathOverview> So probably my problem is that target name in the cross compiling GCC differs from that on the target's GCC (`arm-cortexa9_neon-linux-gnueabihf` vs `arm-linux-gnueabihf`). I'll check if I can change it in `crosstool-NG` options, and see if it fixes the issue. **ADDED:** Unfortunately I was not able to configure `crosstool-ng` toolchain to use target sysroot. Similar issue was reported here: <http://answers.opencv.org/question/180037/cmake-cross-compiler-problem-with-pkg_check_modules-for-some-packages/> I have finally decided to use `dockcross/linux-armv6` image which installs linaro toolchain customized for RPi, at least it compiles "hello world" from box. Though the toolchain seems to be derived also from crosstool-ng, it is downloaded as binary from RPi tools repo, and its configuration significantly differs from one for `dockcross/linux-armv7`. Now I'm trying to cross compile OpenCV per this guide: <http://courses.engr.uky.edu/ideawiki/doku.php?id=resources:sop:cross_compiling_opencv_for_raspberry_pi> and after specifying paths for pkg-config, OpenCV cmake script started to see installed libraries in target's sysroot.
Actually, I don't want to dig into your way because I think it is not a common way to cross compiling. The way you are cross-compiling is not suggested. There are two common ways to cross-compile an app. First, creating a virtual environment just like your embedded board with some virtualization apps like `Qemu`. You can find a very good tutorial [here](https://gnu-linux.org/building-ubuntu-rootfs-for-arm.html). Then you can bring your app there and compile it natively. A drawback for this solution is you are creating a whole filesystem and you should bring all of your app dependencies (which may become confusing) into your main filesystem. Second, you can use `Linaro toolchains` to cross-compile your app. Here is another [tutorial](https://wiki.linaro.org/Platform/DevPlatform/CrossCompile/CrossbuildingQuickStart) and I think you can find more about it. In my opinion, I prefer using Qemu when I need to build the app natively which have a lot of dependencies. On the other hand, cross-compiling apps that don't natively support it can become very confusing.
13,933,123
Following is the code where " throw use; " shows an error.Why? How to use throw for user defined exceptions?Give some example? ``` class use extends Exception{ public String toString() { return "too many exceptions"; } } class user{ public static void main(String s[]) { int i=3; try { if(i>1) throw use; } catch(use e) { System.out.println(e.toString()); } finally{ System.out.println("program executed successfully!"); } } } ```
2012/12/18
[ "https://Stackoverflow.com/questions/13933123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1888988/" ]
you need an instance of the exception class to throw it: ``` throw new use(); ``` or ``` use a = new use(); throw a; ``` In the future please follow Java naming conventions, it will make your code much more readable. (class names should start with a capital letter).
User defined exceptions can be created and thrown in Java. By inheriting the Exception class you can create your own exceptions. And it can be thrown as and when required Following example shows how to create and throw user defined exceptions <http://www.csnotes32.com/2014/09/how-to-create-user-defined-exception-in.html>
13,933,123
Following is the code where " throw use; " shows an error.Why? How to use throw for user defined exceptions?Give some example? ``` class use extends Exception{ public String toString() { return "too many exceptions"; } } class user{ public static void main(String s[]) { int i=3; try { if(i>1) throw use; } catch(use e) { System.out.println(e.toString()); } finally{ System.out.println("program executed successfully!"); } } } ```
2012/12/18
[ "https://Stackoverflow.com/questions/13933123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1888988/" ]
you need an instance of the exception class to throw it: ``` throw new use(); ``` or ``` use a = new use(); throw a; ``` In the future please follow Java naming conventions, it will make your code much more readable. (class names should start with a capital letter).
And remember, you don't need to roll your own. ``` throw new RuntimeException("Do not instantiate this class"); ``` (old question, but I always forget syntax, so stashing on google)
44,555,110
I'm reading a CSV file and creating objects based on the values on each line. I can't really name each object something unique so I do: ``` new User(x, y, z); ``` But how can I then find that newly created object? Is there a way to loop through all objects of a specific class (i.e. User)? Or at least find one based on the ID? (e.g. user(1)) In SQL I could simply ``` select * from X where ID=1 ``` but how can I do this in Java after creating several nameless objects based on the data parsed from a text file?
2017/06/14
[ "https://Stackoverflow.com/questions/44555110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908781/" ]
> > Or at least find one based on the ID? > > > You have an identifier by created `User`? So you should just store the objects in a `Map` where the key is the `User` id and the value is the `User` object. With an `Integer` as id, it would give : ``` Map<Integer, User> usersById = new HashMap<>(); for (...){ usersById.put(userId, new User(userId, x, y, z)); } ``` Then you can retrieve the user in this way : ``` User user = usersById.get(1); ```
First, store the objects into a list. ``` List<User> usersList = new ArrayList<>(); ... ... // add each object to usersList ``` Later on, to imitate your `SQL` query, you can do something along the lines of: ``` Optional<User> result = usersList.stream().filter(x -> x.getId() == 1).findFirst(); ``` This solution assumes you have an `id` field within your `User` class and a getter called `getId()`. reading - [**`Optional<T>`**](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html).
3,583,100
Suppose $A$ is a $3\times3$ matrix such that $\det(A)=\frac{1}{125}$. Find $\det(5A^{−1})$. I know that this can also be written as $\det(5/A)$ However, I am struggling to work out what $A$ is Please help
2020/03/16
[ "https://math.stackexchange.com/questions/3583100", "https://math.stackexchange.com", "https://math.stackexchange.com/users/760139/" ]
You need to know two important properties of the determinant: * $\det(A^{-1}) = \frac{1}{\det(A)}$ * $\det(\lambda A) = \lambda^n \det(A)$ where $A$ is an $n \times n$ matrix Since you know $\det(A)$, you can then determine $$ \det(5 A^{-1}) = 5^3 \det(A^{-1}) = 5^3 \cdot \frac{1}{\frac{1}{125}} = 5^3 \cdot 125$$ The two properties I mentioned before usually go under the name [multiplicativity of determinant](https://en.wikipedia.org/wiki/Determinant#Multiplicativity_and_matrix_groups) and [multilinearity of determinant](https://en.wikipedia.org/wiki/Multilinear_map#Examples). Along with some other useful properties, they are listed [here](https://en.wikipedia.org/wiki/Determinant#Properties_of_the_determinant).
**Hint:** $$\text{ det }(5A^{-1})\text{ det }(A)=\text{ det }(5A^{-1}A)=\text{ det }(5I).$$
54,671,220
I have an int array of melodies. If i press the button it plays the whole song but if i put a break after the `delay`, than it just reset the `i`. How do i make it so that only after another button-press it continues? (i'm still a newbie at this sorry and thanks in advance) ``` int buttonPin = 12; void setup() { // put your setup code here, to run once: pinMode(buttonPin, INPUT); } void loop() { // put your main code here, to run repeatedly: int buttonState = digitalRead(buttonPin); for(int i = 0; i < sizeof(mariomelody); i++) { if(buttonState == HIGH) { tone(8, mariomelody[i], 70); delay(); } } } ```
2019/02/13
[ "https://Stackoverflow.com/questions/54671220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10557540/" ]
Stop the loop while the button press is still held in: ``` int buttonPin = 12; void setup() { // put your setup code here, to run once: pinMode(buttonPin, INPUT); } void loop() { // put your main code here, to run repeatedly: int buttonState = digitalRead(buttonPin); for(int i = 0; i < sizeof(mariomelody); i++) { if(buttonState == HIGH) { tone(8, mariomelody[i], 70); delay(); } while(digitalRead(buttonPin) == HIGH) { // wait until the button is released } while(digitalRead(buttonPin) == LOW) { //wait until the button is pressed again } } } ```
I'm guessing that you want to play the melody while the button is pressed, and stop if the button is released. Then it would be something like: ``` int i = 0; void loop() { if(digitalRead(buttonPin) == HIGH) { tone(8, mariomelody[i], 70); i = (i + 1) % sizeof(mariomelody); delay(); } } ``` To avoid resetting the position to the begin of the melody you need `i` to be a global variable. If you want the button to switch on and off the melody you'll need another global variable `playing`: ``` bool playing = false; void loop() { if(digitalRead(buttonPin) == HIGH) { playing = !playing; while (digitalRead(buttonPin) == HIGH) ; //wait for release } if (playing) { //the rest is the same } } ```
2,581,729
I'm writing some software that modifies a Windows Server's configuration (things like MS-DNS, IIS, parts of the filesystem). My design has a server process that builds an in-memory object graph of the server configuration state and a client which requests this object graph. The server would then serialize the graph, send it to the client (presumably using WCF), the server then makes changes to this graph and sends it back to the server. The server receives the graph and proceeds to make modifications to the server. However I've learned that object-graph serialisation in WCF isn't as simple as I first thought. My objects have a hierarchy and many have parametrised-constructors and immutable properties/fields. There are also numerous collections, arrays, and dictionaries. My understanding of WCF serialisation is that it requires use of either the XmlSerializer or DataContractSerializer, but DCS places restrictions on the design of my object-graph (immutable data seems right-out, it also requires parameter-less constructors). I understand XmlSerializer lets me use my own classes provided they implement ISerializable and have the de-serializer constructor. That is fine by me. I spoke to a friend of mine about this, and he advocates going for a Data Transport Object-only route, where I'd have to maintain a separate DataContract object-graph for the transport of data and re-implement my server objects on the client. Another friend of mine said that because my service only has two operations ("GetServerConfiguration" and "PutServerConfiguration") it might be worthwhile just skipping WCF entirely and implementing my own server that uses Sockets. So my questions are: * Has anyone faced a similar problem before and if so, are there better approaches? Is it wise to send an entire object graph to the client for processing? Should I instead break it down so that the client requests a part of the object graph as it needs it and sends only bits that have changed (thus reducing concurrency-related risks?)? * If sending the object-graph down is the right way, is WCF the right tool? * And if WCF is right, what's the best way to get WCF to serialise my object graph?
2010/04/05
[ "https://Stackoverflow.com/questions/2581729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159145/" ]
Object graphs can be used with DataContract serialization. **Note:** Make sure you're preserving object references, so that you don't end up with multiple copies of the same object in the graph when they should all be the same reference, the default behavior does not preserve identity like this. This can be done by specifying the `preserveObjectReferences` parameter when constructing a [DataContractSerializer](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx) or by specifying `true` for the [IsReference](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.isreference(v=VS.90).aspx) property on `DataContractAttribute` (this last attribute requires .NET **3.5SP1**). However, when sending object graphs over WCF, you have the risk of running afoul of WCF quotas (and there are many) if you don't take care to ensure the graph is kept to a reasonable size. For the `net.tcp` transport, for example, important ones to set are `maxReceivedMessageSize`, `maxStringContentLength`, and `maxArrayLength`. Not to mention a hidden quota of 65335 distinct objects allowed in a graph (`maxObjectsInGraph`), that can only be overridden with difficulty. You can also use classes that only expose read accessors with the `DataContractSerializer`, and have no parameterless constructors: ``` using System; using System.IO; using System.Runtime.Serialization; class DataContractTest { static void Main(string[] args) { var serializer = new DataContractSerializer(typeof(NoParameterLessConstructor)); var obj1 = new NoParameterLessConstructor("Name", 1); var ms = new MemoryStream(); serializer.WriteObject(ms, obj1); ms.Seek(0, SeekOrigin.Begin); var obj2 = (NoParameterLessConstructor)serializer.ReadObject(ms); Console.WriteLine("obj2.Name: {0}", obj2.Name); Console.WriteLine("obj2.Version: {0}", obj2.Version); } [DataContract] class NoParameterLessConstructor { public NoParameterLessConstructor(string name, int version) { Name = name; Version = version; } [DataMember] public string Name { get; private set; } [DataMember] public int Version { get; private set; } } } ``` This works because `DataContractSerializer` can instantiate types without calling the constructor.
You got yourself mixed up with the serializers: * the **XmlSerializer** requires a parameter-less constructor, since when deserializing, the .NET runtime will instantiate a new object of that type and then set its properties * the **DataContractSerializer** has no such requirement Check out the [blog post by Dan Rigsby](http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/) which explains serializers in all their glory and compares the two. Now for your design - my main question is: does it make sense to have a single function that return all the settings, the client manipulates those and then another function which receives back all the information? Couldn't you break those things up into smaller chunks, smaller method calls? E.g. have separate service methods to set each individual item of your configuration? That way, you could * reduce the amount of data being sent across the wire - the object graph to be serialized and deserialized would be much simpler * make your configuration service more granular - e.g. if someone needs to set a single little property, that client doesn't need to read the whole big server config, set one single property, and send back the huge big chunk - just call the appropriate method to set that one property
18,829,558
I have a 2-dimensional array of bool like this ![2-dimensional array of bool](https://i.stack.imgur.com/Vz77j.png) The shape won't have any holes -- even if it has -- I'll ignore them. Now I want to find the Polygon embracing my shape: ![embracing polygon](https://i.stack.imgur.com/zVdBC.png) Is there any algorithm ready to use for this case? I couldn't find any, but I'm not sure whether I know the correct search-term for this task.
2013/09/16
[ "https://Stackoverflow.com/questions/18829558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033412/" ]
You can use a delaunay triangulation and then remove the longest edges. I use the average of all edges multiply with a constant.
After thinking about more a little I found it out and there is a O(n)-way to do it: Search row-wise for the first coordinate that contains at least one adjacent field set true. From there you can definitly take the first step to the right. From now on just walk around the field deciding what direction to walk next based on the four adjacent fields.
25,950,843
I'm trying to fit my 'body' background image to the browsers document size. This code here doesn't change anything in browser when i run it... i see the image but it is repeated twice and the size isn't changing. when debugging i see that the width and height variables are correct but nothing actually happens.... any ideas? ```js $(function() { // onload...do var width = $(document).width(); var height = $(document).height(); $('body').css.backgroundSize = "" + width + "px " + height + "px"; }); ``` ```css body{ background: url(../images/MainMenuScreen.jpg); } ```
2014/09/20
[ "https://Stackoverflow.com/questions/25950843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2290597/" ]
We had the exactly same problem. You can rotate it programmatically by the code - ``` if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait) { NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait]; [[UIDevice currentDevice] setValue:value forKey:@"orientation"]; } ``` There are 2 possible options - 1) before you dismiss the presented viewController, rotate to portrait if needed 2) after you dismiss, rotate to portrait in the "viewDidAppear" of the presenting viewController. One issue with this, is that you can't pass a completion block, but you can use the next callback in iOS8: ``` -(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { if (self.needToDismissAfterRotatation) self.needToDismissAfterRotatation = NO; [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) { } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { // dismiss }]; } } ``` By the way, in iOS8 apple did a huge change in the way the screen rotates, when the app rotates, the screen rotates, and all the elements in the UIWindow rotates as well, this is why when the presented viewController rotates to landscape, also the presenting viewController rotates, even if it only supports portrait... We struggled with this issue for many days, finally we came up with a solution to put the presented viewController in a new UIWindow, and this way it keeps the presenting viewController in portrait **all the time** example project for that: ["modalViewController" in UIWindow](https://github.com/OrenRosen/ModalInWindow) ---
This code will force the UI back to portrait, assuming that the view controller you're trying to force portrait was already the root view controller (if it wasn't already the root, this code will restore the root view controller but not any other view controllers that have been pushed onto it): ``` UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; if (orientation != UIInterfaceOrientationPortrait) { // HACK: setting the root view controller to nil and back again "resets" // the navigation bar to the correct orientation UIWindow *window = [[UIApplication sharedApplication] keyWindow]; UIViewController *vc = window.rootViewController; window.rootViewController = nil; window.rootViewController = vc; } ``` It's not very pretty as it makes an abrupt jump after the top level view controller has been dismissed, but it's better than having it left in landscape.
66,580,485
I don't understand why SVELTE is calling the function specified in an {#await} block when the values returned by the function are changed. I've made a little example: <https://svelte.dev/repl/a962314974eb4a07bd98ecb1c9ccb66c?version=3.35.0> In brief: ```js {#await getList() then alist} {#each alist as item} <div> {item.state} <div class="button" on:click={()=>item.state=!item.state}>Toggle it!</div> </div> {/each} {/await} ``` Function `getList()` is called every time I click on "button" div to toggle a value on object returned by the function. I don't understand why. Somebody could enlighten me? Thank you!
2021/03/11
[ "https://Stackoverflow.com/questions/66580485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3061884/" ]
I think it's because the whole component is rerendered when the state is changed, and as such `getList()` is called again as it's in the render code. A better solution might be to find how to avoid the whole rerender with [immutable](https://svelte.dev/tutorial/svelte-options), but here's a way to make this work: ``` <script> let list = [ { state: true}, { state: true}, { state: true},{ state: true} ] let counter = 0; async function getList(){ counter++; return Promise.resolve(list); } const promise = getList() </script> Times GetList called: {counter} {#await promise then alist} {#each alist as item} <div> {item.state} <div class="button" on:click={()=>item.state=!item.state}>Toggle it!</div> </div> {/each} {/await} ```
A state change does not (normally) cause the entire component to rerender, this is the base tenet of Svelte after all. You can try this by adding a second counter and a button inside the await: ```html {#await getList() then alist} <button on:click={() => counter2++}>Clicked {counter2}</button> ... ``` Clicking this button will increase *counter2* without firing `getList` again. The issue here seems to be caused by the fact that you are editing the result of the async operation directly, which somehow retriggers said operation. Considering the other answer works this must have something to do with it being a function call. An alternative approach to fix this would be to move the internals of your each loop into it's own component: ```html {#await getList() then alist} {#each alist as item} <Child {...item} /> {/each} {/await} ```
44,348,493
How to configure a Ninja web application running on Heroku to force the use of SSL, that is, redirect all requests to HTTPS?
2017/06/03
[ "https://Stackoverflow.com/questions/44348493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639722/" ]
Here is the class to add in the conf package: ``` public class Filters implements ApplicationFilters { @Override public void addFilters (List<Class<? extends Filter>> list) { list.add (HttpsFilter.class); } public static class HttpsFilter implements Filter { @Override public Result filter (FilterChain filterChain, Context context) { if ("http".equals (context.getHeader ("X-Forwarded-Proto"))) { return Results.redirect ("https://" + context.getHostname () + context.getRequestPath ()); } return filterChain.next (context); } } } ```
If you look good in the ninja framework documentation it is indicated how to configure it to get what you want <http://www.ninjaframework.org/documentation/configuration_and_modes.html>
70,071,984
I have these two arrays: ``` const goodCars = [ { name: 'ferrari', price: 22000, condition: { isGood: true, isBad: false } }, { name: 'ford', price: 21000, condition: { isGood: true, isBad: false } }, { name: 'bmw', price: 20000, condition: { isGood: true, isBad: false } }, ]; const badCars = [ { name: 'ford', price: 1111, condition: { isGood: false, isBad: true } }, { name: 'honda', price: 8000, condition: { isGood: false, isBad: true } }, ]; ``` My goal is to produce this final array: ``` const finalCarList = [ { name: 'ferrari', price: 22000, condition: { isGood: true, isBad: false } }, { name: 'ford', price: 21000, condition: { isGood: true, isBad: false }, toCompareWith: { name: 'ford', price: 1111, condition: { isGood: false, isBad: true } }, }, { name: 'bmw', price: 20000, condition: { isGood: true, isBad: false } }, { name: 'honda', price: 8000, condition: { isGood: false, isBad: true } }, ]; ``` Basically I want to merge the two `goodCars` and `badCars` arrays into one but if the cars exists in both good and badd arrays then I want to add the bad car to the good car array as a new field `toCompareWith: {...}` (seen above) I've tried using `map()`, `reduce()`, `for` loops, etc. but my brain has hit a wall and I'm not getting any closer. My attempt: ``` goodCars.map((gc) => { badCars.map((bc) => { if (isCarMatch(gc, bc)) { finalCarList = [ ...finalCarList, { ...gc, toCompareWith: bc }, ]; } }); }); ``` Answer I went with based on the below marked correct one: ✅ ``` let finalCarList: Array<Car> = [...goodCars]; badCars?.forEach((bc) => { const match: Car | undefined = goodCars.find((gc) => isCarMatch(gc, bc)); match ? (match.toCompareWith = bc) // Slot in matching item : (finalCarList = [...finalCarList, bc]); }); ```
2021/11/22
[ "https://Stackoverflow.com/questions/70071984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060888/" ]
You shouldn't use nested loops. Start by copying `goodCars` to `finalCarList`. Then loop over `badCars`. If the car is in `goodCars`, add the bad car as the `toCompareWith` property. Otherwise, push it into `finalCarList`. ``` finalCarList = [...goodCars]; badCars.forEach(bc => { match = goodCars.find(gc => isCarMatch(gc, bc)); if (match) { match.toCompareWith = bc; } else { finalCarList.push(bc); } }); ``` Also, in general you shouldn't use `map()` if the callback function doesn't return anything. If it's called only for side effects, use `forEach()`.
Below is an example using two [`for...of` loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of). The outer loop is the first array and the inner loop is the second array using [`.entries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries) in order to track a matches index. If there's a match, the object in the second array is removed and is assigned as the value of `.toCompareWith` property of the matched object of the first array. After the loops are completed, both arrays are merged. ```js const goodCars = [ { name: 'ferrari', price: 22000, condition: { isGood: true, isBad: false } }, { name: 'ford', price: 21000, condition: { isGood: true, isBad: false } }, { name: 'bmw', price: 20000, condition: { isGood: true, isBad: false } }, ]; const badCars = [ { name: 'ford', price: 1111, condition: { isGood: false, isBad: true } }, { name: 'honda', price: 8000, condition: { isGood: false, isBad: true } }, ]; const mergeCars = (arrA, arrB) => { for (let carA of arrA) { for (let [idx, carB] of arrB.entries()) { if (carA.name === carB.name && carA.condition.isGood !== carB.condition.isGood) { carA.toCompareWith = carB; arrB.splice(idx, 1); } } } return [...arrA, ...arrB]; }; console.log(mergeCars(goodCars, badCars)); ```
28,073,914
I'm having an issue decrementing using a do while loop. Everything is broken up into separate files to keep the class & methods/functions separate (as well as keeping the main clear). The issue I'm having is that it decrements once, but when it loops back through it goes right back to the same value and decrements to the same result. I know it's probably something stupid I did, but I haven't noticed it yet! **To be specific the error I'm getting is when I call the useBrake method.** Gondola.h ``` #ifndef _GONDOLA_CLASS #define _GONDOLA_CLASS class Gondola { private: double load; // load <= 500 double speed; // Speed <= 20 double condition; // 0-100 public: //Constructors Gondola(); Gondola(double ld, double spd, double cnd); //Accessor methods (getters) double getLoad() const; double getSpeed() const; double getCondition() const; //Mutator Methods methods (setters) bool setLoad(double ld); bool setSpeed(double spd); bool setCondition(double cnd); //Other Methods double useBrake(int slowSpeed); }; #endif ``` Gondola.cpp ``` //Accessor and mutator methods #include <iostream> #include "Gondola.h" using namespace std; //Constructors Gondola::Gondola() { load = 0; speed = 0; condition = 100; } Gondola::Gondola(double ld, double spd, double condit) { if(!setLoad(ld)) { load = 500; } if(!setSpeed(spd)) { speed = 20; } if(!setCondition(condit)) { condition = 100; } } //Accessor Methods double Gondola::getLoad() const { return load; } double Gondola::getSpeed() const { return speed; } double Gondola::getCondition() const { return condition; } //Mutator Methods bool Gondola::setLoad(double ld) { bool validLoad = (ld > 0) && (ld <= 500); if(validLoad) { load = ld; } return validLoad; } bool Gondola::setSpeed(double spd) { bool validSpeed = (spd > 0) && (spd <= 20); if(validSpeed) { speed = spd; } return validSpeed; } bool Gondola::setCondition(double cnd) { bool validCondition = (cnd > 0) && (cnd <= 100); if(validCondition) { condition = cnd; } return validCondition; } //Other Functions double Gondola::useBrake(int slowSpeed) { char userResponse = ' '; bool validInput = false; int newSpeed = 0; do { cout << "Do you want to use the brake?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if(!validInput) { cout << "Invalid response. Please try again!" << endl; } if(userResponse == 'y') { newSpeed = (slowSpeed - 5); speed = newSpeed; } }while(!validInput); return slowSpeed; } bool continueBraking() // Asks the user if they want to continue. If yes, the braking loop continues. If no, the program continues { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue braking?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits. { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } ``` Main.cpp ``` /* Paul Christopher Skill 2.2 Description: Program creates gondola object and then the user enters in the load, speed, and condition. The program also has methods to dump and use the brake to slow the speed of the gondola by 5 kph. */ //main program code #include <iostream> #include "Gondola.h" using namespace std; bool continueBraking(); bool askToContinue(); int main() { //Variables double gondolaLoad = 0.0; double gondolaSpeed = 0.0; double gondolaCondition = 0.0; do { //Object Declaration Gondola gondola; //Change variables cout << "Enter a load size for this gondola (1-500): " << endl; cin >> gondolaLoad; gondola.setLoad(gondolaLoad); cout << "Enter a speed for this gondola (<=20): " << endl; cin >> gondolaSpeed; gondola.setSpeed(gondolaSpeed); cout << "Enter a condition for this gondola (1-100): " << endl; cin >> gondolaCondition; gondola.setCondition(gondolaCondition); //New Output cout << "Gondola's new load, speed, and condition: " << endl; cout << gondola.getLoad() << endl; cout << gondola.getSpeed() << endl; cout << gondola.getCondition() << endl; do { gondola.useBrake(gondolaSpeed); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(continueBraking()); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(askToContinue()); system("PAUSE"); return 0; } ```
2015/01/21
[ "https://Stackoverflow.com/questions/28073914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271411/" ]
You need to add a `break;` statement to break out of the `switch` block. ``` switch (x) { case 1: System.out.println("1"); break; default: System.out.println("helllo"); break; // <-- add this here case 2: System.out.println("Benjamin"); break; } ``` Generally speaking, it is also better coding practice to have your `default:` case be the last case in the `switch` block. In this case, the switch is following the pattern: ``` x==1? No, check next case default? Not done yet, check other cases x==2? No, check next case //No more cases, so go back to default default? Yes, do default logic // no break statement in default, so it falls through to case 2: logic without checking the case output case 2 logic break ``` Notice how the block will jump over the default case, and save it until a later time unless we have exhausted all other possible cases.
It prints both strings because you do not have a `break` in your `default` case, so it continues into `case 2`, printing Benjamin. You could fix this by adding a `break` or moving `case 2` above the `default` case.
28,073,914
I'm having an issue decrementing using a do while loop. Everything is broken up into separate files to keep the class & methods/functions separate (as well as keeping the main clear). The issue I'm having is that it decrements once, but when it loops back through it goes right back to the same value and decrements to the same result. I know it's probably something stupid I did, but I haven't noticed it yet! **To be specific the error I'm getting is when I call the useBrake method.** Gondola.h ``` #ifndef _GONDOLA_CLASS #define _GONDOLA_CLASS class Gondola { private: double load; // load <= 500 double speed; // Speed <= 20 double condition; // 0-100 public: //Constructors Gondola(); Gondola(double ld, double spd, double cnd); //Accessor methods (getters) double getLoad() const; double getSpeed() const; double getCondition() const; //Mutator Methods methods (setters) bool setLoad(double ld); bool setSpeed(double spd); bool setCondition(double cnd); //Other Methods double useBrake(int slowSpeed); }; #endif ``` Gondola.cpp ``` //Accessor and mutator methods #include <iostream> #include "Gondola.h" using namespace std; //Constructors Gondola::Gondola() { load = 0; speed = 0; condition = 100; } Gondola::Gondola(double ld, double spd, double condit) { if(!setLoad(ld)) { load = 500; } if(!setSpeed(spd)) { speed = 20; } if(!setCondition(condit)) { condition = 100; } } //Accessor Methods double Gondola::getLoad() const { return load; } double Gondola::getSpeed() const { return speed; } double Gondola::getCondition() const { return condition; } //Mutator Methods bool Gondola::setLoad(double ld) { bool validLoad = (ld > 0) && (ld <= 500); if(validLoad) { load = ld; } return validLoad; } bool Gondola::setSpeed(double spd) { bool validSpeed = (spd > 0) && (spd <= 20); if(validSpeed) { speed = spd; } return validSpeed; } bool Gondola::setCondition(double cnd) { bool validCondition = (cnd > 0) && (cnd <= 100); if(validCondition) { condition = cnd; } return validCondition; } //Other Functions double Gondola::useBrake(int slowSpeed) { char userResponse = ' '; bool validInput = false; int newSpeed = 0; do { cout << "Do you want to use the brake?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if(!validInput) { cout << "Invalid response. Please try again!" << endl; } if(userResponse == 'y') { newSpeed = (slowSpeed - 5); speed = newSpeed; } }while(!validInput); return slowSpeed; } bool continueBraking() // Asks the user if they want to continue. If yes, the braking loop continues. If no, the program continues { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue braking?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits. { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } ``` Main.cpp ``` /* Paul Christopher Skill 2.2 Description: Program creates gondola object and then the user enters in the load, speed, and condition. The program also has methods to dump and use the brake to slow the speed of the gondola by 5 kph. */ //main program code #include <iostream> #include "Gondola.h" using namespace std; bool continueBraking(); bool askToContinue(); int main() { //Variables double gondolaLoad = 0.0; double gondolaSpeed = 0.0; double gondolaCondition = 0.0; do { //Object Declaration Gondola gondola; //Change variables cout << "Enter a load size for this gondola (1-500): " << endl; cin >> gondolaLoad; gondola.setLoad(gondolaLoad); cout << "Enter a speed for this gondola (<=20): " << endl; cin >> gondolaSpeed; gondola.setSpeed(gondolaSpeed); cout << "Enter a condition for this gondola (1-100): " << endl; cin >> gondolaCondition; gondola.setCondition(gondolaCondition); //New Output cout << "Gondola's new load, speed, and condition: " << endl; cout << gondola.getLoad() << endl; cout << gondola.getSpeed() << endl; cout << gondola.getCondition() << endl; do { gondola.useBrake(gondolaSpeed); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(continueBraking()); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(askToContinue()); system("PAUSE"); return 0; } ```
2015/01/21
[ "https://Stackoverflow.com/questions/28073914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271411/" ]
It prints both strings because you do not have a `break` in your `default` case, so it continues into `case 2`, printing Benjamin. You could fix this by adding a `break` or moving `case 2` above the `default` case.
'switch' case is other form of 'if-then-else', the default case is for the final else part. It is advisable to write default at the end of switch.
28,073,914
I'm having an issue decrementing using a do while loop. Everything is broken up into separate files to keep the class & methods/functions separate (as well as keeping the main clear). The issue I'm having is that it decrements once, but when it loops back through it goes right back to the same value and decrements to the same result. I know it's probably something stupid I did, but I haven't noticed it yet! **To be specific the error I'm getting is when I call the useBrake method.** Gondola.h ``` #ifndef _GONDOLA_CLASS #define _GONDOLA_CLASS class Gondola { private: double load; // load <= 500 double speed; // Speed <= 20 double condition; // 0-100 public: //Constructors Gondola(); Gondola(double ld, double spd, double cnd); //Accessor methods (getters) double getLoad() const; double getSpeed() const; double getCondition() const; //Mutator Methods methods (setters) bool setLoad(double ld); bool setSpeed(double spd); bool setCondition(double cnd); //Other Methods double useBrake(int slowSpeed); }; #endif ``` Gondola.cpp ``` //Accessor and mutator methods #include <iostream> #include "Gondola.h" using namespace std; //Constructors Gondola::Gondola() { load = 0; speed = 0; condition = 100; } Gondola::Gondola(double ld, double spd, double condit) { if(!setLoad(ld)) { load = 500; } if(!setSpeed(spd)) { speed = 20; } if(!setCondition(condit)) { condition = 100; } } //Accessor Methods double Gondola::getLoad() const { return load; } double Gondola::getSpeed() const { return speed; } double Gondola::getCondition() const { return condition; } //Mutator Methods bool Gondola::setLoad(double ld) { bool validLoad = (ld > 0) && (ld <= 500); if(validLoad) { load = ld; } return validLoad; } bool Gondola::setSpeed(double spd) { bool validSpeed = (spd > 0) && (spd <= 20); if(validSpeed) { speed = spd; } return validSpeed; } bool Gondola::setCondition(double cnd) { bool validCondition = (cnd > 0) && (cnd <= 100); if(validCondition) { condition = cnd; } return validCondition; } //Other Functions double Gondola::useBrake(int slowSpeed) { char userResponse = ' '; bool validInput = false; int newSpeed = 0; do { cout << "Do you want to use the brake?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if(!validInput) { cout << "Invalid response. Please try again!" << endl; } if(userResponse == 'y') { newSpeed = (slowSpeed - 5); speed = newSpeed; } }while(!validInput); return slowSpeed; } bool continueBraking() // Asks the user if they want to continue. If yes, the braking loop continues. If no, the program continues { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue braking?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits. { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } ``` Main.cpp ``` /* Paul Christopher Skill 2.2 Description: Program creates gondola object and then the user enters in the load, speed, and condition. The program also has methods to dump and use the brake to slow the speed of the gondola by 5 kph. */ //main program code #include <iostream> #include "Gondola.h" using namespace std; bool continueBraking(); bool askToContinue(); int main() { //Variables double gondolaLoad = 0.0; double gondolaSpeed = 0.0; double gondolaCondition = 0.0; do { //Object Declaration Gondola gondola; //Change variables cout << "Enter a load size for this gondola (1-500): " << endl; cin >> gondolaLoad; gondola.setLoad(gondolaLoad); cout << "Enter a speed for this gondola (<=20): " << endl; cin >> gondolaSpeed; gondola.setSpeed(gondolaSpeed); cout << "Enter a condition for this gondola (1-100): " << endl; cin >> gondolaCondition; gondola.setCondition(gondolaCondition); //New Output cout << "Gondola's new load, speed, and condition: " << endl; cout << gondola.getLoad() << endl; cout << gondola.getSpeed() << endl; cout << gondola.getCondition() << endl; do { gondola.useBrake(gondolaSpeed); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(continueBraking()); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(askToContinue()); system("PAUSE"); return 0; } ```
2015/01/21
[ "https://Stackoverflow.com/questions/28073914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271411/" ]
It prints both strings because you do not have a `break` in your `default` case, so it continues into `case 2`, printing Benjamin. You could fix this by adding a `break` or moving `case 2` above the `default` case.
Default is checked as last. Thats why it feels like the compiler 'went' back.
28,073,914
I'm having an issue decrementing using a do while loop. Everything is broken up into separate files to keep the class & methods/functions separate (as well as keeping the main clear). The issue I'm having is that it decrements once, but when it loops back through it goes right back to the same value and decrements to the same result. I know it's probably something stupid I did, but I haven't noticed it yet! **To be specific the error I'm getting is when I call the useBrake method.** Gondola.h ``` #ifndef _GONDOLA_CLASS #define _GONDOLA_CLASS class Gondola { private: double load; // load <= 500 double speed; // Speed <= 20 double condition; // 0-100 public: //Constructors Gondola(); Gondola(double ld, double spd, double cnd); //Accessor methods (getters) double getLoad() const; double getSpeed() const; double getCondition() const; //Mutator Methods methods (setters) bool setLoad(double ld); bool setSpeed(double spd); bool setCondition(double cnd); //Other Methods double useBrake(int slowSpeed); }; #endif ``` Gondola.cpp ``` //Accessor and mutator methods #include <iostream> #include "Gondola.h" using namespace std; //Constructors Gondola::Gondola() { load = 0; speed = 0; condition = 100; } Gondola::Gondola(double ld, double spd, double condit) { if(!setLoad(ld)) { load = 500; } if(!setSpeed(spd)) { speed = 20; } if(!setCondition(condit)) { condition = 100; } } //Accessor Methods double Gondola::getLoad() const { return load; } double Gondola::getSpeed() const { return speed; } double Gondola::getCondition() const { return condition; } //Mutator Methods bool Gondola::setLoad(double ld) { bool validLoad = (ld > 0) && (ld <= 500); if(validLoad) { load = ld; } return validLoad; } bool Gondola::setSpeed(double spd) { bool validSpeed = (spd > 0) && (spd <= 20); if(validSpeed) { speed = spd; } return validSpeed; } bool Gondola::setCondition(double cnd) { bool validCondition = (cnd > 0) && (cnd <= 100); if(validCondition) { condition = cnd; } return validCondition; } //Other Functions double Gondola::useBrake(int slowSpeed) { char userResponse = ' '; bool validInput = false; int newSpeed = 0; do { cout << "Do you want to use the brake?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if(!validInput) { cout << "Invalid response. Please try again!" << endl; } if(userResponse == 'y') { newSpeed = (slowSpeed - 5); speed = newSpeed; } }while(!validInput); return slowSpeed; } bool continueBraking() // Asks the user if they want to continue. If yes, the braking loop continues. If no, the program continues { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue braking?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits. { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } ``` Main.cpp ``` /* Paul Christopher Skill 2.2 Description: Program creates gondola object and then the user enters in the load, speed, and condition. The program also has methods to dump and use the brake to slow the speed of the gondola by 5 kph. */ //main program code #include <iostream> #include "Gondola.h" using namespace std; bool continueBraking(); bool askToContinue(); int main() { //Variables double gondolaLoad = 0.0; double gondolaSpeed = 0.0; double gondolaCondition = 0.0; do { //Object Declaration Gondola gondola; //Change variables cout << "Enter a load size for this gondola (1-500): " << endl; cin >> gondolaLoad; gondola.setLoad(gondolaLoad); cout << "Enter a speed for this gondola (<=20): " << endl; cin >> gondolaSpeed; gondola.setSpeed(gondolaSpeed); cout << "Enter a condition for this gondola (1-100): " << endl; cin >> gondolaCondition; gondola.setCondition(gondolaCondition); //New Output cout << "Gondola's new load, speed, and condition: " << endl; cout << gondola.getLoad() << endl; cout << gondola.getSpeed() << endl; cout << gondola.getCondition() << endl; do { gondola.useBrake(gondolaSpeed); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(continueBraking()); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(askToContinue()); system("PAUSE"); return 0; } ```
2015/01/21
[ "https://Stackoverflow.com/questions/28073914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271411/" ]
You need to add a `break;` statement to break out of the `switch` block. ``` switch (x) { case 1: System.out.println("1"); break; default: System.out.println("helllo"); break; // <-- add this here case 2: System.out.println("Benjamin"); break; } ``` Generally speaking, it is also better coding practice to have your `default:` case be the last case in the `switch` block. In this case, the switch is following the pattern: ``` x==1? No, check next case default? Not done yet, check other cases x==2? No, check next case //No more cases, so go back to default default? Yes, do default logic // no break statement in default, so it falls through to case 2: logic without checking the case output case 2 logic break ``` Notice how the block will jump over the default case, and save it until a later time unless we have exhausted all other possible cases.
'switch' case is other form of 'if-then-else', the default case is for the final else part. It is advisable to write default at the end of switch.
28,073,914
I'm having an issue decrementing using a do while loop. Everything is broken up into separate files to keep the class & methods/functions separate (as well as keeping the main clear). The issue I'm having is that it decrements once, but when it loops back through it goes right back to the same value and decrements to the same result. I know it's probably something stupid I did, but I haven't noticed it yet! **To be specific the error I'm getting is when I call the useBrake method.** Gondola.h ``` #ifndef _GONDOLA_CLASS #define _GONDOLA_CLASS class Gondola { private: double load; // load <= 500 double speed; // Speed <= 20 double condition; // 0-100 public: //Constructors Gondola(); Gondola(double ld, double spd, double cnd); //Accessor methods (getters) double getLoad() const; double getSpeed() const; double getCondition() const; //Mutator Methods methods (setters) bool setLoad(double ld); bool setSpeed(double spd); bool setCondition(double cnd); //Other Methods double useBrake(int slowSpeed); }; #endif ``` Gondola.cpp ``` //Accessor and mutator methods #include <iostream> #include "Gondola.h" using namespace std; //Constructors Gondola::Gondola() { load = 0; speed = 0; condition = 100; } Gondola::Gondola(double ld, double spd, double condit) { if(!setLoad(ld)) { load = 500; } if(!setSpeed(spd)) { speed = 20; } if(!setCondition(condit)) { condition = 100; } } //Accessor Methods double Gondola::getLoad() const { return load; } double Gondola::getSpeed() const { return speed; } double Gondola::getCondition() const { return condition; } //Mutator Methods bool Gondola::setLoad(double ld) { bool validLoad = (ld > 0) && (ld <= 500); if(validLoad) { load = ld; } return validLoad; } bool Gondola::setSpeed(double spd) { bool validSpeed = (spd > 0) && (spd <= 20); if(validSpeed) { speed = spd; } return validSpeed; } bool Gondola::setCondition(double cnd) { bool validCondition = (cnd > 0) && (cnd <= 100); if(validCondition) { condition = cnd; } return validCondition; } //Other Functions double Gondola::useBrake(int slowSpeed) { char userResponse = ' '; bool validInput = false; int newSpeed = 0; do { cout << "Do you want to use the brake?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if(!validInput) { cout << "Invalid response. Please try again!" << endl; } if(userResponse == 'y') { newSpeed = (slowSpeed - 5); speed = newSpeed; } }while(!validInput); return slowSpeed; } bool continueBraking() // Asks the user if they want to continue. If yes, the braking loop continues. If no, the program continues { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue braking?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits. { char userResponse = ' '; bool validInput = false; do { cout << endl; cout << "Do you wish to continue?" << endl; cout << "Enter y for 'yes' or n for 'no'" << endl; cin >> userResponse; validInput = (userResponse == 'y') || (userResponse == 'n'); if (!validInput) { cout << "Invalid response. Please try again!" << endl; } } while (!validInput); return(userResponse == 'y'); } ``` Main.cpp ``` /* Paul Christopher Skill 2.2 Description: Program creates gondola object and then the user enters in the load, speed, and condition. The program also has methods to dump and use the brake to slow the speed of the gondola by 5 kph. */ //main program code #include <iostream> #include "Gondola.h" using namespace std; bool continueBraking(); bool askToContinue(); int main() { //Variables double gondolaLoad = 0.0; double gondolaSpeed = 0.0; double gondolaCondition = 0.0; do { //Object Declaration Gondola gondola; //Change variables cout << "Enter a load size for this gondola (1-500): " << endl; cin >> gondolaLoad; gondola.setLoad(gondolaLoad); cout << "Enter a speed for this gondola (<=20): " << endl; cin >> gondolaSpeed; gondola.setSpeed(gondolaSpeed); cout << "Enter a condition for this gondola (1-100): " << endl; cin >> gondolaCondition; gondola.setCondition(gondolaCondition); //New Output cout << "Gondola's new load, speed, and condition: " << endl; cout << gondola.getLoad() << endl; cout << gondola.getSpeed() << endl; cout << gondola.getCondition() << endl; do { gondola.useBrake(gondolaSpeed); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(continueBraking()); cout << "Gondola's new speed: " << gondola.getSpeed() << endl; }while(askToContinue()); system("PAUSE"); return 0; } ```
2015/01/21
[ "https://Stackoverflow.com/questions/28073914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4271411/" ]
You need to add a `break;` statement to break out of the `switch` block. ``` switch (x) { case 1: System.out.println("1"); break; default: System.out.println("helllo"); break; // <-- add this here case 2: System.out.println("Benjamin"); break; } ``` Generally speaking, it is also better coding practice to have your `default:` case be the last case in the `switch` block. In this case, the switch is following the pattern: ``` x==1? No, check next case default? Not done yet, check other cases x==2? No, check next case //No more cases, so go back to default default? Yes, do default logic // no break statement in default, so it falls through to case 2: logic without checking the case output case 2 logic break ``` Notice how the block will jump over the default case, and save it until a later time unless we have exhausted all other possible cases.
Default is checked as last. Thats why it feels like the compiler 'went' back.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
Random advice: Someone mentioned putting dead objects in a queue to be reused instead of letting the GC at them... but be careful, as this means the GC may have more crap to move around when it consolidates the heap, and may not actually help you. Also, the GC is possibly already using techniques like this. Also, I know of at least one project where the engineers tried pooling and it actually hurt performance. It's tough to get a deep intuition about the GC. I'd recommend having a pooled and unpooled setting so you can always measure the perf differences between the two. Another technique you might use in C# is dropping down to native C++ for key parts that aren't performing well enough... and then use the [Dispose pattern](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) in C# or C++/CLI for managed objects which hold unmanaged resources. Also, be sure when you use value types that you are not using them in ways that implicitly box them and put them on the heap, which might be easy to do coming from Java. Finally, be sure to find a good memory profiler.
I agree with all points said above: the garbage collector is great, but it shouldn't be used as a crutch. I've sat through many wasted hours in code-reviews debating over finer points of the CLR. The best definitive answer is to develop a culture of performance in your organization and actively profile your application using a tool. Bottlenecks will appear and you address as needed.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
I've seen too many cases where people "optimize" the crap out of their code without much concern for how well it's written or how well it works even. I think the first thought should go towards making code solve the business problem at hand. The code should be well crafted and easily maintainable as well as properly tested. After all of that, optimization should be considered, if testing indicates it's needed.
I have the same thought all the time. The truth is, though we were taught to watch out for unnecessary CPU tacts and memory consumption, the cost of little imperfections in our code just negligible in practice. If you are aware of that and always watch, I believe you are okay to write not perfect code. If you have started with .NET/Java and have no prior experience in low level programming, the chances are you will write very abusive and ineffective code. And anyway, as they say, the premature optimization is the root of all evil. You can spend hours optimizing one little function and it turns out then that some other part of code gives a bottleneck. Just keep balance doing it simple and doing it stupidly.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
This is one of those issues where it is really hard to pin down a definitive answer in a way that will help you. The .NET GC is *very* good at tuning itself to the memory needs of you application. Is it good enough that your application can be coded without you needing to worry about memory management? I don't know. There are definitely some common-sense things you can do to ensure that you don't hammer the GC. Using value types is definitely one way of accomplishing this but you need to be careful that you don't introduce other issues with poorly-written structs. For the most part however I would say that the GC will do a good job managing all this stuff for you.
You might consider writing a set of object caches. Instead of creating new instances, you could keep a list of available objects somewhere. It would help you avoid the GC.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
Yes, it's true of .NET as well. Most of us have the luxury of ignoring the details of memory management, but in your case -- or in cases where high volume is causing memory congestion -- then some optimizaition is called for. One optimization you might consider for your case -- something I've been thinking about writing an article about, actually -- is the combination of structs and `ref` for real deterministic disposal. Since you come from a C++ background, you know that in C++ you can instantiate an object either on the heap (using the new keyword and getting back a pointer) or on the stack (by instantiating it like a primitive type, i.e. `MyType myType;`). You can pass stack-allocated items by reference to functions and methods by telling the function to accept a reference (using the `&` keyword before the parameter name in your declaration). Doing this keeps your stack-allocated object in memory for as long as the method in which it was allocated remains in scope; once it goes out of scope, the object is reclaimed, the destructor is called, ba-da-bing, ba-da-boom, Bob's yer Uncle, and all done without pointers. I used that trick to create some amazingly performant code in my C++ days -- at the expense of a larger stack and the risk of a stack overflow, naturally, but careful analysis managed to keep that risk very minimal. My point is that you can do the same trick in C# using structs and refs. The tradeoffs? In addition to the risk of a stack overflow if you're not careful or if you use large objects, you are limited to no inheritance, and you tightly couple your code, making it it less testable and less maintainable. Additionally, you still have to deal with issues whenever you use core library calls. Still, it might be worth a look-see in your case.
I agree with all points said above: the garbage collector is great, but it shouldn't be used as a crutch. I've sat through many wasted hours in code-reviews debating over finer points of the CLR. The best definitive answer is to develop a culture of performance in your organization and actively profile your application using a tool. Bottlenecks will appear and you address as needed.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
Random advice: Someone mentioned putting dead objects in a queue to be reused instead of letting the GC at them... but be careful, as this means the GC may have more crap to move around when it consolidates the heap, and may not actually help you. Also, the GC is possibly already using techniques like this. Also, I know of at least one project where the engineers tried pooling and it actually hurt performance. It's tough to get a deep intuition about the GC. I'd recommend having a pooled and unpooled setting so you can always measure the perf differences between the two. Another technique you might use in C# is dropping down to native C++ for key parts that aren't performing well enough... and then use the [Dispose pattern](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) in C# or C++/CLI for managed objects which hold unmanaged resources. Also, be sure when you use value types that you are not using them in ways that implicitly box them and put them on the heap, which might be easy to do coming from Java. Finally, be sure to find a good memory profiler.
.NET Memory management is very good and being able to programmatically tweak the GC if you need to is good. I like the fact that you can create your own Dispose methods on classes by inheriting from IDisposable and tweaking it to your needs. This is great for making sure that connections to networks/files/databases are always cleaned up and not leaking that way. There is also the worry of cleaning up too early as well.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
This is one of those issues where it is really hard to pin down a definitive answer in a way that will help you. The .NET GC is *very* good at tuning itself to the memory needs of you application. Is it good enough that your application can be coded without you needing to worry about memory management? I don't know. There are definitely some common-sense things you can do to ensure that you don't hammer the GC. Using value types is definitely one way of accomplishing this but you need to be careful that you don't introduce other issues with poorly-written structs. For the most part however I would say that the GC will do a good job managing all this stuff for you.
I agree with all points said above: the garbage collector is great, but it shouldn't be used as a crutch. I've sat through many wasted hours in code-reviews debating over finer points of the CLR. The best definitive answer is to develop a culture of performance in your organization and actively profile your application using a tool. Bottlenecks will appear and you address as needed.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
This is one of those issues where it is really hard to pin down a definitive answer in a way that will help you. The .NET GC is *very* good at tuning itself to the memory needs of you application. Is it good enough that your application can be coded without you needing to worry about memory management? I don't know. There are definitely some common-sense things you can do to ensure that you don't hammer the GC. Using value types is definitely one way of accomplishing this but you need to be careful that you don't introduce other issues with poorly-written structs. For the most part however I would say that the GC will do a good job managing all this stuff for you.
Random advice: Someone mentioned putting dead objects in a queue to be reused instead of letting the GC at them... but be careful, as this means the GC may have more crap to move around when it consolidates the heap, and may not actually help you. Also, the GC is possibly already using techniques like this. Also, I know of at least one project where the engineers tried pooling and it actually hurt performance. It's tough to get a deep intuition about the GC. I'd recommend having a pooled and unpooled setting so you can always measure the perf differences between the two. Another technique you might use in C# is dropping down to native C++ for key parts that aren't performing well enough... and then use the [Dispose pattern](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) in C# or C++/CLI for managed objects which hold unmanaged resources. Also, be sure when you use value types that you are not using them in ways that implicitly box them and put them on the heap, which might be easy to do coming from Java. Finally, be sure to find a good memory profiler.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
This is one of those issues where it is really hard to pin down a definitive answer in a way that will help you. The .NET GC is *very* good at tuning itself to the memory needs of you application. Is it good enough that your application can be coded without you needing to worry about memory management? I don't know. There are definitely some common-sense things you can do to ensure that you don't hammer the GC. Using value types is definitely one way of accomplishing this but you need to be careful that you don't introduce other issues with poorly-written structs. For the most part however I would say that the GC will do a good job managing all this stuff for you.
Although the Garbage Collector is there, bad code remains bad code. Therefore I would say yes as a .Net developer you should still care about how many objects you create and more importantly writing optimized code. I have seen a considerable amount of projects get rejected because of this reason in Code Reviews inside our environment, and I strongly believe it is important.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
Random advice: Someone mentioned putting dead objects in a queue to be reused instead of letting the GC at them... but be careful, as this means the GC may have more crap to move around when it consolidates the heap, and may not actually help you. Also, the GC is possibly already using techniques like this. Also, I know of at least one project where the engineers tried pooling and it actually hurt performance. It's tough to get a deep intuition about the GC. I'd recommend having a pooled and unpooled setting so you can always measure the perf differences between the two. Another technique you might use in C# is dropping down to native C++ for key parts that aren't performing well enough... and then use the [Dispose pattern](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) in C# or C++/CLI for managed objects which hold unmanaged resources. Also, be sure when you use value types that you are not using them in ways that implicitly box them and put them on the heap, which might be easy to do coming from Java. Finally, be sure to find a good memory profiler.
I have the same thought all the time. The truth is, though we were taught to watch out for unnecessary CPU tacts and memory consumption, the cost of little imperfections in our code just negligible in practice. If you are aware of that and always watch, I believe you are okay to write not perfect code. If you have started with .NET/Java and have no prior experience in low level programming, the chances are you will write very abusive and ineffective code. And anyway, as they say, the premature optimization is the root of all evil. You can spend hours optimizing one little function and it turns out then that some other part of code gives a bottleneck. Just keep balance doing it simple and doing it stupidly.
1,132,077
This question has been puzzling me for a long time now. I come from a heavy and long C++ background, and since I started programming in C# and dealing with garbage collection I always had the feeling that such 'magic' would come at a cost. I recently started working in a big MMO project written in Java (server side). My main task is to optimize memory comsumption and CPU usage. Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well. After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time (due to constant collections) and decided to try to minimize object creation, using pools where applicable and reusing everything we can. This has proven to be a really good optimization so far. So, from what I've learned, having a garbage collector is awesome, but you can't just pretend it does not exist, and you still need to take care about object creation and what it implies (at least in Java and a big application like this). So, is this also true for .NET? if it is, to what extent? I often write pairs of functions like these: ``` // Combines two envelopes and the result is stored in a new envelope. public static Envelope Combine( Envelope a, Envelope b ) { var envelope = new Envelope( _a.Length, 0, 1, 1 ); Combine( _a, _b, _operation, envelope ); return envelope; } // Combines two envelopes and the result is 'written' to the specified envelope public static void Combine( Envelope a, Envelope b, Envelope result ) { result.Clear(); ... } ``` A second function is provided in case someone has an already made Envelope that may be reused to store the result, but I find this a little odd. I also sometimes write structs when I'd rather use classes, just because I know there'll be tens of thousands of instances being constantly created and disposed, and this feels really odd to me. I know that as a .NET developer I shouldn't be worrying about this kind of issues, but my experience with Java and common sense tells me that I should. Any light and thoughts on this matter would be much appreciated. Thanks in advance.
2009/07/15
[ "https://Stackoverflow.com/questions/1132077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
Random advice: Someone mentioned putting dead objects in a queue to be reused instead of letting the GC at them... but be careful, as this means the GC may have more crap to move around when it consolidates the heap, and may not actually help you. Also, the GC is possibly already using techniques like this. Also, I know of at least one project where the engineers tried pooling and it actually hurt performance. It's tough to get a deep intuition about the GC. I'd recommend having a pooled and unpooled setting so you can always measure the perf differences between the two. Another technique you might use in C# is dropping down to native C++ for key parts that aren't performing well enough... and then use the [Dispose pattern](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx) in C# or C++/CLI for managed objects which hold unmanaged resources. Also, be sure when you use value types that you are not using them in ways that implicitly box them and put them on the heap, which might be easy to do coming from Java. Finally, be sure to find a good memory profiler.
Although the Garbage Collector is there, bad code remains bad code. Therefore I would say yes as a .Net developer you should still care about how many objects you create and more importantly writing optimized code. I have seen a considerable amount of projects get rejected because of this reason in Code Reviews inside our environment, and I strongly believe it is important.
41,425,460
I have two buttons on my right of my navigation bar. ``` extension UIViewController { func setNavigationBarItem() { let profileButton = UIBarButtonItem(title: "?", style: .plain, target: self, action: #selector(didTapProfileButton(_:))) navigationItem.rightBarButtonItems = [addRightBarButtonWithImage(UIImage(named: "menu")!), profileButton] self.slideMenuController()?.removeRightGestures() self.slideMenuController()?.addRightGestures() } } ``` I have created 2 buttons like this. But the profileButton I want is with background colour and having corner radius to that button. How to add it to make it look like : [![enter image description here](https://i.stack.imgur.com/ZZ1Xi.png)](https://i.stack.imgur.com/ZZ1Xi.png) Ignore black part. `UIBarButton` will be of yellow colour background and corner radius.
2017/01/02
[ "https://Stackoverflow.com/questions/41425460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6665875/" ]
For that you have only one option you need to create `UIButton` instance with design that you want after that create `UIBarButtonItem` instance from that button. ``` let btnProfile = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) btnProfile.setTitle("SY", for: .normal) btnProfile.backgroundColor = UIColor.yellow btnProfile.layer.cornerRadius = 4.0 btnProfile.layer.masksToBounds = true ``` Now create the `UIBarButtonItem` from that button and set it with the `rightBarButtonItems`. ``` navigationItem.rightBarButtonItems = [addRightBarButtonWithImage(UIImage(named: "menu")!), UIBarButtonItem(customView: btnProfile)] ```
``` let profileButton = UIButton() profileButton.frame = CGRect(x:0, y:0, width:30, height:30) profileButton.setTitle("SY", for: .normal) profileButton.setTitle("SY", for: .highlighted) profileButton.backgroundColor = UIColor.yellow profileButton.layer.cornerRadius = 5.0 profileButton.addTarget(self, action: #selector(didTapProfileButton(_:)), for: .touchUpInside) let rightBarButton = UIBarButtonItem(customView: profileButton) self.navigationItem.rightBarButtonItem = rightBarButton ```