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 |
|---|---|---|---|---|---|
13,368,452 | I want to set an unsorted list as a "background". To do that, I have assigned it to be very wide so it matches whatever screen opens the page including 2560px width. But I can't make it center completely with CSS unless there is a trick or something. I am willing to go jquery way. Technically the ul will have the same effect as background-position:top center;
Instead of a code I attach an image with the way it should work (added code)
```
<div style="background-color:black; width:100%; overflow:hidden; height:302px; text-align:center; position:relative">
<ul style="padding:0px; margin:0px; text-align:center; width:2560px; height:100%; margin:0 auto 0; position:relative;">
<li class="image"></li><li class="image"></li><li class="image"></li><li class="image"></li><li class="image"></li><li class="image">
</ul>
</div>
```
i used inline css so its clearer what im trying to do.

any help appreciated | 2012/11/13 | [
"https://Stackoverflow.com/questions/13368452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004105/"
] | Is [this fiddle](http://jsfiddle.net/wpnFZ/) what you want? I think you didn't explain correctly when you said "background"
CSS
```
ul{
list-style-type: none;
margin: 0;
position: relative;
text-align: center;
width: 100%;
background:#FF0000;
}
ul li {
display: inline-block;
height: 65px;
overflow: hidden;
padding: 0;
background:#0000FF;
line-height:65px;
color:#FFF;
padding:0 5px;
}
``` | Are you looking to accomplish something like this?
You can absolutely position the `<ul>` in the middle of the screen using `top: 50%;` as long as you set the `margin-top` to negative half the height of the `<ul>`. For instance, if the `<ul>` height is `100px`, you'll need to set the `margin-top: -50px;` along with `top: 50%; position: absolute;` in order to perfectly vertically center the `<ul>` in the center of the screen.
If you do not know the height of the `<ul>` beforehand, I added some jQuery that will determine the height and adjust the margin-top accordingly. You can change the height of the `<div>` container on the jsFiddle to see that the `<ul>` will be centered vertically regardless of the container's height.
<http://jsfiddle.net/kreCe/1/> |
13,368,452 | I want to set an unsorted list as a "background". To do that, I have assigned it to be very wide so it matches whatever screen opens the page including 2560px width. But I can't make it center completely with CSS unless there is a trick or something. I am willing to go jquery way. Technically the ul will have the same effect as background-position:top center;
Instead of a code I attach an image with the way it should work (added code)
```
<div style="background-color:black; width:100%; overflow:hidden; height:302px; text-align:center; position:relative">
<ul style="padding:0px; margin:0px; text-align:center; width:2560px; height:100%; margin:0 auto 0; position:relative;">
<li class="image"></li><li class="image"></li><li class="image"></li><li class="image"></li><li class="image"></li><li class="image">
</ul>
</div>
```
i used inline css so its clearer what im trying to do.

any help appreciated | 2012/11/13 | [
"https://Stackoverflow.com/questions/13368452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004105/"
] | Is [this fiddle](http://jsfiddle.net/wpnFZ/) what you want? I think you didn't explain correctly when you said "background"
CSS
```
ul{
list-style-type: none;
margin: 0;
position: relative;
text-align: center;
width: 100%;
background:#FF0000;
}
ul li {
display: inline-block;
height: 65px;
overflow: hidden;
padding: 0;
background:#0000FF;
line-height:65px;
color:#FFF;
padding:0 5px;
}
``` | Just for FYI, the solution lies on display:block-inline. :) thanks for all your help |
13,368,452 | I want to set an unsorted list as a "background". To do that, I have assigned it to be very wide so it matches whatever screen opens the page including 2560px width. But I can't make it center completely with CSS unless there is a trick or something. I am willing to go jquery way. Technically the ul will have the same effect as background-position:top center;
Instead of a code I attach an image with the way it should work (added code)
```
<div style="background-color:black; width:100%; overflow:hidden; height:302px; text-align:center; position:relative">
<ul style="padding:0px; margin:0px; text-align:center; width:2560px; height:100%; margin:0 auto 0; position:relative;">
<li class="image"></li><li class="image"></li><li class="image"></li><li class="image"></li><li class="image"></li><li class="image">
</ul>
</div>
```
i used inline css so its clearer what im trying to do.

any help appreciated | 2012/11/13 | [
"https://Stackoverflow.com/questions/13368452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004105/"
] | Are you looking to accomplish something like this?
You can absolutely position the `<ul>` in the middle of the screen using `top: 50%;` as long as you set the `margin-top` to negative half the height of the `<ul>`. For instance, if the `<ul>` height is `100px`, you'll need to set the `margin-top: -50px;` along with `top: 50%; position: absolute;` in order to perfectly vertically center the `<ul>` in the center of the screen.
If you do not know the height of the `<ul>` beforehand, I added some jQuery that will determine the height and adjust the margin-top accordingly. You can change the height of the `<div>` container on the jsFiddle to see that the `<ul>` will be centered vertically regardless of the container's height.
<http://jsfiddle.net/kreCe/1/> | Just for FYI, the solution lies on display:block-inline. :) thanks for all your help |
7,808,035 | I'm trying to get the inverse of the number thats POSTED from a form.
```
<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>
```
In the php file which gets the value, say "1/2",
```
$my_inverse=1/($_POST[inverse_num]); // returns 1 , but..
$my_inverse=1/(1/2); // returns 2, which is required.
```
Why does this happen..coz logically I'm posting the same value. Please suggest. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7808035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996944/"
] | * You can only post text from a form.
* PHP doesn't care if a variable contains a string or a number, it will convert between them.
* **PHP won't resolve text that looks like equations.**
You could do something along the lines of:
```
function simple_fractions ($value) {
if (is_numeric($value)) {
return $value;
}
preg_match('/^(\d+)\/(\d+)$/', $value, $matches);
if ($matches[1] && $matches[2]) {
return $matches[0] / $matches[1];
}
if ($matches[1] == 0) {
return 0;
}
return false;
}
``` | Your two expressions:
```
$my_inverse=1/($_POST[inverse_num]); // array keys shall be quoted
$my_inverse=1/(1/2);
```
Are actually:
```
$my_inverse=1/"1/2";
$my_inverse=1/(1/2);
```
Which does explain the outcome.
If you were to send the string `0.5` instead, then PHP would process it as expected, btw. |
7,808,035 | I'm trying to get the inverse of the number thats POSTED from a form.
```
<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>
```
In the php file which gets the value, say "1/2",
```
$my_inverse=1/($_POST[inverse_num]); // returns 1 , but..
$my_inverse=1/(1/2); // returns 2, which is required.
```
Why does this happen..coz logically I'm posting the same value. Please suggest. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7808035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996944/"
] | * You can only post text from a form.
* PHP doesn't care if a variable contains a string or a number, it will convert between them.
* **PHP won't resolve text that looks like equations.**
You could do something along the lines of:
```
function simple_fractions ($value) {
if (is_numeric($value)) {
return $value;
}
preg_match('/^(\d+)\/(\d+)$/', $value, $matches);
if ($matches[1] && $matches[2]) {
return $matches[0] / $matches[1];
}
if ($matches[1] == 0) {
return 0;
}
return false;
}
``` | What about posting decimals instead of fractions?
e.g. 0.5 |
7,808,035 | I'm trying to get the inverse of the number thats POSTED from a form.
```
<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>
```
In the php file which gets the value, say "1/2",
```
$my_inverse=1/($_POST[inverse_num]); // returns 1 , but..
$my_inverse=1/(1/2); // returns 2, which is required.
```
Why does this happen..coz logically I'm posting the same value. Please suggest. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7808035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996944/"
] | * You can only post text from a form.
* PHP doesn't care if a variable contains a string or a number, it will convert between them.
* **PHP won't resolve text that looks like equations.**
You could do something along the lines of:
```
function simple_fractions ($value) {
if (is_numeric($value)) {
return $value;
}
preg_match('/^(\d+)\/(\d+)$/', $value, $matches);
if ($matches[1] && $matches[2]) {
return $matches[0] / $matches[1];
}
if ($matches[1] == 0) {
return 0;
}
return false;
}
``` | Quentin has a possible solution.
However, another one is even better in my opinion:
```
<select name="inverse_num">
<option value="a">2 </option>
<option value="b">1 </option>
<option value="c">1/2 </option>
<option value="d">1/3 </option>
</select>
```
Then in your submission script:
```
if($_POST['inverse_num'] == 'a'){
$value = 2;
}elseif($_POST['inverse_num'] == 'b'){
$value = 1;
}elseif($_POST['inverse_num'] == 'c'){
$value = 1/2;
}elseif($_POST['inverse_num'] == 'd'){
$value = 1/3;
}
```
Etc....
Nothing complex about this method. |
7,808,035 | I'm trying to get the inverse of the number thats POSTED from a form.
```
<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>
```
In the php file which gets the value, say "1/2",
```
$my_inverse=1/($_POST[inverse_num]); // returns 1 , but..
$my_inverse=1/(1/2); // returns 2, which is required.
```
Why does this happen..coz logically I'm posting the same value. Please suggest. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7808035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996944/"
] | Your two expressions:
```
$my_inverse=1/($_POST[inverse_num]); // array keys shall be quoted
$my_inverse=1/(1/2);
```
Are actually:
```
$my_inverse=1/"1/2";
$my_inverse=1/(1/2);
```
Which does explain the outcome.
If you were to send the string `0.5` instead, then PHP would process it as expected, btw. | What about posting decimals instead of fractions?
e.g. 0.5 |
7,808,035 | I'm trying to get the inverse of the number thats POSTED from a form.
```
<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>
```
In the php file which gets the value, say "1/2",
```
$my_inverse=1/($_POST[inverse_num]); // returns 1 , but..
$my_inverse=1/(1/2); // returns 2, which is required.
```
Why does this happen..coz logically I'm posting the same value. Please suggest. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7808035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996944/"
] | Your two expressions:
```
$my_inverse=1/($_POST[inverse_num]); // array keys shall be quoted
$my_inverse=1/(1/2);
```
Are actually:
```
$my_inverse=1/"1/2";
$my_inverse=1/(1/2);
```
Which does explain the outcome.
If you were to send the string `0.5` instead, then PHP would process it as expected, btw. | Quentin has a possible solution.
However, another one is even better in my opinion:
```
<select name="inverse_num">
<option value="a">2 </option>
<option value="b">1 </option>
<option value="c">1/2 </option>
<option value="d">1/3 </option>
</select>
```
Then in your submission script:
```
if($_POST['inverse_num'] == 'a'){
$value = 2;
}elseif($_POST['inverse_num'] == 'b'){
$value = 1;
}elseif($_POST['inverse_num'] == 'c'){
$value = 1/2;
}elseif($_POST['inverse_num'] == 'd'){
$value = 1/3;
}
```
Etc....
Nothing complex about this method. |
7,808,035 | I'm trying to get the inverse of the number thats POSTED from a form.
```
<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>
```
In the php file which gets the value, say "1/2",
```
$my_inverse=1/($_POST[inverse_num]); // returns 1 , but..
$my_inverse=1/(1/2); // returns 2, which is required.
```
Why does this happen..coz logically I'm posting the same value. Please suggest. | 2011/10/18 | [
"https://Stackoverflow.com/questions/7808035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/996944/"
] | Quentin has a possible solution.
However, another one is even better in my opinion:
```
<select name="inverse_num">
<option value="a">2 </option>
<option value="b">1 </option>
<option value="c">1/2 </option>
<option value="d">1/3 </option>
</select>
```
Then in your submission script:
```
if($_POST['inverse_num'] == 'a'){
$value = 2;
}elseif($_POST['inverse_num'] == 'b'){
$value = 1;
}elseif($_POST['inverse_num'] == 'c'){
$value = 1/2;
}elseif($_POST['inverse_num'] == 'd'){
$value = 1/3;
}
```
Etc....
Nothing complex about this method. | What about posting decimals instead of fractions?
e.g. 0.5 |
47,242,861 | I have `ul` , i want to know number of any of these list items(For example: Tomatoe's number is 3).
```
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
```
How can i do this?
UPD Also I am using vue js and v-for for list rendering.
UPD2 What i really want it is a get array of numbers of active lists when i selected them.
I did this like that:
```
let selectedlist = document.getElementsByClassName('selected')
let list = document.getElementsByTagName('li')
this.indexOfSelectedLists = [] // array that i need
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < selectedlist.length; j++) { // because findIndex() isnt supported
list[i].innerHTML === selectedlist[j].innerHTML
? this.indexOfSelectedLists.push(i)
: null
}
}
```
[](https://i.stack.imgur.com/YY4FS.png) | 2017/11/11 | [
"https://Stackoverflow.com/questions/47242861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7804238/"
] | You can use `querySelectorAll()` to get the elements, and use `forEach()` to display the elements along with their indexes (numbers):
```
var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));
elements.forEach(function(li, index) {
console.log(li.innerText + " is number " + (index + 1));
});
```
**Demo:**
```js
var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));
elements.forEach(function(li, index) {
console.log(li.innerText + " is number " + (index + 1));
});
```
```html
<ul id="myList">
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
</ul>
``` | You can find the index of any element, please check the example.
```js
var findIndex = "Tomato";
$("ul li").each(function(index, item) {
if($(item).text() == findIndex){
console.log("Index of " + findIndex + " is: " + (index + 1));
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
</ul>
``` |
47,242,861 | I have `ul` , i want to know number of any of these list items(For example: Tomatoe's number is 3).
```
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
```
How can i do this?
UPD Also I am using vue js and v-for for list rendering.
UPD2 What i really want it is a get array of numbers of active lists when i selected them.
I did this like that:
```
let selectedlist = document.getElementsByClassName('selected')
let list = document.getElementsByTagName('li')
this.indexOfSelectedLists = [] // array that i need
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < selectedlist.length; j++) { // because findIndex() isnt supported
list[i].innerHTML === selectedlist[j].innerHTML
? this.indexOfSelectedLists.push(i)
: null
}
}
```
[](https://i.stack.imgur.com/YY4FS.png) | 2017/11/11 | [
"https://Stackoverflow.com/questions/47242861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7804238/"
] | You can use `querySelectorAll()` to get the elements, and use `forEach()` to display the elements along with their indexes (numbers):
```
var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));
elements.forEach(function(li, index) {
console.log(li.innerText + " is number " + (index + 1));
});
```
**Demo:**
```js
var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));
elements.forEach(function(li, index) {
console.log(li.innerText + " is number " + (index + 1));
});
```
```html
<ul id="myList">
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
</ul>
``` | In case you're trying to render the index in your `v-for` loop, you could use `v-for="(item, index) of items"` and then access `{{index}}`:
```js
new Vue({
el: '#app',
data() {
return {
items: [ 'Apple', 'Orange', 'Tomato', 'Potato' ],
}
}
})
```
```html
<script src="https://unpkg.com/vue@2.5.2"></script>
<div id="app">
<ul>
<li v-for="(item, index) of items">{{index}} - {{item}}</li>
</ul>
</div>
```
See [Vue's Guide for *List Rendering*](https://v2.vuejs.org/v2/guide/list.html) |
47,242,861 | I have `ul` , i want to know number of any of these list items(For example: Tomatoe's number is 3).
```
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
```
How can i do this?
UPD Also I am using vue js and v-for for list rendering.
UPD2 What i really want it is a get array of numbers of active lists when i selected them.
I did this like that:
```
let selectedlist = document.getElementsByClassName('selected')
let list = document.getElementsByTagName('li')
this.indexOfSelectedLists = [] // array that i need
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < selectedlist.length; j++) { // because findIndex() isnt supported
list[i].innerHTML === selectedlist[j].innerHTML
? this.indexOfSelectedLists.push(i)
: null
}
}
```
[](https://i.stack.imgur.com/YY4FS.png) | 2017/11/11 | [
"https://Stackoverflow.com/questions/47242861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7804238/"
] | You can use `querySelectorAll()` to get the elements, and use `forEach()` to display the elements along with their indexes (numbers):
```
var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));
elements.forEach(function(li, index) {
console.log(li.innerText + " is number " + (index + 1));
});
```
**Demo:**
```js
var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));
elements.forEach(function(li, index) {
console.log(li.innerText + " is number " + (index + 1));
});
```
```html
<ul id="myList">
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
</ul>
``` | No need any javascript code. [v-for](https://v2.vuejs.org/v2/guide/list.html) can handle what you want.
If you define your `v-for` like this: `<li v-for="(fruit, index) in fruits">`, `index` gives you the index number and you can print it out as `{{ index + 1 }}`
[an example](https://v2.vuejs.org/v2/guide/list.html#example-1) from the documentation website. |
47,242,861 | I have `ul` , i want to know number of any of these list items(For example: Tomatoe's number is 3).
```
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
```
How can i do this?
UPD Also I am using vue js and v-for for list rendering.
UPD2 What i really want it is a get array of numbers of active lists when i selected them.
I did this like that:
```
let selectedlist = document.getElementsByClassName('selected')
let list = document.getElementsByTagName('li')
this.indexOfSelectedLists = [] // array that i need
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < selectedlist.length; j++) { // because findIndex() isnt supported
list[i].innerHTML === selectedlist[j].innerHTML
? this.indexOfSelectedLists.push(i)
: null
}
}
```
[](https://i.stack.imgur.com/YY4FS.png) | 2017/11/11 | [
"https://Stackoverflow.com/questions/47242861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7804238/"
] | No need any javascript code. [v-for](https://v2.vuejs.org/v2/guide/list.html) can handle what you want.
If you define your `v-for` like this: `<li v-for="(fruit, index) in fruits">`, `index` gives you the index number and you can print it out as `{{ index + 1 }}`
[an example](https://v2.vuejs.org/v2/guide/list.html#example-1) from the documentation website. | You can find the index of any element, please check the example.
```js
var findIndex = "Tomato";
$("ul li").each(function(index, item) {
if($(item).text() == findIndex){
console.log("Index of " + findIndex + " is: " + (index + 1));
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
</ul>
``` |
47,242,861 | I have `ul` , i want to know number of any of these list items(For example: Tomatoe's number is 3).
```
<li>Apple</li>
<li>Orange</li>
<li>Tomato</li>
<li>Potato</li>
```
How can i do this?
UPD Also I am using vue js and v-for for list rendering.
UPD2 What i really want it is a get array of numbers of active lists when i selected them.
I did this like that:
```
let selectedlist = document.getElementsByClassName('selected')
let list = document.getElementsByTagName('li')
this.indexOfSelectedLists = [] // array that i need
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < selectedlist.length; j++) { // because findIndex() isnt supported
list[i].innerHTML === selectedlist[j].innerHTML
? this.indexOfSelectedLists.push(i)
: null
}
}
```
[](https://i.stack.imgur.com/YY4FS.png) | 2017/11/11 | [
"https://Stackoverflow.com/questions/47242861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7804238/"
] | No need any javascript code. [v-for](https://v2.vuejs.org/v2/guide/list.html) can handle what you want.
If you define your `v-for` like this: `<li v-for="(fruit, index) in fruits">`, `index` gives you the index number and you can print it out as `{{ index + 1 }}`
[an example](https://v2.vuejs.org/v2/guide/list.html#example-1) from the documentation website. | In case you're trying to render the index in your `v-for` loop, you could use `v-for="(item, index) of items"` and then access `{{index}}`:
```js
new Vue({
el: '#app',
data() {
return {
items: [ 'Apple', 'Orange', 'Tomato', 'Potato' ],
}
}
})
```
```html
<script src="https://unpkg.com/vue@2.5.2"></script>
<div id="app">
<ul>
<li v-for="(item, index) of items">{{index}} - {{item}}</li>
</ul>
</div>
```
See [Vue's Guide for *List Rendering*](https://v2.vuejs.org/v2/guide/list.html) |
12,389 | I live in Jacksonville, FL and my insurance premium went up by about $500/yr. I was told that the biggest reason was because my house isn't up to current code for hurricane/wind mitigation. I'm a fairly handy guy and was considering adding hurricane clips on my own. I will also need a new roof in the next few years and was considering a DIY job with a friend. I have a few questions.
1. Do I need a permit to install hurricane clips?
2. Would I be better off waiting until I do the new roof? My only concern here is that I don't want to rip up all the sheathing.
3. Do I need a licensed contractor on the new roof? I realize this probably varies by county.
4. Any other advice? | 2012/02/21 | [
"https://diy.stackexchange.com/questions/12389",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2933/"
] | You neeed a permit for the roofing, and the Florida Building Code also requires you to re-nail the decking to code. There are several other items you need to address. Sealed Roof Deck, Roof to Wall Connections, Porch Column tie-downs, Gable Overhangs, gable Sheathing, and if you have vinyl soffits and ceilings, these also need attention.
The Florida Building Code is a minimum life safety standard and does not fully address risks associatedd with windstorm damage. The code is designed to keep the structure together, mitigation is designed to reduce damage, out of pocket expense, the cost of insurance, and most importantly having a place to live after the event.
Go to [Insurance Institute for Business & Home Safety](http://www.disastersafety.org/main) and download the [FORTIFIED for Existing Homes Engineering Guide](http://www.disastersafety.org/content/data/file/IBHS_FOR-engineering-guide.pdf), this contains everything you will need to consider in a holistic approach. The Florida Wind Mitigation discounts are not a good measure of what you need to do to protect your property and family with a place to live.
"Don't goof when you Re-roof" retrofit it to Bronze and prepare the home for Silver. | It's best to do the clips at the time of the new roof. Also have the decking renailed and install a Secondary Water Resistance (SWR) barrier. You need a permit for the roof only. |
12,389 | I live in Jacksonville, FL and my insurance premium went up by about $500/yr. I was told that the biggest reason was because my house isn't up to current code for hurricane/wind mitigation. I'm a fairly handy guy and was considering adding hurricane clips on my own. I will also need a new roof in the next few years and was considering a DIY job with a friend. I have a few questions.
1. Do I need a permit to install hurricane clips?
2. Would I be better off waiting until I do the new roof? My only concern here is that I don't want to rip up all the sheathing.
3. Do I need a licensed contractor on the new roof? I realize this probably varies by county.
4. Any other advice? | 2012/02/21 | [
"https://diy.stackexchange.com/questions/12389",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/2933/"
] | Had a new roof put on and the roofer informed me that I already had hurricane clips. | It's best to do the clips at the time of the new roof. Also have the decking renailed and install a Secondary Water Resistance (SWR) barrier. You need a permit for the roof only. |
2,587,284 | How would I be able to use the Drupal Fivestar voting module for voting on photos in a gallery without each photo being a separate node. I've used the Fivestar module for voting on seperate nodes, but making each photo in a gallery a node doeasn't seem logical. | 2010/04/06 | [
"https://Stackoverflow.com/questions/2587284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183361/"
] | I'm afraid that there is no special exception for that. You will have to catch ADO NET exceptions and look on the inner exception text.
IMHO your approach is not the more appropriate. You should query the DB in order to check BEFORE the insert if the data will violate the unique constraint. If it does, then you don't insert the record. | You need to implement `ISQLExceptionConverter`.
Check [Custom exception using NHibernate ISqlExceptionConverter](https://stackoverflow.com/questions/1524167/custom-exception-using-nhibernate-isqlexceptionconverter) and <http://fabiomaulo.blogspot.com/2009/06/improving-ado-exception-management-in.html> for examples. |
25,830 | I've just started learning assembly yesterday, and the first useful thing I've written is a `clearmem` function.
I'm looking for general feedback regarding my coding of this function, whether there any flaws with it other than the obvious one of a user passing a value <= 0 to the `size` argument, or an invalid pointer to the `ptr` argument (should I really even check for that in practical use)?
I also observed an odd behavior that I still don't quite understand, so if you can explain that, then that would be much appreciated as well.
**Intel x64 Assembly - on Linux**
```none
clearmem: ; void clearmem( void* ptr, long size )
mov rcx, rsi ; copy rsi/size to rcx (aka the counter register)
next: ; for( long i = size; i > 0; i-- )
mov byte [rdi+rcx-1], 0 ; *(reinterpret_cast<char*>(ptr+i-1)) = 0;
loop next ; dec rcx; cmp rcx, 0; jg next
ret ; return
```
**Intel x64 Assembly - on Windows**
```none
clearmem proc
xchg rcx, rdx ; swap arg1 and arg2... windows uses rcx for arg1, and rdx for arg2
next:
mov byte ptr[rdx+rcx-1], 0
loop next
ret
clearmem endp
```
**Example usage in C++**
```
#include <iostream>
// ...
extern "C" void clearmem( void* ptr, long size );
// ...
int main( int argc, char* argv[] )
{
int z[] = {1,2,3,4,5,6,7,8,9,10};
int zlen = sizeof(z) / sizeof(int);
std::cout << "z[] before clearmem() = ";
print_array<int>(z, zlen);
clearmem(&z, sizeof(z));
std::cout << "z[] after clearmem() = ";
print_array<int>(z, zlen);
return 0;
}
```
**Output of C++ program**
```
z[] before clearmem() = 1,2,3,4,5,6,7,8,9,10
z[] after clearmem() = 0,0,0,0,0,0,0,0,0,0
```
**Odd Behavior**
If I change all of the registers and variables to their 4 byte equivalent (e.g. `rcx` -> `ecx`, `long` -> `int`) then it still works fine in Windows, but on Linux it will segfault. I used GDB to set a break point on `mov byte[rdi+rcx-1], 0` and used `info registers` to see the values in the registers and they were extrmely high. For instance `rdi` was 0x00007FFFFFFFE6E0 at the time, and considering I only have 16 GB of RAM, I would have expected a value less than 0x0000000400000000.
What's going on here? Why does this work on Windows, but not on Linux? Note: Obviously, I know I shouldn't do this, but I like breaking things... | 2013/05/05 | [
"https://codereview.stackexchange.com/questions/25830",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/12437/"
] | I can't say I particularly like this code as it is right now. It seems to me that there are two reasonable approaches: if you think most of what you zero will be in main memory, then you probably just want the most compact code possible for the job. If you think it'll be used to zero data that might be in the cache a noticeable amount of the time, then you want to optimize for speed.
For the former case, I'd probably do something like:
```
mov rcx, rsi
xor rax, rax
rep stosd
```
Recent Intel (and, I believe, AMD) CPUs seem to have a special execution path that lets this run *just* about as fast as anything--if any more than a minuscule percentage of your data may be in main memory, it becomes difficult to measure the difference between this and the fastest code possible.
If you really do want the fastest code possible, then you probably want to avoid complex instructions like `loop`, which is known to be sub-optimal on recent processors (anything since the Pentium Pro, really). For this, you want to use simple instructions for the loop:
```
dec rcx
test rcx, rcx
jnz loop_top
```
Although the `cmp rcx, 0` that you suggest in the comment will work, embedding the immediate value in the instruction makes it somewhat larger and (depending on CPU) somewhat slower to fetch. The `test` accomplishes the same goal (sets/clears Z-flag appropriately) without an immediate value. In this case, you probably want to zero an xmm register, then start with a (possible) `maskmovdqu` to fill in a partial word, in case the data is mis-aligned. Then do the main body of the loop using `movdqa`. Then have another (again, optional) `maskmovdqu` at the end to copy an partial-word tail that might be needed.
If you're writing for an Intel processor (but *not* AMD) it's also worth considering a move to using AVX instructions instead. The current AVX instructions operate on 256-bit operands, and Intel has announced an AVX-512 instruction set that will (obviously enough) operate on 512-bit operands. For operands in main memory, you'll be limited by memory bandwidth either way, but if the data is in cache, this should give a substantial speedup. As far as AMD goes: they do have processors that can execute the current AVX instruction set, but it seems to be poorly enough tuned that performance gains from using it are minimal (at best). Then again, I haven't tried to test using them specifically for zeroing data--for such a simple task, it's possible it'll do better (but from what I recall, loads and stores seem like the bottleneck). | * The comments in the `clearmem` procedure for the Linux block look a bit confusing. You could just have a summary of the procedure commented above, and have the individual comments for each line specify the meaning of the assembly instructions.
Specifically, the lines that describe the C++ code don't quite reflect on the assembly code. `clearmem` itself doesn't take two arguments. The `for` loop comment statement doesn't seem needed, and it may be clearer to specify when the loop should exit. You also don't need the obvious comment for `ret`.
* Since it appears the `extern "C"` corresponds to `clearmem`, I assume everything else can fully utilize C++. If so, I'd use `std::vector` in place of the C-style arrays. However, since `clearmem` performs pointer arithmetic, you should use [`std::vector::data()`](http://en.cppreference.com/w/cpp/container/vector/data) to pass in the underlying dynamic array.
You can then call `size()` for the vector object in `main()` instead of using `sizeof`. This function returns an `std::size_type`, specifically `std::vector<int>::size_type`.
* I'm not sure how `print_array()` is implemented, but I assume it just uses a `for` loop to print the array elements. You might also not need the `template` argument, and with just a vector, you'll have just one argument. In the function's loop, you should then use `const_iterator`s for displaying the elements, although using indices is okay (but iterators are still preferred).
* `clearmem` should take `size_t` instead of `long`; the former is the same type returned by the `sizeof` operator. |
28,339,327 | I was fixing some non-working css style and found that non-breaking space (\u00A0) is not allowed in the css declarations and having it breaks parsing.
It breaks reliably in all browsers, so it seems that such behavior is expected. Does anybody know why it is so?
[Fiddle here](http://jsfiddle.net/tma6ya51/) Text should be red but it is not, removing non breaking space fixes it.
```js
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".text\u00A0{ color: red}";
document.head.appendChild(css);
```
```html
<span class="text">red?</span>
``` | 2015/02/05 | [
"https://Stackoverflow.com/questions/28339327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4531980/"
] | In CSS, U+00A0 NO-BREAK SPACE is not whitespace. Only ASCII spaces, tabs, line breaks and form feeds count as whitespace. From the [spec](http://www.w3.org/TR/CSS21/syndata.html):
>
> Only the characters "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form feed" (U+000C) can occur in white space. Other space-like characters, such as "em-space" (U+2003) and "ideographic space" (U+3000), are never part of white space.
>
>
>
U+00A0 is not mentioned here, but since it is not one of the allowed characters, it's implied to be disallowed.
Since it's not being treated as whitespace, it has to be treated as part of the selector. From [section 4.1.3 of the same document](http://www.w3.org/TR/CSS21/syndata.html#characters) (which *does* mention the code-point U+00A0, although by sheer coincidence):
>
> In CSS, *identifiers* (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (\_)
>
>
>
The selector essentially becomes one that looks for an element with `class="text "`, where the non-breaking space is part of the class name:
```js
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".text\u00A0{ color: red}";
document.head.appendChild(css);
```
```html
<span class="text">red?</span>
<span class="text ">red!</span>
``` | That's because a non breaking space is a character like any other character. It *happens* to look like a space, but it's no different from "a" or "4" or "♥".
```js
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".text\u00A0{ color: red}";
document.head.appendChild(css);
```
```html
<span class="text ">red?</span>
```
As you can see, by adding a non-breaking space to the class name, your example works. |
70,114,392 | I have an input field with type number, my issue is when using Firefox and safari with Arabic keyboard the number are written ٨٦٥ like that, how can I convert this format to 8754 (English format) while the user typing in the filed? Or i prevent it from typing non English format. | 2021/11/25 | [
"https://Stackoverflow.com/questions/70114392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10659300/"
] | The following function will change the field key pressed value of the numbers 0123456789 to the Arabic-Eastern form "٠١٢٣٤٥٦٧٨٩".
if you type 1 it will show ١,
if you type 2 it will show ٢, and so on.
It will not affect the other characters.
It can be improved.
```js
document.getElementById('myTextFieldId').addEventListener("keypress", function(e){
let code=e.keyCode-48;
if (code>=0 && code<10) {
e.target.value = e.target.value.slice(0,e.target.selectionStart)
+ "٠١٢٣٤٥٦٧٨٩"[code]
+ e.target.value.slice(e.target.selectionEnd);
e.target.selectionStart = e.target.selectionEnd = e.target.selectionStart + 1;
e.preventDefault();
}
})
```
```html
<input type="text" id="myTextFieldId" />
``` | you can try this:
```
function arabicToLatinNumbers(arabicNumber){
let result = "";
const arabic1 = '١'.charCodeAt(0);
const english1 = '1'.charCodeAt(0);
for(i = 0; i < arabicNumber.length; i++){
result += String.fromCharCode(arabicNumber.charCodeAt(i) - arabic1 +
english1);
}
return result;
}
const result = arabicToLatinNumbers('٣٤');
console.log(result);//prints 34
``` |
50,993,705 | We have a legacy Delphi 7 application that launches the Windows Defrag and On-screen Keyboard applications as follows:
```
// Defragmentation application
ShellExecute(0, 'open', PChar('C:\Windows\System32\dfrg.msc'), nil, nil, SW_SHOWNORMAL);
// On-screen keyboard
ShellExecute(0, 'open', PChar('C:\Windows\System32\osk.exe'), nil, nil, SW_SHOWNORMAL);
```
Both work on Windows XP but fail on Windows 10. I spotted that the defragmentation application has had a name change to `dfrgui.exe`, but updating the code does not help. The On-screen Keyboard is still called `osk.exe` on Windows 10.
Both applications can be launched manually / directly from the command line or by double-clicking them in Windows Explorer.
My suspicion is that Windows security is preventing my application from launching anything from `C:\Windows\System32`, because I can launch several other applications from `Program Files` and from `C:\Windows`.
Can anyone help? | 2018/06/22 | [
"https://Stackoverflow.com/questions/50993705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2377399/"
] | Delphi 7 produces only 32-bit apps, there is no option to produce 64-bit apps (that was added in XE2).
Accessing a path under `%WINDIR%\System32` from a 32-bit app running on a 64-bit system is subject to WOW64's [File
System Redirector](https://msdn.microsoft.com/en-us/library/windows/desktop/aa384187.aspx), which will silently redirect requests for the 64-bit `System32` folder to the 32-bit `SysWOW64` folder instead.
Chances are, the apps you are trying to run only exist in the 64-bit `System32` folder and not in the 32-bit `SysWOW64` folder.
To avoid redirection, you need to either:
* replace `System32` with the special `Sysnative` alias in your paths (ie `'C:\Windows\Sysnative\osk.exe'`), which only works when running under WOW64, so you have to detect that dynamically at runtime via [`IsWow64Process()`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684139.aspx):
```
function GetSystem32Folder: string;
var
Folder: array[0..MAX_PATH] of Char;
IsWow64: BOOL;
begin
Result := '';
if IsWow64Process(GetCurrentProcess(), @IsWow64) and IsWow64 then
begin
SetString(Result, Folder, GetWindowsDirectory(Folder, Length(Folder)));
if Result <> '' then
Result := IncludeTrailingPathDelimiter(Result) + 'Sysnative' + PathDelim;
end else
begin
SetString(Result, Folder, GetSystemDirectory(Folder, Length(Folder)));
if Result <> '' then
Result := IncludeTrailingPathDelimiter(Result);
end;
end;
function RunDefrag: Boolean;
var
SysFolder: string;
Res: Integer;
begin
SysFolder := GetSystem32Folder;
Res := Integer(ShellExecute(0, nil, PChar(SysFolder + 'dfrgui.exe'), nil, nil, SW_SHOWNORMAL));
if Res = ERROR_FILE_NOT_FOUND then
Res := Integer(ShellExecute(0, nil, PChar(SysFolder + 'dfrg.msc'), nil, nil, SW_SHOWNORMAL));
Result := (Res = 0);
end;
function RunOnScreenKeyboard: Boolean;
begin
Result := (ShellExecute(0, nil, PChar(GetSystem32Folder + 'osk.exe'), nil, nil, SW_SHOWNORMAL) = 0);
end;
```
* temporarily disable the Redirector via [`Wow64DisableWow64FsRedirection()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365743.aspx), and then re-enable it via [`Wow64RevertWow64FsRedirection()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365745.aspx) when done:
```
function GetSystem32Folder: string
var
Folder: array[0..MAX_PATH] of Char;
begin
SetString(Result, Folder, GetSystemDirectory(Folder, Length(Folder)));
if Result <> '' then
Result := IncludeTrailingPathDelimiter(Result);
end;
function RunDefrag: Boolean;
var
SysFolder: string;
OldState: Pointer;
Res: Integer;
begin
Wow64DisableWow64FsRedirection(@OldState);
try
SysFolder := GetSystem32Folder;
Res := Integer(ShellExecute(0, nil, PChar(SysFolder + 'dfrgui.exe'), nil, nil, SW_SHOWNORMAL));
if Res = ERROR_FILE_NOT_FOUND then
Res := Integer(ShellExecute(0, nil, PChar(SysFolder + 'dfrg.msc'), nil, nil, SW_SHOWNORMAL));
Result := Res = 0;
finally
Wow64RevertWow64FsRedirection(OldState);
end;
end;
function RunOnScreenKeyboard: Boolean;
var
OldState: Pointer;
begin
Wow64DisableWow64FsRedirection(@OldState);
try
Result := (ShellExecute(0, nil, PChar(GetSystem32Folder + 'osk.exe'), nil, nil, SW_SHOWNORMAL) = 0);
finally
Wow64RevertWow64FsRedirection(OldState);
end;
end;
```
**Update**: that being said, it turns out that a 32-bit process running under WOW64 is not allowed to run `osk.exe` when UAC is enabled:
[Delphi - On Screen Keyboard (osk.exe) works on Win32 but fails on Win64](https://stackoverflow.com/questions/23116149/)
So, you will have to create a helper 64-bit process to launch `osk.exe` on your app's behalf when it is running under WOW64. | A small addition to Remy Lebeau's answer:
If `Wow64DisableWow64FsRedirection` is not available in your Delphi version, and/or if you are not sure if your target platform will support this API, you could use following code sample that calls the function dynamically:
<https://www.delphipraxis.net/155861-windows-7-64bit-redirection.html>
```
function ChangeFSRedirection(bDisable: Boolean): Boolean;
type
TWow64DisableWow64FsRedirection = Function(Var Wow64FsEnableRedirection: LongBool): LongBool; StdCall;
TWow64EnableWow64FsRedirection = Function(var Wow64FsEnableRedirection: LongBool): LongBool; StdCall;
var
hHandle: THandle;
Wow64DisableWow64FsRedirection: TWow64DisableWow64FsRedirection;
Wow64EnableWow64FsRedirection: TWow64EnableWow64FsRedirection;
Wow64FsEnableRedirection: LongBool;
begin
Result := false;
try
hHandle := GetModuleHandle('kernel32.dll');
@Wow64EnableWow64FsRedirection := GetProcAddress(hHandle, 'Wow64EnableWow64FsRedirection');
@Wow64DisableWow64FsRedirection := GetProcAddress(hHandle, 'Wow64DisableWow64FsRedirection');
if bDisable then
begin
if (hHandle <> 0) and (@Wow64DisableWow64FsRedirection <> nil) then
begin
Result := Wow64DisableWow64FsRedirection(Wow64FsEnableRedirection);
end;
end else
begin
if (hHandle <> 0) and (@Wow64EnableWow64FsRedirection <> nil) then
begin
Result := Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection);
Result := True;
end;
end;
Except
end;
end;
``` |
20,243 | How do I remove an event from My Events? I can't find the old "Remove This Event" link anymore.
 | 2011/10/31 | [
"https://webapps.stackexchange.com/questions/20243",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/8269/"
] | **To remove yourself from the guest list (as opposed to simply declining).**
1. Decline the event.
2. Go to the event page.
3. Bring up the guest list. (Click on "Going" "Maybe" or "Invited")
4. Switch the view to **Declined** using the drop-down.
5. Find your name.
6. Hover over your name and notice the X to the right of it. Click that X and it will ask you if you want to remove the event.
*This might not work with private events*
NOTE: If you have not responded/RSVP'd to the event, simply click on the event. Do not RSVP. Your name will appear as one of the first names on the left, which will make it easier to remove instead of going through the Declined dropdown. | Facebook used to have a "Remove from my events" link at the sidebar of an event page. Now, you just say "Not attending" and it is removed from your list. |
20,243 | How do I remove an event from My Events? I can't find the old "Remove This Event" link anymore.
 | 2011/10/31 | [
"https://webapps.stackexchange.com/questions/20243",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/8269/"
] | **To remove yourself from the guest list (as opposed to simply declining).**
1. Decline the event.
2. Go to the event page.
3. Bring up the guest list. (Click on "Going" "Maybe" or "Invited")
4. Switch the view to **Declined** using the drop-down.
5. Find your name.
6. Hover over your name and notice the X to the right of it. Click that X and it will ask you if you want to remove the event.
*This might not work with private events*
NOTE: If you have not responded/RSVP'd to the event, simply click on the event. Do not RSVP. Your name will appear as one of the first names on the left, which will make it easier to remove instead of going through the Declined dropdown. | Just discovered how to do it after coming here for help.
Just go to the event and look for your name under "Invited"—there is the little `X` you can use to remove it from your events. You don't have to do all the declining, etc. first. This means you don't appear as *Declined* on the event, and don't receive all the notifications when, say, someone writes on its Wall.
Just another example of FB leaving in the same functionality but changing how you access it.
Hope this helps. |
17,727,142 | I have this error in a Component in Joomla
That's my code (the error is in line 263):
```
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/manual/en/book.mysqli.php
* @since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* @var string
* @since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = @mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET @@SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* @since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* @return JDatabaseExporterMySQLi An exporter object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* @return JDatabaseImporterMySQLi An importer object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* @param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* @return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* @return boolean True if supported.
*
* @since 11.1
* @deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*
* @since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 11.1
* @throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 11.1
* @throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* @param boolean $abortOnError Abort on error.
* @param boolean $transactionSafe Transaction safe queries.
*
* @return mixed A database resource if successful, false if not.
*
* @deprecated 12.1
* @since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
``` | 2013/07/18 | [
"https://Stackoverflow.com/questions/17727142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596095/"
] | Function names must be unique in MATLAB. If they are not, so there are duplicate names, then MATLAB uses the first one it finds on your search path.
Having said that, there are a few options open to you.
Option 1. Use @ directories, putting each version in a separate directory. Essentially you are using the ability of MATLAB to apply a function to specific classes. So, you might set up a pair of directories:
```
@char
@double
```
Put your copies of myfun.m in the respective directories. Now when MATLAB sees a double input to myfun, it will direct the call to the double version. When MATLAB gets char input, it goes to the char version.
BE CAREFUL. Do not put these @ directories explicitly on your search path. DO put them INSIDE a directory that is on your search path.
A problem with this scheme is if you call the function with a SINGLE precision input, MATLAB will probably have a fit, so you would need separate versions for single, uint8, int8, int32, etc. You cannot just have one version for all numeric types.
Option 2. Have only one version of the function, that tests the first argument to see if it is numeric or char, then branches to perform either task as appropriate. Both pieces of code will most simply be in one file then. The simple scheme will have subfunctions or nested functions to do the work.
Option 3. Name the functions differently. Hey, its not the end of the world.
Option 4: As Shaun points out, one can simply change the current directory. MATLAB always looks first in your current directory, so it will find the function in that directory as needed. One problem is this is time consuming. Any time you touch a directory, things slow down, because there is now disk input needed.
The worst part of changing directories is in how you use MATLAB. It is (IMHO) a poor programming style to force the user to always be in a specific directory based on what code inputs they wish to run. Better is a data driven scheme. If you will be reading in or writing out data, then be in THAT directory. Use the MATLAB search path to categorize all of your functions, as functions tend not to change much. This is a far cleaner way to work than requiring the user to migrate to specific directories based on how they will be calling a given function.
Personally, I'd tend to suggest option 2 as the best. It is clean. It has only ONE main function that you need to work with. If you want to keep the functions district, put them as separate nested or sub functions inside the main function body. Inside of course, they will have distinct names, based on how they are driven. | EDIT: Old answer no longer good
The run command won't work because its a function, not a script.
Instead, your best approach would be honestly just figure out which of the functions need to be run, get the current dir, change it to the one your function is in, run it, and then change back to your start dir.
This approach, while not perfect, seems MUCH easier to code, to read, and less prone to breaking. And it requires no changing of names or creating extra files or function handles. |
17,727,142 | I have this error in a Component in Joomla
That's my code (the error is in line 263):
```
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/manual/en/book.mysqli.php
* @since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* @var string
* @since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = @mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET @@SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* @since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* @return JDatabaseExporterMySQLi An exporter object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* @return JDatabaseImporterMySQLi An importer object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* @param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* @return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* @return boolean True if supported.
*
* @since 11.1
* @deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*
* @since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 11.1
* @throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 11.1
* @throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* @param boolean $abortOnError Abort on error.
* @param boolean $transactionSafe Transaction safe queries.
*
* @return mixed A database resource if successful, false if not.
*
* @deprecated 12.1
* @since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
``` | 2013/07/18 | [
"https://Stackoverflow.com/questions/17727142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596095/"
] | Function names must be unique in MATLAB. If they are not, so there are duplicate names, then MATLAB uses the first one it finds on your search path.
Having said that, there are a few options open to you.
Option 1. Use @ directories, putting each version in a separate directory. Essentially you are using the ability of MATLAB to apply a function to specific classes. So, you might set up a pair of directories:
```
@char
@double
```
Put your copies of myfun.m in the respective directories. Now when MATLAB sees a double input to myfun, it will direct the call to the double version. When MATLAB gets char input, it goes to the char version.
BE CAREFUL. Do not put these @ directories explicitly on your search path. DO put them INSIDE a directory that is on your search path.
A problem with this scheme is if you call the function with a SINGLE precision input, MATLAB will probably have a fit, so you would need separate versions for single, uint8, int8, int32, etc. You cannot just have one version for all numeric types.
Option 2. Have only one version of the function, that tests the first argument to see if it is numeric or char, then branches to perform either task as appropriate. Both pieces of code will most simply be in one file then. The simple scheme will have subfunctions or nested functions to do the work.
Option 3. Name the functions differently. Hey, its not the end of the world.
Option 4: As Shaun points out, one can simply change the current directory. MATLAB always looks first in your current directory, so it will find the function in that directory as needed. One problem is this is time consuming. Any time you touch a directory, things slow down, because there is now disk input needed.
The worst part of changing directories is in how you use MATLAB. It is (IMHO) a poor programming style to force the user to always be in a specific directory based on what code inputs they wish to run. Better is a data driven scheme. If you will be reading in or writing out data, then be in THAT directory. Use the MATLAB search path to categorize all of your functions, as functions tend not to change much. This is a far cleaner way to work than requiring the user to migrate to specific directories based on how they will be calling a given function.
Personally, I'd tend to suggest option 2 as the best. It is clean. It has only ONE main function that you need to work with. If you want to keep the functions district, put them as separate nested or sub functions inside the main function body. Inside of course, they will have distinct names, based on how they are driven. | OK, so a messy answer, but it should do it. My test function was 'echo'
```
funcstr='echo'; % string representation of function
Fs=which('-all',funcstr);
for v=1:length(Fs)
if (strcmp(Fs{v}(end-1:end),'.m')) % Don''t move built-ins, they will be shadowed anyway
movefile(Fs{v},[Fs{v} '_BK']);
end
end
for v=1:length(Fs)
if (strcmp(Fs{v}(end-1:end),'.m'))
movefile([Fs{v} '_BK'],Fs{v});
end
try
eval([funcstr '(''stringArg'')']);
break;
catch
if (strcmp(Fs{v}(end-1:end),'.m'))
movefile(Fs{v},[Fs{v} '_BK']);
end
end
end
for w=1:v
if (strcmp(Fs{v}(end-1:end),'.m'))
movefile([Fs{v} '_BK'],Fs{v});
end
end
``` |
17,727,142 | I have this error in a Component in Joomla
That's my code (the error is in line 263):
```
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/manual/en/book.mysqli.php
* @since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* @var string
* @since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = @mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET @@SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* @since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* @return JDatabaseExporterMySQLi An exporter object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* @return JDatabaseImporterMySQLi An importer object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* @param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* @return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* @return boolean True if supported.
*
* @since 11.1
* @deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*
* @since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 11.1
* @throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 11.1
* @throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* @param boolean $abortOnError Abort on error.
* @param boolean $transactionSafe Transaction safe queries.
*
* @return mixed A database resource if successful, false if not.
*
* @deprecated 12.1
* @since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
``` | 2013/07/18 | [
"https://Stackoverflow.com/questions/17727142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596095/"
] | Function names must be unique in MATLAB. If they are not, so there are duplicate names, then MATLAB uses the first one it finds on your search path.
Having said that, there are a few options open to you.
Option 1. Use @ directories, putting each version in a separate directory. Essentially you are using the ability of MATLAB to apply a function to specific classes. So, you might set up a pair of directories:
```
@char
@double
```
Put your copies of myfun.m in the respective directories. Now when MATLAB sees a double input to myfun, it will direct the call to the double version. When MATLAB gets char input, it goes to the char version.
BE CAREFUL. Do not put these @ directories explicitly on your search path. DO put them INSIDE a directory that is on your search path.
A problem with this scheme is if you call the function with a SINGLE precision input, MATLAB will probably have a fit, so you would need separate versions for single, uint8, int8, int32, etc. You cannot just have one version for all numeric types.
Option 2. Have only one version of the function, that tests the first argument to see if it is numeric or char, then branches to perform either task as appropriate. Both pieces of code will most simply be in one file then. The simple scheme will have subfunctions or nested functions to do the work.
Option 3. Name the functions differently. Hey, its not the end of the world.
Option 4: As Shaun points out, one can simply change the current directory. MATLAB always looks first in your current directory, so it will find the function in that directory as needed. One problem is this is time consuming. Any time you touch a directory, things slow down, because there is now disk input needed.
The worst part of changing directories is in how you use MATLAB. It is (IMHO) a poor programming style to force the user to always be in a specific directory based on what code inputs they wish to run. Better is a data driven scheme. If you will be reading in or writing out data, then be in THAT directory. Use the MATLAB search path to categorize all of your functions, as functions tend not to change much. This is a far cleaner way to work than requiring the user to migrate to specific directories based on how they will be calling a given function.
Personally, I'd tend to suggest option 2 as the best. It is clean. It has only ONE main function that you need to work with. If you want to keep the functions district, put them as separate nested or sub functions inside the main function body. Inside of course, they will have distinct names, based on how they are driven. | You can also create a function handle for the shadowed function. The problem is that the first function is higher on the matlab path, but you can circumvent that by (temporarily) changing the current directory.
Although it is not nice imo to change that current directory (actually I'd rather never change it while executing code), it will solve the problem quite easily; especially if you use it in the configuration part of your function with a persistent function handle:
```
function outputpars = myMainExecFunction(inputpars)
% configuration
persistent shadowfun;
if isempty(shadowfun)
funpath1 = 'C:\........\x\fun';
funpath2 = 'C:\........\y\fun'; % Shadowed
curcd = cd;
cd(funpath2);
shadowfun = @fun;
cd(curcd); % and go back to the original cd
end
outputpars{1} = shadowfun(inputpars); % will use the shadowed function
oupputpars{2} = fun(inputparts); % will use the function highest on the matlab path
end
```
This problem was also discussed [here](https://stackoverflow.com/q/11781634/1162609) as a possible solution to [this problem](https://stackoverflow.com/q/11779511/1162609).
I believe it actually is the only way to overload a builtin function outside the source directory of the overloading function (eg. you want to run your own `sum.m` in a directory other than where your `sum.m` is located.) |
17,727,142 | I have this error in a Component in Joomla
That's my code (the error is in line 263):
```
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/manual/en/book.mysqli.php
* @since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* @var string
* @since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = @mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET @@SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* @since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* @return JDatabaseExporterMySQLi An exporter object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* @return JDatabaseImporterMySQLi An importer object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* @param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* @return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* @return boolean True if supported.
*
* @since 11.1
* @deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*
* @since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 11.1
* @throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 11.1
* @throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* @param boolean $abortOnError Abort on error.
* @param boolean $transactionSafe Transaction safe queries.
*
* @return mixed A database resource if successful, false if not.
*
* @deprecated 12.1
* @since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
``` | 2013/07/18 | [
"https://Stackoverflow.com/questions/17727142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596095/"
] | OK, so a messy answer, but it should do it. My test function was 'echo'
```
funcstr='echo'; % string representation of function
Fs=which('-all',funcstr);
for v=1:length(Fs)
if (strcmp(Fs{v}(end-1:end),'.m')) % Don''t move built-ins, they will be shadowed anyway
movefile(Fs{v},[Fs{v} '_BK']);
end
end
for v=1:length(Fs)
if (strcmp(Fs{v}(end-1:end),'.m'))
movefile([Fs{v} '_BK'],Fs{v});
end
try
eval([funcstr '(''stringArg'')']);
break;
catch
if (strcmp(Fs{v}(end-1:end),'.m'))
movefile(Fs{v},[Fs{v} '_BK']);
end
end
end
for w=1:v
if (strcmp(Fs{v}(end-1:end),'.m'))
movefile([Fs{v} '_BK'],Fs{v});
end
end
``` | EDIT: Old answer no longer good
The run command won't work because its a function, not a script.
Instead, your best approach would be honestly just figure out which of the functions need to be run, get the current dir, change it to the one your function is in, run it, and then change back to your start dir.
This approach, while not perfect, seems MUCH easier to code, to read, and less prone to breaking. And it requires no changing of names or creating extra files or function handles. |
17,727,142 | I have this error in a Component in Joomla
That's my code (the error is in line 263):
```
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* @package Joomla.Platform
* @subpackage Database
* @see http://php.net/manual/en/book.mysqli.php
* @since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* @var string
* @since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = @mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET @@SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* @since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* @param string $text The string to be escaped.
* @param boolean $extra Optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* @return boolean True if connected to the database engine.
*
* @since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows.
*
* @since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* @return JDatabaseExporterMySQLi An exporter object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* @return JDatabaseImporterMySQLi An importer object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @param resource $cursor An optional database cursor resource to extract the row count from.
*
* @return integer The number of returned rows.
*
* @since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* @param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* @return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* @since 11.1
* @throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* @return string The database connector version.
*
* @since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* @return boolean True if supported.
*
* @since 11.1
* @deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* @return integer The value of the auto-increment field from the last inserted row.
*
* @since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* @return mixed A database cursor resource on success, boolean false on failure.
*
* @since 11.1
* @throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean True if the database was successfully selected.
*
* @since 11.1
* @throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// @deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* @return boolean True on success.
*
* @since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
* @param string $class The class name to use for the returned row object.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* @param mixed $cursor The optional result set cursor from which to fetch the row.
*
* @return void
*
* @since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* @param boolean $abortOnError Abort on error.
* @param boolean $transactionSafe Transaction safe queries.
*
* @return mixed A database resource if successful, false if not.
*
* @deprecated 12.1
* @since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
``` | 2013/07/18 | [
"https://Stackoverflow.com/questions/17727142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2596095/"
] | You can also create a function handle for the shadowed function. The problem is that the first function is higher on the matlab path, but you can circumvent that by (temporarily) changing the current directory.
Although it is not nice imo to change that current directory (actually I'd rather never change it while executing code), it will solve the problem quite easily; especially if you use it in the configuration part of your function with a persistent function handle:
```
function outputpars = myMainExecFunction(inputpars)
% configuration
persistent shadowfun;
if isempty(shadowfun)
funpath1 = 'C:\........\x\fun';
funpath2 = 'C:\........\y\fun'; % Shadowed
curcd = cd;
cd(funpath2);
shadowfun = @fun;
cd(curcd); % and go back to the original cd
end
outputpars{1} = shadowfun(inputpars); % will use the shadowed function
oupputpars{2} = fun(inputparts); % will use the function highest on the matlab path
end
```
This problem was also discussed [here](https://stackoverflow.com/q/11781634/1162609) as a possible solution to [this problem](https://stackoverflow.com/q/11779511/1162609).
I believe it actually is the only way to overload a builtin function outside the source directory of the overloading function (eg. you want to run your own `sum.m` in a directory other than where your `sum.m` is located.) | EDIT: Old answer no longer good
The run command won't work because its a function, not a script.
Instead, your best approach would be honestly just figure out which of the functions need to be run, get the current dir, change it to the one your function is in, run it, and then change back to your start dir.
This approach, while not perfect, seems MUCH easier to code, to read, and less prone to breaking. And it requires no changing of names or creating extra files or function handles. |
16,760,369 | Is it possible to change the top image on a wizard form depending on the wizard form. I can change the left side image but would like to change the top (small image).
```pascal
procedure CurPageChanged(CurPageID: Integer);
begin
if CurPageID = 4 then
filename:= 'babylontoolbar.bmp'
else
filename:= 'label2-crop.bmp';
ExtractTemporaryFile(filename);
(*WizardForm.WizardSmallImageFile.Bitmap.LoadFromFile(ExpandConstant('{tmp}\'+FileName));*)
WizardForm.WizardBitmapImage.Bitmap.LoadFromFile(ExpandConstant('{tmp}\' + FileName));
end;
```
I just would like to know how to reference the small file to replace the `WizardSmallImageFile` which does not work. | 2013/05/26 | [
"https://Stackoverflow.com/questions/16760369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2047180/"
] | The [`WizardSmallImageFile`](http://jrsoftware.org/ishelp/topic_setup_wizardsmallimagefile.htm) directive is mapped to the [`WizardSmallBitmapImage`](http://jrsoftware.org/ishelp/topic_scriptclasses.htm#TWizardForm) control of the `WizardForm`, so in code you can access it this way (anyway, do not hardcode page ID numbers, but instead use the intended [`PageID`](http://jrsoftware.org/ishelp/topic_scriptevents.htm#PageID) constants):
```pascal
procedure CurPageChanged(CurPageID: Integer);
var
FileName: string;
begin
if CurPageID = wpInfoBefore then
FileName := 'babylontoolbar.bmp'
else
FileName := 'label2-crop.bmp';
ExtractTemporaryFile(FileName);
WizardForm.WizardSmallBitmapImage.Bitmap.LoadFromFile(ExpandConstant('{tmp}\' + FileName));
end;
``` | Once again TLama has the answers, just have to keep googling. For those trying to do something similar to this and having problems finding the answer check out [Skipping custom pages based on optional components in Inno Setup](https://stackoverflow.com/questions/13921535/skipping-custom-pages-based-on-optional-components-in-inno-setup) |
47,163,679 | Im trying to prefill my document with salesforcse Lead Name, however i cant accomplish it, the signHereTabs, and dateSignedTab is showing but the
texttabs dont get any data,
The REST API Documentation <https://docs.docusign.com/esign/restapi/CustomTabs/CustomTabs/create/#request>
says: that the row field is the "Specifies the row number in a Salesforce table that the merge field value corresponds to." but if i pass the salesforce record id im getting the error:
DocuSign Response{
"errorCode": "INVALID\_REQUEST\_PARAMETER",
"message": "The request contained at least one invalid parameter. int value expected for parameter: mergeField.row"
}
This is my json request:
{
"emailSubject": "Agreement",
"emailBlurb": "MSTSolutions is sending you this request for your electronic signature and enter or update confidential payment information.Please review and electronically sign by following the link below.",
"templateId": "42a4815d-f8ac-4972-b1ea-2e1534324658",
"envelopeIdStamping": "false",
"templateRoles": [{
"roleName": "Signer 1",
"name": "TEST TEST",
"email": "xxx@xxxx.com",
"recipientId": "1",
"tabs": {
"signHereTabs": [{
"xPosition": "25",
"yPosition": "50",
"documentId": "1",
"pageNumber": "1"
}],
"dateSignedTabs": [{
"name": "Date Signed",
"xPosition": "25",
"yPosition": "100",
"documentId": "1",
"pageNumber": "1"
}],
"textTabs": [{
"tabLabel": "LeadFirstName",
"xPosition": "25",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1",
"mergeField": {
"configurationType":"Salesforce",
"path":"Lead",
"row":"00Q29000003fI13",
"writeback":"true",
"allowSenderToEdit":"true",
}
}]
}
}],
"status": "sent"
}
Thanks | 2017/11/07 | [
"https://Stackoverflow.com/questions/47163679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8901551/"
] | Move your return out and just return the array
```js
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib;
}
alert(fibonacci());
``` | You want to make sure you dont return from the function inside the loop. Move the return line outside the loop but still within the function.
```js
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib;
}
alert(fibonacci());
``` |
47,163,679 | Im trying to prefill my document with salesforcse Lead Name, however i cant accomplish it, the signHereTabs, and dateSignedTab is showing but the
texttabs dont get any data,
The REST API Documentation <https://docs.docusign.com/esign/restapi/CustomTabs/CustomTabs/create/#request>
says: that the row field is the "Specifies the row number in a Salesforce table that the merge field value corresponds to." but if i pass the salesforce record id im getting the error:
DocuSign Response{
"errorCode": "INVALID\_REQUEST\_PARAMETER",
"message": "The request contained at least one invalid parameter. int value expected for parameter: mergeField.row"
}
This is my json request:
{
"emailSubject": "Agreement",
"emailBlurb": "MSTSolutions is sending you this request for your electronic signature and enter or update confidential payment information.Please review and electronically sign by following the link below.",
"templateId": "42a4815d-f8ac-4972-b1ea-2e1534324658",
"envelopeIdStamping": "false",
"templateRoles": [{
"roleName": "Signer 1",
"name": "TEST TEST",
"email": "xxx@xxxx.com",
"recipientId": "1",
"tabs": {
"signHereTabs": [{
"xPosition": "25",
"yPosition": "50",
"documentId": "1",
"pageNumber": "1"
}],
"dateSignedTabs": [{
"name": "Date Signed",
"xPosition": "25",
"yPosition": "100",
"documentId": "1",
"pageNumber": "1"
}],
"textTabs": [{
"tabLabel": "LeadFirstName",
"xPosition": "25",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1",
"mergeField": {
"configurationType":"Salesforce",
"path":"Lead",
"row":"00Q29000003fI13",
"writeback":"true",
"allowSenderToEdit":"true",
}
}]
}
}],
"status": "sent"
}
Thanks | 2017/11/07 | [
"https://Stackoverflow.com/questions/47163679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8901551/"
] | Also, you can minimise the code and do something like:
```js
function fibonacci() {
for (var n = [0, 1], r = 2; r <= 10; r++)
n[r] = n[r - 2] + n[r - 1];
return n
}
console.log(fibonacci());
``` | Move your return out and just return the array
```js
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib;
}
alert(fibonacci());
``` |
47,163,679 | Im trying to prefill my document with salesforcse Lead Name, however i cant accomplish it, the signHereTabs, and dateSignedTab is showing but the
texttabs dont get any data,
The REST API Documentation <https://docs.docusign.com/esign/restapi/CustomTabs/CustomTabs/create/#request>
says: that the row field is the "Specifies the row number in a Salesforce table that the merge field value corresponds to." but if i pass the salesforce record id im getting the error:
DocuSign Response{
"errorCode": "INVALID\_REQUEST\_PARAMETER",
"message": "The request contained at least one invalid parameter. int value expected for parameter: mergeField.row"
}
This is my json request:
{
"emailSubject": "Agreement",
"emailBlurb": "MSTSolutions is sending you this request for your electronic signature and enter or update confidential payment information.Please review and electronically sign by following the link below.",
"templateId": "42a4815d-f8ac-4972-b1ea-2e1534324658",
"envelopeIdStamping": "false",
"templateRoles": [{
"roleName": "Signer 1",
"name": "TEST TEST",
"email": "xxx@xxxx.com",
"recipientId": "1",
"tabs": {
"signHereTabs": [{
"xPosition": "25",
"yPosition": "50",
"documentId": "1",
"pageNumber": "1"
}],
"dateSignedTabs": [{
"name": "Date Signed",
"xPosition": "25",
"yPosition": "100",
"documentId": "1",
"pageNumber": "1"
}],
"textTabs": [{
"tabLabel": "LeadFirstName",
"xPosition": "25",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1",
"mergeField": {
"configurationType":"Salesforce",
"path":"Lead",
"row":"00Q29000003fI13",
"writeback":"true",
"allowSenderToEdit":"true",
}
}]
}
}],
"status": "sent"
}
Thanks | 2017/11/07 | [
"https://Stackoverflow.com/questions/47163679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8901551/"
] | Also, you can minimise the code and do something like:
```js
function fibonacci() {
for (var n = [0, 1], r = 2; r <= 10; r++)
n[r] = n[r - 2] + n[r - 1];
return n
}
console.log(fibonacci());
``` | You want to make sure you dont return from the function inside the loop. Move the return line outside the loop but still within the function.
```js
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib;
}
alert(fibonacci());
``` |
47,163,679 | Im trying to prefill my document with salesforcse Lead Name, however i cant accomplish it, the signHereTabs, and dateSignedTab is showing but the
texttabs dont get any data,
The REST API Documentation <https://docs.docusign.com/esign/restapi/CustomTabs/CustomTabs/create/#request>
says: that the row field is the "Specifies the row number in a Salesforce table that the merge field value corresponds to." but if i pass the salesforce record id im getting the error:
DocuSign Response{
"errorCode": "INVALID\_REQUEST\_PARAMETER",
"message": "The request contained at least one invalid parameter. int value expected for parameter: mergeField.row"
}
This is my json request:
{
"emailSubject": "Agreement",
"emailBlurb": "MSTSolutions is sending you this request for your electronic signature and enter or update confidential payment information.Please review and electronically sign by following the link below.",
"templateId": "42a4815d-f8ac-4972-b1ea-2e1534324658",
"envelopeIdStamping": "false",
"templateRoles": [{
"roleName": "Signer 1",
"name": "TEST TEST",
"email": "xxx@xxxx.com",
"recipientId": "1",
"tabs": {
"signHereTabs": [{
"xPosition": "25",
"yPosition": "50",
"documentId": "1",
"pageNumber": "1"
}],
"dateSignedTabs": [{
"name": "Date Signed",
"xPosition": "25",
"yPosition": "100",
"documentId": "1",
"pageNumber": "1"
}],
"textTabs": [{
"tabLabel": "LeadFirstName",
"xPosition": "25",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1",
"mergeField": {
"configurationType":"Salesforce",
"path":"Lead",
"row":"00Q29000003fI13",
"writeback":"true",
"allowSenderToEdit":"true",
}
}]
}
}],
"status": "sent"
}
Thanks | 2017/11/07 | [
"https://Stackoverflow.com/questions/47163679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8901551/"
] | ```
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return (fib);
}
alert(fibonacci());
``` | You want to make sure you dont return from the function inside the loop. Move the return line outside the loop but still within the function.
```js
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib;
}
alert(fibonacci());
``` |
47,163,679 | Im trying to prefill my document with salesforcse Lead Name, however i cant accomplish it, the signHereTabs, and dateSignedTab is showing but the
texttabs dont get any data,
The REST API Documentation <https://docs.docusign.com/esign/restapi/CustomTabs/CustomTabs/create/#request>
says: that the row field is the "Specifies the row number in a Salesforce table that the merge field value corresponds to." but if i pass the salesforce record id im getting the error:
DocuSign Response{
"errorCode": "INVALID\_REQUEST\_PARAMETER",
"message": "The request contained at least one invalid parameter. int value expected for parameter: mergeField.row"
}
This is my json request:
{
"emailSubject": "Agreement",
"emailBlurb": "MSTSolutions is sending you this request for your electronic signature and enter or update confidential payment information.Please review and electronically sign by following the link below.",
"templateId": "42a4815d-f8ac-4972-b1ea-2e1534324658",
"envelopeIdStamping": "false",
"templateRoles": [{
"roleName": "Signer 1",
"name": "TEST TEST",
"email": "xxx@xxxx.com",
"recipientId": "1",
"tabs": {
"signHereTabs": [{
"xPosition": "25",
"yPosition": "50",
"documentId": "1",
"pageNumber": "1"
}],
"dateSignedTabs": [{
"name": "Date Signed",
"xPosition": "25",
"yPosition": "100",
"documentId": "1",
"pageNumber": "1"
}],
"textTabs": [{
"tabLabel": "LeadFirstName",
"xPosition": "25",
"yPosition": "200",
"documentId": "1",
"pageNumber": "1",
"mergeField": {
"configurationType":"Salesforce",
"path":"Lead",
"row":"00Q29000003fI13",
"writeback":"true",
"allowSenderToEdit":"true",
}
}]
}
}],
"status": "sent"
}
Thanks | 2017/11/07 | [
"https://Stackoverflow.com/questions/47163679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8901551/"
] | Also, you can minimise the code and do something like:
```js
function fibonacci() {
for (var n = [0, 1], r = 2; r <= 10; r++)
n[r] = n[r - 2] + n[r - 1];
return n
}
console.log(fibonacci());
``` | ```
function fibonacci() {
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return (fib);
}
alert(fibonacci());
``` |
23,869,016 | I'm trying to fully understand how the method works, see the code below:
```
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
```
I've debugged the method using BlueJ. The line:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
```
(s.charAt(0) == ' ' ? 1 : 0)
```
and ignoring the 0's.
Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg) | 2014/05/26 | [
"https://Stackoverflow.com/questions/23869016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274207/"
] | Since the method returns an int, not a string, it adds the numbers, not concatenates as characters/strings. ie
```
0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
```
not
```
"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"
== "01000000100100000010"
```
below returns an int, since countspaces returns an int
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
``` | ```
(s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1))
```
This one basically sums up the `0`s and `1`s.
Take note of the return value of the method which is an `int`. The return value of `4` is perfectly fine.
To put in other words:
>
> 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0
> + 1 + 0 = 4
>
>
> |
23,869,016 | I'm trying to fully understand how the method works, see the code below:
```
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
```
I've debugged the method using BlueJ. The line:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
```
(s.charAt(0) == ' ' ? 1 : 0)
```
and ignoring the 0's.
Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg) | 2014/05/26 | [
"https://Stackoverflow.com/questions/23869016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274207/"
] | ```
(s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1))
```
This one basically sums up the `0`s and `1`s.
Take note of the return value of the method which is an `int`. The return value of `4` is perfectly fine.
To put in other words:
>
> 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0
> + 1 + 0 = 4
>
>
> | Here's an attempt to write the function in "English" in case that helps you understand it:
```
int countspaces( string ) {
if string has no characters {
return 0
}
else {
if first character in string is a space
add 1
otherwise
add 0
to result of countspaces( string_with_first_character_removed )
}
}
``` |
23,869,016 | I'm trying to fully understand how the method works, see the code below:
```
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
```
I've debugged the method using BlueJ. The line:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
```
(s.charAt(0) == ' ' ? 1 : 0)
```
and ignoring the 0's.
Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg) | 2014/05/26 | [
"https://Stackoverflow.com/questions/23869016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274207/"
] | ```
(s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1))
```
This one basically sums up the `0`s and `1`s.
Take note of the return value of the method which is an `int`. The return value of `4` is perfectly fine.
To put in other words:
>
> 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0
> + 1 + 0 = 4
>
>
> | The point of recursion is that the function is called over and over again, you could roughly say it's some sort of loop.
```
if (s.length() == 0)
return 0;
```
This code is stopping condition (because the recursion stops at this point) of your recursive function, it will return 0 when the length of provided string is 0. Nothing much to explain here, I think that is pretty obvious.
And this part is core part of your recursive function:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
`s.charAt(0) == ' ' ? 1 : 0` uses a [*ternary operator*](http://en.wikipedia.org/wiki/%3F%3a#Usage), it checks if the first character in string is space, if it's true it uses value of 1, else it uses 0.
`countspaces(s.substring(1))` calls the function again, with substring that removes first character.
Function returns `int` value of 0 or 1, it sums the values returned, and as you know, `x + 0 = x`, so only the cases where first character is space (function returns 1) affect your final result.
This calls occurs until the function passes itself empty string, when it hits the *stopping condition*, where it goes back through the call stack, summing returned values and values from ternary operator and finally returns the expected result. |
23,869,016 | I'm trying to fully understand how the method works, see the code below:
```
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
```
I've debugged the method using BlueJ. The line:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
```
(s.charAt(0) == ' ' ? 1 : 0)
```
and ignoring the 0's.
Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg) | 2014/05/26 | [
"https://Stackoverflow.com/questions/23869016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274207/"
] | Since the method returns an int, not a string, it adds the numbers, not concatenates as characters/strings. ie
```
0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
```
not
```
"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"
== "01000000100100000010"
```
below returns an int, since countspaces returns an int
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
``` | Here's an attempt to write the function in "English" in case that helps you understand it:
```
int countspaces( string ) {
if string has no characters {
return 0
}
else {
if first character in string is a space
add 1
otherwise
add 0
to result of countspaces( string_with_first_character_removed )
}
}
``` |
23,869,016 | I'm trying to fully understand how the method works, see the code below:
```
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
```
I've debugged the method using BlueJ. The line:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
```
(s.charAt(0) == ' ' ? 1 : 0)
```
and ignoring the 0's.
Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg) | 2014/05/26 | [
"https://Stackoverflow.com/questions/23869016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274207/"
] | Since the method returns an int, not a string, it adds the numbers, not concatenates as characters/strings. ie
```
0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
```
not
```
"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"
== "01000000100100000010"
```
below returns an int, since countspaces returns an int
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
``` | The point of recursion is that the function is called over and over again, you could roughly say it's some sort of loop.
```
if (s.length() == 0)
return 0;
```
This code is stopping condition (because the recursion stops at this point) of your recursive function, it will return 0 when the length of provided string is 0. Nothing much to explain here, I think that is pretty obvious.
And this part is core part of your recursive function:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
`s.charAt(0) == ' ' ? 1 : 0` uses a [*ternary operator*](http://en.wikipedia.org/wiki/%3F%3a#Usage), it checks if the first character in string is space, if it's true it uses value of 1, else it uses 0.
`countspaces(s.substring(1))` calls the function again, with substring that removes first character.
Function returns `int` value of 0 or 1, it sums the values returned, and as you know, `x + 0 = x`, so only the cases where first character is space (function returns 1) affect your final result.
This calls occurs until the function passes itself empty string, when it hits the *stopping condition*, where it goes back through the call stack, summing returned values and values from ternary operator and finally returns the expected result. |
23,869,016 | I'm trying to fully understand how the method works, see the code below:
```
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
```
I've debugged the method using BlueJ. The line:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
```
(s.charAt(0) == ' ' ? 1 : 0)
```
and ignoring the 0's.
Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg) | 2014/05/26 | [
"https://Stackoverflow.com/questions/23869016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274207/"
] | Here's an attempt to write the function in "English" in case that helps you understand it:
```
int countspaces( string ) {
if string has no characters {
return 0
}
else {
if first character in string is a space
add 1
otherwise
add 0
to result of countspaces( string_with_first_character_removed )
}
}
``` | The point of recursion is that the function is called over and over again, you could roughly say it's some sort of loop.
```
if (s.length() == 0)
return 0;
```
This code is stopping condition (because the recursion stops at this point) of your recursive function, it will return 0 when the length of provided string is 0. Nothing much to explain here, I think that is pretty obvious.
And this part is core part of your recursive function:
```
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
```
`s.charAt(0) == ' ' ? 1 : 0` uses a [*ternary operator*](http://en.wikipedia.org/wiki/%3F%3a#Usage), it checks if the first character in string is space, if it's true it uses value of 1, else it uses 0.
`countspaces(s.substring(1))` calls the function again, with substring that removes first character.
Function returns `int` value of 0 or 1, it sums the values returned, and as you know, `x + 0 = x`, so only the cases where first character is space (function returns 1) affect your final result.
This calls occurs until the function passes itself empty string, when it hits the *stopping condition*, where it goes back through the call stack, summing returned values and values from ternary operator and finally returns the expected result. |
66,419,484 | Is there any list of sample utterances to the google smart home device types/traits? Since, google smarthome action device types/traits are pre-built, It's terrible not stating some sample utterances under each device type/trait in the google action developer documentation. Otherwise, developer has no clue what are supported utterances. | 2021/03/01 | [
"https://Stackoverflow.com/questions/66419484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8886366/"
] | >
> he compiler suggests that `let &x = &foo` moves the string hello, which I'm aware of and don't see where the problem is
>
>
>
The problem is that you've given the compiler an immutable reference to a variable (`&foo`) and then asked it to move away the underlying data. Which is not an operation that is permitted by immutable references.
To make this more explicit, extract the moving-out part into another function:
```
fn pattern_matching_1_helper(r: &String) {
let &x = r;
println!("{}", x);
}
fn pattern_matching_1() {
let foo = String::from("hello");
pattern_matching_1_helper(&foo);
}
```
I hope it's obvious that `pattern_matching_1_helper` cannot compile on its own. But the combined version in your code is really no different.
`pattern_matching_2` compiles because `i32` is `Copy`, so the compiler doesn't need to move. | ```
fn pattern_matching_3() {
let foo = String::from("hello");
let x = foo;
println!("{}", x);
}
```
This works because `foo` is moved into `x`, so `foo` is no longer a usable variable. It's ok to move data from the variable that owns it, as long as that variable is never used again.
```
fn pattern_matching_1() {
let foo = String::from("hello");
let &x = &foo;
println!("{}", x);
}
```
This doesn't work because `foo` is still the owner of the string but you are trying to move the data out of `x`, which has only borrowed it.
`pattern_matching_2` works because `i32` is `Copy`, so nothing is moved. |
45,072,531 | I am building a console application which runs on timer, it is a scheduler SMS sending application the methods are included in main method. How can i make sure that user can't input any character so that the application continues until the machine stops. Together i want to view the Information regarding the execution of application. I have disabled the close button too. The source code is as follows:
```
public class Program
{
private const int MF_BYCOMMAND = 0x00000000;
public const int SC_CLOSE = 0xF060;
[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
static void Main(string[] args)
{
DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_CLOSE, MF_BYCOMMAND);
Timer t = new Timer(TimerCallback, null, 0, 5000);
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
Console.WriteLine("SMS Banking Schedule: " + DateTime.Now);
DLLSendSMS dllSendSMS = new DLLSendSMS();
dllSendSMS.GetMessages(null);
GC.Collect();
}
}
``` | 2017/07/13 | [
"https://Stackoverflow.com/questions/45072531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'd suggest building a Windows Service for this purpose, you can ensure it will start (if desired) on machine startup and will run in the background. You can log information to log files, the Event log etc. to ensure everything is working correctly.
Visual Studio has templates for services that make is very easy to build one quickly. | Reference this answer <https://stackoverflow.com/a/32532767/6611487>
```
class Writer
{
public void WriteLine(string myText)
{
for (int i = 0; i < myText.Length; i++)
{
if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)
{
Console.Write(myText.Substring(i, myText.Length - i));
break;
}
Console.Write(myText[i]);
System.Threading.Thread.Sleep(pauseTime);
}
Console.WriteLine("");
}
}
``` |
45,072,531 | I am building a console application which runs on timer, it is a scheduler SMS sending application the methods are included in main method. How can i make sure that user can't input any character so that the application continues until the machine stops. Together i want to view the Information regarding the execution of application. I have disabled the close button too. The source code is as follows:
```
public class Program
{
private const int MF_BYCOMMAND = 0x00000000;
public const int SC_CLOSE = 0xF060;
[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
static void Main(string[] args)
{
DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_CLOSE, MF_BYCOMMAND);
Timer t = new Timer(TimerCallback, null, 0, 5000);
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
Console.WriteLine("SMS Banking Schedule: " + DateTime.Now);
DLLSendSMS dllSendSMS = new DLLSendSMS();
dllSendSMS.GetMessages(null);
GC.Collect();
}
}
``` | 2017/07/13 | [
"https://Stackoverflow.com/questions/45072531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are two solutions of this problem.
1. When you want something to run continuously you should create
windows service.
2. if you want to change your existing code then try following code. I have added while loop.
```
public class Program
{
private const int MF_BYCOMMAND = 0x00000000;
public const int SC_CLOSE = 0xF060;
[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
static void Main(string[] args)
{
DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_CLOSE, MF_BYCOMMAND);
Timer t = new Timer(TimerCallback, null, 0, 5000);
//Removed readline and added while loop (infinite)
while(true)
{
}
}
private static void TimerCallback(Object o)
{
Console.WriteLine("SMS Banking Schedule: " + DateTime.Now);
DLLSendSMS dllSendSMS = new DLLSendSMS();
dllSendSMS.GetMessages(null);
GC.Collect();
}
}
``` | Reference this answer <https://stackoverflow.com/a/32532767/6611487>
```
class Writer
{
public void WriteLine(string myText)
{
for (int i = 0; i < myText.Length; i++)
{
if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)
{
Console.Write(myText.Substring(i, myText.Length - i));
break;
}
Console.Write(myText[i]);
System.Threading.Thread.Sleep(pauseTime);
}
Console.WriteLine("");
}
}
``` |
27,108 | >
> Hallo Steffi, wie geht es dir heute?
>
>
> Fein, und dir?
>
>
> Sehr gut, danke.
>
>
>
Kann man *fein* in diesem Kontext verwenden? | 2015/12/11 | [
"https://german.stackexchange.com/questions/27108",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/3480/"
] | **Ja**, man kann auch mit *fein* antworten.
Fein ist einerseits das Gegenteil von grob, wie in *fein gemahlenes Mehl, feiner Zucker, feine Handarbeit, feiner Humor, feinste Brüsseler Spitze* aber ist wohl, weil so oft ein Qualitätsmerkmal, auch als allgemeines Wort für *gut* auf Bereiche adaptiert worden, in denen es die ursprüngliche Bedeutung nicht hat - das ist allerdings meine Spekulation.
"Das hast Du fein gemacht", sagt man beispielsweise auch zu einem Köter, der brav einen Stock apportiert hat. | **Nein**. Ich habe es noch nie in diesem Zusammenhang gehört. Es klingt als würde jemand versuchen das englische "fine" einzudeutschen.
Wenn "fein" im Sinn von "gut" verwendet wird, passiert das meist bezogen auf Qualität (fein gemacht, feine Handwerksarbeit, ...) im Gegensatz zu grob/schlecht ausgeführter Arbeit. Niemand sagt "Es geht mir fein". |
27,108 | >
> Hallo Steffi, wie geht es dir heute?
>
>
> Fein, und dir?
>
>
> Sehr gut, danke.
>
>
>
Kann man *fein* in diesem Kontext verwenden? | 2015/12/11 | [
"https://german.stackexchange.com/questions/27108",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/3480/"
] | Das ist möglicherweise auch örtlich bedingt, aber wenn ich es höre kommt es komisch rüber. Also keiner wird sich beschweren und alle werden es verstehen, aber es ist eher ungewöhnlich. | **Nein**. Ich habe es noch nie in diesem Zusammenhang gehört. Es klingt als würde jemand versuchen das englische "fine" einzudeutschen.
Wenn "fein" im Sinn von "gut" verwendet wird, passiert das meist bezogen auf Qualität (fein gemacht, feine Handwerksarbeit, ...) im Gegensatz zu grob/schlecht ausgeführter Arbeit. Niemand sagt "Es geht mir fein". |
6,000,030 | I have an object which contains 7 items.
```
$obj.gettype().name
Object[]
$obj.length
7
```
I want to loop through in batches of 3. I do NOT want to use the modulus function, I actually want to be able to create a new object with just the 3 items from that batch. Pseudo code:
```
$j=0
$k=1
for($i=0;$i<$obj.length;$i+=3){
$j=$i+2
$myTmpObj = $obj[$i-$j] # create tmpObj which contains items 1-3, then items 4-6, then 7 etc
echo "Batch $k
foreach($item in $myTmpObj){
echo $item
}
$k++
}
Batch 1
item 1
item 2
item 3
Batch 2
item 4
item 5
item 6
Batch 3
Item 7
```
Regards,
ted | 2011/05/14 | [
"https://Stackoverflow.com/questions/6000030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737490/"
] | Your pseudo code is almost real. I have just changed its syntax and used the range operator (`..`):
```
# demo input (btw, also uses ..)
$obj = 1..7
$k = 1
for($i = 0; $i -lt $obj.Length; $i += 3) {
# end index
$j = $i + 2
if ($j -ge $obj.Length) {
$j = $obj.Length - 1
}
# create tmpObj which contains items 1-3, then items 4-6, then 7 etc
$myTmpObj = $obj[$i..$j]
# show batches
"Batch $k"
foreach($item in $myTmpObj) {
$item
}
$k++
}
```
The output looks exactly as required. | See if this one may work as required (I assume your *item n* is an element of `$obj`)
```
$obj | % {$i=0;$j=0;$batches=@{}}
if($i!=3 and $batches["Batch $j"]) { $batches["Batch $j"]+=$_; $i+=1 }
else {$i=1;$j+=1;$batches["Batch $j"]=@($_)}
} {$batches}
```
Should return an HashTable (`$batches`) with keys such as `"Batch 1"`, `"Batch 2"`, ... each key related to an array of three items. |
51,175,514 | I am importing value from store
```
import {store} from '../../store/store'
```
and I have Variable:-
```
let Data = {
textType: '',
textData: null
};
```
When i use `console.log(store.state.testData)`
Getting Below result in console:-
```
{__ob__: Observer}
counters:Array(4)
testCounters:Array(0)
__ob__:Observer {value: {…}, dep: Dep, vmCount: 0}
get counters:ƒ reactiveGetter()
set counters:ƒ reactiveSetter(newVal)
get usageUnitCounters:ƒ reactiveGetter()
set usageUnitCounters:ƒ reactiveSetter(newVal)
__proto__:Object
```
and when i directly access `console.log(store.state.testData.testCounters)`
Getting Below result in console:-
```
[__ob__: Observer]
length:0
__ob__:Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__:Array
```
but if i access `console.log(store.state.testData.testCounters)` with setTimeout then i get required value for testCounters.
```
setTimeout(() => {
console.log(tore.state.testData.testCounters);
}, 13000)
```
But i need to assign **testCounter** value to ***Data*** variable but as data is not available it pass blank value as defined. How can i wait untill ***testCounters*** Data will be available or do we have any other methods?
```
export { Data }
``` | 2018/07/04 | [
"https://Stackoverflow.com/questions/51175514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6590125/"
] | If I understand your question correctly, you're trying to access `store.state.testData.testCounters` once it's set.
the way you could do that is to use a computed and a watch
```
computed: {
testData() {
return this.$store.state.testData;
}
},
watch: {
testData: {
immediate: true,
deep: false,
handler(newValue, oldValue) {
console.log(newValue);
}
}
},
```
the watch will trigger once after mounted (because `immediate` is set to `true`, but you can set it to `false`) it will trigger again when the value changes.
On a side note, you can use the spread operator to display the object values without the observables like this:
`console.log({...store.state.testData})` | As it returns observable you should subscribe the store.
```
store.subscribe(res => {
console.log(res) //all state values are available in payload
})
``` |
51,175,514 | I am importing value from store
```
import {store} from '../../store/store'
```
and I have Variable:-
```
let Data = {
textType: '',
textData: null
};
```
When i use `console.log(store.state.testData)`
Getting Below result in console:-
```
{__ob__: Observer}
counters:Array(4)
testCounters:Array(0)
__ob__:Observer {value: {…}, dep: Dep, vmCount: 0}
get counters:ƒ reactiveGetter()
set counters:ƒ reactiveSetter(newVal)
get usageUnitCounters:ƒ reactiveGetter()
set usageUnitCounters:ƒ reactiveSetter(newVal)
__proto__:Object
```
and when i directly access `console.log(store.state.testData.testCounters)`
Getting Below result in console:-
```
[__ob__: Observer]
length:0
__ob__:Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__:Array
```
but if i access `console.log(store.state.testData.testCounters)` with setTimeout then i get required value for testCounters.
```
setTimeout(() => {
console.log(tore.state.testData.testCounters);
}, 13000)
```
But i need to assign **testCounter** value to ***Data*** variable but as data is not available it pass blank value as defined. How can i wait untill ***testCounters*** Data will be available or do we have any other methods?
```
export { Data }
``` | 2018/07/04 | [
"https://Stackoverflow.com/questions/51175514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6590125/"
] | If I understand your question correctly, you're trying to access `store.state.testData.testCounters` once it's set.
the way you could do that is to use a computed and a watch
```
computed: {
testData() {
return this.$store.state.testData;
}
},
watch: {
testData: {
immediate: true,
deep: false,
handler(newValue, oldValue) {
console.log(newValue);
}
}
},
```
the watch will trigger once after mounted (because `immediate` is set to `true`, but you can set it to `false`) it will trigger again when the value changes.
On a side note, you can use the spread operator to display the object values without the observables like this:
`console.log({...store.state.testData})` | This worked for me
```
computed: {
audioPlayerStatus() {
return this.$store.getters.loadedAudioPlayer;
}
},
watch: {
'$store.state.loadedAudioPlayer.isTrackPlaying': function() {
...
}
},
``` |
51,175,514 | I am importing value from store
```
import {store} from '../../store/store'
```
and I have Variable:-
```
let Data = {
textType: '',
textData: null
};
```
When i use `console.log(store.state.testData)`
Getting Below result in console:-
```
{__ob__: Observer}
counters:Array(4)
testCounters:Array(0)
__ob__:Observer {value: {…}, dep: Dep, vmCount: 0}
get counters:ƒ reactiveGetter()
set counters:ƒ reactiveSetter(newVal)
get usageUnitCounters:ƒ reactiveGetter()
set usageUnitCounters:ƒ reactiveSetter(newVal)
__proto__:Object
```
and when i directly access `console.log(store.state.testData.testCounters)`
Getting Below result in console:-
```
[__ob__: Observer]
length:0
__ob__:Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__:Array
```
but if i access `console.log(store.state.testData.testCounters)` with setTimeout then i get required value for testCounters.
```
setTimeout(() => {
console.log(tore.state.testData.testCounters);
}, 13000)
```
But i need to assign **testCounter** value to ***Data*** variable but as data is not available it pass blank value as defined. How can i wait untill ***testCounters*** Data will be available or do we have any other methods?
```
export { Data }
``` | 2018/07/04 | [
"https://Stackoverflow.com/questions/51175514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6590125/"
] | As it returns observable you should subscribe the store.
```
store.subscribe(res => {
console.log(res) //all state values are available in payload
})
``` | This worked for me
```
computed: {
audioPlayerStatus() {
return this.$store.getters.loadedAudioPlayer;
}
},
watch: {
'$store.state.loadedAudioPlayer.isTrackPlaying': function() {
...
}
},
``` |
71,846,744 | I have some recycler view code in a function that gets called several times as bluetooth devices are scanned. My code is working but I am wondering what unseen effects are occurring from having my recycler view initialization code in a function that gets repeated a lot? I eventually want to update the list rather than replace it via `notifyDataSetChanged()` but I am unsure how to do that with my current code structure. Any help would be appreciated!
```
@SuppressLint("MissingPermission", "NotifyDataSetChanged")
fun displayDevices(
scannedDevicesStrings: TreeSet<String>,
deviceMap: HashMap<String, String>
) {
val sortedDeviceMap = deviceMap.toSortedMap()
Log.d(TAG, "displayDevices: ${sortedDeviceMap.entries}")
// Set linear layout manager for the widget.
val linearLayoutManager = LinearLayoutManager(applicationContext)
binding.recyclerviewDevices.layoutManager = linearLayoutManager
// Specify an adapter.
listAdapter = CustomAdapter(scannedDevicesStrings.toList(), sortedDeviceMap, bluetoothManager)
binding.recyclerviewDevices.adapter = listAdapter
listAdapter.notifyDataSetChanged()
// Notify the view to update when data is changed.
if ( binding.recyclerviewDevices.isAttachedToWindow) {
binding.progressBarCyclic.visibility = GONE
}
}
```
This code calls my `CustomAdapter()` class which looks like this:
```
class CustomAdapter(
private val treeSet: List<String>,
private var hashMap: SortedMap<String, String>,
private val bluetoothManager: BluetoothManager
) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.textview_list_item)
val listLayout: FrameLayout = view.findViewById(R.id.item_layout)
val context: Context = view.context
val textView2: TextView = view.findViewById(R.id.textview_list_item_address)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.text_device_row_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val deviceList = hashMap.keys.toList()
val macAddressList = hashMap.values.toList()
holder.textView.text = deviceList.elementAt(position)
holder.textView2.text = macAddressList.elementAt(position)
val selectedDeviceString = deviceList.elementAt(position).toString()
val selectedDevice = bluetoothManager.adapter.getRemoteDevice(hashMap[selectedDeviceString])
val sharedPreferences = holder.context.getSharedPreferences("mSharedPrefs", Context.MODE_PRIVATE) ?: return
with(sharedPreferences.edit()) {
putString("selectedDeviceString", selectedDevice.toString())
apply()
}
holder.listLayout.setOnClickListener {
val intent = Intent(holder.context, DeviceActivity::class.java)
intent.putExtra("btDevice", selectedDevice)
intent.putExtra("btDeviceName", selectedDeviceString)
sharedPreferences.edit().putString("loadedFrom", "loadedFromCustomAdapter").apply()
sharedPreferences.edit().putString("selectedDeviceName", selectedDeviceString).apply()
sharedPreferences.edit().putString("selectedDeviceString", selectedDevice.toString()).apply()
holder.context.startActivity(intent)
}
}
override fun getItemCount() = treeSet.size
}
``` | 2022/04/12 | [
"https://Stackoverflow.com/questions/71846744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17987933/"
] | Setting a new adapter makes the `RecyclerView` reinitialise itself, and it'll create all the `ViewHolder`s again, etc. You'd want to avoid that really. This is generally how you'd make it update:
```
class CustomAdapter(
private var data: List<Thing>
...
) {
fun setData(data: List<Thing>) {
// store the data and do any other setup work
this.data = data
// make sure the RecyclerView updates to show the new data
notifyDataSetChanged()
}
}
```
Then you just need to keep a reference to the adapter when you first create it in `onCreate` or whatever, and call `theAdapter.setData(newData)` whenever you get the new stuff. You're just setting up by creating an adapter to handle displaying your data in the list, and then you hand it data whenever it needs to update.
The actual "how things update" logic is in `setData` - it's the adapter's business how the adapter works internally, y'know? Right now it's the most basic `notifyDataSetChanged()` call, i.e. "refresh everything", but you could change that later - the outside world doesn't need to care about that though.
---
I noticed in `onBindViewHolder` you're doing this:
```
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val deviceList = hashMap.keys.toList()
val macAddressList = hashMap.values.toList()
```
That function runs *every time* a `ViewHolder` needs to display some new information (just before it scrolls onto the screen, basically) so you're creating a lot of lists whenever you scroll. Really you should do that once, when the data is set - derive your lists from the source and keep them around:
```
class CustomAdapter(
initialData: List<Thing> // not a var now - see init block
...
) {
// these might need to be lateinit since you're init-ing through a function
private var data: List<Thing>
private var deviceList: List<String>
private var macAddressList: List<String>
init {
setData(initialData)
}
fun setData(data: List<Thing>) {
// Now you're storing the data and deriving the other lists
// You might not even need to store the 'data' object if you're not using it?
this.data = data
deviceList = data.keys.toList()
macAddressList = data.values.toList()
// make sure the RecyclerView updates to show the new data
notifyDataSetChanged()
}
}
```
So now `setData` takes some source data, derives the lists you need to use and stores those, and calls the update function. Because that setup has to be done, you need to call this function every time the source data is set - including when you first create the adapter. That's why the data parameter in the constructor isn't a `var`, it's just used in the initialisation, passed to the `setData` call.
Or alternatively, don't pass any data in the constructor at all - just create the adapter, and immediately call `setData` on it. Initialise the variables to `emptyList()` etc, and then you don't need to handle the "setup at construction time" case at all!
---
Just another couple of tips - I don't know what `treeSet` is for, but you're using its size in `getItemCount`. You shouldn't do that, it should usually reflect the size of the data set you're actually displaying, which is the contents of `hashSet` - when you get a `position` in `onBindViewHolder`, you're looking up an element in `hashSet`, not `treeSet`, so that should be your source for the number of items
The other thing is, all that stuff in `onBindViewHolder`... you're doing a lot of setup work that should really only happen when the item is actually clicked. Usually you'd set up the click listener once, in `onCreateViewHolder`, and when binding you'd set a field on the viewholder telling it which `position` it's currently displaying. If the click listener fires, *then* you can look up the current `position` in the data, create `Intent`s, etc
Even if you don't move that into the VH, at least move the setup code into the `onClickListener` so it doesn't run every time a new item scrolls into view. That `sharedPreferences` bit is especially a problem - that gets overwritten every time a new item is bound (and they can be bound when they're still off-screen) so it probably isn't set to what you expect | Setting the adapter multiple times should be avoided. Doing so causes its scroll position to be lost and reset to the top, and causes it to have to reinflate all of its views and ViewHolders. Instead, you should update the model your adapter points at and notifyDataSetChanged() on it (or better yet, use DiffUtil to update individual items). |
71,846,744 | I have some recycler view code in a function that gets called several times as bluetooth devices are scanned. My code is working but I am wondering what unseen effects are occurring from having my recycler view initialization code in a function that gets repeated a lot? I eventually want to update the list rather than replace it via `notifyDataSetChanged()` but I am unsure how to do that with my current code structure. Any help would be appreciated!
```
@SuppressLint("MissingPermission", "NotifyDataSetChanged")
fun displayDevices(
scannedDevicesStrings: TreeSet<String>,
deviceMap: HashMap<String, String>
) {
val sortedDeviceMap = deviceMap.toSortedMap()
Log.d(TAG, "displayDevices: ${sortedDeviceMap.entries}")
// Set linear layout manager for the widget.
val linearLayoutManager = LinearLayoutManager(applicationContext)
binding.recyclerviewDevices.layoutManager = linearLayoutManager
// Specify an adapter.
listAdapter = CustomAdapter(scannedDevicesStrings.toList(), sortedDeviceMap, bluetoothManager)
binding.recyclerviewDevices.adapter = listAdapter
listAdapter.notifyDataSetChanged()
// Notify the view to update when data is changed.
if ( binding.recyclerviewDevices.isAttachedToWindow) {
binding.progressBarCyclic.visibility = GONE
}
}
```
This code calls my `CustomAdapter()` class which looks like this:
```
class CustomAdapter(
private val treeSet: List<String>,
private var hashMap: SortedMap<String, String>,
private val bluetoothManager: BluetoothManager
) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.textview_list_item)
val listLayout: FrameLayout = view.findViewById(R.id.item_layout)
val context: Context = view.context
val textView2: TextView = view.findViewById(R.id.textview_list_item_address)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.text_device_row_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val deviceList = hashMap.keys.toList()
val macAddressList = hashMap.values.toList()
holder.textView.text = deviceList.elementAt(position)
holder.textView2.text = macAddressList.elementAt(position)
val selectedDeviceString = deviceList.elementAt(position).toString()
val selectedDevice = bluetoothManager.adapter.getRemoteDevice(hashMap[selectedDeviceString])
val sharedPreferences = holder.context.getSharedPreferences("mSharedPrefs", Context.MODE_PRIVATE) ?: return
with(sharedPreferences.edit()) {
putString("selectedDeviceString", selectedDevice.toString())
apply()
}
holder.listLayout.setOnClickListener {
val intent = Intent(holder.context, DeviceActivity::class.java)
intent.putExtra("btDevice", selectedDevice)
intent.putExtra("btDeviceName", selectedDeviceString)
sharedPreferences.edit().putString("loadedFrom", "loadedFromCustomAdapter").apply()
sharedPreferences.edit().putString("selectedDeviceName", selectedDeviceString).apply()
sharedPreferences.edit().putString("selectedDeviceString", selectedDevice.toString()).apply()
holder.context.startActivity(intent)
}
}
override fun getItemCount() = treeSet.size
}
``` | 2022/04/12 | [
"https://Stackoverflow.com/questions/71846744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17987933/"
] | Setting the adapter multiple times should be avoided. Doing so causes its scroll position to be lost and reset to the top, and causes it to have to reinflate all of its views and ViewHolders. Instead, you should update the model your adapter points at and notifyDataSetChanged() on it (or better yet, use DiffUtil to update individual items). | I finished updating my code and it works great! The data no longer jumps to the top when new data is added. Thought I would post the code for anyone who is interested.
Here is my adapter:
```
class CustomAdapter(
private val bluetoothManager: BluetoothManager
) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
private var sortedMap = emptyMap<String, String>()
private var deviceList = emptyList<String>()
private var macAddressList = emptyList<String>()
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.textview_list_item)
val listLayout: FrameLayout = view.findViewById(R.id.item_layout)
val context: Context = view.context
val textView2: TextView = view.findViewById(R.id.textview_list_item_address)
}
@SuppressLint("NotifyDataSetChanged")
fun setData(sortedMap: SortedMap<String, String>) {
this.sortedMap = sortedMap
deviceList = sortedMap.keys.toList()
macAddressList = sortedMap.values.toList()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.text_device_row_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = deviceList.elementAt(position)
holder.textView2.text = macAddressList.elementAt(position)
holder.listLayout.setOnClickListener {
val selectedDeviceString = deviceList.elementAt(position).toString()
val selectedDevice = bluetoothManager.adapter.getRemoteDevice(sortedMap[selectedDeviceString])
val sharedPreferences = holder.context.getSharedPreferences("mSharedPrefs", Context.MODE_PRIVATE) ?: return@setOnClickListener
with(sharedPreferences.edit()) {
putString("selectedDeviceString", selectedDevice.toString())
apply()
}
val intent = Intent(holder.context, DeviceActivity::class.java)
intent.putExtra("btDevice", selectedDevice)
intent.putExtra("btDeviceName", selectedDeviceString)
sharedPreferences.edit().putString("loadedFrom", "loadedFromCustomAdapter").apply()
sharedPreferences.edit().putString("selectedDeviceName", selectedDeviceString).apply()
sharedPreferences.edit().putString("selectedDeviceString", selectedDevice.toString()).apply()
holder.context.startActivity(intent)
}
}
override fun getItemCount() = sortedMap.size
}
```
And the activity `onCreate()` code:
```
// Specify an adapter.
listAdapter = CustomAdapter(bluetoothManager)
binding.recyclerviewDevices.adapter = listAdapter
```
And my function that updates the data:
```
@SuppressLint("MissingPermission", "NotifyDataSetChanged")
fun displayDevices(
deviceMap: HashMap<String, String>
) {
val sortedDeviceMap = deviceMap.toSortedMap()
listAdapter.setData(sortedDeviceMap)
Log.d(TAG, "displayDevices: ${sortedDeviceMap.entries}")
// Notify the view to update when data is changed.
if ( binding.recyclerviewDevices.isAttachedToWindow) {
binding.progressBarCyclic.visibility = GONE
}
}
``` |
71,846,744 | I have some recycler view code in a function that gets called several times as bluetooth devices are scanned. My code is working but I am wondering what unseen effects are occurring from having my recycler view initialization code in a function that gets repeated a lot? I eventually want to update the list rather than replace it via `notifyDataSetChanged()` but I am unsure how to do that with my current code structure. Any help would be appreciated!
```
@SuppressLint("MissingPermission", "NotifyDataSetChanged")
fun displayDevices(
scannedDevicesStrings: TreeSet<String>,
deviceMap: HashMap<String, String>
) {
val sortedDeviceMap = deviceMap.toSortedMap()
Log.d(TAG, "displayDevices: ${sortedDeviceMap.entries}")
// Set linear layout manager for the widget.
val linearLayoutManager = LinearLayoutManager(applicationContext)
binding.recyclerviewDevices.layoutManager = linearLayoutManager
// Specify an adapter.
listAdapter = CustomAdapter(scannedDevicesStrings.toList(), sortedDeviceMap, bluetoothManager)
binding.recyclerviewDevices.adapter = listAdapter
listAdapter.notifyDataSetChanged()
// Notify the view to update when data is changed.
if ( binding.recyclerviewDevices.isAttachedToWindow) {
binding.progressBarCyclic.visibility = GONE
}
}
```
This code calls my `CustomAdapter()` class which looks like this:
```
class CustomAdapter(
private val treeSet: List<String>,
private var hashMap: SortedMap<String, String>,
private val bluetoothManager: BluetoothManager
) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.textview_list_item)
val listLayout: FrameLayout = view.findViewById(R.id.item_layout)
val context: Context = view.context
val textView2: TextView = view.findViewById(R.id.textview_list_item_address)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.text_device_row_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val deviceList = hashMap.keys.toList()
val macAddressList = hashMap.values.toList()
holder.textView.text = deviceList.elementAt(position)
holder.textView2.text = macAddressList.elementAt(position)
val selectedDeviceString = deviceList.elementAt(position).toString()
val selectedDevice = bluetoothManager.adapter.getRemoteDevice(hashMap[selectedDeviceString])
val sharedPreferences = holder.context.getSharedPreferences("mSharedPrefs", Context.MODE_PRIVATE) ?: return
with(sharedPreferences.edit()) {
putString("selectedDeviceString", selectedDevice.toString())
apply()
}
holder.listLayout.setOnClickListener {
val intent = Intent(holder.context, DeviceActivity::class.java)
intent.putExtra("btDevice", selectedDevice)
intent.putExtra("btDeviceName", selectedDeviceString)
sharedPreferences.edit().putString("loadedFrom", "loadedFromCustomAdapter").apply()
sharedPreferences.edit().putString("selectedDeviceName", selectedDeviceString).apply()
sharedPreferences.edit().putString("selectedDeviceString", selectedDevice.toString()).apply()
holder.context.startActivity(intent)
}
}
override fun getItemCount() = treeSet.size
}
``` | 2022/04/12 | [
"https://Stackoverflow.com/questions/71846744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17987933/"
] | Setting a new adapter makes the `RecyclerView` reinitialise itself, and it'll create all the `ViewHolder`s again, etc. You'd want to avoid that really. This is generally how you'd make it update:
```
class CustomAdapter(
private var data: List<Thing>
...
) {
fun setData(data: List<Thing>) {
// store the data and do any other setup work
this.data = data
// make sure the RecyclerView updates to show the new data
notifyDataSetChanged()
}
}
```
Then you just need to keep a reference to the adapter when you first create it in `onCreate` or whatever, and call `theAdapter.setData(newData)` whenever you get the new stuff. You're just setting up by creating an adapter to handle displaying your data in the list, and then you hand it data whenever it needs to update.
The actual "how things update" logic is in `setData` - it's the adapter's business how the adapter works internally, y'know? Right now it's the most basic `notifyDataSetChanged()` call, i.e. "refresh everything", but you could change that later - the outside world doesn't need to care about that though.
---
I noticed in `onBindViewHolder` you're doing this:
```
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val deviceList = hashMap.keys.toList()
val macAddressList = hashMap.values.toList()
```
That function runs *every time* a `ViewHolder` needs to display some new information (just before it scrolls onto the screen, basically) so you're creating a lot of lists whenever you scroll. Really you should do that once, when the data is set - derive your lists from the source and keep them around:
```
class CustomAdapter(
initialData: List<Thing> // not a var now - see init block
...
) {
// these might need to be lateinit since you're init-ing through a function
private var data: List<Thing>
private var deviceList: List<String>
private var macAddressList: List<String>
init {
setData(initialData)
}
fun setData(data: List<Thing>) {
// Now you're storing the data and deriving the other lists
// You might not even need to store the 'data' object if you're not using it?
this.data = data
deviceList = data.keys.toList()
macAddressList = data.values.toList()
// make sure the RecyclerView updates to show the new data
notifyDataSetChanged()
}
}
```
So now `setData` takes some source data, derives the lists you need to use and stores those, and calls the update function. Because that setup has to be done, you need to call this function every time the source data is set - including when you first create the adapter. That's why the data parameter in the constructor isn't a `var`, it's just used in the initialisation, passed to the `setData` call.
Or alternatively, don't pass any data in the constructor at all - just create the adapter, and immediately call `setData` on it. Initialise the variables to `emptyList()` etc, and then you don't need to handle the "setup at construction time" case at all!
---
Just another couple of tips - I don't know what `treeSet` is for, but you're using its size in `getItemCount`. You shouldn't do that, it should usually reflect the size of the data set you're actually displaying, which is the contents of `hashSet` - when you get a `position` in `onBindViewHolder`, you're looking up an element in `hashSet`, not `treeSet`, so that should be your source for the number of items
The other thing is, all that stuff in `onBindViewHolder`... you're doing a lot of setup work that should really only happen when the item is actually clicked. Usually you'd set up the click listener once, in `onCreateViewHolder`, and when binding you'd set a field on the viewholder telling it which `position` it's currently displaying. If the click listener fires, *then* you can look up the current `position` in the data, create `Intent`s, etc
Even if you don't move that into the VH, at least move the setup code into the `onClickListener` so it doesn't run every time a new item scrolls into view. That `sharedPreferences` bit is especially a problem - that gets overwritten every time a new item is bound (and they can be bound when they're still off-screen) so it probably isn't set to what you expect | I finished updating my code and it works great! The data no longer jumps to the top when new data is added. Thought I would post the code for anyone who is interested.
Here is my adapter:
```
class CustomAdapter(
private val bluetoothManager: BluetoothManager
) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
private var sortedMap = emptyMap<String, String>()
private var deviceList = emptyList<String>()
private var macAddressList = emptyList<String>()
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.textview_list_item)
val listLayout: FrameLayout = view.findViewById(R.id.item_layout)
val context: Context = view.context
val textView2: TextView = view.findViewById(R.id.textview_list_item_address)
}
@SuppressLint("NotifyDataSetChanged")
fun setData(sortedMap: SortedMap<String, String>) {
this.sortedMap = sortedMap
deviceList = sortedMap.keys.toList()
macAddressList = sortedMap.values.toList()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.text_device_row_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = deviceList.elementAt(position)
holder.textView2.text = macAddressList.elementAt(position)
holder.listLayout.setOnClickListener {
val selectedDeviceString = deviceList.elementAt(position).toString()
val selectedDevice = bluetoothManager.adapter.getRemoteDevice(sortedMap[selectedDeviceString])
val sharedPreferences = holder.context.getSharedPreferences("mSharedPrefs", Context.MODE_PRIVATE) ?: return@setOnClickListener
with(sharedPreferences.edit()) {
putString("selectedDeviceString", selectedDevice.toString())
apply()
}
val intent = Intent(holder.context, DeviceActivity::class.java)
intent.putExtra("btDevice", selectedDevice)
intent.putExtra("btDeviceName", selectedDeviceString)
sharedPreferences.edit().putString("loadedFrom", "loadedFromCustomAdapter").apply()
sharedPreferences.edit().putString("selectedDeviceName", selectedDeviceString).apply()
sharedPreferences.edit().putString("selectedDeviceString", selectedDevice.toString()).apply()
holder.context.startActivity(intent)
}
}
override fun getItemCount() = sortedMap.size
}
```
And the activity `onCreate()` code:
```
// Specify an adapter.
listAdapter = CustomAdapter(bluetoothManager)
binding.recyclerviewDevices.adapter = listAdapter
```
And my function that updates the data:
```
@SuppressLint("MissingPermission", "NotifyDataSetChanged")
fun displayDevices(
deviceMap: HashMap<String, String>
) {
val sortedDeviceMap = deviceMap.toSortedMap()
listAdapter.setData(sortedDeviceMap)
Log.d(TAG, "displayDevices: ${sortedDeviceMap.entries}")
// Notify the view to update when data is changed.
if ( binding.recyclerviewDevices.isAttachedToWindow) {
binding.progressBarCyclic.visibility = GONE
}
}
``` |
9,526,725 | I am currently trying to create a program that takes two inputs a base and an exponent, so basically im going to ask for those two things for example if the user of Prolog inputs base 2 and exponent 3, I want it to return 8.., Here is what I got so far, and doesnt work:
```
base:- write('Input the base: '),read(X),expo(X).
exponent:- write('Input the exponent '),read(Y),expo(Y).
expo(X,Y):- A is Y*Y,B is A*X,write(B).
```
**HELP PLEASE** | 2012/03/02 | [
"https://Stackoverflow.com/questions/9526725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1187813/"
] | * You've defined `expo/2` (i.e. a predicate `expo` with two arguments), but you're calling `expo/1`.
* The way you've split up your `read/1` calls into different predicates means `X` and `Y` are in different scopes; you'll never be able to call `expo(X,Y)` unless you put `read(X)` and `read(Y)` within the same rule.
* Your exponentiation definition is wrong. X^Y is not Y\*Y\*X. If you're required to implement this yourself, you'll need a recursive predicate to do it. If not, use the built-in exponentiation operator, `X**Y`. | See [this question](https://stackoverflow.com/questions/8240952/rule-to-calculate-power-of-a-number-when-the-exponent-is-negative-in-prolog) to see how to implement pow correctly. For the input part, you might want to consider not to bother implementing it until your `pow/
3` predicate works. To test this predicate, you can just use `?- pow(2, 3, R).` in the meantime.
And Prolog should answer with `R = 8.`.
And as said in a previous answer, the input part is wrong. But this previous answer already gave sufficient leads about how to better the situation so I'll leave it at that. |
18,345,299 | I'm working on making a walker in Wordpress. I saw some example code and it had the following syntax on one of it's lines:
```
!empty($item->attr_title)
and $attributes .= ' title="'.esc_attr($item->attr_title).'"';
```
What does this do? I would assume that if the object attributes are not empty it appends the title string, but I'm not sure the role of the "and" word here. | 2013/08/20 | [
"https://Stackoverflow.com/questions/18345299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701495/"
] | That's a shorthand for:
```
if (!empty($item->attr_title)) {
$attributes .= ' title="'.esc_attr($item->attr_title).'"';
}
``` | This is an example of "[short-circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation)".
This is basically a short hand way of writing:
```
if(!empty($item->attr_title)) {
$attributes .= ...
}
```
It works because the boolean operation `and` stops evaluation if the first term is falsy. If it's truthy, the right hand side is evaluated. Since we're not interested in the return value, this has the same effect as the if statement. |
18,345,299 | I'm working on making a walker in Wordpress. I saw some example code and it had the following syntax on one of it's lines:
```
!empty($item->attr_title)
and $attributes .= ' title="'.esc_attr($item->attr_title).'"';
```
What does this do? I would assume that if the object attributes are not empty it appends the title string, but I'm not sure the role of the "and" word here. | 2013/08/20 | [
"https://Stackoverflow.com/questions/18345299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701495/"
] | That's a shorthand for:
```
if (!empty($item->attr_title)) {
$attributes .= ' title="'.esc_attr($item->attr_title).'"';
}
``` | The `and` keyword (in this case the same as `&&`) checks if the condition left of it **and** the one right of it are true. There is an optimation that if the left hand condition is false the right hand one will not be checked or executed. So your code would be the same as:
```
if(!empty($item->attr_title) {
$attributes .= ' title="'.esc_attr($item->attr_title).'"';
}
``` |
18,345,299 | I'm working on making a walker in Wordpress. I saw some example code and it had the following syntax on one of it's lines:
```
!empty($item->attr_title)
and $attributes .= ' title="'.esc_attr($item->attr_title).'"';
```
What does this do? I would assume that if the object attributes are not empty it appends the title string, but I'm not sure the role of the "and" word here. | 2013/08/20 | [
"https://Stackoverflow.com/questions/18345299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701495/"
] | PHP does short circuit evaluation of boolean expressions, that is, only as many terms are evaluated until the result is definite.
```
true and something()
```
will evaluate `something()` (the complete expression could still eval to false), whereas
```
false and something()
```
will stop evaluating after the `false` term. | This is an example of "[short-circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation)".
This is basically a short hand way of writing:
```
if(!empty($item->attr_title)) {
$attributes .= ...
}
```
It works because the boolean operation `and` stops evaluation if the first term is falsy. If it's truthy, the right hand side is evaluated. Since we're not interested in the return value, this has the same effect as the if statement. |
18,345,299 | I'm working on making a walker in Wordpress. I saw some example code and it had the following syntax on one of it's lines:
```
!empty($item->attr_title)
and $attributes .= ' title="'.esc_attr($item->attr_title).'"';
```
What does this do? I would assume that if the object attributes are not empty it appends the title string, but I'm not sure the role of the "and" word here. | 2013/08/20 | [
"https://Stackoverflow.com/questions/18345299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701495/"
] | PHP does short circuit evaluation of boolean expressions, that is, only as many terms are evaluated until the result is definite.
```
true and something()
```
will evaluate `something()` (the complete expression could still eval to false), whereas
```
false and something()
```
will stop evaluating after the `false` term. | The `and` keyword (in this case the same as `&&`) checks if the condition left of it **and** the one right of it are true. There is an optimation that if the left hand condition is false the right hand one will not be checked or executed. So your code would be the same as:
```
if(!empty($item->attr_title) {
$attributes .= ' title="'.esc_attr($item->attr_title).'"';
}
``` |
18,345,299 | I'm working on making a walker in Wordpress. I saw some example code and it had the following syntax on one of it's lines:
```
!empty($item->attr_title)
and $attributes .= ' title="'.esc_attr($item->attr_title).'"';
```
What does this do? I would assume that if the object attributes are not empty it appends the title string, but I'm not sure the role of the "and" word here. | 2013/08/20 | [
"https://Stackoverflow.com/questions/18345299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701495/"
] | This is an example of "[short-circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation)".
This is basically a short hand way of writing:
```
if(!empty($item->attr_title)) {
$attributes .= ...
}
```
It works because the boolean operation `and` stops evaluation if the first term is falsy. If it's truthy, the right hand side is evaluated. Since we're not interested in the return value, this has the same effect as the if statement. | The `and` keyword (in this case the same as `&&`) checks if the condition left of it **and** the one right of it are true. There is an optimation that if the left hand condition is false the right hand one will not be checked or executed. So your code would be the same as:
```
if(!empty($item->attr_title) {
$attributes .= ' title="'.esc_attr($item->attr_title).'"';
}
``` |
25,304,237 | I am newbie at android , I am creating an application which I want login screen to appear on first use after installation of app , but I am not figuring out how to kill that activity , when user opens app again next time. I mean that I don't want login screen activity to appear again. I googled a lot but didn't got any useful answers.
here is my code which I use in onDestroy() method.
```
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
android.os.Process.killProcess(MODE_PRIVATE);
}
```
If I am wrong please help me out of this problem, Thanks in advance | 2014/08/14 | [
"https://Stackoverflow.com/questions/25304237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3884000/"
] | You're supposed to store data in the `SharedPreferences` ([How to use SharedPreferences in Android to store, fetch and edit values](https://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values)) that indicate for your application that you have already provided persistent login information so that the login screen does not have to load. Although considering that is the launcher activity of the app, what you would probably need to do is start a new activity from your login activity if it's not needed, and then finish the activity.
Also, if you want to finish an Activity, then you just need to call `finish()`. | You will have to [save a value](http://developer.android.com/training/basics/data-storage/files.html) somewhere on your phone. On every start up, you have to check that value. If it is true, you launch the login screen and save the value as false. If it is false, you skip login screen. Another way to do it is to check if user credentials exists. If they do, you use them otherwise you show login screen. |
36,260,948 | ```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DOUBLE(20,10),
mypercentage DOUBLE(25,20),
Modifikation INT(10) UNSIGNED,
)
```
I get the error: Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 8 ?>
Another 'SQL-statement checking' website gives me this error:
Error 1: could not prepare statement (1 near "UNSIGNED": syntax error)
please help!!! | 2016/03/28 | [
"https://Stackoverflow.com/questions/36260948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5751841/"
] | First, remove the comma at the end of the last column definition. Then, if you want to specify scale and precision, use `DECIMAL`:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DECIMAL(20,10),
mypercentage DECIMAL(25,20),
Modifikation INT(10) UNSIGNED
)
```
You can use scale and precision with `DOUBLE PRECISION`, but for monetary values, you should use fixed point representation. For the "percentage" this is not so important:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DECIMAL(20,10),
mypercentage DOUBLE PRECISION,
Modifikation INT(10) UNSIGNED
)
``` | Remove , from last column for fixing the query error.
Here is correct syntax of query
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DOUBLE(20,10),
mypercentage DOUBLE(25,20),
Modifikation INT(10) UNSIGNED
)
``` |
36,260,948 | ```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DOUBLE(20,10),
mypercentage DOUBLE(25,20),
Modifikation INT(10) UNSIGNED,
)
```
I get the error: Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 8 ?>
Another 'SQL-statement checking' website gives me this error:
Error 1: could not prepare statement (1 near "UNSIGNED": syntax error)
please help!!! | 2016/03/28 | [
"https://Stackoverflow.com/questions/36260948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5751841/"
] | First, remove the comma at the end of the last column definition. Then, if you want to specify scale and precision, use `DECIMAL`:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DECIMAL(20,10),
mypercentage DECIMAL(25,20),
Modifikation INT(10) UNSIGNED
)
```
You can use scale and precision with `DOUBLE PRECISION`, but for monetary values, you should use fixed point representation. For the "percentage" this is not so important:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DECIMAL(20,10),
mypercentage DOUBLE PRECISION,
Modifikation INT(10) UNSIGNED
)
``` | Its all because of the comma before the ')' |
36,260,948 | ```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DOUBLE(20,10),
mypercentage DOUBLE(25,20),
Modifikation INT(10) UNSIGNED,
)
```
I get the error: Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 8 ?>
Another 'SQL-statement checking' website gives me this error:
Error 1: could not prepare statement (1 near "UNSIGNED": syntax error)
please help!!! | 2016/03/28 | [
"https://Stackoverflow.com/questions/36260948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5751841/"
] | First, remove the comma at the end of the last column definition. Then, if you want to specify scale and precision, use `DECIMAL`:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DECIMAL(20,10),
mypercentage DECIMAL(25,20),
Modifikation INT(10) UNSIGNED
)
```
You can use scale and precision with `DOUBLE PRECISION`, but for monetary values, you should use fixed point representation. For the "percentage" this is not so important:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DECIMAL(20,10),
mypercentage DOUBLE PRECISION,
Modifikation INT(10) UNSIGNED
)
``` | Here try this:
```
CREATE TABLE my_table (
Nr INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Datum TIMESTAMP,
Name VARCHAR(20),
Mymoney DOUBLE(20,10),
mypercentage DOUBLE(25,20),
Modifikation INT(10) UNSIGNED
);
``` |
31,210,485 | Thanks for taking the time to read this SQL rookie's belated plea; it's much appreciated.
I'm trying to run an update statement in Server Management Studio 2012 using code that I thought I'd used hundreds of times, but for some reason, it's throwing an error back at me. So maybe I haven't.
I've been looking at this one for a while, removed all my original aliases, tried rewriting it and experimenting with different joins. I've searched all over for similar errors, but most seem to point to using the wrong aliases or incorrect use of the `WHERE` clause. Either might be the case here, I admit, but none is similar to the situation I have.
Using `SELECT` on the statement gives me the results I was expecting and the code passed the syntax checks, but I'm getting this message.
>
> column or expression 'DIS\_ID' cannot be updated
>
>
>
When I try to run it. I assume it's something simple that I'm doing wrong, as I'm fairly new at this, but I've exhausted everything I can think of trying. I will admit to not being an expert in different types of joins, but I get the same `SELECT` results using a `LEFT` or `RIGHT` join.
```
UPDATE
DIS_Territories
SET
DIS_Territories.DIS_ID = '1'
FROM
DIS_Territories
INNER JOIN
Territories
ON
DIS_Territories.BT_ID = Territories.BT_ID
WHERE (BT_State = 'Louisiana') AND (BT_County = 'Bienville') OR
(BT_State = 'Louisiana') AND (BT_County = 'Bossier') OR
(BT_State = 'Louisiana') AND (BT_County = 'Richland') OR
(BT_State = 'Louisiana') AND (BT_County = 'Union') OR
(BT_State = 'Louisiana') AND (BT_County = 'Webster') OR
(BT_State = 'Louisiana') AND (BT_County = 'West Carroll')
```
The data type for the column I'm trying to amend is Integer, not allowing nulls. If I'm missing any crucial information, my apologies and I'd be very grateful if someone would let me know what else I should provide.
EDIT: The `DIS_Territories` table structure is as follows:
```
USE [live.data]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Dis_Territories](
[BDT_ID] [int] IDENTITY(1,1) NOT NULL,
[BT_ID] [int] NULL,
[DIS_ID] [int] NULL
) ON [PRIMARY]
GO
```
For the record, I'm having the same issue on both my *development* and *live* databases.
Thanks very much if you're still reading.
-Rodger | 2015/07/03 | [
"https://Stackoverflow.com/questions/31210485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3805339/"
] | Reading the [react-router 0.13 -> 1.0 Upgrade Guide](https://github.com/rackt/react-router/blob/master/UPGRADE_GUIDE.md) and [this example](https://github.com/rackt/react-router/tree/master/examples/passing-props-to-children) led me to the following:
```
{ this.props.children &&
React.cloneElement(this.props.children, {newprop: this.state.someobject }) }
```
Instead of including the child components directly, we clone them and inject the new properties. (The guard handles the case where there is no child component to be rendered.) Now, when the child component renders, it can access the needed property at `this.props.newprop`. | The easy way is to just use `this.state`, but if you absolutely have to use `this.props` then you should probably extend `Router.createElement`.
First add the `createElement` prop to your `Router` render.
```js
React.render(
<Router history={history} children={Routes} createElement={createElement} />,
document.getElementById('app')
);
```
Wrap all of your components in a new `Container` component.
```js
function createElement(Component, props) {
return <Container component={Component} routerProps={props} />;
}
```
Your `Container` component will probably look something like this. Pass an `onLoadData` function down to your component.
```js
import React from 'react';
import _ from 'lodash';
class Container extends React.Component {
constructor(props) {
super(props);
this.state = { props: props.routerProps };
}
onLoadData(props) {
var mergedProps = _.merge(this.state.props, props);
this.setState({ props: mergedProps });
}
render() {
var Component = this.props.component;
return <Component {...this.state.props} onLoadData={this.onLoadData.bind(this)} />;
}
}
```
Then from your loaded component, when you get your data back from the server, just fire `this.props.onLoadData(data)` and the data will be merged with your current props.
[Read the `Router.createElement` Documentation](http://rackt.github.io/react-router/tags/v1.0.0-beta3.html#-createelement-component-props-) |
10,145,291 | Currently, I'm stuck with some code like `fooA()` (don't mind the body) which expects a specific container, say `vector<double>`, as argument.
```
double fooA(std::vector<double> const& list)
{
return list[0];
}
```
Now, I want to generalize and use iterators instead:
```
template<typename InputIterator>
double fooB(InputIterator first, InputIterator last)
{
return *first;
}
```
How to state that `fooB()` requires the iterator to iterate over `double`?
Someone might pass a `vector<string>::iterator` or, even worse as it might compile without a warning, a `vector<int>::iterator`. | 2012/04/13 | [
"https://Stackoverflow.com/questions/10145291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332092/"
] | For C++03:
```
#include <iterator>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/utility/enable_if.hpp>
template<typename InputIterator>
typename boost::enable_if<
boost::is_same<
typename boost::remove_cv<
typename std::iterator_traits<InputIterator>::value_type
>::type,
double // expected value_type
>,
double // fooB return type
>::type
fooB(InputIterator first, InputIterator last)
{
return *first;
}
```
Another C++03 solution which doesn't use Boost, but will likely produce much uglier errors when passing an invalid type:
```
#include <iterator>
void fooB_helper(double) { }
template<typename T> void fooB_helper(T const&);
template<typename InputIterator>
double fooB(InputIterator first, InputIterator last)
{
fooB_helper(typename std::iterator_traits<InputIterator>::value_type());
return *first;
}
```
For C++11 you can use expression SFINAE instead of `enable_if`, or you can use `static_assert` instead of SFINAE altogether. | If you don't want to use Boost/C++11, you might be able to get away with this approach:
```
template<typename B, template<typename A1, typename B1> class Container>
double fooB(typename Container<int, B>::iterator first,
typename Container<int, B>::iterator last)
{
return 0;
}
```
to call:
```
vector<int> a;
fooB<vector<int>::allocator_type, vector>(a.begin(), a.end());
```
A bit ugly, but works :)
Also: non-portable as the std collection implementations canhave more than two template parameters (the second one is an allocator with a default value) |
66,445,821 | Let's take this object :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
}
],
"comments": "Lorem ipsum dolor sit amet"
```
I need to pass to every property, including elements of all arrays recursively, a function. Let's say this one :
```
property => {
return typeof object === 'string' ? toUpperCase(property) : property
}
```
So the final object would look like :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "THIS IS A STRING"
}
}
],
"comments": "LOREM IPSUM DOLOR SIT AMET"
```
How do I pass this function to every property ? | 2021/03/02 | [
"https://Stackoverflow.com/questions/66445821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7246752/"
] | Like this?
```js
function mapRec(x, fn) {
if (Array.isArray(x))
return x.map(v => mapRec(v, fn));
if (x && typeof x === 'object')
return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, mapRec(v, fn)]));
return fn(x);
}
//
obj = {
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
},
],
"comments": "Lorem ipsum dolor sit amet"
}
res = mapRec(obj, x => x.toUpperCase ? x.toUpperCase() : x)
console.log(res)
``` | Use an algorithm that recursively iterates the object properties and call the `str.toUpperCase()` function to all strings found. Working example:
```js
const input = {
date: "1983-09-24",
values: [{
shares: 500,
accountType: 1,
},
{
options: {
"hey": "this is a string"
}
}
],
comments: "Lorem ipsum dolor sit amet"
}
function convertToUpperCase(obj) {
for (key in obj) {
if (typeof obj[key] === 'object' && obj != null)
convertToUpperCase(obj[key]);
else if (typeof obj[key] === 'string')
obj[key] = obj[key].toUpperCase();
}
return obj;
}
console.log(convertToUpperCase(input));
``` |
66,445,821 | Let's take this object :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
}
],
"comments": "Lorem ipsum dolor sit amet"
```
I need to pass to every property, including elements of all arrays recursively, a function. Let's say this one :
```
property => {
return typeof object === 'string' ? toUpperCase(property) : property
}
```
So the final object would look like :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "THIS IS A STRING"
}
}
],
"comments": "LOREM IPSUM DOLOR SIT AMET"
```
How do I pass this function to every property ? | 2021/03/02 | [
"https://Stackoverflow.com/questions/66445821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7246752/"
] | Like this?
```js
function mapRec(x, fn) {
if (Array.isArray(x))
return x.map(v => mapRec(v, fn));
if (x && typeof x === 'object')
return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, mapRec(v, fn)]));
return fn(x);
}
//
obj = {
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
},
],
"comments": "Lorem ipsum dolor sit amet"
}
res = mapRec(obj, x => x.toUpperCase ? x.toUpperCase() : x)
console.log(res)
``` | You can recursively call the function below if they incoming value is an array or the value is not a string. If it is a string, assign the value as the uppercase version.
This modifies the object in-place.
```js
const obj = {
"date": "1983-09-24",
"values": [{
"shares": 500,
"accountType": 1,
}, {
"options": {
"hey": "this is a string"
}
}],
"comments": "Lorem ipsum dolor sit amet"
};
const isObject = obj => typeof obj === 'object' && obj !== null;
const valuesToUpperCase = (obj) => {
if (isObject(obj)) {
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === 'string') {
obj[key] = value.toUpperCase();
} else {
valuesToUpperCase(value);
}
});
} else if (Array.isArray(obj)) {
obj.forEach(item => valuesToUpperCase(item));
}
};
valuesToUpperCase(obj);
console.log(obj);
```
```css
.as-console-wrapper { top: 0; max-height: 100% !important; }
```
Here is a version that allows you to pass a callback:
```js
const obj = {
"date": "1983-09-24",
"values": [{
"shares": 500,
"accountType": 1,
}, {
"options": {
"hey": "this is a string"
}
}],
"comments": "Lorem ipsum dolor sit amet"
};
const transformValues = (obj, fn) => {
if (Array.isArray(obj))
obj.forEach(item => transformValues(item, fn));
else if (typeof obj === 'object')
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === 'string') obj[key] = fn(value);
else transformValues(value, fn);
});
};
transformValues(obj, str => str.toUpperCase());
console.log(obj);
```
```css
.as-console-wrapper { top: 0; max-height: 100% !important; }
``` |
66,445,821 | Let's take this object :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
}
],
"comments": "Lorem ipsum dolor sit amet"
```
I need to pass to every property, including elements of all arrays recursively, a function. Let's say this one :
```
property => {
return typeof object === 'string' ? toUpperCase(property) : property
}
```
So the final object would look like :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "THIS IS A STRING"
}
}
],
"comments": "LOREM IPSUM DOLOR SIT AMET"
```
How do I pass this function to every property ? | 2021/03/02 | [
"https://Stackoverflow.com/questions/66445821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7246752/"
] | Like this?
```js
function mapRec(x, fn) {
if (Array.isArray(x))
return x.map(v => mapRec(v, fn));
if (x && typeof x === 'object')
return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, mapRec(v, fn)]));
return fn(x);
}
//
obj = {
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
},
],
"comments": "Lorem ipsum dolor sit amet"
}
res = mapRec(obj, x => x.toUpperCase ? x.toUpperCase() : x)
console.log(res)
``` | You could use reduce with a recursive transformation function to walk all the values:
```js
const input = {
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
}
],
"comments": "Lorem ipsum dolor sit amet"
}
// Utility function for transforming non-object values.
// If value has a toUpperCase function, invoke it, otherwise return the input value.
const transformValue = value => value?.toUpperCase?.() ?? value;
// Recursively transform the object's properties
const transformObject = obj => Object.entries(obj).reduce((acc, [key, value]) => {
acc[key] = typeof value === 'object'
? transformObject(value) // value is an object. call transformObject on it too.
: transformValue(value); // not an object. transform the value.
return acc;
}, {});
const output = transformObject(input);
console.log(output);
``` |
66,445,821 | Let's take this object :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
}
],
"comments": "Lorem ipsum dolor sit amet"
```
I need to pass to every property, including elements of all arrays recursively, a function. Let's say this one :
```
property => {
return typeof object === 'string' ? toUpperCase(property) : property
}
```
So the final object would look like :
```
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "THIS IS A STRING"
}
}
],
"comments": "LOREM IPSUM DOLOR SIT AMET"
```
How do I pass this function to every property ? | 2021/03/02 | [
"https://Stackoverflow.com/questions/66445821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7246752/"
] | Like this?
```js
function mapRec(x, fn) {
if (Array.isArray(x))
return x.map(v => mapRec(v, fn));
if (x && typeof x === 'object')
return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, mapRec(v, fn)]));
return fn(x);
}
//
obj = {
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
},
],
"comments": "Lorem ipsum dolor sit amet"
}
res = mapRec(obj, x => x.toUpperCase ? x.toUpperCase() : x)
console.log(res)
``` | here you go
```
let a =
{
"date": "1983-09-24",
"values": [
{
"shares": 500,
"accountType": 1,
},
{
"options": {
"hey": "this is a string"
}
}
],
"comments": "Lorem ipsum dolor sit amet"
}
function upperAllProps(inObj){
for (const [key, value] of Object.entries(inObj)) {
if(typeof value === 'string') { inObj[key] = value.toUpperCase();}
else if(typeof value === 'object') {upperAllProps(value);}
}
}
console.log(a);
upperAllProps(a);
console.log(a);
``` |
12,582,002 | I'm trying to make a query like so:
```
UPDATE table1 SET col1 = 'foo', col2 = 'bar';
UPDATE table2 SET hi = 'bye', bye = 'hi';
```
But when I go to save, Access errors with:
>
> Characters found after end of SQL statement
>
>
>
After some searching, it would appear this is because Access can only do one query at a time.
How can I do this? | 2012/09/25 | [
"https://Stackoverflow.com/questions/12582002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1563422/"
] | Where are you working? You can run multiple queries in VBA or via macros. Some examples:
```
CurrentDB.Execute "UPDATE table1 SET col1 = 'foo', col2 = 'bar';", dbFailOnError
CurrentDB.Execute "UPDATE table2 SET hi = 'bye', bye = 'hi';", dbFailOnError
```
Saved query:
```
CurrentDb.Execute "Query5", dbFailOnError
``` | I found this sample:
[MS ACCESS 2007: UPDATE QUERY THAT UPDATES VALUES IN ONE TABLE WITH VALUES FROM ANOTHER TABLE](http://www.techonthenet.com/access/queries/update2_2007.php)
uses the designer to create the query easily:
```
UPDATE Big INNER JOIN Bot ON Big.PART = Bot.PART
SET Bot.MFG = [Big].[MFG];
``` |
50,695,594 | i wrote a program that saves 3 different positions of my sensor. I want the backroundcolor of my textboxes green if the Sensor is back in the saved position. Becaus the values are changing realy fast and precise i decided just to compare the first 3 values. So i started my program and saved a position by clicking. The position is saved and the textboxes are immediatley green which is fine because the Sensor is still in this position. But after that i get an exception for cross threading and i dont understand it. Im new into C# and i thougt i solved this problem with the invokes at the beginning of my function.
```
private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
{
if (button3clicked == true)
{
if (!Dispatcher.CheckAccess())
{
textBox5.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
if (!Dispatcher.CheckAccess())
{
textBox7.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
if (!Dispatcher.CheckAccess())
{
textBox8.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
if (!Dispatcher.CheckAccess())
{
textBox9.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
else
{
tBr1.Text = text[0];
tBi1.Text = text[1];
tBj1.Text = text[2];
tBk1.Text = text[3];
button3clicked = false;
}
string firstthreetBr1 = new string(text[0].Take(3).ToArray());
string firstthreetBi1 = new string(text[1].Take(3).ToArray());
string firstthreetBj1 = new string(text[2].Take(3).ToArray());
string firstthreetBk1 = new string(text[3].Take(3).ToArray());
if (firstthreetBr1 == tBr1.Text.Substring(0,3)) <------ EXCEPTION HERE
{
tBr1.Background = Brushes.Green;
}
if (firstthreetBi1 == tBi1.Text.Substring(0, 3))
{
tBi1.Background = Brushes.Green;
}
if (firstthreetBj1 == tBj1.Text.Substring(0, 3))
{
tBj1.Background = Brushes.Green;
}
if (firstthreetBk1 == tBk1.Text.Substring(0, 3))
{
tBk1.Background = Brushes.Green;
}
}
}
```
Can someone explain it to me? | 2018/06/05 | [
"https://Stackoverflow.com/questions/50695594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9841493/"
] | I have made similar (not the same - you should understand not copy paste) situation for you.
on button click I am creating 3 threads which are updating text of Textboxes (which were created in UI thread)
```
private void btnStart_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(() => ThreadRunner(1));
Thread t2 = new Thread(() => ThreadRunner(2));
Thread t3 = new Thread(() => ThreadRunner(3));
t1.Start();
t2.Start();
t3.Start();
}
private void ThreadRunner(int threadNum)
{
while(true)
{
TextBoxUpdater(threadNum);
Thread.Sleep(100 * threadNum);
}
}
```
and method which is being called to update textboxes,
```
private void TextBoxUpdater(int num)
{
//here i m checking, if it is from different thread then UI thread
//if yes then Invoke is used,
// so it will call the same method but in UI thread
if(this.InvokeRequired)
{
txtBox1.BeginInvoke(new Action(() => TextBoxUpdater(num)));
txtBox2.BeginInvoke(new Action(() => TextBoxUpdater(num)));
txtBox3.BeginInvoke(new Action(() => TextBoxUpdater(num)));
}
else
{
//If it is UI thread (meaning this call is coming from If part of this method)
//and as it is UI thread now, we can update textbox's text
txtBox1.Text = num.ToString();
txtBox2.Text = num.ToString();
txtBox3.Text = num.ToString();
}
//but after all above checks, we are leving below code without any checking
//so once if part of this code will call this function again and else part of code runs
// and then after completing that call,
// flow will retun back to if part (not that it is not UI thread),
// then flow will directly checks below codition and throw an exception
if (txtBox1.Text.Substring(1) == "1")
{
}
}
```
with minimum changes you can do it like below to prevent exception.
```
private void TextBoxUpdater(int num)
{
//here i m checking, if it is from different thread then UI thread
//if yes then Invoke is used,
// so it will call the same method but in UI thread
if(this.InvokeRequired)
{
txtBox1.BeginInvoke(new Action(() => TextBoxUpdater(num)));
txtBox2.BeginInvoke(new Action(() => TextBoxUpdater(num)));
txtBox3.BeginInvoke(new Action(() => TextBoxUpdater(num)));
}
else
{
//If it is UI thread (meaning this call is coming from If part of this method)
//and as it is UI thread now, we can update textbox's text
txtBox1.Text = num.ToString();
txtBox2.Text = num.ToString();
txtBox3.Text = num.ToString();
//perform this logic too insdie of else block
if (txtBox1.Text.Substring(1) == "1")
{
}
}
}
```
But then too, your method will end up calling too many unnecessary calls to `TextBoxUpdater` . **you should wonder why I'm stating this.**
so to fix this part, you should modify your method like below.
```
private void TextBoxUpdater(int num)
{
if (this.InvokeRequired)
{
//if current call is form other than UI thread invoke to UI thread
this.BeginInvoke(new Action(() => TextBoxUpdater(num)));
}
else
{
//If it is UI thread (meaning this call is coming from If part of this method)
//and as it is UI thread now, we can update textbox's text
txtBox1.Text = num.ToString();
txtBox2.Text = num.ToString();
txtBox3.Text = num.ToString();
if (txtBox1.Text.Substring(1) == "1")
{
}
}
}
``` | As Matthew has commented You have to write return statement after every BeginInvoke(). This code throws an exception because after Your method returns from BeginInvoke() it goes deeper into the code. |
2,940,289 | The question is:
You own 6 songs by Adele, 4 by Katy Perry, and 5 by Lady Gaga. How many different playlists can you make that consist of 4 Adele songs, 3 Perry songs, and 2 Gaga songs, if you do allow repeated songs?
One method I tried is 4^6 \* 3^4 \* 2^5.
I also tried C(6,4) \* C(4,3) \* C(5\*2).
Both of these are wrong and I am not sure how to calculate this correctly. | 2018/10/03 | [
"https://math.stackexchange.com/questions/2940289",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/594549/"
] | If you look only at the order of the artists being played, then there are $$\frac{9!}{4!3!2!} = \frac{362880}{24\*6\*2} = 1260$$
possible orderings. This is because there are $9$ songs, which would have $9!$ orderings if all songs were different, but for now we treat the the songs by each artist as the same so we divide out the number of ways we could order the $4$ Adele songs, and similarly divide by $3!$ for Perry and $2!$ for Gaga.
Another way to see the above would be to first choose which $4$ of the $9$ slots will be Adele songs, which gives $\binom{9}{4}$ choices. Of the remaining $5$ slots, choose which $3$ of them will be Katy Perry songs. This gives $\binom{5}{3}$ choices. The remaining 2 slots will then be Gaga songs. Put together this gives
$$\binom{9}{4}\binom{5}{3} = \frac{9!}{4!5!}\frac{5!}{3!2!} = \frac{9!}{4!3!2!}$$
as above.
Now that we know which artist is in which slot, we have to choose the songs to play. Each song that comes on by a particular artist can be any one of the songs by that artist. So for each Adele song there are $6$ possibilities, and there are $6\*6\*6\*6=6^4$ selections of four Adele songs all together. Similarly $4^3$ for Katy Perry songs, and $5^2$ for Lady Gaga.
Putting this together, you get $\binom{9}{4}\binom{5}{3}\*6^4\*4^3\*5^2 = 2612736000$. | For Adele there are $\binom{6}{4} = 15$ four song combinations where all songs are different plus $\binom{6}{3}\cdot 3 = 60$ where $2$ are the same, plus $\binom{6}{2} = 15$ where $2$ pairs are the same, plus $\binom{6}{2}\cdot 2 = 30$ where $3$ are the same and $6$ where all $4$ are the same. This makes a sequence of $15+60+15+30+6$.
Repeating this for Perry is a sequence of $4+12+4$ and for Gaga a sequence of $10+5$
This gives a total of $126\cdot 20\cdot 15 = 37800$ unique nine-song playlists which can't all be permutated in the same way if order matters. This would be:
$600\cdot 9! + 4500\cdot \frac{9!}{2!} + 1800\cdot \frac{9!}{3!} + 240\cdot \frac{9!}{4!} + 9900\cdot \frac{9!}{2!2!} + 6900\cdot \frac{9!}{2!3!} + 840\cdot \frac{9!}{2!4!} + 5700\cdot \frac{9!}{2!2!2!} + 3600\cdot \frac{9!}{2!2!3!} + 900\cdot \frac{9!}{2!2!2!2!} + 300\cdot \frac{9!}{2!2!2!3!} + 600\cdot \frac{9!}{2!3!3!} + 360\cdot \frac{9!}{2!2!4!} + 120\cdot \frac{9!}{2!3!4!} + 1200\cdot \frac{9!}{3!3!} + 240\cdot \frac{9!}{3!4!} = 2612736000$ |
3,439,291 | Natural deduction has "natural" rules of deduction but has very "unnatural" and inpractical way of writing proofs as a trees. Is there some decently formalized way of writing natural deduction proofs that is useful in structuring everyday mathematical proofs? | 2019/11/17 | [
"https://math.stackexchange.com/questions/3439291",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/23730/"
] | What's unnatural about trees? They're an elegant way of capturing the structure of the proof: each node of the tree is labeled by a sentence and the deduction rule used to conclude that sentence, and the children of the node are the premises used by the rule.
If you just want to be able to arrange your proof on paper in a more efficient way, you can just make a numbered list of sentences, and next to each one indicate the rule used to conclude it, together with the numbers of the premises used. As long as you make sure that each item on the list (except the conclusion of the proof) is used as a premise for exactly one later item on this list, such a list captures exactly the same information as a proof tree.
In a comment to Bram28's answer, you write "I was thinking about paper friendly way of writing natural deduction rules (or very similar rules) so I can use it in my everyday work". If your everyday work is proof theory, then I can see the need for an efficient way of writing down formal proofs. But if your everyday work is doing (ordinary) mathematics, I'll suggest a much more efficient way of writing proofs, that mathematicians have been effectively using for centuries: natural language. | I find the [Fitch notation](https://en.wikipedia.org/wiki/Fitch_notation) that has very explicit subproof structures, and that have to be strictly nested inside each other to be most like 'natural' deduction. It certainly looks very different from [the Wikipedia page on Natural Deduction](https://en.wikipedia.org/wiki/Natural_deduction), which is probably what you are looking at. The Wikipedia page does refer to several different [sequential representations](https://en.wikipedia.org/wiki/Natural_deduction#Sequential_presentations) rather than trees, and one of those is the Fitch notation. But please note that there are also sequential notations, such as the Lemmon System ([System L](https://en.wikipedia.org/wiki/System_L)), where assumptions can be discharged in any order ... which in my eyes is less 'natural' than the Fitch notation: when we do a mathematical proof, for example, we tend to discharge assumptions in the reverse order in which we introduce them, and that is exactly what the Fitch notation does. So again, in my eyes that is a much more 'natural' deductive system, even as there are many systems of 'natural deduction'.
Finally, I should mention that Fitch systems are characterized by having exactly one Introduction and one Elimination rule for each operator which, while mathematically elegant, does not always make for the most user-friendly system in terms of elementary inferences. For example, you won't find handy inference principles like Modus Tollens, Disjunctive Syllogism in a typical Fitch system. Also, Fitch systems typically don't have equivalence principles, such as DeMorgan or Distribution as part of their inference rules. So, there are some systems, the best known one of which is probably Copi's system (*with* Conditional Proof (CP) and Indirect Proof (with IP), that have some of those additional inference rules, but that have these strictly nested subproof structures as well. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | This sounds like a good time to take advantage of EFS (Encrypting File System). Any files encrypted using EFS will be inaccessible after the account password has been forcefully reset.
<http://support.microsoft.com/kb/290260>
Set up your browser so that it stores your profile in an encrypted directory, and you're good to go. | For the particular example (saved passwords in a browser) I would recommend using the master password provided by Firefox. It encrypts the password cache.
In KDE (and Gnome) there are tools like Wallet, which also provide a secure storage for credentials (e.g. for browser, mail app, chat client, etc) using a separate password. I believe something like this is available for Windows, too.
Another way would be to encrypt your home directory with [TrueCrypt](http://www.truecrypt.org) using a container file which contains your profile and documents. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | While I'd generally agree with the comments that if you can't trust your Domain Admins there is something that needs to be fixed in your environment I can see some good arguments for providing an additional layer of access control under some circumstances.
In any case even if you are just being personally paranoid I would recommend that you check to see if your system has a built in Trusted Platform Module and if the vendor provides drivers and a security suite for it. Pretty much all business class PC's now have a reasonably capable TPM that will provide secure credential storage amongst other things. With a decent security suite to go with it, that will give you [A] a defence against rogue admins and [B] the ability to withstand a domain password reset (unlike EFS). Lenovo have a nice write up [here on their Client Security Suite](http://archive.is/O6ipZ "URL leads to www.pc.ibm.com/us/think/thinkvantagetech/security.html") that leverages the built in TPM on Thinkpads to provide a hardware secured credential store, and it uses that credential store to protect the keys to a password manager and an encrypted private disk. If you install this without Active Directory integration you can then use their Browser Security mechanisms or simply run a portable browser install from the protected disk and you will have the additional security layer you want. | For the particular example (saved passwords in a browser) I would recommend using the master password provided by Firefox. It encrypts the password cache.
In KDE (and Gnome) there are tools like Wallet, which also provide a secure storage for credentials (e.g. for browser, mail app, chat client, etc) using a separate password. I believe something like this is available for Windows, too.
Another way would be to encrypt your home directory with [TrueCrypt](http://www.truecrypt.org) using a container file which contains your profile and documents. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | If you can't trust the other domain admins then they shouldn't be domain admins, for the same reason that if you couldn't be trusted you shouldn't be one either.
If someone were to change your password this would be logged, the person found and terminated (I'm assuming you have auditing enabled).
Personally I wouldn't worry about it, it's probably not going to happen.
If that worried about it, take the advice of the others here, don't save your passwords. If it's saved it can be read eventually. | Another option for saving your password is using [this UPEK fingerprint reader](http://www.upek.com/solutions/eikon/default.asp) to remember them. It's not free but it's pretty cheap. You'll need to authenticate with your finger every time you want it to log you in to your saved websites. I've been using it for a couple months now without issues.
Keep in mind, fingerprint readers are not impossible to hack, but it would stop the casual hacker. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | While I'd generally agree with the comments that if you can't trust your Domain Admins there is something that needs to be fixed in your environment I can see some good arguments for providing an additional layer of access control under some circumstances.
In any case even if you are just being personally paranoid I would recommend that you check to see if your system has a built in Trusted Platform Module and if the vendor provides drivers and a security suite for it. Pretty much all business class PC's now have a reasonably capable TPM that will provide secure credential storage amongst other things. With a decent security suite to go with it, that will give you [A] a defence against rogue admins and [B] the ability to withstand a domain password reset (unlike EFS). Lenovo have a nice write up [here on their Client Security Suite](http://archive.is/O6ipZ "URL leads to www.pc.ibm.com/us/think/thinkvantagetech/security.html") that leverages the built in TPM on Thinkpads to provide a hardware secured credential store, and it uses that credential store to protect the keys to a password manager and an encrypted private disk. If you install this without Active Directory integration you can then use their Browser Security mechanisms or simply run a portable browser install from the protected disk and you will have the additional security layer you want. | Why would someone change your password without telling you? Is this something that has happened in the past? |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | This sounds like a good time to take advantage of EFS (Encrypting File System). Any files encrypted using EFS will be inaccessible after the account password has been forcefully reset.
<http://support.microsoft.com/kb/290260>
Set up your browser so that it stores your profile in an encrypted directory, and you're good to go. | If you can't trust the other domain admins then they shouldn't be domain admins, for the same reason that if you couldn't be trusted you shouldn't be one either.
If someone were to change your password this would be logged, the person found and terminated (I'm assuming you have auditing enabled).
Personally I wouldn't worry about it, it's probably not going to happen.
If that worried about it, take the advice of the others here, don't save your passwords. If it's saved it can be read eventually. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | This sounds like a good time to take advantage of EFS (Encrypting File System). Any files encrypted using EFS will be inaccessible after the account password has been forcefully reset.
<http://support.microsoft.com/kb/290260>
Set up your browser so that it stores your profile in an encrypted directory, and you're good to go. | If you are saving passwords in Internet Explore the passwords are encrypted against your logon password using [Protected Storage](http://msdn.microsoft.com/en-us/library/bb432403%28VS.85%29.aspx). If someone else changes your password they will not gain anything. (<http://support.microsoft.com/kb/290260>)
If you are using an alternate browser then you will probably need to look at how that browser protects the data. For example in firefox you can set a master password.
Whole-disk encryption is probably the most effective option to protect locally stored data.
If you don't trust your fellow administrators and are worried about them stealing you password I would suggest that you need to make sure there are no keyloggers. It would be much easier for them to simply load up a keylogger. With a hardware keylogger there is pretty much no way you could detect them stealing your passwords. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | If you are saving passwords in Internet Explore the passwords are encrypted against your logon password using [Protected Storage](http://msdn.microsoft.com/en-us/library/bb432403%28VS.85%29.aspx). If someone else changes your password they will not gain anything. (<http://support.microsoft.com/kb/290260>)
If you are using an alternate browser then you will probably need to look at how that browser protects the data. For example in firefox you can set a master password.
Whole-disk encryption is probably the most effective option to protect locally stored data.
If you don't trust your fellow administrators and are worried about them stealing you password I would suggest that you need to make sure there are no keyloggers. It would be much easier for them to simply load up a keylogger. With a hardware keylogger there is pretty much no way you could detect them stealing your passwords. | While I'd generally agree with the comments that if you can't trust your Domain Admins there is something that needs to be fixed in your environment I can see some good arguments for providing an additional layer of access control under some circumstances.
In any case even if you are just being personally paranoid I would recommend that you check to see if your system has a built in Trusted Platform Module and if the vendor provides drivers and a security suite for it. Pretty much all business class PC's now have a reasonably capable TPM that will provide secure credential storage amongst other things. With a decent security suite to go with it, that will give you [A] a defence against rogue admins and [B] the ability to withstand a domain password reset (unlike EFS). Lenovo have a nice write up [here on their Client Security Suite](http://archive.is/O6ipZ "URL leads to www.pc.ibm.com/us/think/thinkvantagetech/security.html") that leverages the built in TPM on Thinkpads to provide a hardware secured credential store, and it uses that credential store to protect the keys to a password manager and an encrypted private disk. If you install this without Active Directory integration you can then use their Browser Security mechanisms or simply run a portable browser install from the protected disk and you will have the additional security layer you want. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | This sounds like a good time to take advantage of EFS (Encrypting File System). Any files encrypted using EFS will be inaccessible after the account password has been forcefully reset.
<http://support.microsoft.com/kb/290260>
Set up your browser so that it stores your profile in an encrypted directory, and you're good to go. | Another option for saving your password is using [this UPEK fingerprint reader](http://www.upek.com/solutions/eikon/default.asp) to remember them. It's not free but it's pretty cheap. You'll need to authenticate with your finger every time you want it to log you in to your saved websites. I've been using it for a couple months now without issues.
Keep in mind, fingerprint readers are not impossible to hack, but it would stop the casual hacker. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | If you are saving passwords in Internet Explore the passwords are encrypted against your logon password using [Protected Storage](http://msdn.microsoft.com/en-us/library/bb432403%28VS.85%29.aspx). If someone else changes your password they will not gain anything. (<http://support.microsoft.com/kb/290260>)
If you are using an alternate browser then you will probably need to look at how that browser protects the data. For example in firefox you can set a master password.
Whole-disk encryption is probably the most effective option to protect locally stored data.
If you don't trust your fellow administrators and are worried about them stealing you password I would suggest that you need to make sure there are no keyloggers. It would be much easier for them to simply load up a keylogger. With a hardware keylogger there is pretty much no way you could detect them stealing your passwords. | Another option for saving your password is using [this UPEK fingerprint reader](http://www.upek.com/solutions/eikon/default.asp) to remember them. It's not free but it's pretty cheap. You'll need to authenticate with your finger every time you want it to log you in to your saved websites. I've been using it for a couple months now without issues.
Keep in mind, fingerprint readers are not impossible to hack, but it would stop the casual hacker. |
74,316 | Lets say you don't want anyone to be able to log into your windows profile.
I like to save passwords in my web browser.
However, I'm not the only one who has a domain admin account. Someone else can just
reset the password in AD and then he/she would be able to log into my machine.
How can I prevent this?
Is there some application which can force an additional login or
some other free solutions?
EDIT: Thanks for your suggestions, I meant additional security in general without focusing
too much on web browser passwords. Looks like encrypted home directory will solve my problem. | 2009/10/14 | [
"https://serverfault.com/questions/74316",
"https://serverfault.com",
"https://serverfault.com/users/4694/"
] | This sounds like a good time to take advantage of EFS (Encrypting File System). Any files encrypted using EFS will be inaccessible after the account password has been forcefully reset.
<http://support.microsoft.com/kb/290260>
Set up your browser so that it stores your profile in an encrypted directory, and you're good to go. | Why would someone change your password without telling you? Is this something that has happened in the past? |
6,789,640 | I want to create control, which uploads file to the server using JavaScript, with the following features
1. Drag drop support
2. Use only HTML and JavaScript(without any server side code) | 2011/07/22 | [
"https://Stackoverflow.com/questions/6789640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207565/"
] | From: <http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.innerhtml%28VS.80%29.aspx>
Do not read from or assign a value to this property. Otherwise, a System.NotSupportedException exception is thrown. This property is inherited from the HtmlContainerControl class and is not applicable to the HtmlTable class. | A HtmlTable does have the InnerHtml property: <http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.aspx>
You are missing a caps:
```
string resutlt=baseCalendar.innerHtml.Tostring(); // note innerHtml -> InnerHtml
```
However, even though it will compile, you must note that:
>
> ### Caution
>
>
> Do not read from or assign a value to this property.
> Otherwise, a System.NotSupportedException exception is thrown. This
> property is inherited from the HtmlContainerControl class and is not
> applicable to the HtmlTable class.
>
>
> |
6,789,640 | I want to create control, which uploads file to the server using JavaScript, with the following features
1. Drag drop support
2. Use only HTML and JavaScript(without any server side code) | 2011/07/22 | [
"https://Stackoverflow.com/questions/6789640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207565/"
] | I hope you want the HTML code for the table you created which cannot be achieved by innerHTML those are valid in case of div, here you should rather use `RenderControl` something on these lines
```
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
baseCalendar.RenderControl(htw)
``` | A HtmlTable does have the InnerHtml property: <http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.aspx>
You are missing a caps:
```
string resutlt=baseCalendar.innerHtml.Tostring(); // note innerHtml -> InnerHtml
```
However, even though it will compile, you must note that:
>
> ### Caution
>
>
> Do not read from or assign a value to this property.
> Otherwise, a System.NotSupportedException exception is thrown. This
> property is inherited from the HtmlContainerControl class and is not
> applicable to the HtmlTable class.
>
>
> |
6,789,640 | I want to create control, which uploads file to the server using JavaScript, with the following features
1. Drag drop support
2. Use only HTML and JavaScript(without any server side code) | 2011/07/22 | [
"https://Stackoverflow.com/questions/6789640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207565/"
] | Here you have to use manually write a Table instead of using HtmlTable
```
string str = "<table>";
for (int i = 0; i < 6; i++)
{
str += "<tr><td style='color:red'>" + i.ToString() + "</td></tr>";
}
str += "</table>";
mainDiv.InnerHtml = str;
```
And in ASPX page
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="mainDiv">
</div>
</form>
</body>
</html>
``` | A HtmlTable does have the InnerHtml property: <http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.aspx>
You are missing a caps:
```
string resutlt=baseCalendar.innerHtml.Tostring(); // note innerHtml -> InnerHtml
```
However, even though it will compile, you must note that:
>
> ### Caution
>
>
> Do not read from or assign a value to this property.
> Otherwise, a System.NotSupportedException exception is thrown. This
> property is inherited from the HtmlContainerControl class and is not
> applicable to the HtmlTable class.
>
>
> |
6,789,640 | I want to create control, which uploads file to the server using JavaScript, with the following features
1. Drag drop support
2. Use only HTML and JavaScript(without any server side code) | 2011/07/22 | [
"https://Stackoverflow.com/questions/6789640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207565/"
] | I hope you want the HTML code for the table you created which cannot be achieved by innerHTML those are valid in case of div, here you should rather use `RenderControl` something on these lines
```
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
baseCalendar.RenderControl(htw)
``` | From: <http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.innerhtml%28VS.80%29.aspx>
Do not read from or assign a value to this property. Otherwise, a System.NotSupportedException exception is thrown. This property is inherited from the HtmlContainerControl class and is not applicable to the HtmlTable class. |
6,789,640 | I want to create control, which uploads file to the server using JavaScript, with the following features
1. Drag drop support
2. Use only HTML and JavaScript(without any server side code) | 2011/07/22 | [
"https://Stackoverflow.com/questions/6789640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207565/"
] | From: <http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable.innerhtml%28VS.80%29.aspx>
Do not read from or assign a value to this property. Otherwise, a System.NotSupportedException exception is thrown. This property is inherited from the HtmlContainerControl class and is not applicable to the HtmlTable class. | Here you have to use manually write a Table instead of using HtmlTable
```
string str = "<table>";
for (int i = 0; i < 6; i++)
{
str += "<tr><td style='color:red'>" + i.ToString() + "</td></tr>";
}
str += "</table>";
mainDiv.InnerHtml = str;
```
And in ASPX page
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="mainDiv">
</div>
</form>
</body>
</html>
``` |
6,789,640 | I want to create control, which uploads file to the server using JavaScript, with the following features
1. Drag drop support
2. Use only HTML and JavaScript(without any server side code) | 2011/07/22 | [
"https://Stackoverflow.com/questions/6789640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207565/"
] | I hope you want the HTML code for the table you created which cannot be achieved by innerHTML those are valid in case of div, here you should rather use `RenderControl` something on these lines
```
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
baseCalendar.RenderControl(htw)
``` | Here you have to use manually write a Table instead of using HtmlTable
```
string str = "<table>";
for (int i = 0; i < 6; i++)
{
str += "<tr><td style='color:red'>" + i.ToString() + "</td></tr>";
}
str += "</table>";
mainDiv.InnerHtml = str;
```
And in ASPX page
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="mainDiv">
</div>
</form>
</body>
</html>
``` |
24,082 | When using a yeast cake from another brew, is it possible to use too much? If so, what is the limit for a 5 gallon keg? | 2019/04/03 | [
"https://homebrew.stackexchange.com/questions/24082",
"https://homebrew.stackexchange.com",
"https://homebrew.stackexchange.com/users/17215/"
] | General advice is to use about a cup of slurry, but less would be fine depending on the beer. You don't want to use way too much, as a lot of the flavour compounds you're after occur during the growth phase, which you would truncate or skip by massively overpitching. | There is not really any hard and fast rule, I would say it depends on a number of factors.
1. Age of yeast cake
2. Gravity of last brew
3. how rapidly you want to get this one going
In a professional setting you would check cell count, viability and a number of other factors. But unless you have stain and a microscope this is not really an option.
The older the yeast cake the more I would use as the viability and vitality of your yeast are likely to be lower.
Same for the ABV of the last brew the higher the abv the less healthy your yeast will be.
If from an old cake with high ABV maybe use 3 cups from a very fresh brew at ~4% then as Frazbro suggests a single cup of cake should more than suffice. |
65,294 | We have a small movie of iPhone screen . We would like to show that movie as if its inside an `iPhone` device.
So i would like to take an iPhone image, and play the movie inside its screen.
Using a `mac`, till now i just couldn't find any solution on how to do that .
With `iMovie` it seems bad and very hard for editing .
Are there any other simple solution ?? | 2016/01/11 | [
"https://graphicdesign.stackexchange.com/questions/65294",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/55698/"
] | Since you mention a simple solution, if you are preparing this for a presentation you could use Powerpoint or Keynote.
Just:
* Add a layer with the photo (cropped in the center if it goes on top)
* Add [a layer with the video](http://www.wikihow.com/Embed-Video-in-PowerPoint) (cropped to the exact screen size if it goes on top)
It's quick and dirty, but works. | I wrote a How-to guide that explains how to play a YouTube video inside an iPhone frame, using AppDemoStore platform: [HOW TO: Play a YouTube Video Inside an iPhone Device Image](http://blog.appdemostore.com/2016/02/how-to-play-youtube-video-inside-iphone.html).
The result looks like this: [Starbucks iPhone App Demo Video](https://www.appdemostore.com/embed?id=4883593696378880)
The advantage of this approach is that you can easily embed the video+frame into your website and it will work cross-platform. However, it works only for YouTube videos.
Give it a try and let me know if you need any help - I'm part of the AppDemoStore team. |
20,125,403 | Yes, it's [Euler problem 5](http://projecteuler.net/problem=5). I'm new to python and I'm trying to solve a couple of problems to get used to the syntax. And yes I know that there are other question regarding the same problem, but I have to know why my code is not working:
```
import sys
def IsEvDivBy1to20(n):
for i in range(1,21):
if n%i!=0:
return 0
return 1
SmallMultiple = 0
for i in range(sys.maxsize**10):
if IsEvDivBy1to20(i) == 1:
SmallMultiple = i
break
print(SmallMultiple)
```
It returns `0`. | 2013/11/21 | [
"https://Stackoverflow.com/questions/20125403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1806838/"
] | `range()` by default starts at 0. The first time through your loop, then, `i` is 0: and so the first time through your (horribly-named) function, the values being compared against are 0. | Your code fails because,
```
range(sys.maxsize**10)
```
The first value returned by `range` is 0 and every number between 1 and 21 divides 0 without leaving any remainder. So, 0 is considered as the solution. |
20,125,403 | Yes, it's [Euler problem 5](http://projecteuler.net/problem=5). I'm new to python and I'm trying to solve a couple of problems to get used to the syntax. And yes I know that there are other question regarding the same problem, but I have to know why my code is not working:
```
import sys
def IsEvDivBy1to20(n):
for i in range(1,21):
if n%i!=0:
return 0
return 1
SmallMultiple = 0
for i in range(sys.maxsize**10):
if IsEvDivBy1to20(i) == 1:
SmallMultiple = i
break
print(SmallMultiple)
```
It returns `0`. | 2013/11/21 | [
"https://Stackoverflow.com/questions/20125403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1806838/"
] | `range()` by default starts at 0. The first time through your loop, then, `i` is 0: and so the first time through your (horribly-named) function, the values being compared against are 0. | Also: Euler problems are not about brute forcing, it's also about finding an efficient solution.
For example, if a number is evenly divisible by the numbers 1 - 20 you can simply multiply 1 \* 2 \* ... \* 20 = ... to find an upper bound. This number would clearly satisfy the conditions but it's likely not the smallest number.
You can then reason as follows: if the number can be divided by 6 then it can also be divided by 2 and 3. So I don't really need to include 6 in the 1 \* 2 \* ... \* 20 multiplication. You can repeatedly apply this reasoning to find a much smaller upper bound and work your way towards the final answer. |
20,125,403 | Yes, it's [Euler problem 5](http://projecteuler.net/problem=5). I'm new to python and I'm trying to solve a couple of problems to get used to the syntax. And yes I know that there are other question regarding the same problem, but I have to know why my code is not working:
```
import sys
def IsEvDivBy1to20(n):
for i in range(1,21):
if n%i!=0:
return 0
return 1
SmallMultiple = 0
for i in range(sys.maxsize**10):
if IsEvDivBy1to20(i) == 1:
SmallMultiple = i
break
print(SmallMultiple)
```
It returns `0`. | 2013/11/21 | [
"https://Stackoverflow.com/questions/20125403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1806838/"
] | Your code fails because,
```
range(sys.maxsize**10)
```
The first value returned by `range` is 0 and every number between 1 and 21 divides 0 without leaving any remainder. So, 0 is considered as the solution. | Also: Euler problems are not about brute forcing, it's also about finding an efficient solution.
For example, if a number is evenly divisible by the numbers 1 - 20 you can simply multiply 1 \* 2 \* ... \* 20 = ... to find an upper bound. This number would clearly satisfy the conditions but it's likely not the smallest number.
You can then reason as follows: if the number can be divided by 6 then it can also be divided by 2 and 3. So I don't really need to include 6 in the 1 \* 2 \* ... \* 20 multiplication. You can repeatedly apply this reasoning to find a much smaller upper bound and work your way towards the final answer. |
56,480,837 | I am looking for a way to get the output of the `cat()` command as a string (instead of having it printed to the screen). I thought that `paste()` would do this, but there are differences:
```
> cat("A", c(1,2,3), sep=",")
A,1,2,3
> paste("A", c(1,2,3), sep=",")
[1] "A,1" "A,2" "A,3"
> paste("A", c(1,2,3), collapse=",")
[1] "A 1,A 2,A 3"
```
Is there a function to get what `cat()` would print? | 2019/06/06 | [
"https://Stackoverflow.com/questions/56480837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648741/"
] | You might also adapt your current code:
```
paste(c("A", c(1,2,3)), collapse = ",")
↑↑ ↑
[1] "A,1,2,3"
``` | If we specifically want to do this with `cat` (`How to get the output of cat as a string instead of printing it?`), then capture the output with `capture.output`. The `print/cat` returns `NULL`
```
capture.output(cat("A", c(1,2,3), sep=","))
#[1] "A,1,2,3"
```
If we want to get the output written, it has the option `file`
```
cat("A", c(1, 2, 3), sep=",", file = "file.txt")
```
---
Or using `toString` from `base R`
```
toString(c("A", c(1,2,3)))
#[1] "A, 1, 2, 3"
```
---
Or with `str_c`
```
library(stringr)
str_c(c("A", c(1,2,3)), collapse=",")
#[1] "A,1,2,3"
``` |
47,899,714 | The moment I place div2 within div1, div1 just drops by some random degree. Not sure what's going on here since I just placed div3 within div1 and it's working just fine.
```css
.propertyOverview {
height: 430px;
width: 357px;
margin-right: 10px;
margin-top: 15px;
background-color: white;
display: inline-block;
border: solid 1px #E8E8E8;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
.propertyImage {
height: 260px;
width: 355px;
background-color: #a29c9c;
border-radius: 5px 5px 0 0;
margin-left: -15px;
}
```
```html
<div class="col-sm-10 col-sm-offset-1">
<div class="container propertyOverview">
<div class="propertyImage"></div>
<div>
Sample text
</div>
</div>
```
[Screen shot of what I'm looking at](https://i.stack.imgur.com/Nsiqn.png) | 2017/12/20 | [
"https://Stackoverflow.com/questions/47899714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9012921/"
] | Apply `vertical-align:top` for `inline-block` element, because the default alignment is baseline. It will resolve the issue.
```
.propertyOverview {
height: 430px;
width: 357px;
margin-right: 10px;
margin-top: 15px;
background-color: white;
display: inline-block;
vertical-align:top; /* Added this one for alignment */
border: solid 1px #E8E8E8;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
``` | This might help you:
```
.propertyOverview{
height: 430px;
width: 357px;
margin-right: 10px;
margin-top: 15px;
background-color: white;
display: inline-block;
vertical-align:top;
border: solid 1px #E8E8E8;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
.propertyImage {
height: 260px;
width: 357px;
background-color: #a29c9c;
border-radius: 5px 5px 0 0;
margin-left:0;
}
```
<https://jsfiddle.net/jungrupak/ptqbbugw/> |
19,079,687 | I have written a HTML 5 application that uses AngularJS and interfaces with a Java REST backend running on Tomcat.
I use Spring Security to handle login and security.
When the user enters the website he is forwarded to a login page which creates a session and redirects to the index page. The REST calls that loads further data from the server then uses that session to authenticate.
If there is no session in place, I fallback to basic authentication over HTTP, such that it is possible to invoke the REST endpoints separately from the web application.
The problem I have now is when the session expires. This causes a `HTTP 401 Unauthenticated` response from the server. I thought I can catch that error and redirect the user back to the login page with Javascript. However before my error handler is called, the browser first shows a login window, only if I click cancel my Javascript error handler can handle the response.
My question is, is there a way to prevent the browser from showing this login window? Or is this a general problem with my application design?
The alternative might be not to use a session at all and to cache username and password in the application. Then I need to send it with every REST call using basic authentication, would that be a better approach?
The following is the HTTP response from the server:
```
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
WWW-Authenticate: Basic realm="Spring Security Application"
Content-Type: text/html;charset=utf-8
Content-Length: 999
Date: Mon, 30 Sep 2013 11:00:34 GMT
```
**Update:** It appears that the reason for this is the `WWW-Authenticate` header, which causes the browser to display the login dialog. | 2013/09/29 | [
"https://Stackoverflow.com/questions/19079687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/474034/"
] | I finally found the solution for this. As I mentioned in my update the reason is, that the response contains the `WWW-Authenticate` header field. My solution was then to change the configuration of spring security to return a different header:
```
WWW-Authenticate: FormBased
```
To do this I had to implement the `AuthenticaitonEntryPoint` interface and manually set the header and status code in the response:
```
@Component( "restAuthenticationEntryPoint" )
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence( HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException ) throws IOException {
response.setHeader("WWW-Authenticate", "FormBased");
response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
}
}
```
then I changed the configuration of spring-security and set the `entry-point-ref` to point to the new class:
```
<http pattern="/rest/**" create-session="never" entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/rest/**" access="ROLE_USER" />
<http-basic />
<session-management />
</http>
``` | If you want to avoid changing the server and make it return `WWW-Authenticate` header for all other callers, you can change your client to send its request with `X-Requested-With` header with `XMLHttpRequest` value.
By default, Spring Security will not to send `WWW-Authenticate` for such requests. (see [Spring source](https://github.com/spring-projects/spring-security/blob/master/config/src/main/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurer.java#L83)) |
17,172 | What is the first example of a Western government passing a [sin or vice tax](http://en.wikipedia.org/wiki/Sin_tax) -- that is, a tax passed primarily to discourage consumption of certain goods due to moral, not economic, concerns? Protective tariffs and mercantilist policies therefore don't count.
States have a long history of [directly regulating consumption](http://en.wikipedia.org/wiki/Sumptuary_law), but I'm curious about when states first began to indirectly regulate consumption. The first formal treatment of using taxes to reduce "externalities" that I know of comes from [Arthur C. Pigou in 1920](http://en.wikipedia.org/wiki/Pigovian_tax#Pigou.27s_original_argument), but obviously statesmen had long known that [taxes have the power](http://en.wikipedia.org/wiki/McCulloch_v._Maryland#Background) to discourage targeted behaviors. I think that Hamilton's Whiskey tax was overwhelmingly a fiscal measure, but [he was at least aware](http://www.urban.org/books/TTP/davie.cfm) that it had a moral angle:
>
> The consumption of ardent spirits particularly, no doubt very much on
> account of their cheapness, is carried on to an extreme, which is
> truely to be regretted, as well in regard to the health and morals, as
> to the economy of the community.
>
>
>
So I'm inclined not to count the Whiskey tax. What is the first example of a Western government passing a tax *primarily* to discourage "immoral" behavior? | 2014/11/19 | [
"https://history.stackexchange.com/questions/17172",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/8341/"
] | Not sure they were the first laws primarily motivated by "moral outrage" but the the effects on the poor of cheap, low quality gin certainly was a factor in passing the British Gin Acts of 1736 and 1751 - cf Hogarth's Gin Lane and Beer Street.
<http://en.m.wikipedia.org/wiki/Gin_Craze#Increased_Consumption_of_Gin> | The issuance of fines or taxes on luxury goods is part of the general phenomenon known as [**sumptuary laws**](https://en.wikipedia.org/wiki/Sumptuary_law). The Wikipedia article gives a good history. Also, note that [Roman censors](https://en.wikipedia.org/wiki/Roman_censor) had the power to fine anybody they thought was living in a luxurious or dissipated manner. The Romans, in fact, made a huge deal out of enforcing puritanical morality on their citizens. Julius Caesar and Octavius both did stints as censors and used to brag about the heads they knocked for excessive luxury. |
3,582,011 | In natural deduction there is a rule that says given a contradiction you can assume p i.e., $\frac{\bot}{p}$. I know that is a case when you show the soundness of the natural deduction system.
I tried to use induction to prove it. Here is my idea:
Suppose that $\forall j<i, \alpha\_1, ...,\alpha\_n \models \gamma\_j $. A proof of natural deduction looks like this:
Step 1 $\gamma\_1$ ... Step j $\gamma\_j ...$ Step m $\gamma\_m$...Step i $\gamma\_i=\gamma\_j\wedge\gamma\_m$ by the introduction of $\wedge$, so $\alpha\_1, ...,\alpha\_n \models \gamma\_j$ and $\neg\alpha\_1, ...,\alpha\_n \models \gamma\_m$ by hypothesis. So by definition of $\wedge$ and $\models$, $(\alpha\_1\wedge\neg\alpha\_1), ...,\alpha\_n \models \gamma\_i$
$\therefore \bot\models\gamma\_i$ | 2020/03/15 | [
"https://math.stackexchange.com/questions/3582011",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/711706/"
] | We can use a truth table to prove that for any logical propositions $A$ and $B$ (they need not be related in any way), we have:
$A\land \neg A \implies B$.
[](https://i.stack.imgur.com/aNHxI.png)
Using a form of natural deduction, we have:
[](https://i.stack.imgur.com/kAZvu.png) | Short answer : the inference rule holds because, from a semantic point of view , the conditional
(contradictory antecedent) $\rightarrow$( whatever consequent )
is always a tautology.
---
* Consider this reasoning.
Premise 1 : P&Q
Premise 2 : ~P
Conclusion : R.
Note that here, proposition R is chosen arbitrarily. I could have chosen any proposition instead of R, even ~(P&~P) , even ~Q, absolutely whatever. This is what I am going to show.
* In case ***the conjunction of the premises imply logically the conclusion***, the reasoning is valid.
In other words, in case the conditional
((P&Q)&~P) $\rightarrow$ R
is a tautology ( a formula that is true in all possible situations/ interpretations), the reasoning is valid.
* By building the truth table of this formula, you will see that in all possible situations ( that is, in all the rows of the truth table) the antecedent - namely (P&Q)&~P - is false.
Now, the truth table of the " if ...then" operator tells you that : *if the antecedent of a conditional is false* ( lines 3-4 of the ->'s defining truth table) *the whole conditional is automatically true*.
In the particular case of our formula's truth table, every row corresponds either to line 3 or line 4 of the truth table defining the --> operator.
This is why the formula is true in all possible cases.
[](https://i.stack.imgur.com/CI2Rc.png)
* Conclusion : the premises imply logically the conclusion, and the reasoning is valid, because
( .... contradictory antecedent) $\rightarrow$ ( whatever consequent )
is always a tautology. |
15,344,397 | I am about to start developing a classified web application. but I am facing certain difficulties
while building the DB design:
User can post their advertisements under different types of pre-existing catagories (like Vehicles, Real Estate, Computers, Education etc). But each category have their certain specific fields/properties as well as some common fields/properties.
My difficulties is like after filling a post Ad, say for Bike, I am saving the common i/p values to my advertisement\_t table (as below).
but where will I store other fields values specific to Bike like: Bike Manufacture, Bike Model, Bike Year etc?
same way, if a user wanted to post an advertisement for House(rent), I can save the common i/p values to my advertisement\_t table.
but where will I store other fields values specific to House For Rent like: total area(sq), No of Rooms, etc. and how will I map.
My Tables are below:
```
category_id
------------
(catId, parentCatId, cat_title, cat_desc)
advertisement_t
----------------
(adId, catId, userId, ad_title, ad_desc, photoId, postDate, statusId, price, ad_address, adValidFrom, adValidTo, adIsDeleted)
Photo_t
--------
(photoId, primary_photo, sec_photo1, sec_photo_2, sec_photo_3)
user_t
-------
(userId, username, password, email, activationkey, isvalidated, joinedDate, activatedDate, statusId)
```
I dont have any idea how other classified sites(like olx, freeadds) used to maintain(persist & display) their posted advertisement data on their database.
If any one has any idea, please help.
Thanks in advance. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15344397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1619751/"
] | I usually like classify these data into 2 groups (1) searchable data which will be saved in some column/mapped to column and (2) junk data( i call that additional\_info) saved in a text column in json\_encoded format.
For searchable columns, you can add another table category\_values table, which has
(category\_id, category\_value, ad\_id)
Again, if your DB is expected to grow huge with category type repeating often, you can break the category\_values table to two as
(value\_id, Category\_id, category\_value) and (value\_id, ad\_id). This results in more joins and need not be introduced in you case I believe. | I did something close to this Once.
And I can see 2 options:
Something you shouldn't do - Implement lots of tables for the required Goods (Houses, Cars, Bikes,..) which is not a very good idea because work would never end and it wouldn't be extensible.
My suggestion:
Add 3 more tables:
CustomField (To set a list of possible fields used by categories)
-----------------------------------------------------------------
(CFid, Title)
CategoryCField (Associative relation to know what fields to display when user enters a new ad)
----------------------------------------------------------------------------------------------
(catId, CFid)
StoredCFData (Actually store the Data)
--------------------------------------
(id, adId, CFid, value)
You can find however 2 problems doing it this way. Making a "relation circle" which is not very good, but if carefully done will do the work. And having to reduce the DataType of costum fields to text/numbers to make it simple. You'll have troubles applying it to Radio buttons or Combo Boxes.
Best Luck,
Raul |
23,891,491 | I am trying to populate a spinner with data pulled from the web, which I have stored in an ArrayList. The trouble is, I tried to put the data in an ArrayAdapter, and then use that to populate the spinner. But my app keeps crashing, and the logcat is telling me that there's a null pointer exception at company.setAdapter(adapter); I can't figure out why the adapter is null.
```
cList = new ArrayList<Company>();
getCompanies();
for(int i = 0; i < cList.size(); i++){
nameList.add(cList.get(i).getNameAndCountry());
}
orChoice = (RadioGroup) findViewById(R.id.radioGroup1);
company = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_add_new, nameList);
//ArrayAdapter.createFromResource(this,R.array.product_types, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
company.setAdapter(adapter);
```
Here's the activity layout xml:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".AddNew" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/offer" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/request" />
</RadioGroup>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/radioGroup1"
android:layout_marginTop="25dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/company" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/textView1"
android:layout_marginTop="5dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/spinner1"
android:layout_marginTop="25dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/model" />
<Spinner
android:id="@+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/textView2"
android:layout_marginTop="5dp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/spinner2"
android:layout_marginTop="25dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/quantity2" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number"
android:layout_marginTop="5dp"
android:layout_below="@+id/textView3" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/editText1"
android:layout_marginTop="25dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/currency2" />
<Spinner
android:id="@+id/spinner3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/textView4"
android:layout_marginTop="5dp" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="25dp"
android:layout_marginLeft="175dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/price" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView5"
android:layout_alignLeft="@+id/textView5"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="number" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/spinner3"
android:layout_marginTop="25dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/delivery_date" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/textView6"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="date" />
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/radioGroup1"
android:layout_below="@+id/editText3"
android:layout_marginTop="25dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/specs" />
<EditText
android:id="@+id/editText4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignLeft="@+id/textView7"
android:layout_below="@+id/textView7"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignLeft="@+id/textView8"
android:layout_below="@+id/textView8"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editText4"
android:layout_toRightOf="@+id/editText4"
android:text="@string/comments"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="@string/submit" />
```
And here's the Logcat:
```
05-27 17:07:16.968: E/AndroidRuntime(5586): FATAL EXCEPTION: main
05-27 17:07:16.968: E/AndroidRuntime(5586): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.onegdd.orbit/com.onegdd.orbit.AddNew}: java.lang.NullPointerException
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.ActivityThread.access$600(ActivityThread.java:140)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.os.Looper.loop(Looper.java:137)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.ActivityThread.main(ActivityThread.java:4895)
05-27 17:07:16.968: E/AndroidRuntime(5586): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 17:07:16.968: E/AndroidRuntime(5586): at java.lang.reflect.Method.invoke(Method.java:511)
05-27 17:07:16.968: E/AndroidRuntime(5586): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
05-27 17:07:16.968: E/AndroidRuntime(5586): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
05-27 17:07:16.968: E/AndroidRuntime(5586): at dalvik.system.NativeStart.main(Native Method)
05-27 17:07:16.968: E/AndroidRuntime(5586): Caused by: java.lang.NullPointerException
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.widget.AbsSpinner.setAdapter(AbsSpinner.java:114)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.widget.Spinner.setAdapter(Spinner.java:380)
05-27 17:07:16.968: E/AndroidRuntime(5586): at com.onegdd.orbit.AddNew.onCreate(AddNew.java:68)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.Activity.performCreate(Activity.java:5163)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
05-27 17:07:16.968: E/AndroidRuntime(5586): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2061)
05-27 17:07:16.968: E/AndroidRuntime(5586): ... 11 more
``` | 2014/05/27 | [
"https://Stackoverflow.com/questions/23891491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323662/"
] | `LinkedListIterator iter = <some other LinkedListIterator>` is called *copy initialization* and calls a "hidden" constructor: the copy constructor (C++03) resp. move constructor (if present, and if the initializer is a temporary, in C++11). These two constructors are not provided in your code, yet they exist: They are generated by the compiler, and they are generated as public. Therefore they are accessible from outside the class and you do not get a compiler error.
Bartek mentions copy elision in his answer, so I'll add my remark for clarity: The copy/move ctor must be accessible (in this case: public) for copy initialization, regardless of wether copy elision takes place or not, i.e. even if it does not get called. | There's no compilation error because the constructor is called from (i.e. "the object is created in") the `LinkedList` class (in particular from its `begin()` member function), which is a `friend`. No one else can instantiate that class, so the second line fails.
---
Specifically, looking at `begin()`:
```
inline LinkedListIterator LinkedList::begin()
{
return first_;
}
```
it's (with regard to access) equivalent to:
```
return LinkedListIterator(first_);
```
which calls `private` `LinkedListIterator::LinkedListIterator(Node* p)`.
Then, copy ellision *could* be performed, or a default copy (or move) constructor, which is public by default, could be called. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.