qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
4,382 | I have seen one form of using *avoir*, recently, like this: **à avoir eu**.
I forgot the phrase itself, but, for example in this phrase I just found in Google:
>
> Les jeunes de l’OM sont 2 sur 14 à avoir eu le bac cette année.
>
>
>
What kind of form is it? When/Where it supposed to be used?.. | 2012/11/06 | [
"https://french.stackexchange.com/questions/4382",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/1606/"
] | This *à* is a preposition and is not part of the verb form. This sentence is based on the construction “***être*** [un certain nombre] **à**” like in:
>
> Ils **sont** 3 sur 4 **à** regarder la télé plus de trois heures par jour.
>
> Ils **sont** plus de la moitié **à** regretter son départ.
>
>
>
This preposition is then followed by a verb in infinitive form. In French an infinitive can be given an “accomplished aspect” (*aspect révolu*), which is formed using the appropriate auxiliary verb (it depends on the main verb) and the past participle. In your case “*avoir*” becomes “*avoir eu*”. Other examples:
>
> Elle se rappelle *avoir marché* sur les Champs Élysées.
>
> Il pensait *avoir résolu* le problème.
>
> Ils croient *être allés* sur Mars.
>
>
>
And in passive form:
>
> Il croyait *avoir été compris*.
>
>
> | You can translate it word by word to “to have had”, and as far as I can tell, it has the same meaning.
*Avoir eu* is called the [**past infinitive**](http://french.about.com/od/grammar/a/pastinfinitive.htm) of *avoir*, and “indicates an action that occurred before the action of the main verb, but only when the subject of both verbs is the same.”
The second part of it is *“être quelques-uns à faire quelque chose”*, which does not translate very well in English, but means “those who did this (or to whom this happened) were, say, a few”.
Here, “they were 2 out of 14 to pass the exam” seems not so poorly said. (Or “… to have received their diploma”, to stick to the french construction) |
17,630,368 | Will the contents and rendering output be indexed by Google and other search engines?
Code:
```
<script>
var html = '<!DOCTYPE html>';
html += '<html>';
html += '<head>';
html += '<meta charset="utf8" />';
html += '<title>This Is The Stacked Overflown Network</title>';
html += '<meta name="description" value="i, are, description, ized" />';
html += '<meta name="keywords" value="key, words, and, all, that" />';
html += '</head>';
html += '<body>';
html += '<h1>The Stacked Overflown Network</h1>';
html += '<hr />';
html += '<p>Will I get the opportunity to be indexed at the Googol Seek Engine?</p>';
html += '<p><strong> - No! You Will Not! And bye bye!</strong></p>';
html += '</html>';
html += '</html>';
html += "\n";
document.write( html );
</script>
``` | 2013/07/13 | [
"https://Stackoverflow.com/questions/17630368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | That's *definitely* **not** a good style of writing Webpages.
Many crawlers *don't run* JavaScript at all.
Though it may be possible that JavaScript *source code* gets indexed to some extent, this content is very unlikely to get high rating.
The *result* of the script *may* be indexed by Google, but some crawlers just won't get your content. | Crawlers doesn't run the Javascript in the page, so any information in a script is very likely to be ignored.
Some crawlers might try to parse some information from some scripts, but generally it won't be indexed at all. If you have some information that you want to be indexed, you should put it where the crawler can very easily find it.
If a crawler would consider any information inside a script, it would have to be sure that the information actually ended up in the page. Otherwise it would be easy to use that to put a lot of invisible keywords in a page, similar to how some used to put text with the same color as the background in the page to try to fool the crawlers. |
19,001,457 | I have created one group of radio buttons in a table like
```
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" />
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
```
and when any of the radio button clicked then the background of parent is need to be changed and JQuery for it is like-
```
$(document).on('click', '#8-9', function (event) {
$checked = $("#8-9").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#ff0000");
$(this).parent().css("color", "#fff");
}
});
$(document).on('click', '#9-10', function (event) {
$checked = $("#9-10").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#252525");
$(this).parent().css("color", "#fff");
}
});
```
this code is working , when radio is clicked the background of parent is changed, but when radio is unchecked the background of parent is not been reset to default. Is there any mistake in my script or any other way is there of this? | 2013/09/25 | [
"https://Stackoverflow.com/questions/19001457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2814574/"
] | Check this : <http://jsfiddle.net/ChaitanyaMunipalle/R4htK/>
First you have to reset css of parent of radio buttons and then set which ever is checked.
```
$('input[name=radios]').on('change', function() {
$('input[name=radios]').parent().css("background-color", "#ff0000");
$('input[name=radios]').parent().css("color", "#fff");
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
});
``` | the problem is that your binding to the radio buttons separately so the click only happens once. Try this
```
var selected = null;
$(document).on("click", "input[type='radio']", function(){
if(selected != null){
selected.parent().css({backgroundColor:"white", color:"black"});
}
$(this).parent().css({backgroundColor:"black", color:"white"});
selected = $(this);
})
```
<http://jsfiddle.net/ricobano/YBW9c/> |
19,001,457 | I have created one group of radio buttons in a table like
```
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" />
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
```
and when any of the radio button clicked then the background of parent is need to be changed and JQuery for it is like-
```
$(document).on('click', '#8-9', function (event) {
$checked = $("#8-9").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#ff0000");
$(this).parent().css("color", "#fff");
}
});
$(document).on('click', '#9-10', function (event) {
$checked = $("#9-10").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#252525");
$(this).parent().css("color", "#fff");
}
});
```
this code is working , when radio is clicked the background of parent is changed, but when radio is unchecked the background of parent is not been reset to default. Is there any mistake in my script or any other way is there of this? | 2013/09/25 | [
"https://Stackoverflow.com/questions/19001457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2814574/"
] | Check this : <http://jsfiddle.net/ChaitanyaMunipalle/R4htK/>
First you have to reset css of parent of radio buttons and then set which ever is checked.
```
$('input[name=radios]').on('change', function() {
$('input[name=radios]').parent().css("background-color", "#ff0000");
$('input[name=radios]').parent().css("color", "#fff");
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
});
``` | You can optimize the code like below
```
$(document).on('change', '.radioBtn', function (event) {
$('.radioBtn').parent().css("background-color", "#FFF").css("color", "#000");
$(this).parent().css("background-color", "#000").css("color", "#fff");
});
```
And modify the HTMl like this,
```
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" class="radioBtn" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" class="radioBtn"/>
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
```
Check this <http://jsfiddle.net/8fWZG/1/>
You need to modify the color codes as per your requirement. |
19,001,457 | I have created one group of radio buttons in a table like
```
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" />
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
```
and when any of the radio button clicked then the background of parent is need to be changed and JQuery for it is like-
```
$(document).on('click', '#8-9', function (event) {
$checked = $("#8-9").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#ff0000");
$(this).parent().css("color", "#fff");
}
});
$(document).on('click', '#9-10', function (event) {
$checked = $("#9-10").is(':checked');
if ($checked) {
$(this).parent().css("background-color", "#000");
$(this).parent().css("color", "#fff");
} else {
$(this).parent().css("background-color", "#252525");
$(this).parent().css("color", "#fff");
}
});
```
this code is working , when radio is clicked the background of parent is changed, but when radio is unchecked the background of parent is not been reset to default. Is there any mistake in my script or any other way is there of this? | 2013/09/25 | [
"https://Stackoverflow.com/questions/19001457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2814574/"
] | You can optimize the code like below
```
$(document).on('change', '.radioBtn', function (event) {
$('.radioBtn').parent().css("background-color", "#FFF").css("color", "#000");
$(this).parent().css("background-color", "#000").css("color", "#fff");
});
```
And modify the HTMl like this,
```
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td>
<input type="radio" name="radios" id="8-9" class="radioBtn" />
<label for="8-9">08-09 am</label>
</td>
</tr>
<tr>
<td>
<input type="radio" name="radios" id="9-10" class="radioBtn"/>
<label for="9-10">09-10 am</label>
</td>
</tr>
</tbody>
</table>
```
Check this <http://jsfiddle.net/8fWZG/1/>
You need to modify the color codes as per your requirement. | the problem is that your binding to the radio buttons separately so the click only happens once. Try this
```
var selected = null;
$(document).on("click", "input[type='radio']", function(){
if(selected != null){
selected.parent().css({backgroundColor:"white", color:"black"});
}
$(this).parent().css({backgroundColor:"black", color:"white"});
selected = $(this);
})
```
<http://jsfiddle.net/ricobano/YBW9c/> |
44,541,048 | I have already done some searches, and this question is a duplicate of another post. I am posting this just for future reference.
Is it possible to define SUMPRODUCT without explicitly using variable names x, y?
Original Function:
```
let SUMPRODUCT x y = List.map2 (*) x y |> List.sum
SUMPRODUCT [1;4] [3;25] // Result: 103
```
I was hoping to do this:
```
// CONTAINS ERROR!
let SUMPRODUCT = (List.map2 (*)) >> List.sum
// CONTAINS ERROR!
```
But F# comes back with an error.
I have already found the solution on another post, but if you have any suggestions please let me know. Thank you. | 2017/06/14 | [
"https://Stackoverflow.com/questions/44541048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7676509/"
] | Function composition only works when the input function takes a single argument. However, in your example, the result of `List.map2 (*)` is a function that takes two separate arguments and so it cannot be easily composed with `List.sum` using `>>`.
There are various ways to work around this if you really want, but I would not do that. I think `>>` is nice in a few rare cases where it fits nicely, but trying to over-use it leads to unreadable mess.
In some functional languages, the core library defines helpers for turning function with two arguments into a function that takes a tuple and vice versa.
```
let uncurry f (x, y) = f x y
let curry f x y = f (x, y)
```
You could use those two to define your `sumProduct` like this:
```
let sumProduct = curry ((uncurry (List.map2 (*))) >> List.sum)
```
Now it is point-free and understanding it is a fun mental challenge, but for all practical purposes, nobody will be able to understand the code and it is also longer than your original explicit version:
```
let sumProduct x y = List.map2 (*) x y |> List.sum
``` | According to this post:
[What am I missing: is function composition with multiple arguments possible?](https://stackoverflow.com/questions/5446199/what-am-i-missing-is-function-composition-with-multiple-arguments-possible?noredirect=1&lq=1)
Sometimes "pointed" style code is better than "pointfree" style code, and there is no good way to unify the type difference of the original function to what I hope to achieve. |
323,978 | how to prove $\forall n$ : $p\_1p\_2...p\_n +1$ isn't the perfect square. $p\_i$ is $i$th prime number. | 2013/03/07 | [
"https://math.stackexchange.com/questions/323978",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/48921/"
] | Let $n \ge 1$. Since $2$ is the first prime, our product is even. Thus $p\_1\cdots p\_n+1$ is odd. Suppose it is equal to the odd perfect square $m^2$.
Note that $m^2-1$ is divisible by $4$, indeed by $8$. But $p\_1\cdots p\_n$ is not divisible by $4$. Thus $p\_1\cdots p\_n+1$ cannot be a perfect square.
**Remark:** The prime $2$ played a crucial role in this argument. Note for example that $3\cdot 5+1=4^2$, and $11\cdot 13 +1=12^2$. | Hints:
$$(1)\;\;\;\;\;\forall\,n\in\Bbb Z\;\;,\;\;\;n^2=0,1\pmod 4$$
$$(2)\;\;\;\;\;\;\;\text{What Thomas Andrews wrote in his comment above}$$ |
323,978 | how to prove $\forall n$ : $p\_1p\_2...p\_n +1$ isn't the perfect square. $p\_i$ is $i$th prime number. | 2013/03/07 | [
"https://math.stackexchange.com/questions/323978",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/48921/"
] | Let $n \ge 1$. Since $2$ is the first prime, our product is even. Thus $p\_1\cdots p\_n+1$ is odd. Suppose it is equal to the odd perfect square $m^2$.
Note that $m^2-1$ is divisible by $4$, indeed by $8$. But $p\_1\cdots p\_n$ is not divisible by $4$. Thus $p\_1\cdots p\_n+1$ cannot be a perfect square.
**Remark:** The prime $2$ played a crucial role in this argument. Note for example that $3\cdot 5+1=4^2$, and $11\cdot 13 +1=12^2$. | Let $P\_n = \underbrace{\color{red}{p\_1}p\_2 \cdots p\_n}\_{Q\_n} +1$. As $\color{red}{p\_1}=2$ and $2 \nmid p\_i$ for $i≥2$ therefore $Q\_n \equiv 2$(mod $4$) $\implies P\_n \equiv 3$(mod $4$). But for $n \in \mathbb{Z}, n^2 \not \equiv 3$(mod $4$). Therefore $P\_n$ is not a perfect square. $\Box$ |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | FSharp 275 bytes
================
```
let f (p : string, q : string) =
let l = if p.Length < q.Length then p.Length else q.Length
p.Substring(0,l).ToCharArray() |> Array.mapi (fun i x -> (((int(x) - 32) * (int(q.[i]) - 32)) % 95) + 32) |> Array.map (fun x -> char(x).ToString()) |> Array.fold(+) ""
``` | [Python 2](https://docs.python.org/2/), ~~95~~ 73 bytes
=======================================================
* Thanks @Zacharý for 4 bytes: unwanted brackets removed
```python
lambda x,y:''.join(chr((ord(i)-32)*(ord(j)-32)%95+32)for i,j in zip(x,y))
```
[Try it online!](https://tio.run/##HcsxDsIwDEDRq3hBtiEwFDGAxE1YWqKojsCO3CARLh@qTv8tv7Q6mw493R/9Nb6nOMI3tBviKZsoPWcnMo8kfDwPvN@cN@@ul8OaZA4SMojCTwqtM3MvLlohEU6mEQOKxs9SvSH3Pw "Python 2 – Try It Online") |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [Haskell](https://www.haskell.org/), ~~60~~ 57 bytes
====================================================
```hs
zipWith(\a b->toEnum$f a*f b`mod`95+32)
f=(-32+).fromEnum
```
[Try it online!](https://tio.run/##ddFPa8IwFADwez7F8ylUp91B3WEDexljjFEQdtgOwkztH6Np0qUJQ8XP3iV1bhTruyQkvzxe3lvTcptwXh38LnAqMkOzBB7nc@j6R5LNFtWeFe9Mr/sLCpEfaPkkTN5Lgd6kEC1zGS/v74aT8YCks74/GQ8Ht6mSuUNVTpmAGRRGv2kFPcgAv6WMEXBtRKZ2SA4@QVZGAkeAZcGZRrgIPwDcGG41OtYiGvSXvUAshachp1onCttY48y9CRMQif1qouChjzVrGoKR0eBSd5zvnAMbqf8N8b6M1EnpjcDDOrzLir3V9pO9Zh45NWf0153W7@2oErYOrejO0cxOB690YkP3e0uZiE2pVc0jKWJsobGShaWFiThbOagl5@0FpNTeEFQOWBi7J6KdRif6/FF3yy1Xp@aaSHAKnHOYOn3eXsjzBcEwCMJ6bG69kjcIwwCJf6x@AA "Haskell – Try It Online")
First line is an anonymous function taking two arguments.
This a straight forward implementation of the algorithm: `zipWith` takes both strings and applies a given function to the pairs of characters. It handles the truncation and also works for empty strings. `fromEnum` and `toEnum` are alternatives to `ord` and `chr` to switch between characters and their ASCII values which do not need a lengthy import.
**Edit:** -3 bytes thanks to Bruce Forte. | [K (oK)](https://github.com/JohnEarnest/ok), 26 bytes
=====================================================
**Solution:**
```
`c$32+95!*/-32+(&/#:'x)$x:
```
[Try it online!](https://tio.run/##y9bNz/7/PyFZxdhI29JUUUtfF8jQUNNXtlKv0FSpsNJQysxLKS0uKapUslZKys9LUdL8/x8A "K (oK) – Try It Online")
**Example:**
```
`c$32+95!*/-32+(&/#:'x)$x:("split";"isbn")
"july"
```
**Explanation:**
Evaluation is performed right-to-left:
```
`c$32+95!*/-32+(&/#:'x)$x: / the solution
x: / assign input to variable x
$ / pad right to length on left
( #:'x) / count each x (return length of each char list in list)
&/ / min-over, get the minimum of these counts
-32+ / subtract 32, this automagically converts chars -> ints
*/ / multiply-over, product of the two lists
95! / modulo 95
32+ / add 32 back again
`c$ / convert to character array
``` |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [R](https://www.r-project.org/), 88 bytes
=========================================
```r
function(r,s,u=utf8ToInt)intToUtf8((((u(r)-32)*(u(s)-32))%%95+32)[0:min(nchar(c(r,s)))])
```
anonymous function; takes input as two strings; third argument is just to ensure this is a one line function and save some bytes.
The TIO link below returns an array with entries named with the first input.
[Try all test cases!](https://tio.run/##ZY5BSwMxEIXv/oo0UJLUFERb0FJ7lR56qyCIh93NbjeQncRkgqx/fp1sEQQfgffNMJl5cerYfj11GRq0HmTUSefnjN3j2R8BlQU8@1cqJSnLqNYP92pFlGZSy@XT9pbg/W43WJDQ9FWUTVmjlPpQ01CF4EbZ6UZym2rgml8f@yOuGa8zMsuMX1AhPrPHNglqf3lvaBpjNZJZMDlhLBhy7WxDEL1zZC9v9JNvmHOObcrC0@Fw4krf0OEUnMXr2SOdAIFsqBDbOM@1DFqLfRvZTpbG4lclCZ8ltOgzXOJIcPm2gaz2YMiQrpOZkgYIKEaJ/S@Hmn4A "R – Try It Online") | [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes
=================================================
```
øŀC32-ƒ*95%32+Cṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuMWAQzMyLcaSKjk1JTMyK0PhuYUiLCIiLCJbXCJ3b29kXCIsIFwiaHVuZ3J5XCJdIl0=)
```
øŀC32-ƒ*95%32+Cṅ # Example input: ["wood", "hungry"]
øŀ # Align to left by padding to the right with spaces: ["wood ", "hungry"]
C # Character codes: [[119, 111, 111, 100, 32, 32], [104, 117, 110, 103, 114, 121]]
32- # Subtract 32: [[87, 79, 79, 68, 0, 0], [72, 85, 78, 71, 82, 89]]
ƒ* # Element-wise multiply both: [6264, 6715, 6162, 4828, 0, 0]
95% # Modulo 95: [89, 65, 82, 78, 0, 0]
32+ # Add 32: [121, 97, 114, 110, 32, 32]
C # From character codes: ["y", "a", "r", "n", " ", " "]
ṅ # Join together: "yarn "
``` |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [Python 2](https://docs.python.org/2/), ~~75~~ 70 bytes
=======================================================
*-3 bytes thanks to Dennis' suggestion of shooqie's suggestion. -2 bytes thanks to Zacharý's suggestion.*
```python
lambda*l:''.join(chr((ord(i)-32)*(ord(j)-32)%95+32)for i,j in zip(*l))
```
[Try it online!](https://tio.run/##HcYxDsIwDADAr3hBtkNhKGIAiZ@wtERRHQU7csNQPh9Qp7u6tcV07Onx7GV6z3EK5Y54ziZKr8WJzCMJny4jh/15/@F2Pf5J5iBDBlH4SqVQmHt10QaJUDR@1uYbDoCzaUTuPw "Python 2 – Try It Online") | Dyalog APL, ~~36~~ ~~34~~ ~~33~~ ~~25~~ 24 bytes
================================================
```
{⎕UCS 32+95|×⌿32-⎕UCS↑⍵}
```
[Try it online (TryAPL)!](http://tryapl.org/?a=%7B%u2395UCS%2032+95%7C%D7%u233F32-%u2395UCS%u2191%u2375%7D%27split%27%20%27isbn%27&run)
[Try it online (TIO)!](https://tio.run/##Tc@xTsMwEAbgPU9x7WIk1KUtAwxdGBBDpgqJrUpqK7V0tYNzFgrQtRNFdEA8CQsLA2/iFwl26UW9xefv/pPsosaRbAu0VdetPdIibN@fw9vH3fUcJuPzy4uX38/w@jMZj/4xbPdh97XJUjZFDzsQdt9Ju07opjQCkoJoatQkMsH3k/YWpDVCEKwLIuXiBE6LY7kCozStlIOrsxgqPUFaHXBgwBWHD96SangyPFTkR2sl48qbyrURyRUtY/Wk60jaSN@Q67m0RkaufYl6yUgWMaJLx5FkCpiIN/f9s1KbiSkgIkwZ@ZqJfDbL@y@m/g8)
Input is a list of strings, and has trailing whitespace.
Here's how it works:
```
{⎕UCS 32+95|×⌿32-⎕UCS↑⍵}
↑⍵ - the input as a 2d array
⎕UCS - codepoints
32- - subtract 32
×⌿ - element wise product reduction ([a,b]=>a×b)
95| - Modulo 95
32+ - Add 32
⎕UCS - Unicode characters
``` |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes
===============================================================
```
.BÇ32-`*₃%32+çJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fz@lwu7GRboLWo6ZmVWMj7cPLvf7/j1YvLsjJLEkuSqyqzElMyUwtzk3MTs1NBQlkphap66hnFiflqcdyAQA "05AB1E – Try It Online")
-1 for Emigna pointing out `₃` pushes `95`.
---
```
# ['hi', 'you']
.B # [['hi ', 'you']]
Ç # [[[104, 105, 32], [121, 111, 117]]]
32- # [[[72, 73, 0], [89, 79, 85]]]
` # [[72, 73, 0], [89, 79, 85]]
* # [[6408, 5767, 0]]
₃% # [[43, 67, 0]]
32+ # [[75, 99, 32]]
ç # [['K', 'c', ' ']]
J # ['Kc ']
```
---
```
.BÇ32-`*95%žQsèJ
```
is another. | Common Lisp, 99 bytes
=====================
```
(lambda(a b)(map'string(lambda(x y)(code-char(+(mod(*(-(#1=char-code x)32)(-(#1#y)32))95)32)))a b))
```
[Try it online!](https://tio.run/##NcxBCoMwFATQq3ziwvmWLKp00YWH@SZFBWNCtNScPjWCqxnewJhl3kJGiPO6EzIWcYMVCA0MJ6He9nMZbz4oMYy3H20miXjAeYsGGtWzL6LLRgd3LV9YpVL5/bqCyytn9fPeKlLTdx1jUqf8AQ) |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [MATL](https://github.com/lmendo/MATL), 12 bytes
================================================
```
c32-p95\32+c
```
[**Try it online!**](https://tio.run/##y00syfn/P9nYSLfA0jTG2Eg7@f//avXigpzMEnUdBfXM4qQ89VoA "MATL – Try It Online")
### Explanation
```
c % Implicitly input cell array of 2 strings. Convert to 2-row char matrix.
% This pads the shorter string with spaces
32- % Subtract 32, element-wise. Each char is interpreted as its ASCII code.
% Note that padding spaces will give 0.
p % Product of each column. Since (padding) spaces have been mapped to 0, the
% product effectively eliminates those colums. So the effect is the same as
% if string length had been limited by the shorter one
95\ % Modulo 95, element-wise
32+ % Add 32, element-wise
c % Convert to char. Implicitly display
``` | [Factor](https://factorcode.org/), 39 bytes
===========================================
```
[ [ [ 32 - ] bi@ * 95 mod 32 + ] 2map ]
```
[Try it online!](https://tio.run/##HY4xC8IwFIR3f8WRRVB0qDioIG7SxUWcpEOaPjHYJjHvOUjpb4@J3PR93ME9tBEf0@1aX857aGZvGC@KjnoMWp4IkUS@IVonYHp/yBliHGYjRijLrVNQHHorClNRGWt03s2l7IVi8VO6o2RTYYUGrT1hgd0Wg@@KW2ZXDTqgSWNu/18cC6/TDw "Factor – Try It Online")
Explanation:
------------
This is a quotation (anonymous function) that takes two strings from the data stack and leaves one string on the data stack. In Factor, strings are just sequences of unicode code points and can be manipulated like any other sequence.
* Assuming a data stack that looks like `"split" "isbn"` when this function is called...
* `[ [ 32 - ] bi@ * 95 mod 32 + ]` push a quotation to the data stack (to be used later by `2map`) `"split" "isbn" [ [ 32 - ] bi@ * 95 mod 32 + ]`
* `2map` map over two sequences, combining them into one sequence with the given quotation which has stack effect `( x x -- x )`.
* At the beginning of the first iteration of `2map`, the data stack looks like this: `115 105`
* `[ 32 - ]` push a quotation to the data stack to be used later by the word `bi@`. `115 105 [ 32 - ]`
* `bi@` apply a quotation to the object on top of the data stack *and* the second-top object on the data stack `83 73`
* `*` multiply top two objects on the data stack `6059`
* `95` push `95` to the data stack `6059 95`
* `mod` reduce NOS (next on stack) modulo TOS (top of stack) `74`
* `32` push `32` to the data stack `74 32`
* `+` add top two objects on the data stack `106`
* So, at the end of the quotation to `2map`, we are left with `106`, which is the code point for `'j'`, which is the first element of the output sequence. The quotation given to `2map` will be run on each pair of elements until one of the two sequences no longer has any elements, meaning the output sequence will have the same size as the shorter of the two input sequences. |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes
=================================================================
```
z⁶O_32P€‘ịØṖ
```
[Try it online!](https://tio.run/##ATIAzf9qZWxsef//euKBtk9fMzJQ4oKs4oCY4buLw5jhuZb///9bJ3NwbGl0JywgJ2lzYm4nXQ "Jelly – Try It Online")
-3 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). | [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 52 bytes
================================================================
```
[,:$#'"!MIN$take"![CS#.toarr]"!32-prod 95%32+#:''#`]
```
[Try it online!](https://tio.run/##bZExT8MwEIX3/opLUnSJ2magZcBDhcSAOoSFBalUIqnd1qqJjXMWKn8@JIU2ccSTPPjpe3enu4ry7VHwul5P2TjCMMhWz2PKjyIM1o8vUUo6t3YTBvPbmbGaw/3dzfx2EjHE6H1TP7DdaBTH8CesjJKE0BPKqigxGUEMnu1Bv85/EK6A6xKR4CMnEvYM@dn2h5mAUkg6CAssvlbCwhG0FYJLBIOL@u3w02kSVa8uhmf5M@GX1rwPHVy5t6cBRDY/@SvYf0vTQShL7iqyA6jQJfdmMq5QcutDpJUatLOt1UN4GxtuHJ9eg8HWWqeDcAFKKVh00NXx22XLZebPdHaSBNbAIE1T2MEUNs25DMQx5s0Ji@ZpR8YRJs3xZp2QsSb4BpMJcFmZ@gc "Stacked – Try It Online")
Function that takes two arguments from the stack.
Explanation
-----------
```
[,:$#'"!MIN$take"![CS#.toarr]"!32-prod 95%32+#:''#`]
```
Let's look at the first part, assuming the top two items are `'split'` and `'isbn'`:
```
,:$#'"!MIN$take"! stack: ('split' 'isbn')
, pair top two: (('split' 'isbn'))
: duplicate: (('split' 'isbn') ('split' 'isbn'))
$#' length function literal: (('split' 'isbn') ('split' 'isbn') $#')
"! execute on each: (('split' 'isbn') (5 4))
MIN obtain the minimum: (('split' 'isbn') 4)
$take "take" function literal: (('split' 'isbn') 4 $take)
(e.g. `'asdf' 2 take` is `'as'`)
"! vectorized binary each: (('spli' 'isbn'))
```
This part performs the cropping.
Then:
```
[CS#.toarr]"! stack: (('spli' 'isbn'))
[ ]"! perform the inside on each string
string `'spli'`:
CS convert to a character string: $'spli'
#. vectorized "ord": (115 112 108 105)
toarr convert to array: (115 112 108 105)
(needed for empty string, since `$'' #.` == `$''` not `()`
```
Then, the last part:
```
32-prod 95%32+#:''#` stack: (((115 112 108 105) (105 115 98 110)))
32- subtract 32 from each character code: (((83 80 76 73) (73 83 66 78)))
prod reduce multiplication over the array: ((6059 6640 5016 5694))
95% modulus 95: ((74 85 76 89))
32+ add 32: ((106 117 108 121))
#: convert to characters: (('j' 'u' 'l' 'y'))
''#` join: ('july')
``` |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [Red](http://www.red-lang.org), 81 bytes
========================================
```red
func[a b][repeat i min length? a length? b[prin a/:i - 32 *(b/:i - 32)% 95 + 32]]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OlEhKTa6KLUgNbFEIVMhNzNPISc1L70kw14hEc5Kii4oAkok6ltlKugqGBspaGkkwdiaqgqWpgraQFZs7P80BaXigpzMEiUFpczipDyl/wA "Red – Try It Online") | JavaScript (ES6), 89 bytes
==========================
Javascript and the curse of the lengthy function names ...
Using currying and the fact that `charCodeAt` returns `NaN` when called with an invalid position. There can be trailing nulls in the output.
```
a=>b=>a.replace(/./g,(c,i)=>String.fromCharCode((z=x=>x.charCodeAt(i)-32)(a)*z(b)%95+32))
```
**Test**
```js
var f=
a=>b=>a.replace(/./g,(c,i)=>String.fromCharCode((z=x=>x.charCodeAt(i)-32)(a)*z(b)%95+32))
q=x=>'['+x+']'
;[["isbn", "split"],["", ""],["", "I don't matter"],[" ", "Me neither :("],
["but I do!", "!!!!!!!!!"],['quotes', '""""""'],["wood", "hungry"],["tray", "gzip"],
["industry", "bond"],["public", "toll"],["roll", "dublin"],["GX!", "GX!"],
["4 lll 4", "4 lll 4"],["M>>M", "M>>M"]]
.forEach(([a,b])=>console.log(q(a)+' x '+q(b)+' --> '+q(f(a)(b))))
``` |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | [Python 2](https://docs.python.org/2/), ~~75~~ 70 bytes
=======================================================
*-3 bytes thanks to Dennis' suggestion of shooqie's suggestion. -2 bytes thanks to Zacharý's suggestion.*
```python
lambda*l:''.join(chr((ord(i)-32)*(ord(j)-32)%95+32)for i,j in zip(*l))
```
[Try it online!](https://tio.run/##HcYxDsIwDADAr3hBtkNhKGIAiZ@wtERRHQU7csNQPh9Qp7u6tcV07Onx7GV6z3EK5Y54ziZKr8WJzCMJny4jh/15/@F2Pf5J5iBDBlH4SqVQmHt10QaJUDR@1uYbDoCzaUTuPw "Python 2 – Try It Online") | C#, 166 bytes
=============
```c#
using System.Linq;s=>t=>{int e=s.Length,n=t.Length,l=e>n?n:e;return string.Concat(s.Substring(0,l).Select((c,i)=>(char)((((c-32)*(t.Substring(0,l)[i]-32))%95)+32)));}
```
I'm sure there's a lot of golfing to be done but I don't have time right now.
[Try it online!](https://tio.run/##ZVDBTsMwDL3nK6JKSAl0EQJxgJJwQOI0JEQPHBCHLPO2SJkLtYuEpn57SVcmMXgX2@/52bIDzbYNNkNHEdey/iKGbSV@V2Ye8aMSIiRPJJ/ETsgMYs8xyM8mLuWjj6j0np7EEQ8dhlviNg8qj4spOidX0sqBrGPrdhFZgiUzB1zzpkTLhzRZcHiHN1C1wF2LP35z32DwrMjU3WKi1HmZtKkhQWClQhm1dSpsfKtVRphdXuhTxX/6X@PbKOiT6yt9Nia66od87uGOvIaaBOaljQz5FaCO969UQe8pcqFVEWmBxTjhv/0Z/HLvzuLI96IfvgE "C# (Mono) – Try It Online")
Full/Formatted Version:
```c#
using System;
using System.Linq;
class P
{
static void Main()
{
Func<string, Func<string, string>> f = s => t =>
{
int e = s.Length, n = t.Length, l = e > n ? n : e;
return string.Concat(s.Substring(0, l).Select((c, i) => (char)((((c - 32) * (t.Substring(0, l)[i] - 32)) % 95) + 32)));
};
Console.WriteLine(string.Concat(f("split")("isbn")));
Console.ReadLine();
}
}
``` |
133,767 | Inspired by [this](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) challenge (thanks @cairdcoinheringaahing for the title!), your task is to take two printable ASCII strings and multiply them element-wise with the following rules.
### How does it work?
Given two strings (for example `split` and `isbn`) you will first, truncate the longer one such that they have equal length and then determine their [ASCII codes](https://en.wikipedia.org/wiki/ASCII#Printable_characters):
```
split -> spli -> [115, 112, 108, 105]
isbn -> isbn -> [105, 115, 98, 110]
```
The next step will be to map them to the range `[0..94]` by subtracting `32` of each code:
```
[115, 112, 108, 105] -> [83, 80, 76, 73]
[105, 115, 98, 110] -> [73, 83, 66, 78]
```
Now you will multiply them element-wise modulo `95` (to stay in the printable range):
```
[83, 80, 76, 73] ⊗ [73, 83, 66, 78] -> [74, 85, 76, 89]
```
Add `32` to get back to the range `[32..126]`:
```
[74, 85, 76, 89] -> [106, 117, 108, 121]
```
And the final step is to map them back to ASCII characters:
```
[106, 117, 108, 121] -> "july"
```
### Rules
* You will write a program/function that implements the described steps on two strings and either prints or returns the resulting string
* The input format is flexible: you can take two strings, a tuple of strings, list of strings etc.
* The input may consist of one or two empty strings
* The input will be characters in the printable range (`[32..126]`)
* The output is either printed to the console or you return a string
* The output is allowed to have trailing whitespaces
### Test cases
```
"isbn", "split" -> "july"
"", "" -> ""
"", "I don't matter" -> ""
" ", "Me neither :(" -> " "
"but I do!", "!!!!!!!!!" -> "but I do!"
'quotes', '""""""' -> 'ck_iKg'
"wood", "hungry" -> "yarn"
"tray", "gzip" -> "jazz"
"industry", "bond" -> "drop"
"public", "toll" -> "fall"
"roll", "dublin" -> "ball"
"GX!", "GX!" -> "!!!"
"4 lll 4", "4 lll 4" -> "4 lll 4"
"M>>M", "M>>M" -> ">MM>"
```
**Note**: The quotes are just for readability, in the 6th test case I used `'` instead of `"`. | 2017/07/21 | [
"https://codegolf.stackexchange.com/questions/133767",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/48198/"
] | Mathematica, 114 bytes
======================
```
(a=Min@StringLength[x={##}];FromCharacterCode[Mod[Times@@(#-32&/@ToCharacterCode/@(StringTake[#,a]&/@x)),95]+32])&
```
**input**
>
> ["public","toll"]
>
>
> | [Factor](http://factorcode.org), 45
===================================
```
[ [ [ 32 - ] bi@ * 95 mod 32 + ] "" 2map-as ]
```
It's a quotation (lambda), `call` it with two strings on the stack, leaves the new string on the stack.
As a word:
```
: s* ( s1 s2 -- ps ) [ [ 32 - ] bi@ * 95 mod 32 + ] "" 2map-as ;
"M>>M" "M>>M" s* ! => ">MM>"
dup s* ! => "M>>M"
dup s* ! => ">MM>"
...
``` |
26,642,767 | I am trying to insert some rows to a PRODUCT table and I get an ORA\_00913: too many values
at first and third line, column 13
insert into PRODUCT (prod\_id, group\_id, prod\_name, price)
values ('000004', '0000045666', 'lampaan', 95,15);
insert into PRODUCT (prod\_id, group\_id, prod\_name, price)
values ('000005', '0000045667', 'golvlampaan', 111,55);
Could anyone help me?
Thanks!! | 2014/10/29 | [
"https://Stackoverflow.com/questions/26642767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4062211/"
] | You want to place the last condition at the top.
```
//CHECK EACH ONE AND ADD IT TO THE APPROPRIATE BUCKET
while (scoreFile >> score)
{
if (score < 0 || score > 200)
bucket[8]++;
else if (score <= 24)
bucket[0]++;
else if (score <= 49)
bucket[1]++;
else if (score <= 74)
bucket[2]++;
else if (score <= 99)
bucket[3]++;
else if (score <= 124)
bucket[4]++;
else if (score <= 149)
bucket[5]++;
else if (score <= 174)
bucket[6]++;
else if (score <= 200)
bucket[7]++;
scoreRow++;
}
``` | Each score here can only go into one bucket. If score < 0, it will be evaluated by the first if statement and placed in that bucket.
So your last else if() will only catch values over 200, and if you have have any negative scores, they'll all land in the first bucket. |
8,886,296 | I have a Datagridview which I populate from a Dataset created from an XML file. This part works and I can get the entire contents of the Dataset to display in a datagrid. I have the added functionality to filter the datagridview based upon a date and sold flag. This also works OK as the datagridview updates as you cycle through the dates. However I need to do some calculations on the "filtered" datagridview. These calculations are need to convert various currencies into GBP. So after some research on the best way to do this I decided to loop through the visible datagridview and test each of the visible. This is the code I cam up with. Unfortunately when run it all the tests fail and it try to carry out the else clause which then fails with a "Input string was not in a correct format" Exception. However I do not think that is the issue as I put a watch on the Price and Currency values and they "Do not Exist in the current Context"...now im stuck and would appreciate some help. Perhaps im going about this wrong way...
Thanks
Harry
```
for (int i = 1; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1["currency", i].ToString() == "USD")
{
myCommission += double.Parse(dataGridView1["commission", i].ToString()) * (double.Parse(dataGridView1["price", i].ToString()) * UStoGB);
}
else if (dataGridView1["currency", i].ToString() == "EURO")
{
myCommission += double.Parse(dataGridView1["commission", i].ToString()) * (double.Parse(dataGridView1["price", i].ToString()) * EUtoGB);
}
else
{
myCommission += double.Parse(dataGridView1["commission", i].ToString()) * double.Parse(dataGridView1["price", i].ToString());
}
}
``` | 2012/01/16 | [
"https://Stackoverflow.com/questions/8886296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152667/"
] | `map.input.file` environment parameter has the file name which the mapper is processing. Get this value in the mapper and use this as the output key for the mapper and then all the k/v from a single file to go to one reducer.
The code in the mapper. BTW, I am using the old MR API
```
@Override
public void configure(JobConf conf) {
this.conf = conf;
}
@Override.
public void map(................) throws IOException {
String filename = conf.get("map.input.file");
output.collect(new Text(filename), value);
}
```
And use MultipleOutputFormat, this allows to write multiple output files for the job. The file names can be derived from the output keys and values. | Hadoop 'chunks' data into blocks of a configured size. Default is 64MB blocks. You may see where this causes issues for your approach; Each mapper may get only a piece of a file. If the file is less than 64MB (or whatever value is configured), then each mapper will get only 1 file.
I've had a very similar constraint; I needed a set of files (output from previous reducer in chain) to be entirely processed by a single mapper. I use the <64MB fact in my solution
The main thrust of my solution is that I set it up to provide the mapper with the file name it needed to process, and internal to the mapper had it load/read the file. This allows a single mapper to process an entire file - It's not distributed processing of the file, but with the constraint of "I don't want individual files distributed" - it works. :)
I had the process that launched my MR write out the file names of the files to process into individual files. Where those files were written was the input directory. As each file is <64MB, then a single mapper will be generated for each file. The `map` process will be called exactly once (as there is only 1 entry in the file).
I then take the value passed to the mapper and can open the file and do whatever mapping I need to do.
Since hadoop tries to be smart about how it does Map/Reduce processes, it may be required to specify the number of reducers to use so that each mapper goes to a single reducer. This can be set via the `mapred.reduce.tasks` configuration. I do this via `job.setNumReduceTasks("mapred.reduce.tasks",[NUMBER OF FILES HERE]);`
My process had some additional requirements/constraints that may have made this specific solution appealing; but for an example of a 1:in to 1:out; I've done it, and the basics are laid out above.
HTH |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | Using the position occupied by the terms $1000$ we can write the determinant in a nicer way
$$\left| \begin{array}{ccc}
1 & 1000 & 2 & 3 &4\\
5 & 6 &7&1000 &8\\
1000&9&8&7&6\\
5 & 4&3&2&1000\\
1&2&1000&3&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
1000 & 1 & 2 & 3 &4\\
6 & 5 &7&1000 &8\\
9& 1000&8&7&6\\
4 & 5&3&2&1000\\
2&1&1000&3&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
1000 & 3 & 2 & 3 &4\\
6 & 1000 &7&5 &8\\
9& 7 &8&1000&6\\
4 & 2&3&5&1000\\
2&3&1000&1&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
1000 & 3 & 3 & 2 &4\\
6 & 1000 &5&7 &8\\
9& 7 &1000&8&6\\
4 & 2&5&3&1000\\
2&3&1&1000&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
1000 & 3 & 3 & 4 &2\\
6 & 1000 &5&8 &7\\
9& 7 &1000&6&8\\
4 & 2&5&1000&3\\
2&3&1&4&1000\\ \end{array} \right|=10^{15}+x.$$
Now, having in mind that in a determinant of a matrix of order $5$ there are $120$ terms and one of them is $10^{15}$ we can bound $x.$ Indeed, we have that
$$x>-119 \cdot 1000^3\cdot 9\cdot 8= -8568\cdot 10^9.$$
So,
$$10^{15}+x>10^{15}-8568\cdot 10^9>0.$$ | With an even number of adjacent row swaps, you can put the $1000$s on the diagonal. That determinant must be positive. Using the algorithm which looks at minors, the largest term is always positive. |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | Expand the determinant as a sum of $120$ terms, each being a product of $5$ factors. (That is, *imagine* you expand it; don't write it out. . . )
All these terms will be positive; then $60$ of them will be added and $60$ will be subtracted. Just one of the terms will be $1000^5$, and by checking the permutation you can see that it will have a positive coefficient.
Every other term will be at most $1000^3\times8\times9$; since exactly $60$ of these terms will be subtracted, we have
$$\eqalign{D
&\ge1000^5-60\times1000^3\times8\times9\cr
&>1000^5-100\times1000^3\times10\times10\cr
&=990\times1000^4\ .\cr}$$ | With an even number of adjacent row swaps, you can put the $1000$s on the diagonal. That determinant must be positive. Using the algorithm which looks at minors, the largest term is always positive. |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | By definition, the determinant is the sum of $60$ positive and $60$ negative terms, one of which is $\mbox{sgn}{\left(
\begin{array}{ccccc}
1 & 2 & 3 & 4 & 5 \\
3 & 1 & 5 & 2 & 4 \\
\end{array}
\right)}(1000)^5=\mbox{sgn}\left((13542)\right)(1000)^5=+(1000)^5$.
Each of the other terms has absolute value at most $9\cdot1000^4$, so the sum of the 60 negative terms is greater than or equal to $-60\cdot9\cdot1000^4$, and the determinant is greater than or equal to $(1000)^5-60\cdot9\cdot1000^4$, which is positive. | With an even number of adjacent row swaps, you can put the $1000$s on the diagonal. That determinant must be positive. Using the algorithm which looks at minors, the largest term is always positive. |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | Using the position occupied by the terms $1000$ we can write the determinant in a nicer way
$$\left| \begin{array}{ccc}
1 & 1000 & 2 & 3 &4\\
5 & 6 &7&1000 &8\\
1000&9&8&7&6\\
5 & 4&3&2&1000\\
1&2&1000&3&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
1000 & 1 & 2 & 3 &4\\
6 & 5 &7&1000 &8\\
9& 1000&8&7&6\\
4 & 5&3&2&1000\\
2&1&1000&3&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
1000 & 3 & 2 & 3 &4\\
6 & 1000 &7&5 &8\\
9& 7 &8&1000&6\\
4 & 2&3&5&1000\\
2&3&1000&1&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
1000 & 3 & 3 & 2 &4\\
6 & 1000 &5&7 &8\\
9& 7 &1000&8&6\\
4 & 2&5&3&1000\\
2&3&1&1000&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
1000 & 3 & 3 & 4 &2\\
6 & 1000 &5&8 &7\\
9& 7 &1000&6&8\\
4 & 2&5&1000&3\\
2&3&1&4&1000\\ \end{array} \right|=10^{15}+x.$$
Now, having in mind that in a determinant of a matrix of order $5$ there are $120$ terms and one of them is $10^{15}$ we can bound $x.$ Indeed, we have that
$$x>-119 \cdot 1000^3\cdot 9\cdot 8= -8568\cdot 10^9.$$
So,
$$10^{15}+x>10^{15}-8568\cdot 10^9>0.$$ | You can use 1000 in every row to eliminate the other element to get an upper triangular matrix, and in the process for 1000 is large enough, you can reckon the element in other column won't change. Then you can get the elements on the diagonal all are1000, which shows the determinant is positive.` |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | Expand the determinant as a sum of $120$ terms, each being a product of $5$ factors. (That is, *imagine* you expand it; don't write it out. . . )
All these terms will be positive; then $60$ of them will be added and $60$ will be subtracted. Just one of the terms will be $1000^5$, and by checking the permutation you can see that it will have a positive coefficient.
Every other term will be at most $1000^3\times8\times9$; since exactly $60$ of these terms will be subtracted, we have
$$\eqalign{D
&\ge1000^5-60\times1000^3\times8\times9\cr
&>1000^5-100\times1000^3\times10\times10\cr
&=990\times1000^4\ .\cr}$$ | You can use 1000 in every row to eliminate the other element to get an upper triangular matrix, and in the process for 1000 is large enough, you can reckon the element in other column won't change. Then you can get the elements on the diagonal all are1000, which shows the determinant is positive.` |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | By definition, the determinant is the sum of $60$ positive and $60$ negative terms, one of which is $\mbox{sgn}{\left(
\begin{array}{ccccc}
1 & 2 & 3 & 4 & 5 \\
3 & 1 & 5 & 2 & 4 \\
\end{array}
\right)}(1000)^5=\mbox{sgn}\left((13542)\right)(1000)^5=+(1000)^5$.
Each of the other terms has absolute value at most $9\cdot1000^4$, so the sum of the 60 negative terms is greater than or equal to $-60\cdot9\cdot1000^4$, and the determinant is greater than or equal to $(1000)^5-60\cdot9\cdot1000^4$, which is positive. | You can use 1000 in every row to eliminate the other element to get an upper triangular matrix, and in the process for 1000 is large enough, you can reckon the element in other column won't change. Then you can get the elements on the diagonal all are1000, which shows the determinant is positive.` |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | Using the position occupied by the terms $1000$ we can write the determinant in a nicer way
$$\left| \begin{array}{ccc}
1 & 1000 & 2 & 3 &4\\
5 & 6 &7&1000 &8\\
1000&9&8&7&6\\
5 & 4&3&2&1000\\
1&2&1000&3&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
1000 & 1 & 2 & 3 &4\\
6 & 5 &7&1000 &8\\
9& 1000&8&7&6\\
4 & 5&3&2&1000\\
2&1&1000&3&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
1000 & 3 & 2 & 3 &4\\
6 & 1000 &7&5 &8\\
9& 7 &8&1000&6\\
4 & 2&3&5&1000\\
2&3&1000&1&4\\ \end{array} \right|=-\left| \begin{array}{ccc}
1000 & 3 & 3 & 2 &4\\
6 & 1000 &5&7 &8\\
9& 7 &1000&8&6\\
4 & 2&5&3&1000\\
2&3&1&1000&4\\ \end{array} \right|\\=\left| \begin{array}{ccc}
1000 & 3 & 3 & 4 &2\\
6 & 1000 &5&8 &7\\
9& 7 &1000&6&8\\
4 & 2&5&1000&3\\
2&3&1&4&1000\\ \end{array} \right|=10^{15}+x.$$
Now, having in mind that in a determinant of a matrix of order $5$ there are $120$ terms and one of them is $10^{15}$ we can bound $x.$ Indeed, we have that
$$x>-119 \cdot 1000^3\cdot 9\cdot 8= -8568\cdot 10^9.$$
So,
$$10^{15}+x>10^{15}-8568\cdot 10^9>0.$$ | By definition, the determinant is the sum of $60$ positive and $60$ negative terms, one of which is $\mbox{sgn}{\left(
\begin{array}{ccccc}
1 & 2 & 3 & 4 & 5 \\
3 & 1 & 5 & 2 & 4 \\
\end{array}
\right)}(1000)^5=\mbox{sgn}\left((13542)\right)(1000)^5=+(1000)^5$.
Each of the other terms has absolute value at most $9\cdot1000^4$, so the sum of the 60 negative terms is greater than or equal to $-60\cdot9\cdot1000^4$, and the determinant is greater than or equal to $(1000)^5-60\cdot9\cdot1000^4$, which is positive. |
1,039,031 | HW Problem here, not sure where I'm messing up.
Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses.
So I calculated:
$E(x) = 100\frac{18}{38} = \frac{900}{19}$
$var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$
$\sigma = \sqrt{\frac{9000}{361}} = 4.993...$
Then this is what I was thinking:
$P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$
Which would give
$\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$
Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$
However I know from the back of the book it should be $.6808$. So where am I going wrong?
EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any. | 2014/11/26 | [
"https://math.stackexchange.com/questions/1039031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180176/"
] | Expand the determinant as a sum of $120$ terms, each being a product of $5$ factors. (That is, *imagine* you expand it; don't write it out. . . )
All these terms will be positive; then $60$ of them will be added and $60$ will be subtracted. Just one of the terms will be $1000^5$, and by checking the permutation you can see that it will have a positive coefficient.
Every other term will be at most $1000^3\times8\times9$; since exactly $60$ of these terms will be subtracted, we have
$$\eqalign{D
&\ge1000^5-60\times1000^3\times8\times9\cr
&>1000^5-100\times1000^3\times10\times10\cr
&=990\times1000^4\ .\cr}$$ | By definition, the determinant is the sum of $60$ positive and $60$ negative terms, one of which is $\mbox{sgn}{\left(
\begin{array}{ccccc}
1 & 2 & 3 & 4 & 5 \\
3 & 1 & 5 & 2 & 4 \\
\end{array}
\right)}(1000)^5=\mbox{sgn}\left((13542)\right)(1000)^5=+(1000)^5$.
Each of the other terms has absolute value at most $9\cdot1000^4$, so the sum of the 60 negative terms is greater than or equal to $-60\cdot9\cdot1000^4$, and the determinant is greater than or equal to $(1000)^5-60\cdot9\cdot1000^4$, which is positive. |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | It pretty simple to respond orientation change in react native. Every view in react native have a listener called **onLayout** which get invoked upon orientation change. We just need to implement this. It's better to store dimension in state variable and update on each orientation change so that re-rendering happens after change. Other wise we need to reload the view to respond the orientation change.
[](https://i.stack.imgur.com/omHkY.gif)
```
import React, { Component } from "react";
import { StyleSheet, Text, View, Image, Dimensions } from "react-native";
var { height, width } = Dimensions.get("window");
export default class Com extends Component {
constructor() {
console.log("constructor");
super();
this.state = {
layout: {
height: height,
width: width
}
};
}
_onLayout = event => {
console.log(
"------------------------------------------------" +
JSON.stringify(event.nativeEvent.layout)
);
this.setState({
layout: {
height: event.nativeEvent.layout.height,
width: event.nativeEvent.layout.width
}
});
};
render() {
console.log(JSON.stringify(this.props));
return (
<View
style={{ backgroundColor: "red", flex: 1 }}
onLayout={this._onLayout}
>
<View
style={{
backgroundColor: "green",
height: this.state.layout.height - 10,
width: this.state.layout.width - 10,
margin: 5
}}
/>
</View>
);
}
}
``` | For anyone using [Exponent](https://getexponent.com/) you just need to remove the [`orientation`](https://docs.getexponent.com/versions/v14.0.0/guides/configuration.html#orientation) key from your `exp.json`. |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | You can use react-native-orientation to detect and perform changes on orientation change.
```
var Orientation = require('react-native-orientation');
```
Also use Dimension class which return size(width, height).
```
Dimensions.get('window')
```
Use these methods to play with orientations
```
componentDidMount() {
Orientation.lockToPortrait(); //this will lock the view to Portrait
//Orientation.lockToLandscape(); //this will lock the view to Landscape
//Orientation.unlockAllOrientations(); //this will unlock the view to all Orientations
// self = this;
console.log('componentDidMount');
Orientation.addOrientationListener(this._orientationDidChange);
}
componentWillUnmount() {
console.log('componentWillUnmount');
Orientation.getOrientation((err,orientation)=> {
console.log("Current Device Orientation: ", orientation);
});
Orientation.removeOrientationListener(this._orientationDidChange);
}
_orientationDidChange(orientation) {
console.log('Orientation changed to '+orientation);
console.log(self);
if (orientation == 'LANDSCAPE') {
//do something with landscape layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
} else {
//do something with portrait layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
}
self.setState({
screenWidth:screenWidth
});
}
```
I also used this but It's performance is too low.
Hope that helps... | For anyone using [Exponent](https://getexponent.com/) you just need to remove the [`orientation`](https://docs.getexponent.com/versions/v14.0.0/guides/configuration.html#orientation) key from your `exp.json`. |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | Neither `onLayout` or `Dimensions.addEventListener` worked for us in React 16.3.
Here's a flexbox hack which made the image resize on change of orientation. (We also used React's nice but poorly documented ImageBackground component to get text on top of the image):
```
<View style={styles.container}>
<View style={styles.imageRowWithResizeHack}>
<ImageBackground
style={styles.imageContainer}
imageStyle={styles.thumbnailImg}
source={{ uri: thumbnailUrl }}
>
<View style={styles.imageText}>
<Text style={styles.partnerName}>{partnerName}</Text>
<Text style={styles.title}>{title.toUpperCase()}</Text>
</View>
</ImageBackground>
<View style={styles.imageHeight} />
</View>
</View>
const styles = StyleSheet.create({
container: {
position: 'relative',
flex: 1
},
imageRowWithResizeHack: {
flex: 1,
flexDirection: 'row'
},
imageContainer: {
flex: 1
},
imageHeight: {
height: 200
},
thumbnailImg: {
resizeMode: 'cover'
},
imageText: {
position: 'absolute',
top: 30,
left: TEXT_PADDING_LEFT
},
partnerName: {
fontWeight: '800',
fontSize: 20,
color: PARTNER_NAME_COLOR
},
title: {
color: COLOR_PRIMARY_TEXT,
fontSize: 90,
fontWeight: '700',
marginTop: 10,
marginBottom: 20
},
});
```
The `imageHeight` style will set the height of the View component (which is invisible to the user), and Flexbox will then automatically flex the image on the same row to be of the same height. So you're basically setting the height of the image in an indirect manner. Flex will ensure it flexes to fill the entire container on orientation change. | OK. I found an answer to this. Need to implement the following in our viewcontroller and call refresh our ReactNative view inside it.
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | For more recent versions of React Native, orientation change doesn't necessarily trigger onLayout, but `Dimensions` provides a more directly relevant event:
```
class App extends Component {
constructor() {
super();
this.state = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
};
Dimensions.addEventListener("change", (e) => {
this.setState(e.window);
});
}
render() {
return (
<View
style={{
width: this.state.width,
height: this.state.height,
}}
>
</View>
);
}
}
```
Note that this code is for the root component of an app. If using it deeper within the app, you will need to include a corresponding removeEventListener call. | You can use react-native-orientation to detect and perform changes on orientation change.
```
var Orientation = require('react-native-orientation');
```
Also use Dimension class which return size(width, height).
```
Dimensions.get('window')
```
Use these methods to play with orientations
```
componentDidMount() {
Orientation.lockToPortrait(); //this will lock the view to Portrait
//Orientation.lockToLandscape(); //this will lock the view to Landscape
//Orientation.unlockAllOrientations(); //this will unlock the view to all Orientations
// self = this;
console.log('componentDidMount');
Orientation.addOrientationListener(this._orientationDidChange);
}
componentWillUnmount() {
console.log('componentWillUnmount');
Orientation.getOrientation((err,orientation)=> {
console.log("Current Device Orientation: ", orientation);
});
Orientation.removeOrientationListener(this._orientationDidChange);
}
_orientationDidChange(orientation) {
console.log('Orientation changed to '+orientation);
console.log(self);
if (orientation == 'LANDSCAPE') {
//do something with landscape layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
} else {
//do something with portrait layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
}
self.setState({
screenWidth:screenWidth
});
}
```
I also used this but It's performance is too low.
Hope that helps... |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | Neither `onLayout` or `Dimensions.addEventListener` worked for us in React 16.3.
Here's a flexbox hack which made the image resize on change of orientation. (We also used React's nice but poorly documented ImageBackground component to get text on top of the image):
```
<View style={styles.container}>
<View style={styles.imageRowWithResizeHack}>
<ImageBackground
style={styles.imageContainer}
imageStyle={styles.thumbnailImg}
source={{ uri: thumbnailUrl }}
>
<View style={styles.imageText}>
<Text style={styles.partnerName}>{partnerName}</Text>
<Text style={styles.title}>{title.toUpperCase()}</Text>
</View>
</ImageBackground>
<View style={styles.imageHeight} />
</View>
</View>
const styles = StyleSheet.create({
container: {
position: 'relative',
flex: 1
},
imageRowWithResizeHack: {
flex: 1,
flexDirection: 'row'
},
imageContainer: {
flex: 1
},
imageHeight: {
height: 200
},
thumbnailImg: {
resizeMode: 'cover'
},
imageText: {
position: 'absolute',
top: 30,
left: TEXT_PADDING_LEFT
},
partnerName: {
fontWeight: '800',
fontSize: 20,
color: PARTNER_NAME_COLOR
},
title: {
color: COLOR_PRIMARY_TEXT,
fontSize: 90,
fontWeight: '700',
marginTop: 10,
marginBottom: 20
},
});
```
The `imageHeight` style will set the height of the View component (which is invisible to the user), and Flexbox will then automatically flex the image on the same row to be of the same height. So you're basically setting the height of the image in an indirect manner. Flex will ensure it flexes to fill the entire container on orientation change. | Appart from the answer given by user `Rajan Twanabashu` you can also use the [react-native-styleman](https://github.com/anubhavgupta/react-native-styleman) library to handle orientation change very easily:
Here is an example of how you would do that:
```js
import { withStyles } from 'react-native-styleman';
const styles = () => ({
container: {
// your common styles here for container node.
flex: 1,
// lets write a media query to change background color automatically based on the device's orientation
'@media': [
{
orientation: 'landscape', // for landscape
styles: { // apply following styles
// these styles would be applied when the device is in landscape
// mode.
backgroundColor: 'green'
//.... more landscape related styles here...
}
},
{
orientation: 'portrait', // for portrait
styles: { // apply folllowing styles
// these styles would be applied when the device is in portrait
// mode.
backgroundColor: 'red'
//.... more protrait related styles here...
}
}
]
}
});
let Component = ({ styles })=>(
<View style={styles.container}>
<Text>Some Text</Text>
</View>
);
// use `withStyles` Higher order Component.
Component = withStyles(styles)(Component);
export {
Component
};
``` |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | The simplest way is:
```
import React, { Component } from 'react';
import { Dimensions, View, Text } from 'react-native';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
}
this.onLayout = this.onLayout.bind(this);
}
onLayout(e) {
this.setState({
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
});
}
render() {
return(
<View
onLayout={this.onLayout}
style={{width: this.state.width}}
>
<Text>Layout width: {this.state.width}</Text>
</View>
);
}
}
``` | It pretty simple to respond orientation change in react native. Every view in react native have a listener called **onLayout** which get invoked upon orientation change. We just need to implement this. It's better to store dimension in state variable and update on each orientation change so that re-rendering happens after change. Other wise we need to reload the view to respond the orientation change.
[](https://i.stack.imgur.com/omHkY.gif)
```
import React, { Component } from "react";
import { StyleSheet, Text, View, Image, Dimensions } from "react-native";
var { height, width } = Dimensions.get("window");
export default class Com extends Component {
constructor() {
console.log("constructor");
super();
this.state = {
layout: {
height: height,
width: width
}
};
}
_onLayout = event => {
console.log(
"------------------------------------------------" +
JSON.stringify(event.nativeEvent.layout)
);
this.setState({
layout: {
height: event.nativeEvent.layout.height,
width: event.nativeEvent.layout.width
}
});
};
render() {
console.log(JSON.stringify(this.props));
return (
<View
style={{ backgroundColor: "red", flex: 1 }}
onLayout={this._onLayout}
>
<View
style={{
backgroundColor: "green",
height: this.state.layout.height - 10,
width: this.state.layout.width - 10,
margin: 5
}}
/>
</View>
);
}
}
``` |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | For more recent versions of React Native, orientation change doesn't necessarily trigger onLayout, but `Dimensions` provides a more directly relevant event:
```
class App extends Component {
constructor() {
super();
this.state = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
};
Dimensions.addEventListener("change", (e) => {
this.setState(e.window);
});
}
render() {
return (
<View
style={{
width: this.state.width,
height: this.state.height,
}}
>
</View>
);
}
}
```
Note that this code is for the root component of an app. If using it deeper within the app, you will need to include a corresponding removeEventListener call. | Appart from the answer given by user `Rajan Twanabashu` you can also use the [react-native-styleman](https://github.com/anubhavgupta/react-native-styleman) library to handle orientation change very easily:
Here is an example of how you would do that:
```js
import { withStyles } from 'react-native-styleman';
const styles = () => ({
container: {
// your common styles here for container node.
flex: 1,
// lets write a media query to change background color automatically based on the device's orientation
'@media': [
{
orientation: 'landscape', // for landscape
styles: { // apply following styles
// these styles would be applied when the device is in landscape
// mode.
backgroundColor: 'green'
//.... more landscape related styles here...
}
},
{
orientation: 'portrait', // for portrait
styles: { // apply folllowing styles
// these styles would be applied when the device is in portrait
// mode.
backgroundColor: 'red'
//.... more protrait related styles here...
}
}
]
}
});
let Component = ({ styles })=>(
<View style={styles.container}>
<Text>Some Text</Text>
</View>
);
// use `withStyles` Higher order Component.
Component = withStyles(styles)(Component);
export {
Component
};
``` |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | It pretty simple to respond orientation change in react native. Every view in react native have a listener called **onLayout** which get invoked upon orientation change. We just need to implement this. It's better to store dimension in state variable and update on each orientation change so that re-rendering happens after change. Other wise we need to reload the view to respond the orientation change.
[](https://i.stack.imgur.com/omHkY.gif)
```
import React, { Component } from "react";
import { StyleSheet, Text, View, Image, Dimensions } from "react-native";
var { height, width } = Dimensions.get("window");
export default class Com extends Component {
constructor() {
console.log("constructor");
super();
this.state = {
layout: {
height: height,
width: width
}
};
}
_onLayout = event => {
console.log(
"------------------------------------------------" +
JSON.stringify(event.nativeEvent.layout)
);
this.setState({
layout: {
height: event.nativeEvent.layout.height,
width: event.nativeEvent.layout.width
}
});
};
render() {
console.log(JSON.stringify(this.props));
return (
<View
style={{ backgroundColor: "red", flex: 1 }}
onLayout={this._onLayout}
>
<View
style={{
backgroundColor: "green",
height: this.state.layout.height - 10,
width: this.state.layout.width - 10,
margin: 5
}}
/>
</View>
);
}
}
``` | OK. I found an answer to this. Need to implement the following in our viewcontroller and call refresh our ReactNative view inside it.
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | You can use react-native-orientation to detect and perform changes on orientation change.
```
var Orientation = require('react-native-orientation');
```
Also use Dimension class which return size(width, height).
```
Dimensions.get('window')
```
Use these methods to play with orientations
```
componentDidMount() {
Orientation.lockToPortrait(); //this will lock the view to Portrait
//Orientation.lockToLandscape(); //this will lock the view to Landscape
//Orientation.unlockAllOrientations(); //this will unlock the view to all Orientations
// self = this;
console.log('componentDidMount');
Orientation.addOrientationListener(this._orientationDidChange);
}
componentWillUnmount() {
console.log('componentWillUnmount');
Orientation.getOrientation((err,orientation)=> {
console.log("Current Device Orientation: ", orientation);
});
Orientation.removeOrientationListener(this._orientationDidChange);
}
_orientationDidChange(orientation) {
console.log('Orientation changed to '+orientation);
console.log(self);
if (orientation == 'LANDSCAPE') {
//do something with landscape layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
} else {
//do something with portrait layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
}
self.setState({
screenWidth:screenWidth
});
}
```
I also used this but It's performance is too low.
Hope that helps... | Neither `onLayout` or `Dimensions.addEventListener` worked for us in React 16.3.
Here's a flexbox hack which made the image resize on change of orientation. (We also used React's nice but poorly documented ImageBackground component to get text on top of the image):
```
<View style={styles.container}>
<View style={styles.imageRowWithResizeHack}>
<ImageBackground
style={styles.imageContainer}
imageStyle={styles.thumbnailImg}
source={{ uri: thumbnailUrl }}
>
<View style={styles.imageText}>
<Text style={styles.partnerName}>{partnerName}</Text>
<Text style={styles.title}>{title.toUpperCase()}</Text>
</View>
</ImageBackground>
<View style={styles.imageHeight} />
</View>
</View>
const styles = StyleSheet.create({
container: {
position: 'relative',
flex: 1
},
imageRowWithResizeHack: {
flex: 1,
flexDirection: 'row'
},
imageContainer: {
flex: 1
},
imageHeight: {
height: 200
},
thumbnailImg: {
resizeMode: 'cover'
},
imageText: {
position: 'absolute',
top: 30,
left: TEXT_PADDING_LEFT
},
partnerName: {
fontWeight: '800',
fontSize: 20,
color: PARTNER_NAME_COLOR
},
title: {
color: COLOR_PRIMARY_TEXT,
fontSize: 90,
fontWeight: '700',
marginTop: 10,
marginBottom: 20
},
});
```
The `imageHeight` style will set the height of the View component (which is invisible to the user), and Flexbox will then automatically flex the image on the same row to be of the same height. So you're basically setting the height of the image in an indirect manner. Flex will ensure it flexes to fill the entire container on orientation change. |
29,914,585 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select option[text="Two"]'); //This selects by text
$('select option[value="4"]'); //This selects by value
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29914585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3658423/"
] | The simplest way is:
```
import React, { Component } from 'react';
import { Dimensions, View, Text } from 'react-native';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
}
this.onLayout = this.onLayout.bind(this);
}
onLayout(e) {
this.setState({
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
});
}
render() {
return(
<View
onLayout={this.onLayout}
style={{width: this.state.width}}
>
<Text>Layout width: {this.state.width}</Text>
</View>
);
}
}
``` | You can use react-native-orientation to detect and perform changes on orientation change.
```
var Orientation = require('react-native-orientation');
```
Also use Dimension class which return size(width, height).
```
Dimensions.get('window')
```
Use these methods to play with orientations
```
componentDidMount() {
Orientation.lockToPortrait(); //this will lock the view to Portrait
//Orientation.lockToLandscape(); //this will lock the view to Landscape
//Orientation.unlockAllOrientations(); //this will unlock the view to all Orientations
// self = this;
console.log('componentDidMount');
Orientation.addOrientationListener(this._orientationDidChange);
}
componentWillUnmount() {
console.log('componentWillUnmount');
Orientation.getOrientation((err,orientation)=> {
console.log("Current Device Orientation: ", orientation);
});
Orientation.removeOrientationListener(this._orientationDidChange);
}
_orientationDidChange(orientation) {
console.log('Orientation changed to '+orientation);
console.log(self);
if (orientation == 'LANDSCAPE') {
//do something with landscape layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
} else {
//do something with portrait layout
screenWidth=Dimensions.get('window').width;
console.log('screenWidth:'+screenWidth);
}
self.setState({
screenWidth:screenWidth
});
}
```
I also used this but It's performance is too low.
Hope that helps... |
4,185,231 | I had to extract the 2nd parameter (array) from an onclick attribute on an image, but jQuery just returned a function onclick and not its string value as expected. So I had to use a native method.
A quick search says it **may** work some browsers like FF, but not IE. I use Chrome.
```
<img src="path/pic.png" onclick="funcName(123456,[12,34,56,78,890]);" />
```
I thought this would work, but **it does not**:
```
var div = $('div_id');
var onclick_string = $(div).find('img').eq(0).attr('onclick');
var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit)
```
**This works**
```
var div = $('div_id');
var onclick_string = $(div).find('img')[0].getAttributeNode('onclick').value;
var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit)
```
Is there another way of getting the 2nd parameter ? | 2010/11/15 | [
"https://Stackoverflow.com/questions/4185231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52025/"
] | Why not store it in the data property?
```
<img src="path/pic.png" onclick="funcName(123456);" data-mydata='12,34,56,78,890' />
var div_data = $('div_id').data('mydata').split(',');
``` | **UPDATE**
I used the following code to loop through a collection of span tags and output their onclick strings. it's hacky but it works (firefox 7, JQuery 1.5.1). You can even override the string value.
```
$("span").each(function(index)
{
alert( $(this)[0].attributes.onclick.nodeValue );
});
``` |
39,443,875 | Is there a way to create/define a variable available to all php files(like superglobals)
>
> Example:
>
>
> i define a variable in **file1.php** `$car = ferrari`
>
>
> then in **file2.php** i write `echo $car;`
>
>
> then it will output `ferrari`
>
>
>
how can i define a variable in file1.php and access it in file2.php
**EDIT:**
The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it. | 2016/09/12 | [
"https://Stackoverflow.com/questions/39443875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4619900/"
] | Create one constant file and include it in file in where you want to access those constants.
Include file as
```
include 'file_path';
``` | Hi The best way to do this is,
You make a .php file called "defines.php" and make sure to include that file in your each .php files.
make your variables, constants sits in that file. So that you can access them.
Other method would be, you can set the values to a existing Global variable.
like,
`$_SERVER['car'] = "ferrari"`
Thanks. |
39,443,875 | Is there a way to create/define a variable available to all php files(like superglobals)
>
> Example:
>
>
> i define a variable in **file1.php** `$car = ferrari`
>
>
> then in **file2.php** i write `echo $car;`
>
>
> then it will output `ferrari`
>
>
>
how can i define a variable in file1.php and access it in file2.php
**EDIT:**
The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it. | 2016/09/12 | [
"https://Stackoverflow.com/questions/39443875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4619900/"
] | Create one constant file and include it in file in where you want to access those constants.
Include file as
```
include 'file_path';
``` | You can use `SESSION` or `include` concept.
1) By using `SESSION`
**file1.php**
```
session_start();
$_SESSION['car'] = 'ferrari';
```
**file2.php**
```
session_start();
echo $_SESSION['car']; //Result: ferrari
```
2) By using `include`
**file2.php**
```
include 'file1.php';
echo $car //Result: ferrari
``` |
39,443,875 | Is there a way to create/define a variable available to all php files(like superglobals)
>
> Example:
>
>
> i define a variable in **file1.php** `$car = ferrari`
>
>
> then in **file2.php** i write `echo $car;`
>
>
> then it will output `ferrari`
>
>
>
how can i define a variable in file1.php and access it in file2.php
**EDIT:**
The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it. | 2016/09/12 | [
"https://Stackoverflow.com/questions/39443875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4619900/"
] | * create init.php in your project's root directory.
If you need constant variable (so, you can't edit it)
- create constants.php in your project's root dir.
If you need editable variable
- create globals.php in your project's root dir.
**constants.php**
```
<?php
define('CAR', 'ferrari');
```
**globals.php**
```
<?php
class Globals
{
public static $car = 'ferrari';
}
```
include **constants.php** and **globals.php** to **init.php**.
```
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'constants.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'globals.php');
```
include **init.php** to php sources.
```
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'init.php');
```
If you need variable for long use, not only one pageload, then use session. (user logins, settings, ...)
```
<?php
$_SESSION['car'] = 'ferrari';
```
In your php sources, you can use constant and global variables:
Example:
```
<?php
echo CAR; //ferrari
echo Globals::$car; //ferrari
Globals::$car = 'renault'; //set your global variable
echo Globals::$car; //renault
```
**Refs:**
>
> <http://php.net/manual/en/language.oop5.static.php>
>
>
> <http://php.net/manual/en/function.define.php>
>
>
> <http://php.net/manual/en/function.dirname.php>
>
>
> <http://php.net/manual/en/reserved.variables.session.php>
>
>
> | Create one constant file and include it in file in where you want to access those constants.
Include file as
```
include 'file_path';
``` |
39,443,875 | Is there a way to create/define a variable available to all php files(like superglobals)
>
> Example:
>
>
> i define a variable in **file1.php** `$car = ferrari`
>
>
> then in **file2.php** i write `echo $car;`
>
>
> then it will output `ferrari`
>
>
>
how can i define a variable in file1.php and access it in file2.php
**EDIT:**
The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it. | 2016/09/12 | [
"https://Stackoverflow.com/questions/39443875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4619900/"
] | * create init.php in your project's root directory.
If you need constant variable (so, you can't edit it)
- create constants.php in your project's root dir.
If you need editable variable
- create globals.php in your project's root dir.
**constants.php**
```
<?php
define('CAR', 'ferrari');
```
**globals.php**
```
<?php
class Globals
{
public static $car = 'ferrari';
}
```
include **constants.php** and **globals.php** to **init.php**.
```
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'constants.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'globals.php');
```
include **init.php** to php sources.
```
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'init.php');
```
If you need variable for long use, not only one pageload, then use session. (user logins, settings, ...)
```
<?php
$_SESSION['car'] = 'ferrari';
```
In your php sources, you can use constant and global variables:
Example:
```
<?php
echo CAR; //ferrari
echo Globals::$car; //ferrari
Globals::$car = 'renault'; //set your global variable
echo Globals::$car; //renault
```
**Refs:**
>
> <http://php.net/manual/en/language.oop5.static.php>
>
>
> <http://php.net/manual/en/function.define.php>
>
>
> <http://php.net/manual/en/function.dirname.php>
>
>
> <http://php.net/manual/en/reserved.variables.session.php>
>
>
> | Hi The best way to do this is,
You make a .php file called "defines.php" and make sure to include that file in your each .php files.
make your variables, constants sits in that file. So that you can access them.
Other method would be, you can set the values to a existing Global variable.
like,
`$_SERVER['car'] = "ferrari"`
Thanks. |
39,443,875 | Is there a way to create/define a variable available to all php files(like superglobals)
>
> Example:
>
>
> i define a variable in **file1.php** `$car = ferrari`
>
>
> then in **file2.php** i write `echo $car;`
>
>
> then it will output `ferrari`
>
>
>
how can i define a variable in file1.php and access it in file2.php
**EDIT:**
The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it. | 2016/09/12 | [
"https://Stackoverflow.com/questions/39443875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4619900/"
] | * create init.php in your project's root directory.
If you need constant variable (so, you can't edit it)
- create constants.php in your project's root dir.
If you need editable variable
- create globals.php in your project's root dir.
**constants.php**
```
<?php
define('CAR', 'ferrari');
```
**globals.php**
```
<?php
class Globals
{
public static $car = 'ferrari';
}
```
include **constants.php** and **globals.php** to **init.php**.
```
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'constants.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'globals.php');
```
include **init.php** to php sources.
```
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'init.php');
```
If you need variable for long use, not only one pageload, then use session. (user logins, settings, ...)
```
<?php
$_SESSION['car'] = 'ferrari';
```
In your php sources, you can use constant and global variables:
Example:
```
<?php
echo CAR; //ferrari
echo Globals::$car; //ferrari
Globals::$car = 'renault'; //set your global variable
echo Globals::$car; //renault
```
**Refs:**
>
> <http://php.net/manual/en/language.oop5.static.php>
>
>
> <http://php.net/manual/en/function.define.php>
>
>
> <http://php.net/manual/en/function.dirname.php>
>
>
> <http://php.net/manual/en/reserved.variables.session.php>
>
>
> | You can use `SESSION` or `include` concept.
1) By using `SESSION`
**file1.php**
```
session_start();
$_SESSION['car'] = 'ferrari';
```
**file2.php**
```
session_start();
echo $_SESSION['car']; //Result: ferrari
```
2) By using `include`
**file2.php**
```
include 'file1.php';
echo $car //Result: ferrari
``` |
1,947,650 | Find all positive integers $x,y$ such that $7^{x}-3^{y}=4$.
It is the problem I think it can be solve using theory of congruency. But I can't process somebody please help me .
Thank you | 2016/09/30 | [
"https://math.stackexchange.com/questions/1947650",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/342519/"
] | Let us go down the rabbit hole. Assume that there is a solution with $ x, y > 1 $, and rearrange to find
$$ 7(7^{x-1} - 1) = 3(3^{y-1} - 1) $$
Note that $ 7^{x-1} - 1 $ is divisible by $ 3 $ exactly once (since $ x > 1 $): the contradiction will arise from this.
Reducing modulo $ 7 $ we find that $ 3^{y-1} \equiv 1 $, and since the order of $ 3 $ modulo $ 7 $ is $ 6 $, we find that $ y-1 $ is divisible by $ 6 $, hence $ 3^{y-1} - 1 $ is divisible by $ 3^6 - 1 = 2^3 \times 7 \times 13 $. Now, reducing modulo $ 13 $ we find that $ 7^{x-1} \equiv 1 $, and since the order of $ 7 $ modulo $ 13 $ is $ 12 $, we find that $ x-1 $ is divisible by $ 12 $. As above, this implies that $ 7^{x-1} - 1 $ is divisible by $ 7^{12} - 1 $, which is divisible by $ 9 $. This is the desired contradiction, hence there are no solutions with $ x, y > 1 $.
For an outline of the method I used here, see [Will Jagy](https://math.stackexchange.com/users/10400/will-jagy)'s answers to [this related question](https://math.stackexchange.com/questions/1941354/elementary-solution-of-exponential-diophantine-equation-2x-3y-7/). | If you take this equation mod 7 and mod 3, it becomes clearer:
$$ 7^x-3^y \equiv 4 \mod 7 \implies -3^y \equiv 4 \mod 7 $$
$$ 7^x-3^y \equiv 4 \mod 3 \implies 7^x \equiv 4 \mod 3 $$
This isolates the variables. You can either use Chinese Remainder Theorem or convert the new modular equations to normal equations to continue (as far as I can see). |
55,114,017 | I have a page with print button which prints a table. Now in Chrome or IE it works fine but in Firefox it does not show the table headers. Here are some screenshots of Chrome and Firefox.
In Firefox:

In Chrome:
 | 2019/03/12 | [
"https://Stackoverflow.com/questions/55114017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4898967/"
] | try using AUTO or IDENTITY policy.
like:
```
@GeneratedValue(strategy = GenerationType.IDENTITY)
``` | Here is the ID field definition in your entity class
```
@Id
@GeneratedValue
@Column(name = "customer_id", unique = true, nullable = false)
private int id;
```
**Here ID field is unique and not null**. So you must have to provide the data on ID field during insertion.
First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.
The `@Id`annotation is inherited from `javax.persistence.Id`, indicating the member field below is the primary key of current entity. Hence your Hibernate and spring framework as well as you can do some `reflect` works based on this annotation. for details please check [javadoc for Id](http://docs.oracle.com/javaee/6/api/javax/persistence/Id.html)
The `@GeneratedValue` annotation is to configure the way of increment of the specified column(field).
For example when using `Mysql`, you may specify `auto_increment` in the definition of table to make it self-incremental, and then use
```
@GeneratedValue(strategy = GenerationType.IDENTITY)
``` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | In several languages NULL is handled differently: Most people know about two-valued logic where `true` and `false` are the only comparable values in boolean expressions (even is false is defined as 0 and true as anything else).
In Standard SQL you have to think about [three-valued logic](http://en.wikipedia.org/wiki/Three-valued_logic). NULL is not treated as a real value, you could rather call it "unknown". So if the value is unknown it is not clear if in your case `state` is 0, 1, or anything else. So `NULL != 1` results to `NULL` again.
This concludes that whereever you filter something that may be NULL, you have to treat NULL values by yourself. Note that the syntax is different as well: NULL values can only be compare with `x IS NULL` instead of `x = NULL`. See Wikipedia for a truth table showing the results of logic operations. | Yest it's normal, you can maybe put a database settings to fixed that
But you could modify your code and do something like that :
```
SELECT * FROM STATUS WHERE STATE != '1' OR STATE != '2' or STATE is null;
```
Look at this for more info :
<http://www.w3schools.com/sql/sql_null_values.asp> |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | Yest it's normal, you can maybe put a database settings to fixed that
But you could modify your code and do something like that :
```
SELECT * FROM STATUS WHERE STATE != '1' OR STATE != '2' or STATE is null;
```
Look at this for more info :
<http://www.w3schools.com/sql/sql_null_values.asp> | I created script to [research Oracle](https://livesql.oracle.com/apex/livesql/file/index.html) behavior:
```
create table field_values
(
is_user_deletable VARCHAR2(1 CHAR),
resource_mark VARCHAR2(3 CHAR)
)
insert into field_values values (NULL, NULL);
insert into field_values values ('Y', NULL);
insert into field_values values ('N', NULL);
select * from field_values; -- 3 row
-- 1 row, bad
update field_values set resource_mark = 'D' where is_user_deletable = 'Y';
update field_values set resource_mark = 'D' where is_user_deletable <> 'N';
update field_values set resource_mark = 'D' where is_user_deletable != 'N';
update field_values set resource_mark = 'D' where is_user_deletable not in ('Y');
-- 2 rows, good, but needs more SQL and more comparisons. Does DB optimizes?
update field_values set resource_mark = 'D' where is_user_deletable = 'N' or is_user_deletable is null;
-- it better to have ('Y' and NULL) or ('N' and NULL), but not 'Y' and 'N' and NULL (avoid quires with https://en.wikipedia.org/wiki/Three-valued_logic)
-- adding new column which is 'Y' or 'N' only into existing table may be very long locking operation on existing table (or running long DML script)
``` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | Yest it's normal, you can maybe put a database settings to fixed that
But you could modify your code and do something like that :
```
SELECT * FROM STATUS WHERE STATE != '1' OR STATE != '2' or STATE is null;
```
Look at this for more info :
<http://www.w3schools.com/sql/sql_null_values.asp> | use `NVL` like so: `SELECT * FROM STATUS WHERE NVL(STATE,'X') != '1' AND NVL(STATE,'X')!= '2';` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | In several languages NULL is handled differently: Most people know about two-valued logic where `true` and `false` are the only comparable values in boolean expressions (even is false is defined as 0 and true as anything else).
In Standard SQL you have to think about [three-valued logic](http://en.wikipedia.org/wiki/Three-valued_logic). NULL is not treated as a real value, you could rather call it "unknown". So if the value is unknown it is not clear if in your case `state` is 0, 1, or anything else. So `NULL != 1` results to `NULL` again.
This concludes that whereever you filter something that may be NULL, you have to treat NULL values by yourself. Note that the syntax is different as well: NULL values can only be compare with `x IS NULL` instead of `x = NULL`. See Wikipedia for a truth table showing the results of logic operations. | multiple `or`'s with `where`'s can quickly become hard to read and uncertain as to results.
I would recommend extra parenthesis plus the use of the `IN` statement (`NOT IN` in this case), e.g.
`SELECT * FROM STATUS WHERE (STATE NOT IN ('1', '2')) or STATE is null;`
Implmentations can vary between database vendor but the above explicit syntax should make sure of the results. |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | In several languages NULL is handled differently: Most people know about two-valued logic where `true` and `false` are the only comparable values in boolean expressions (even is false is defined as 0 and true as anything else).
In Standard SQL you have to think about [three-valued logic](http://en.wikipedia.org/wiki/Three-valued_logic). NULL is not treated as a real value, you could rather call it "unknown". So if the value is unknown it is not clear if in your case `state` is 0, 1, or anything else. So `NULL != 1` results to `NULL` again.
This concludes that whereever you filter something that may be NULL, you have to treat NULL values by yourself. Note that the syntax is different as well: NULL values can only be compare with `x IS NULL` instead of `x = NULL`. See Wikipedia for a truth table showing the results of logic operations. | I created script to [research Oracle](https://livesql.oracle.com/apex/livesql/file/index.html) behavior:
```
create table field_values
(
is_user_deletable VARCHAR2(1 CHAR),
resource_mark VARCHAR2(3 CHAR)
)
insert into field_values values (NULL, NULL);
insert into field_values values ('Y', NULL);
insert into field_values values ('N', NULL);
select * from field_values; -- 3 row
-- 1 row, bad
update field_values set resource_mark = 'D' where is_user_deletable = 'Y';
update field_values set resource_mark = 'D' where is_user_deletable <> 'N';
update field_values set resource_mark = 'D' where is_user_deletable != 'N';
update field_values set resource_mark = 'D' where is_user_deletable not in ('Y');
-- 2 rows, good, but needs more SQL and more comparisons. Does DB optimizes?
update field_values set resource_mark = 'D' where is_user_deletable = 'N' or is_user_deletable is null;
-- it better to have ('Y' and NULL) or ('N' and NULL), but not 'Y' and 'N' and NULL (avoid quires with https://en.wikipedia.org/wiki/Three-valued_logic)
-- adding new column which is 'Y' or 'N' only into existing table may be very long locking operation on existing table (or running long DML script)
``` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | In several languages NULL is handled differently: Most people know about two-valued logic where `true` and `false` are the only comparable values in boolean expressions (even is false is defined as 0 and true as anything else).
In Standard SQL you have to think about [three-valued logic](http://en.wikipedia.org/wiki/Three-valued_logic). NULL is not treated as a real value, you could rather call it "unknown". So if the value is unknown it is not clear if in your case `state` is 0, 1, or anything else. So `NULL != 1` results to `NULL` again.
This concludes that whereever you filter something that may be NULL, you have to treat NULL values by yourself. Note that the syntax is different as well: NULL values can only be compare with `x IS NULL` instead of `x = NULL`. See Wikipedia for a truth table showing the results of logic operations. | use `NVL` like so: `SELECT * FROM STATUS WHERE NVL(STATE,'X') != '1' AND NVL(STATE,'X')!= '2';` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | multiple `or`'s with `where`'s can quickly become hard to read and uncertain as to results.
I would recommend extra parenthesis plus the use of the `IN` statement (`NOT IN` in this case), e.g.
`SELECT * FROM STATUS WHERE (STATE NOT IN ('1', '2')) or STATE is null;`
Implmentations can vary between database vendor but the above explicit syntax should make sure of the results. | I created script to [research Oracle](https://livesql.oracle.com/apex/livesql/file/index.html) behavior:
```
create table field_values
(
is_user_deletable VARCHAR2(1 CHAR),
resource_mark VARCHAR2(3 CHAR)
)
insert into field_values values (NULL, NULL);
insert into field_values values ('Y', NULL);
insert into field_values values ('N', NULL);
select * from field_values; -- 3 row
-- 1 row, bad
update field_values set resource_mark = 'D' where is_user_deletable = 'Y';
update field_values set resource_mark = 'D' where is_user_deletable <> 'N';
update field_values set resource_mark = 'D' where is_user_deletable != 'N';
update field_values set resource_mark = 'D' where is_user_deletable not in ('Y');
-- 2 rows, good, but needs more SQL and more comparisons. Does DB optimizes?
update field_values set resource_mark = 'D' where is_user_deletable = 'N' or is_user_deletable is null;
-- it better to have ('Y' and NULL) or ('N' and NULL), but not 'Y' and 'N' and NULL (avoid quires with https://en.wikipedia.org/wiki/Three-valued_logic)
-- adding new column which is 'Y' or 'N' only into existing table may be very long locking operation on existing table (or running long DML script)
``` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | multiple `or`'s with `where`'s can quickly become hard to read and uncertain as to results.
I would recommend extra parenthesis plus the use of the `IN` statement (`NOT IN` in this case), e.g.
`SELECT * FROM STATUS WHERE (STATE NOT IN ('1', '2')) or STATE is null;`
Implmentations can vary between database vendor but the above explicit syntax should make sure of the results. | use `NVL` like so: `SELECT * FROM STATUS WHERE NVL(STATE,'X') != '1' AND NVL(STATE,'X')!= '2';` |
8,036,691 | This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as:
```
SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
```
I get the same results as running:
```
SELECT * FROM STATUS WHERE STATE = '0';
```
I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?
I'm running my commands through Oracle SQL Developer. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8036691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982475/"
] | use `NVL` like so: `SELECT * FROM STATUS WHERE NVL(STATE,'X') != '1' AND NVL(STATE,'X')!= '2';` | I created script to [research Oracle](https://livesql.oracle.com/apex/livesql/file/index.html) behavior:
```
create table field_values
(
is_user_deletable VARCHAR2(1 CHAR),
resource_mark VARCHAR2(3 CHAR)
)
insert into field_values values (NULL, NULL);
insert into field_values values ('Y', NULL);
insert into field_values values ('N', NULL);
select * from field_values; -- 3 row
-- 1 row, bad
update field_values set resource_mark = 'D' where is_user_deletable = 'Y';
update field_values set resource_mark = 'D' where is_user_deletable <> 'N';
update field_values set resource_mark = 'D' where is_user_deletable != 'N';
update field_values set resource_mark = 'D' where is_user_deletable not in ('Y');
-- 2 rows, good, but needs more SQL and more comparisons. Does DB optimizes?
update field_values set resource_mark = 'D' where is_user_deletable = 'N' or is_user_deletable is null;
-- it better to have ('Y' and NULL) or ('N' and NULL), but not 'Y' and 'N' and NULL (avoid quires with https://en.wikipedia.org/wiki/Three-valued_logic)
-- adding new column which is 'Y' or 'N' only into existing table may be very long locking operation on existing table (or running long DML script)
``` |
36,259,849 | I am using ViewPager to hold my Fragments. I have two Fragments with different Parse Queries. One of My Fragment has grid view layout. I have created and Adapter for the GridView to load images.
This is my fragment
```
public class FeedsFragment extends Fragment {
GridView gridview;
List<ParseObject> ob;
FeedsGridAdapter adapter;
private List<ParseFeeds> phonearraylist = null;
View rootView;
public static final String TAG = FeedsFragment.class.getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.feeds_layout,
container, false);
new RemoteDataTask().execute();
return rootView;
}
private class RemoteDataTask extends AsyncTask<Void,Void,Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// Create the array
phonearraylist = new ArrayList<ParseFeeds>();
try {
// Locate the class table named "SamsungPhones" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"AroundMe");
// Locate the column named "position" in Parse.com and order list
// by ascending
// query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().getUsername());
query.orderByAscending("createdAt");
ob = query.find();
for (ParseObject country : ob) {
ParseFile image = (ParseFile) country.get("videoThumbs");
ParseFeeds map = new ParseFeeds();
map.setPhone(image.getUrl());
phonearraylist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Locate the gridview in gridview_main.xml
gridview = (GridView) rootView.findViewById(R.id.gridview);
// Pass the results into ListViewAdapter.java
adapter = new FeedsGridAdapter(FeedsFragment.this.getActivity(),
phonearraylist);
// Binds the Adapter to the ListView
gridview.setAdapter(adapter);
}
}
}
```
The Adapter I created to load the images into
```
public static final String TAG = FeedsGridAdapter.class.getSimpleName();
// Declare Variables
Context context;
LayoutInflater inflater;
ImageLoader imageLoader;
private List<ParseFeeds> phonearraylist = null;
private ArrayList<ParseFeeds> arraylist;
public FeedsGridAdapter(Context context, List<ParseFeeds> phonearraylist) {
this.context = context;
this.phonearraylist = phonearraylist;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<ParseFeeds>();
this.arraylist.addAll(phonearraylist);
imageLoader = new ImageLoader(context);
}
public class ViewHolder {
ImageView phone;
}
@Override
public int getCount() {
return phonearraylist.size();
}
@Override
public Object getItem(int position) {
return phonearraylist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.feeds_layout, null);
// Locate the ImageView in gridview_item.xml
holder.phone = (ImageView) view.findViewById(R.id.videoThumb);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Load image into GridView
imageLoader.DisplayImage(phonearraylist.get(position).getPhone(),
holder.phone);
// Capture GridView item click
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(context, SingleVideoView.class);
// Pass all data phone
intent.putExtra("phone", phonearraylist.get(position)
.getPhone());
context.startActivity(intent);
}
});
return view;
}
}
```
**Here its giving me NullPointerException on imageLoader.DisplayImage(phonearraylist.get(position).getPhone(),
holder.phone);**
When I run the same code in another project with only one Fragment its working but when I use it in my current project with Two Fargments having different parse queries it gives me NullPointerException.Please help I wasted around 5 days on this to get it working tried everything possible at my end.
Here is my ImageLoader Class
```
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
// int stub_id = ;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(R.drawable.camera_iris);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(R.drawable.camera_iris);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
``` | 2016/03/28 | [
"https://Stackoverflow.com/questions/36259849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5958776/"
] | There is a NullPointerException `imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone);`
Which leads to a suspiciously null `(ImageView) holder.phone`.
**Why it must be null ?**
Because it might not be lying inside the view you inflated to.
**So**
You should check if you are inflating a proper layout from resource and not making any of the most common mistakes like using activity/fragment's layout resource instead of using adapter's item layout.
You're welcome. | ImageLoader Initialize like below way
```
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc()//.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
``` |
33,549,067 | I have successfully converted event to method (for use in ViewModel) using **EventTriggerBehavior** and **CallMethodAction** as shown in the following example (here picked a Page **Loaded** event for illustration).
`<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:CallMethodAction TargetObject="{Binding Mode=OneWay}" MethodName="PageLoadedCommand"/>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>`
However, no success when it comes to the **CurrentStateChanged** event of **VisualStateGroup** as shown below (yes, nested within the `<VisualStateGroup>` block as **CurrentStateChanged** event belongs to **VisualStateGroup**):
`<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="CurrentStateChanged">
<core:CallMethodAction MethodName="CurrentVisualStateChanged" TargetObject="{Binding Mode=OneWay}"/>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>`
I suspect there may be issues with VisualStateGroup (or VisualStateManager) and the **CurrentStateChanged** event. I am saying this because, I can get this approach to work with other events. I have checked and rechecked the **CallMethodAction** method signatures (event arguments passing format) but no chance.
If you managed to get **CurrentStateChanged** event triggering as above (or with an alternative approach), I would very much like to know. | 2015/11/05 | [
"https://Stackoverflow.com/questions/33549067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5525674/"
] | >
> However, no success when it comes to the CurrentStateChanged event of VisualStateGroup as shown below
>
>
>
Yes, the EventTriggerBehavior won't work for VisualStateGroup.CurrentStateChanged event.
The feasible way is to create a **custom Behavior** that specifically targets this scenario, please see [this blog](https://marcominerva.wordpress.com/2014/07/29/a-behavior-to-handle-visualstate-in-universal-apps-with-mvvm/) wrote by **Marco Minerva**
This behavior can help us to monitor the current VisualStatus, in the Set method of custom property(ViewModelState type), calling method as you wish:
```
public class MainViewModel : ViewModelBase
{
public enum ViewModelState
{
Default,
Details
}
private ViewModelState currentState;
public ViewModelState CurrentState
{
get { return currentState; }
set
{
this.Set(ref currentState, value);
OnCurrentStateChanged(value);
}
}
public RelayCommand GotoDetailsStateCommand { get; set; }
public RelayCommand GotoDefaultStateCommand { get; set; }
public MainViewModel()
{
GotoDetailsStateCommand = new RelayCommand(() =>
{
CurrentState = ViewModelState.Details;
});
GotoDefaultStateCommand = new RelayCommand(() =>
{
CurrentState = ViewModelState.Default;
});
}
public void OnCurrentStateChanged(ViewModelState e)
{
Debug.WriteLine("CurrentStateChanged: " + e.ToString());
}
}
```
**Please check my completed sample on [Github](https://github.com/Myfreedom614/UWP-Samples/tree/master/MvvmVisualStatesBehaviorUWPApp1/MvvmVisualStatesBehaviorUWPApp1)** | Could be due to the latest SDK, and I managed to get it working with dynamic binding (for event to method pattern) as follows.
In XAML bind to `CurrentStateChanged` event as:
```
<VisualStateGroup CurrentStateChanged="{x:Bind ViewModel.CurrentVisualStateChanged}">
```
In ViewModel provide the CurrentStateChanged() method with CurrentStateChanged event signature as:
```
public void CurrentVisualStateChanged(object sender, VisualStateChangedEventArgs e)
{
var stateName = e?.NewState.Name; // get VisualState name from View
...
// more code to make use of the VisualState
}
```
The above didn't work for me a while back, and now I tried after *VS2015 Update 2* and my suspicion is that the latest SDK got enhanced?? Whatever, it is good news that you can now get to VisualState names in view-model thru dynamic binding. |
61,881 | We have a Honeywell whole-house humidifier attached to the duct directly above the heating element/electronics of our furnace. A few possible pertinent facts:
* The water intake is attached via a saddle valve.
* The drainage line leads to a pump. The intake for the pump is a PVC pipe, which the drainage line rests inside. The drainage line for the pump resides in a sink in another room.
* The humidistat is attached to the intake duct.
Whenever we run the humidifier, we end up with a small amount of water on the floor. It doesn't tend to appear for some time, but it consistently appears within 4-8 hours. I have never actually observed the water exiting the humidifier, so I don't know where it's coming from precisely. Part of my concern (and the reason that we don't currently use the humidifier) is that the water is draining down the interior of the duct.
I'm reasonably certain that the pump is not the reason for the leak. I've poured water directly into the pump's intake pipe and it proved capable of handling the water as fast as I supplied it.
I've also changed the filter in the humidifier, but the leak persisted.
The final wrinkle is that we had a plumber in for an unrelated issue who observed that the water pressure in our house is abnormally high (I believe he said it was 150 PSI, but I may remember incorrectly).
My questions:
1. What are the likely reasons for the leak?
2. How can I definitively determine where the leak is originating from without watching the humidifier for hours?
3. Is the high water pressure a possible culprit? | 2015/03/12 | [
"https://diy.stackexchange.com/questions/61881",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/13047/"
] | I can only provide anecdotal answers to questions 2 & 3.
2. I have successfully used a few drops of concentrated food coloring, at different places I suspect for leaks in a water softener and its related valves and plumbing. I used 3 different colors if memory serves me right. We had a very slow/unnoticeable leak, apart from the puddle of course. I was able to determine which valve is was based on the color dye that showed up in the leak (blue in this case).
3. The failed water softener in this case did fail due to high water pressure. I would see if there is any manufacturers rating for the humidifier's working water pressure. There is no telling what parts, valves or plumbing inside the unit make be deforming/failing under such high pressure.
Good luck in your troubleshooting and fix. | Our humidifier leaks in a similar manner, but the only way I could figure it out was to run the humidifier and watch for it (sounds awfully boring). I tracked it down to a tiny leak in the spout that feeds the overflow tube. The drops were running down the tube and leaking off the lowest point (where it curves), which was a few inches away from the humidifier. Good luck! |
23,471,926 | I know I can use `CASE` statement inside `VALUES` part of an insert statement but I am a bit confused.
I have a statement like, | 2014/05/05 | [
"https://Stackoverflow.com/questions/23471926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2737135/"
] | Here's a query structure that you can use (using JohnnyBeGoody's suggestion of using a SELECT statement to select the values).
```
INSERT INTO TABLE_XYZ (ED_MSISDN, ED_OTHER_PARTY, ED_DURATION)
SELECT
'2054896545' ED_MSISDN,
'6598898745' ED_OTHER_PARTY,
CASE
WHEN ED_OTHER_PARTY = '6598898745' THEN '9999999'
ELSE '88888'
END ED_DURATION
FROM DUAL;
``` | You cannot self-reference a column in an `insert` statement - that would cause an "ORA-00984: column not allowed here" error.
You could, however, use a `before insert` trigger to achieve the same functionality:
```
CREATE OR REPLACE TRIGGER table_xyz_tr
BEFORE INSERT ON table_xyz
FOR EACH ROW
NEW.ed_duration = CASE NEW.ed_other_party
WHEN '6598898745' THEN '9999999'
ELSE '88888' END;
END;
``` |
23,471,926 | I know I can use `CASE` statement inside `VALUES` part of an insert statement but I am a bit confused.
I have a statement like, | 2014/05/05 | [
"https://Stackoverflow.com/questions/23471926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2737135/"
] | You can try also a procedure:
```
create or replace procedure insert_XYZ (P_ED_MSISDN IN VARCHAR2,
P_ED_OTHER_PARTY IN VARCHAR2) is
begin
INSERT INTO TABLE_XYZ ( ED_MSISDN,
ED_OTHER_PARTY,
ED_DURATION)
VALUES (P_ED_MSISDN ,
P_ED_OTHER_PARTY ,
CASE
WHEN P_ED_OTHER_PARTY = '6598898745' THEN
'9999999'
ELSE
'88888'
END);
END;
``` | You cannot self-reference a column in an `insert` statement - that would cause an "ORA-00984: column not allowed here" error.
You could, however, use a `before insert` trigger to achieve the same functionality:
```
CREATE OR REPLACE TRIGGER table_xyz_tr
BEFORE INSERT ON table_xyz
FOR EACH ROW
NEW.ed_duration = CASE NEW.ed_other_party
WHEN '6598898745' THEN '9999999'
ELSE '88888' END;
END;
``` |
23,471,926 | I know I can use `CASE` statement inside `VALUES` part of an insert statement but I am a bit confused.
I have a statement like, | 2014/05/05 | [
"https://Stackoverflow.com/questions/23471926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2737135/"
] | You can try also a procedure:
```
create or replace procedure insert_XYZ (P_ED_MSISDN IN VARCHAR2,
P_ED_OTHER_PARTY IN VARCHAR2) is
begin
INSERT INTO TABLE_XYZ ( ED_MSISDN,
ED_OTHER_PARTY,
ED_DURATION)
VALUES (P_ED_MSISDN ,
P_ED_OTHER_PARTY ,
CASE
WHEN P_ED_OTHER_PARTY = '6598898745' THEN
'9999999'
ELSE
'88888'
END);
END;
``` | Here's a query structure that you can use (using JohnnyBeGoody's suggestion of using a SELECT statement to select the values).
```
INSERT INTO TABLE_XYZ (ED_MSISDN, ED_OTHER_PARTY, ED_DURATION)
SELECT
'2054896545' ED_MSISDN,
'6598898745' ED_OTHER_PARTY,
CASE
WHEN ED_OTHER_PARTY = '6598898745' THEN '9999999'
ELSE '88888'
END ED_DURATION
FROM DUAL;
``` |
22,739,757 | //i want to display list items in list view i am put all the items in list i want to display all the items in listview it is displaying but getting same names where i keep the for loop in getview.Please help me how can i pshow the list items in listview.
```
public class Listjava extends Activity {
/** Called when the activity is first created. */
int i = 0;
List<Contact> contacts;
MyBaseAdapter adapter;
final DatabaseHandler db = new DatabaseHandler(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
contacts = db.getAllContacts();
ListView list = (ListView) findViewById(R.id.listView1);
adapter = new MyBaseAdapter(getApplicationContext(), contacts);
list.setAdapter(adapter);
}
public class MyBaseAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public MyBaseAdapter(Context applicationContext, List<Contact> contacts) {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return contacts.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.layoutlist, null);
}
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName()
+ " ,Phone: " + cn.getPhoneNumber();
// Writing Contacts to logsout
System.out.println("log" + log);
TextView title2 = (TextView) vi
.findViewById(R.id.txt_ttlsm_row); // title
// String song = title.get(position).toString();
title2.setText(cn.getName());
TextView title22 = (TextView) vi
.findViewById(R.id.txt_ttlcontact_row2); // notice
title22.setText(cn.getPhoneNumber());
}
return vi;
}
}
}
``` | 2014/03/30 | [
"https://Stackoverflow.com/questions/22739757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114723/"
] | Change the MyBaseAdapter class like below.
```
public class MyBaseAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
List<Contact> contacts;
public MyBaseAdapter(Context applicationContext, List<Contact> contacts) {
// TODO Auto-generated constructor stub
this.contacts = contacts;// Initialize here
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return contacts.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return contacts.get(position);// Changed
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position; //Changed
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.layoutlist, null);
}
Contact cn = (Contact) getItem(position);
TextView title2 = (TextView) vi
.findViewById(R.id.txt_ttlsm_row); // title
title2.setText(cn.getName());
TextView title22 = (TextView) vi
.findViewById(R.id.txt_ttlcontact_row2); // notice
title22.setText(cn.getPhoneNumber());
return vi;
}
}
``` | You should not add for loop inside the getView method instead use contacts list like this :
```
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.layoutlist, null);
}
String log = "Id: " + contacts.get(position).getID() + " ,Name: " + contacts.get(position).getName()
+ " ,Phone: " + contacts.get(position).getPhoneNumber();
// Writing Contacts to logsout
System.out.println("log" + log);
TextView title2 = (TextView) vi
.findViewById(R.id.txt_ttlsm_row); // title
// String song = title.get(position).toString();
title2.setText(contacts.get(position).getName());
TextView title22 = (TextView) vi
.findViewById(R.id.txt_ttlcontact_row2); // notice
title22.setText(contacts.get(position).getPhoneNumber());
return vi;
}
``` |
64,125,262 | I have a table with a list of folders and I want to return only the top level folders.
For example, if the original table (tblFolders) has a single column (Fldrs) as below:
**Fldrs**
```
C:\Folder1
C:\Folder1\Subfolder1
C:\Folder1\Subfolder2
C:\Folder2\Subfolder1
```
I'd like to return:
```
C:\Folder1
C:\Folder2\Subfolder1
```
Thanks in advance | 2020/09/29 | [
"https://Stackoverflow.com/questions/64125262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14362939/"
] | A standard SQL solution is to UNION all your dates
```
SELECT MyID, MAX(thedate ) AS maxdate, MIN(thedate ) AS mindate
FROM
(
SELECT MyID, Date1 AS thedate FROM table
UNION ALL
SELECT MyID, Date2 AS thedate FROM table
UNION ALL
SELECT MyID, Date3 AS thedate FROM table
UNION ALL
SELECT MyID, Date4 AS thedate FROM table
) T
GROUP BY MyID
```
There might be better other solutions with window functions, depending on your RDBMS, which you haven't specified. But this one should work with any RDBMS. | Most, but not all, databases actually support `least()` and `greatest()`:
```
select t.*,
least(date1, date2, date3, date4) as min_date,
greatest(date1, date2, date3, date4) as max_date
from t;
```
The only caveat is that the return value is `NULL` if *any* of the values are `NULL`. That doesn't seem to be an issue based on the example data in your question.
EDIT:
On SQL Server, you would unpivot and use `apply`:
```
select t.*, v.*
from t cross apply
(select max(dte) as max_date, min(dte) as min_date
from (values (t.date1), (t.date2), (t.date3), (t.date4)) v(dte)
) v
``` |
64,125,262 | I have a table with a list of folders and I want to return only the top level folders.
For example, if the original table (tblFolders) has a single column (Fldrs) as below:
**Fldrs**
```
C:\Folder1
C:\Folder1\Subfolder1
C:\Folder1\Subfolder2
C:\Folder2\Subfolder1
```
I'd like to return:
```
C:\Folder1
C:\Folder2\Subfolder1
```
Thanks in advance | 2020/09/29 | [
"https://Stackoverflow.com/questions/64125262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14362939/"
] | A standard SQL solution is to UNION all your dates
```
SELECT MyID, MAX(thedate ) AS maxdate, MIN(thedate ) AS mindate
FROM
(
SELECT MyID, Date1 AS thedate FROM table
UNION ALL
SELECT MyID, Date2 AS thedate FROM table
UNION ALL
SELECT MyID, Date3 AS thedate FROM table
UNION ALL
SELECT MyID, Date4 AS thedate FROM table
) T
GROUP BY MyID
```
There might be better other solutions with window functions, depending on your RDBMS, which you haven't specified. But this one should work with any RDBMS. | Answering my own question here - after a fair amount of digging I don't think there is a good existing solution for this. So I ended up writing my own functions to handle this.
Here is the code for those functions:
```
CREATE FUNCTION dbo.maxDate(@date1 DATETIME, @date2 DATETIME) RETURNS DATETIME AS
BEGIN
DECLARE @result DATETIME
IF @date1 > @date2 SET @result = @date1
ELSE SET @result = @date2
RETURN @result
END
go
CREATE FUNCTION dbo.minDate(@date1 DATETIME, @date2 DATETIME) RETURNS DATETIME AS
BEGIN
DECLARE @result DATETIME
IF @date1 < @date2 SET @result = @date1
ELSE SET @result = @date2
RETURN @result
END
go
```
This then allows for a query similar to the second suggestion in my question:
```
SELECT
MyID,
dbo.minDate(Date1, dbo.minDate(Date2, dbo.minDate(Date3, Date4))),
dbo.maxDate(Date1, dbo.maxDate(Date2, dbo.maxDate(Date3, Date4)))
FROM ...
``` |
64,125,262 | I have a table with a list of folders and I want to return only the top level folders.
For example, if the original table (tblFolders) has a single column (Fldrs) as below:
**Fldrs**
```
C:\Folder1
C:\Folder1\Subfolder1
C:\Folder1\Subfolder2
C:\Folder2\Subfolder1
```
I'd like to return:
```
C:\Folder1
C:\Folder2\Subfolder1
```
Thanks in advance | 2020/09/29 | [
"https://Stackoverflow.com/questions/64125262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14362939/"
] | A standard SQL solution is to UNION all your dates
```
SELECT MyID, MAX(thedate ) AS maxdate, MIN(thedate ) AS mindate
FROM
(
SELECT MyID, Date1 AS thedate FROM table
UNION ALL
SELECT MyID, Date2 AS thedate FROM table
UNION ALL
SELECT MyID, Date3 AS thedate FROM table
UNION ALL
SELECT MyID, Date4 AS thedate FROM table
) T
GROUP BY MyID
```
There might be better other solutions with window functions, depending on your RDBMS, which you haven't specified. But this one should work with any RDBMS. | In SQL Server, where `least()` and `greatest()` are not available, I would recommend a lateral join to unpivot the columns to rows, and then aggregation to pull out the min and max value:
```
select t.myid, x.*
from mytable t
cross apply (
select max(dt) maxdate, min(dt) mindate
from (values (date1), (date2), (date3)) x(dt)
) x
```
This is more efficient than `union`, because it scans the table only once (as opposed to once per `union` member). |
40,501,502 | Its my first project using CodeIgniter and it is not as easy as it seems.
I have to import different JSs and CSSs in different pages and I'm stuck.
First of all, I've seen that hardcoding echos are not CI way of doing it so I made a simple class like
```
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Fileload {
public function loadjs($filename)
{
echo '<script language="javascript" type="text/javascript" src="'.$filename.'"></script>';
}
public function loadcss($filename)
{
echo '<link rel="stylesheet" type="text/css" href="'.$filename.'" >';
}
}
?>
```
And in my controller I used it like
```
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->library('fileload');
$this->load->view('head');
$this->load->view('mainpage');
$this->fileload->loadjs('//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js');
$this->load->view('tail');
}
}
```
But the slick library supposed to be at the bottom right above the 'tail' is at the top inside of head> tag, which is inside view('head');
It seems that the controllers' methods are not running in the sequence I've wrote it down. It should've echoed the script file first.
Can anybody explain how this CodeIgniter controller works?? | 2016/11/09 | [
"https://Stackoverflow.com/questions/40501502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4408351/"
] | Ok, so you tell Emacs to find-file some foo.py file, and Emacs reads it into a new `fundamental-mode` buffer and then calls `python-mode`.
That's an autoload, so first it must load `python.el`, after which your eval-after-load kicks in and you start messing with the selected buffer.
After that, `python-mode` is actually called -- but you've left some other buffer selected, so the mode gets enabled for that buffer, and foo.py remains in fundamental-mode.
Wrapping your code in `save-current-buffer` would be a sensible start, but you might also want to be more explicit in your manipulations, rather than relying on `other-window` to do what you want. | Based on the accepted answer given in [When window is split on startup, how to open the file on the right side?](https://stackoverflow.com/questions/41095426/when-window-is-split-on-startup-how-to-open-the-file-on-the-right-side/41095888) I was able to implement the desired behavior:
```
(defun my-eval-after-load-python (buffer alist direction &optional size pixelwise)
(setq initial-frame-alist '((top . 44) (left . 18) (width . 135) (height . 49)))
(let ((window
(cond
((get-buffer-window buffer (selected-frame)))
((window-in-direction direction))
(t (split-window (selected-window) size direction pixelwise))
)
))
(window--display-buffer buffer window 'window alist display-buffer-mark-dedicated)
(run-python (python-shell-parse-command))
(other-window 1)
(python-shell-switch-to-shell)
(select-window window)
)
)
(eval-after-load "python" '(my-eval-after-load-python (current-buffer) nil 'right (floor (* 0.49 (window-width)))))
``` |
40,501,502 | Its my first project using CodeIgniter and it is not as easy as it seems.
I have to import different JSs and CSSs in different pages and I'm stuck.
First of all, I've seen that hardcoding echos are not CI way of doing it so I made a simple class like
```
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Fileload {
public function loadjs($filename)
{
echo '<script language="javascript" type="text/javascript" src="'.$filename.'"></script>';
}
public function loadcss($filename)
{
echo '<link rel="stylesheet" type="text/css" href="'.$filename.'" >';
}
}
?>
```
And in my controller I used it like
```
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->library('fileload');
$this->load->view('head');
$this->load->view('mainpage');
$this->fileload->loadjs('//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js');
$this->load->view('tail');
}
}
```
But the slick library supposed to be at the bottom right above the 'tail' is at the top inside of head> tag, which is inside view('head');
It seems that the controllers' methods are not running in the sequence I've wrote it down. It should've echoed the script file first.
Can anybody explain how this CodeIgniter controller works?? | 2016/11/09 | [
"https://Stackoverflow.com/questions/40501502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4408351/"
] | Start with the basics first. Get rid of your python related configurations. Restart emacs and see if opening a .py file opens it in python-mode.
If this does not work, check the value of auto-mode-alist. This is an association list where each element of the list is a cons cell where the car is the key and the cdr is the value associated with that key. Thes cons cells are often written as "dotted pairs" i.e. (key . value). So the auto-mode-alist is just a list of associations where each association is used to associate a filename pattern with an emacs mode. The filename patterns are usually represented as regular expressions.
When you open a file in emacs, it will check the auto-mode-alist to see if any of the keys (regular expressions) match the filename. If one matches, then emacs will start that mode once the file is loaded. When there are no matches, emacs will default to just using fundamental mode.
So, if you find emacs does not put the buffer in python-mode when you open a file with a name which ends in the extension .py, the most likely cause is that therre is no auto-mode-alist entry which a key which matches the filename you are using.
I don't program with python, but I note on my system, there is the following entry in my auto-mode-alist
```
("\\.pyw?\\'" . python-mode)
```
When I open test.py, my emacs opens the file in python-mode.
Get this bit working or verify it is working in a vanilla emacs. If it isn't, then add the appropriate entry, test it works and then add back your configuration.
If yo find it works correctly until you add your setup function, then come back and we can look at the function. The way you have defined your function is a bit messy and could certainly be improved, but nothing obvious jumps out as being a problem, which is why I'd like to see if just opeing a pythong file without any other python setup stuff works. | Based on the accepted answer given in [When window is split on startup, how to open the file on the right side?](https://stackoverflow.com/questions/41095426/when-window-is-split-on-startup-how-to-open-the-file-on-the-right-side/41095888) I was able to implement the desired behavior:
```
(defun my-eval-after-load-python (buffer alist direction &optional size pixelwise)
(setq initial-frame-alist '((top . 44) (left . 18) (width . 135) (height . 49)))
(let ((window
(cond
((get-buffer-window buffer (selected-frame)))
((window-in-direction direction))
(t (split-window (selected-window) size direction pixelwise))
)
))
(window--display-buffer buffer window 'window alist display-buffer-mark-dedicated)
(run-python (python-shell-parse-command))
(other-window 1)
(python-shell-switch-to-shell)
(select-window window)
)
)
(eval-after-load "python" '(my-eval-after-load-python (current-buffer) nil 'right (floor (* 0.49 (window-width)))))
``` |
29,642,188 | Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
```
when I test the function with
```
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
```
I get `['ookcoo', 'emoo', 'omesoo', 'eggsmoo']` but I want `ookcoo emoo omesoo eggsmoo` | 2015/04/15 | [
"https://Stackoverflow.com/questions/29642188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772905/"
] | Use `' '.join(list)` for concatenating the list elements into a string.
In your code:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return ' '.join([cow_latinify_word(word) for word in words])
``` | Your function `cow_latinify_sentence` returns a list of strings you need to [`join`](https://docs.python.org/3.3/library/stdtypes.html#str.join) with spaces to get your desired output:
```
print(" ".join(cow_latin))
``` |
29,642,188 | Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
```
when I test the function with
```
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
```
I get `['ookcoo', 'emoo', 'omesoo', 'eggsmoo']` but I want `ookcoo emoo omesoo eggsmoo` | 2015/04/15 | [
"https://Stackoverflow.com/questions/29642188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772905/"
] | Just add an asterisk before the variable name to unpack the list and feed its elements as positional arguments to `print`.
```
print(*cow_latin)
``` | Your function `cow_latinify_sentence` returns a list of strings you need to [`join`](https://docs.python.org/3.3/library/stdtypes.html#str.join) with spaces to get your desired output:
```
print(" ".join(cow_latin))
``` |
29,642,188 | Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
```
when I test the function with
```
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
```
I get `['ookcoo', 'emoo', 'omesoo', 'eggsmoo']` but I want `ookcoo emoo omesoo eggsmoo` | 2015/04/15 | [
"https://Stackoverflow.com/questions/29642188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772905/"
] | Your function `cow_latinify_sentence` returns a list of strings you need to [`join`](https://docs.python.org/3.3/library/stdtypes.html#str.join) with spaces to get your desired output:
```
print(" ".join(cow_latin))
``` | Let's define our variables:
```
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"
```
Find the cow-latin:
```
>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'
``` |
29,642,188 | Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
```
when I test the function with
```
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
```
I get `['ookcoo', 'emoo', 'omesoo', 'eggsmoo']` but I want `ookcoo emoo omesoo eggsmoo` | 2015/04/15 | [
"https://Stackoverflow.com/questions/29642188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772905/"
] | Use `' '.join(list)` for concatenating the list elements into a string.
In your code:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return ' '.join([cow_latinify_word(word) for word in words])
``` | Let's define our variables:
```
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"
```
Find the cow-latin:
```
>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'
``` |
29,642,188 | Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
```
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
```
when I test the function with
```
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
```
I get `['ookcoo', 'emoo', 'omesoo', 'eggsmoo']` but I want `ookcoo emoo omesoo eggsmoo` | 2015/04/15 | [
"https://Stackoverflow.com/questions/29642188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772905/"
] | Just add an asterisk before the variable name to unpack the list and feed its elements as positional arguments to `print`.
```
print(*cow_latin)
``` | Let's define our variables:
```
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"
```
Find the cow-latin:
```
>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'
``` |
47,913,649 | I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options:
>
> You can access TensorBoard locally at <http://localhost:6006> or using
> your SageMaker notebook instance proxy/6006/(TensorBoard will not work
> if forget to put the slash, '/', in end of the url). If TensorBoard
> started on a different port, adjust these URLs to match.
>
>
>
When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there?
Or if I use `run_tensorboard_locally=False`, what should the proxy url be? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47913649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3461257/"
] | You can access TensorBoard on your notebook using the link "proxy/6006".
If you set run\_tensorboard\_locally=False then it won't start TensorBoard.
If the URL you clicked gives you the error "[Errno 111] Connection refused" then it seems that training has already stopped. According to <https://github.com/aws/sagemaker-python-sdk> it "terminates TensorBoard when the execution ends" so it seems you have to access it during the training step only. | "Local" there refers to the machine which is running the estimator.fit method. So if you are running the example notebook on a SageMaker notebook instance, tensorboard will be running on that machine.
The "proxy/6006" part of the text you quoted is a clickable link which will bring up TensorBoard on your notebook. The full URL will be "https://.notebook..sagemaker.aws/proxy/6006/". |
47,913,649 | I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options:
>
> You can access TensorBoard locally at <http://localhost:6006> or using
> your SageMaker notebook instance proxy/6006/(TensorBoard will not work
> if forget to put the slash, '/', in end of the url). If TensorBoard
> started on a different port, adjust these URLs to match.
>
>
>
When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there?
Or if I use `run_tensorboard_locally=False`, what should the proxy url be? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47913649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3461257/"
] | Here is my solution:
If URL of my sagemaker notebook instance is:
```
https://myinstance.notebook.us-east-1.sagemaker.aws/notebooks/image_classify.ipynb
```
And URL of accessing TensorBoard will be:
```
https://myinstance.notebook.us-east-1.sagemaker.aws/proxy/6006/
``` | "Local" there refers to the machine which is running the estimator.fit method. So if you are running the example notebook on a SageMaker notebook instance, tensorboard will be running on that machine.
The "proxy/6006" part of the text you quoted is a clickable link which will bring up TensorBoard on your notebook. The full URL will be "https://.notebook..sagemaker.aws/proxy/6006/". |
47,913,649 | I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options:
>
> You can access TensorBoard locally at <http://localhost:6006> or using
> your SageMaker notebook instance proxy/6006/(TensorBoard will not work
> if forget to put the slash, '/', in end of the url). If TensorBoard
> started on a different port, adjust these URLs to match.
>
>
>
When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there?
Or if I use `run_tensorboard_locally=False`, what should the proxy url be? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47913649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3461257/"
] | "Local" there refers to the machine which is running the estimator.fit method. So if you are running the example notebook on a SageMaker notebook instance, tensorboard will be running on that machine.
The "proxy/6006" part of the text you quoted is a clickable link which will bring up TensorBoard on your notebook. The full URL will be "https://.notebook..sagemaker.aws/proxy/6006/". | You can find a more detailed tutorial here: <https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tensorboard.html>
You can save your logs like this:
```
LOG_DIR = os.path.join(os.getcwd(), "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
EFS_PATH_LOG_DIR = "/".join(LOG_DIR.strip("/").split('/')[1:-1])
```
Then lunch Tensorboard by following these steps:
Open a new `Terminal`.
Install Tensorboard and launch it (Copy EFS\_PATH\_LOG\_DIR from the Jupyter notebook):
```
pip install tensorboard
tensorboard --logdir <EFS_PATH_LOG_DIR>
```
Open Tensorboard:
`https://<YOUR_Notebook_URL>.studio.region.sagemaker.aws/jupyter/default/proxy/6006/`
If you store your logs in an S3 you can luanch it again from Terminal by doing:
```
AWS_REGION=region tensorboard --logdir s3://bucket_name/logs/
```
and then again going to the same url: `https://<YOUR_Notebook_URL>.studio.region.sagemaker.aws/jupyter/default/proxy/6006/` |
47,913,649 | I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options:
>
> You can access TensorBoard locally at <http://localhost:6006> or using
> your SageMaker notebook instance proxy/6006/(TensorBoard will not work
> if forget to put the slash, '/', in end of the url). If TensorBoard
> started on a different port, adjust these URLs to match.
>
>
>
When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there?
Or if I use `run_tensorboard_locally=False`, what should the proxy url be? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47913649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3461257/"
] | Here is my solution:
If URL of my sagemaker notebook instance is:
```
https://myinstance.notebook.us-east-1.sagemaker.aws/notebooks/image_classify.ipynb
```
And URL of accessing TensorBoard will be:
```
https://myinstance.notebook.us-east-1.sagemaker.aws/proxy/6006/
``` | You can access TensorBoard on your notebook using the link "proxy/6006".
If you set run\_tensorboard\_locally=False then it won't start TensorBoard.
If the URL you clicked gives you the error "[Errno 111] Connection refused" then it seems that training has already stopped. According to <https://github.com/aws/sagemaker-python-sdk> it "terminates TensorBoard when the execution ends" so it seems you have to access it during the training step only. |
47,913,649 | I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options:
>
> You can access TensorBoard locally at <http://localhost:6006> or using
> your SageMaker notebook instance proxy/6006/(TensorBoard will not work
> if forget to put the slash, '/', in end of the url). If TensorBoard
> started on a different port, adjust these URLs to match.
>
>
>
When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there?
Or if I use `run_tensorboard_locally=False`, what should the proxy url be? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47913649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3461257/"
] | You can access TensorBoard on your notebook using the link "proxy/6006".
If you set run\_tensorboard\_locally=False then it won't start TensorBoard.
If the URL you clicked gives you the error "[Errno 111] Connection refused" then it seems that training has already stopped. According to <https://github.com/aws/sagemaker-python-sdk> it "terminates TensorBoard when the execution ends" so it seems you have to access it during the training step only. | You can find a more detailed tutorial here: <https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tensorboard.html>
You can save your logs like this:
```
LOG_DIR = os.path.join(os.getcwd(), "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
EFS_PATH_LOG_DIR = "/".join(LOG_DIR.strip("/").split('/')[1:-1])
```
Then lunch Tensorboard by following these steps:
Open a new `Terminal`.
Install Tensorboard and launch it (Copy EFS\_PATH\_LOG\_DIR from the Jupyter notebook):
```
pip install tensorboard
tensorboard --logdir <EFS_PATH_LOG_DIR>
```
Open Tensorboard:
`https://<YOUR_Notebook_URL>.studio.region.sagemaker.aws/jupyter/default/proxy/6006/`
If you store your logs in an S3 you can luanch it again from Terminal by doing:
```
AWS_REGION=region tensorboard --logdir s3://bucket_name/logs/
```
and then again going to the same url: `https://<YOUR_Notebook_URL>.studio.region.sagemaker.aws/jupyter/default/proxy/6006/` |
47,913,649 | I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options:
>
> You can access TensorBoard locally at <http://localhost:6006> or using
> your SageMaker notebook instance proxy/6006/(TensorBoard will not work
> if forget to put the slash, '/', in end of the url). If TensorBoard
> started on a different port, adjust these URLs to match.
>
>
>
When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there?
Or if I use `run_tensorboard_locally=False`, what should the proxy url be? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47913649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3461257/"
] | Here is my solution:
If URL of my sagemaker notebook instance is:
```
https://myinstance.notebook.us-east-1.sagemaker.aws/notebooks/image_classify.ipynb
```
And URL of accessing TensorBoard will be:
```
https://myinstance.notebook.us-east-1.sagemaker.aws/proxy/6006/
``` | You can find a more detailed tutorial here: <https://docs.aws.amazon.com/sagemaker/latest/dg/studio-tensorboard.html>
You can save your logs like this:
```
LOG_DIR = os.path.join(os.getcwd(), "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
EFS_PATH_LOG_DIR = "/".join(LOG_DIR.strip("/").split('/')[1:-1])
```
Then lunch Tensorboard by following these steps:
Open a new `Terminal`.
Install Tensorboard and launch it (Copy EFS\_PATH\_LOG\_DIR from the Jupyter notebook):
```
pip install tensorboard
tensorboard --logdir <EFS_PATH_LOG_DIR>
```
Open Tensorboard:
`https://<YOUR_Notebook_URL>.studio.region.sagemaker.aws/jupyter/default/proxy/6006/`
If you store your logs in an S3 you can luanch it again from Terminal by doing:
```
AWS_REGION=region tensorboard --logdir s3://bucket_name/logs/
```
and then again going to the same url: `https://<YOUR_Notebook_URL>.studio.region.sagemaker.aws/jupyter/default/proxy/6006/` |
37,458,388 | We have a table with three columns: id, fieldName, fieldValue. This table has many records. We want to quickly access a list of the distinct fieldNames.
When we create a view with a clustered index, we get this, but we have another problem: we have many processes that delete from the table by the id column. These have deadlocks, when multiple deletes run concurrently, since they are trying to update the index.
If we create a view without an index, there are no deadlocks, but the view becomes very slow to use.
Is there any way to create a view (or otherwise get the distinct fieldNames) that will work quickly, but also not lock on deletes?
Adding data to the question, to answer some of the suggestions provided:
We very rarely add new fieldNames, and deleting existing fieldNames is even rarer. Almost all new records use the existing fieldNames.
There are few distinct fieldNames (about 30), but hundreds of millions of records in the table.
We do have an index on fieldName in the table, but getting a list of the distinct fieldNames is still very slow if the view is not indexed. | 2016/05/26 | [
"https://Stackoverflow.com/questions/37458388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50667/"
] | You don't need the view. Paul White blogged about how to find distinct values quickly in [Performance Tuning the Whole Query Plan](http://sqlperformance.com/2014/10/t-sql-queries/performance-tuning-whole-plan).
He uses a recursive CTE to seek the next distinct value. Basically doing one seek per iteration/value jumping through the index. This will be faster for few distinct values but somewhere as the number of distinct values, compared to the number of rows in the table, increases there is a tipping point where a scan will be faster.
In your case it would look something like this.
Setup:
```
create table dbo.YourTable
(
id int identity primary key,
fieldName varchar(20) not null,
fieldValue varchar(20) null
);
go
create index IX_YourTable_fieldName on dbo.YourTable(fieldName);
go
insert into dbo.YourTable(fieldName) values
('F1'),
('F1'),
('F1'),
('F2'),
('F2'),
('F2'),
('F3');
```
Query:
```
with C as
(
select top (1) T.fieldName
from dbo.YourTable as T
order by T.fieldName
union all
select R.fieldName
from (
select T.fieldName,
row_number() over (order by T.fieldName) as rn
from dbo.YourTable as T
inner join C
on C.fieldName < T.fieldName
) as R
where R.rn = 1
)
select C.fieldName
from C
option (maxrecursion 0);
```
Queryplan:
[](https://i.stack.imgur.com/CSKL7.png) | Why not creating an extra index on the fieldNames column - I see no need for a view. |
36,064,401 | I was trying to do something in Swift that would be easy in Objective-C using KVC. The new [Contacts framework](https://developer.apple.com/library/watchos/documentation/Contacts/Reference/Contacts_Framework/index.html) added in iOS9 is for the most part easier to use than the [old AddressBook API](https://developer.apple.com/library/ios/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Introduction.html). But finding a contact by its mobile phone number seems to be difficult. The predicates provided for finding contacts are limited to the name and the unique identifier. In Objective-C you could get all the contacts and then use an NSPredicate to filter on a KVC query. The structure is:
CNContact->phoneNumbers->(String, CNPhoneNumber->stringValue)
Presume in the code below that I fetched the contacts via:
```
let keys = [CNContactEmailAddressesKey,CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
let fetchRequest = CNContactFetchRequest(keysToFetch: keys)
var contacts:[CNContact] = []
try! CNContactStore().enumerateContactsWithFetchRequest(fetchRequest) { ...
```
I want to compare the stringValue to a known value. Here's what I have so far from a playground:
```
import UIKit
import Contacts
let JennysPhone = "111-867-5309"
let SomeOtherPhone = "111-111-2222"
let AndAThirdPhone = "111-222-5309"
let contact1 = CNMutableContact()
contact1.givenName = "Jenny"
let phone1 = CNPhoneNumber(stringValue: JennysPhone)
let phoneLabeled1 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone1)
contact1.phoneNumbers.append(phoneLabeled1)
let contact2 = CNMutableContact()
contact2.givenName = "Billy"
let phone2 = CNPhoneNumber(stringValue: SomeOtherPhone)
let phoneLabeled2 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone2)
contact2.phoneNumbers.append(phoneLabeled2)
let contact3 = CNMutableContact()
contact3.givenName = "Jimmy"
let phone3 = CNPhoneNumber(stringValue: SomeOtherPhone)
let phoneLabeled3 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone3)
contact3.phoneNumbers.append(phoneLabeled3)
let contacts = [contact1, contact2, contact3]
let matches = contacts.filter { (contact) -> Bool in
let phoneMatches = contact.phoneNumbers.filter({ (labeledValue) -> Bool in
if let v = labeledValue.value as? CNPhoneNumber
{
return v.stringValue == JennysPhone
}
return false
})
return phoneMatches.count > 0
}
if let jennysNum = matches.first?.givenName
{
print("I think I found Jenny: \(jennysNum)")
}
else
{
print("I could not find Jenny")
}
```
This does work, but it's not efficient. On a device I would need to run this in a background thread, and it could take a while if the person has a lot of contacts. Is there a better way to find a contact by phone number (or email address, same idea) using the new iOS Contacts framework? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36064401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2969719/"
] | If you are looking for a more Swift-y way to do it:
```
let matches = contacts.filter {
return $0.phoneNumbers
.flatMap { $0.value as? CNPhoneNumber }
.contains { $0.stringValue == JennysPhone }
}
```
`.flatMap` casts each member of `phoneNumbers` from type `CNLabeledValue` to type `CNPhoneNumber`, ignoring those that cannot be casted.
`.contains` checks if any of these phone numbers matches Jenny's number. | I'm guessing you're wanting a more swift-y way, but obviously anything you can do in Obj-C can also be done in swift. So, you can still use NSPredicate:
```
let predicate = NSPredicate(format: "ANY phoneNumbers.value.digits CONTAINS %@", "1118675309")
let contactNSArray = contacts as NSArray
let contactsWithJennysPhoneNumber = contactNSArray.filteredArrayUsingPredicate(predicate)
``` |
7,318,402 | I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8.
```
public class MainClass {
public static void main(String args[]) throws Exception {
String s = "साहिलसाहिल";
System.out.print(s);
}
}
```
After compilation, I get 2 errors of illegal character. Why so? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7318402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290410/"
] | You have to specify the appropriate encoding :
```
javac -encoding utf8 MainClass.java
``` | Try compiling like this:
```
javac -encoding UTF-8 MainClass.java
```
Make sure that you use the correct name for the encoding too.
If this fails, it is likely that the problem that the Notepad is adding a BOM at the front, and that is confusing the java compiler. If that is your problem, you should stop using Notepad for editing UTF-8 files. Use a decent text editor that doesn't add a BOM to UTF-8 files. |
7,318,402 | I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8.
```
public class MainClass {
public static void main(String args[]) throws Exception {
String s = "साहिलसाहिल";
System.out.print(s);
}
}
```
After compilation, I get 2 errors of illegal character. Why so? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7318402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290410/"
] | You have to specify the appropriate encoding :
```
javac -encoding utf8 MainClass.java
``` | try it with
`java -Dfile.encoding=UTF8 MainClass.java` |
7,318,402 | I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8.
```
public class MainClass {
public static void main(String args[]) throws Exception {
String s = "साहिलसाहिल";
System.out.print(s);
}
}
```
After compilation, I get 2 errors of illegal character. Why so? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7318402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290410/"
] | You have to specify the appropriate encoding :
```
javac -encoding utf8 MainClass.java
``` | You need to save the source file in UTF-8 format (easy to do it using Notepad++ or Eclipse IDE) and then compile with the `-encoding` switch to `javac`.
```
javac -encoding utf8 MainClass.java
``` |
7,318,402 | I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8.
```
public class MainClass {
public static void main(String args[]) throws Exception {
String s = "साहिलसाहिल";
System.out.print(s);
}
}
```
After compilation, I get 2 errors of illegal character. Why so? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7318402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290410/"
] | Try compiling like this:
```
javac -encoding UTF-8 MainClass.java
```
Make sure that you use the correct name for the encoding too.
If this fails, it is likely that the problem that the Notepad is adding a BOM at the front, and that is confusing the java compiler. If that is your problem, you should stop using Notepad for editing UTF-8 files. Use a decent text editor that doesn't add a BOM to UTF-8 files. | try it with
`java -Dfile.encoding=UTF8 MainClass.java` |
7,318,402 | I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8.
```
public class MainClass {
public static void main(String args[]) throws Exception {
String s = "साहिलसाहिल";
System.out.print(s);
}
}
```
After compilation, I get 2 errors of illegal character. Why so? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7318402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290410/"
] | Try compiling like this:
```
javac -encoding UTF-8 MainClass.java
```
Make sure that you use the correct name for the encoding too.
If this fails, it is likely that the problem that the Notepad is adding a BOM at the front, and that is confusing the java compiler. If that is your problem, you should stop using Notepad for editing UTF-8 files. Use a decent text editor that doesn't add a BOM to UTF-8 files. | You need to save the source file in UTF-8 format (easy to do it using Notepad++ or Eclipse IDE) and then compile with the `-encoding` switch to `javac`.
```
javac -encoding utf8 MainClass.java
``` |
7,318,402 | I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8.
```
public class MainClass {
public static void main(String args[]) throws Exception {
String s = "साहिलसाहिल";
System.out.print(s);
}
}
```
After compilation, I get 2 errors of illegal character. Why so? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7318402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/290410/"
] | try it with
`java -Dfile.encoding=UTF8 MainClass.java` | You need to save the source file in UTF-8 format (easy to do it using Notepad++ or Eclipse IDE) and then compile with the `-encoding` switch to `javac`.
```
javac -encoding utf8 MainClass.java
``` |
22,115,008 | I am trying to get my edit to work I need the contact detail data to load when the user data loads. I have set the data in a similar manner to how I am retrieving the list of roles. I also don't know how to retrieve according to the model currently I was hard-coding it to retrieve 28. Would greatly appreciate any help provided.
```
public function edit($id = null) {
//Populate roles dropdownlist
$data = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set('roles', $data);
$data2 = $this->User->ContactDetail->find('first', array(
'conditions' => array('ContactDetail.id' =>'28')));
$this->set('contactdetails', $data2);
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
```
my view is set up in the following manner
```
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Edit User'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role_id');
echo $this->Form->input('ContactDetail.name');
echo $this->Form->input('ContactDetail.surname');
echo $this->Form->input('ContactDetail.address1');
echo $this->Form->input('ContactDetail.address2');
echo $this->Form->input('ContactDetail.country');
echo $this->Form->input('ContactDetail.email');
echo $this->Form->input('ContactDetail.fax');
?>
<label>Are you interested in buying property in Malta?</label>
<?php
$interest_buy = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_buy_property',array('type'=>'radio','options'=>$interest_buy,'value'=>'0','legend'=>FALSE));
?>
<label>Are you interested in renting property in Malta?</label>
<?php
$interest_rent = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_rent_property',array('type'=>'radio','options'=>$interest_rent,'value'=>'0','legend'=>FALSE));
echo $this->Form->input('ContactDetail.mobile');
echo $this->Form->input('ContactDetail.phone');
echo $this->Form->input('ContactDetail.postcode');
echo $this->Form->input('ContactDetail.town');
echo $this->Form->input('ContactDetail.newsletter',array('type'=>'checkbox','label'=>'Would you like to register for the newsletter?' ,'checked'=>'1','legend'=>FALSE,));
?>
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
```
**User Model**
```
public $primaryKey = 'id';
public $displayField = 'username';
public function bindNode($user) {
return array('model' => 'Role', 'foreign_key' => $user['User']['role_id']);
}
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password(
$this->data['User']['password']
);
return true;
}
public $belongsTo = array(
'Role' => array('className' => 'Role'));
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id'));
public $actsAs = array('Acl' => array('type' => 'requester', 'enabled' => false));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['role_id'])) {
$roleId = $this->data['User']['role_id'];
} else {
$roleId = $this->field('role_id');
}
if (!$roleId) {
return null;
} else {
return array('Role' => array('id' => $roleId));
}
}
}
```
**ContactDetail Model**
```
public $primaryKey = 'id';
public $displayField = 'name';
``` | 2014/03/01 | [
"https://Stackoverflow.com/questions/22115008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/696406/"
] | `email` is being called on a nil `@user`, and `@user` is going to always be nil.
Looking at this line:
```
unless @user_check = nil
```
Using a single equals is assignment, not an equality comparison.
You'll want to do:
```
unless @user_check == nil
```
or the more idomatic Ruby:
```
unless @user_check.nil?
``` | Taking `unless @user_check = nil` statement for inspection:--
`=` is assignment and `==` is equality comparison operator. I guess you just missed using `==` because of typo.
Use ruby `.nil?` method instead.
like `unless @user_check.nil?`
Use [delayed\_job](https://github.com/collectiveidea/delayed_job) to send emails. |
96,984 | When another moderator sends a direct user message, the notification appears for all other moderators as a dropdown alert. This is somewhat distracting, and also impossible to get back to once it's closed. I feel like this type of alert makes more sense *for moderators* as a global inbox notification, since it's more of a "you should read this message" inbox type item. For users on the receiving end, it should probably be *both* a global inbox notification *and* a dropdown message, to ensure that they receive it. | 2011/06/30 | [
"https://meta.stackexchange.com/questions/96984",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/139837/"
] | The users **also typically get an email -- you know, a real, physical email in their email inbox** -- and that contains the text with a link to the moderator message URL, so I'm not sure I can agree with this.
It is the default option when sending a moderator message. | *When I logged in today I could swear I saw a moderator message appear* right before Firefox died loading another page\*.
I don't know what it was. I can't find anything in my inbox which would generate such a message. Perhaps it was a badge notification or a notice on an open bounty? or?
But I don't see any recent badges that I didn't already know about. My bounties still have a few days to go...?? (and haven't generated much interest anyways...)
It would be awesome if there was some simple way just to keep a record of which notifications I recently *should've seen* barring the gamma ray burst which just hosed my browser...
Note: This doesn't have to be a queue, it could simply be listed in the profile under **activity** as a separate sub-tag **system notifications** (or perhaps simply **system**). |
96,984 | When another moderator sends a direct user message, the notification appears for all other moderators as a dropdown alert. This is somewhat distracting, and also impossible to get back to once it's closed. I feel like this type of alert makes more sense *for moderators* as a global inbox notification, since it's more of a "you should read this message" inbox type item. For users on the receiving end, it should probably be *both* a global inbox notification *and* a dropdown message, to ensure that they receive it. | 2011/06/30 | [
"https://meta.stackexchange.com/questions/96984",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/139837/"
] | As per [Moderator message notifications should be red in the global inbox for those involved](https://meta.stackexchange.com/questions/133837/moderator-message-notifications-should-be-red-in-the-global-inbox), this has now been implemented as a "notification" (not an inbox message), and will be changed to a proper inbox message soon. | *When I logged in today I could swear I saw a moderator message appear* right before Firefox died loading another page\*.
I don't know what it was. I can't find anything in my inbox which would generate such a message. Perhaps it was a badge notification or a notice on an open bounty? or?
But I don't see any recent badges that I didn't already know about. My bounties still have a few days to go...?? (and haven't generated much interest anyways...)
It would be awesome if there was some simple way just to keep a record of which notifications I recently *should've seen* barring the gamma ray burst which just hosed my browser...
Note: This doesn't have to be a queue, it could simply be listed in the profile under **activity** as a separate sub-tag **system notifications** (or perhaps simply **system**). |
18,899,045 | What's the proper way to write this query? I have a column named TimeStamp in my customers table. I'm getting errors when trying to find customers who created an account in 2012. I've tried:
```
SELECT 'TimeStamp' AS CreatedDate
FROM customers
WHERE 'CreatedDate' >= '2012-01-01' AND 'CreatedDate' <= '2012-12-31'
```
and also
```
SELECT *
FROM customers
WHERE 'TimeStamp' >= '2012-01-01' AND 'TimeStamp' <= '2012-12-31'
```
and always get no results (there should be thousands) | 2013/09/19 | [
"https://Stackoverflow.com/questions/18899045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2795892/"
] | You must not use single quotes around column names as they are identifiers.
```
SELECT *
FROM customers
WHERE TimeStamp >= '2012-01-01' AND TimeStamp <= '2012-12-31'
```
If it happens that your column name is a reserved keyword, you can escape it by using `backtick` eg,
```
WHERE `select` .... -- SELECT is a reserved keyword
```
or use it along with the tableName
```
FROM tb
WHERE tb.select .... -- SELECT is a reserved keyword
``` | You can use backticks to escape keywords like `timestamp`. That worked for me.
```sql
select `timestamp` from users;
``` |
60,844,852 | I am looking for a prettier way to delete some special characters (`{}[]()*?!^:|&"/\~`) if they exists in the first and the last position of a string called query. My way is pretty ugly but does the work.
```js
while(
query.charAt(1)==":" ||
query.charAt(1)=="{" ||
query.charAt(1)=="}" ||
query.charAt(1)=="[" ||
query.charAt(1)=="]" ||
query.charAt(1)=="*" ||
query.charAt(1)=="-" ||
query.charAt(1)=="^" ||
query.charAt(1)=="(" ||
query.charAt(1)==")" ||
query.charAt(1)=="|" ||
query.charAt(1)=='"' ||
query.charAt(1)=="/" ||
query.charAt(1)=="_" ||
query.charAt(1)=='"' ||
query.charAt(1)=="~"
){
query = query.slice(1);
}
while(
query.charAt(query.length-1)=="!" ||
query.charAt(query.length-1)==":" ||
query.charAt(query.length-1)=="{" ||
query.charAt(query.length-1)=="}" ||
query.charAt(query.length-1)=="[" ||
query.charAt(query.length-1)=="]" ||
query.charAt(query.length-1)=="*" ||
query.charAt(query.length-1)=="?" ||
query.charAt(query.length-1)=="^" ||
query.charAt(query.length-1)=="(" ||
query.charAt(query.length-1)==")" ||
query.charAt(query.length-1)=="|" ||
query.charAt(query.length-1)=="&" ||
query.charAt(query.length-1)=='"' ||
query.charAt(query.length-1)=="/" ||
query.charAt(query.length-1)=="\\"||
query.charAt(query.length-1)=="~"
){
query = query.slice(0, -1);
}
``` | 2020/03/25 | [
"https://Stackoverflow.com/questions/60844852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12602828/"
] | Use a regular expression instead:
```
query = query.replace(/^[-:{}[\]*^()|"]+|[-:{}[\]*^()|"]+$/g, '');
```
This pattern is composed of:
```
^[CHARS]+|[CHARS]+$
```
where `CHARS` are the characters you want to remove.
* `^[CHARS]+` - Match one or more of those characters at the beginning of the string
* `|` OR match
* `[CHARS]+$` - one or more of those characters at the end of the string | Using a regular expression as proposed in [CertainPerformance's answer](https://stackoverflow.com/a/60844881/218196) should be the preferred solution.
But just to demonstrate that it's possible to improve this solution without having to use regular expressions (and for those who are uncomfortable using them), there are a couple of things you could do:
* Avoid repeated calls to `query.charAt`. You can store the character at the position in a variable. The character doesn't change inside the condition.
* Instead of using `.charAt` you can also access the character at a specific position via bracket notation. `foo.charAt(0)` is the same as `foo[0]`.
* Instead of writing out multiple conditions you can use a lookup table or a `Set`.
* Instead of chipping off characters one by one, find the *last* position from the start (or *first* from the end) that his one of your characters.
Also `query.charAt(1)` doesn't seem correct, that would get the character at the second position. If you want to get the character at the first position you have to use `0`. Like everything else in JavaScript, strings are 0-based.
Applying what I said above, you would get:
```js
function trim(str, charsStart, charsEnd) {
charsStart = new Set([...charsStart]);
charsEnd = new Set([...charsEnd]);
// trim from the start
let trimFrom = null;
for (let i = 0; charsStart.has(str[i]); i++) {
trimFrom = i + 1;
}
if (trimFrom != null) {
str = str.slice(trimFrom)
}
// trim from the end
let trimTo = null;
for (let i = str.length-1; charsEnd.has(str[i]); i--) {
trimTo = i;
}
if (trimTo != null) {
str = str.slice(0,trimTo)
}
return str;
}
console.log(trim('-*&sometext&:!', ':{}[]*-^()|"/_~', '!:{}[]*?^()|&"/\\~'))
```
---
This solution is an improvement over yours insofar that `trim` is a reusable function. However it's should be obvious that using a regular expression allows a much more concise implementation.
I'm refraining from saying that this solution is more "complex" than regular expressions because the behavior of regular expressions can also complex and the logic presented here in itself is actually not complex (at least I hope it's relatively easy to follow). |
60,844,852 | I am looking for a prettier way to delete some special characters (`{}[]()*?!^:|&"/\~`) if they exists in the first and the last position of a string called query. My way is pretty ugly but does the work.
```js
while(
query.charAt(1)==":" ||
query.charAt(1)=="{" ||
query.charAt(1)=="}" ||
query.charAt(1)=="[" ||
query.charAt(1)=="]" ||
query.charAt(1)=="*" ||
query.charAt(1)=="-" ||
query.charAt(1)=="^" ||
query.charAt(1)=="(" ||
query.charAt(1)==")" ||
query.charAt(1)=="|" ||
query.charAt(1)=='"' ||
query.charAt(1)=="/" ||
query.charAt(1)=="_" ||
query.charAt(1)=='"' ||
query.charAt(1)=="~"
){
query = query.slice(1);
}
while(
query.charAt(query.length-1)=="!" ||
query.charAt(query.length-1)==":" ||
query.charAt(query.length-1)=="{" ||
query.charAt(query.length-1)=="}" ||
query.charAt(query.length-1)=="[" ||
query.charAt(query.length-1)=="]" ||
query.charAt(query.length-1)=="*" ||
query.charAt(query.length-1)=="?" ||
query.charAt(query.length-1)=="^" ||
query.charAt(query.length-1)=="(" ||
query.charAt(query.length-1)==")" ||
query.charAt(query.length-1)=="|" ||
query.charAt(query.length-1)=="&" ||
query.charAt(query.length-1)=='"' ||
query.charAt(query.length-1)=="/" ||
query.charAt(query.length-1)=="\\"||
query.charAt(query.length-1)=="~"
){
query = query.slice(0, -1);
}
``` | 2020/03/25 | [
"https://Stackoverflow.com/questions/60844852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12602828/"
] | Use a regular expression instead:
```
query = query.replace(/^[-:{}[\]*^()|"]+|[-:{}[\]*^()|"]+$/g, '');
```
This pattern is composed of:
```
^[CHARS]+|[CHARS]+$
```
where `CHARS` are the characters you want to remove.
* `^[CHARS]+` - Match one or more of those characters at the beginning of the string
* `|` OR match
* `[CHARS]+$` - one or more of those characters at the end of the string | In case you cannot easily understand regex, you can do another way (still ugly, but maybe better than yours. Not tested.):
```js
const filter = '{}[]()*?!^:|&"/\~';//include escape yourself
const listChar = filter.split('')//
for(let i = 0; i < listChar.length; i += 1)
{
const char = listChar[i];
while (str.indexOf(char) != -1)
str = str.replace(char, "");
}
``` |
53,433,285 | I'm having this json stored in db
```
{
"endDate": "2018-10-10",
"startDate": "2017-09-05",
"oldKeyValue": {
"foo": 1000,
"bar": 2000,
"baz": 3000
},
"anotherValue": 0
}
```
How can I rename `"oldKeyValue"` key to `"newKeyValue"` without knowing the index of the key in an `UPDATE` query? I'm looking for something like this
```
UPDATE `my_table` SET `my_col` = JSON()
```
NOTE: only the key needs to change, the values (i.e. `{"foo": 1000, "bar": 2000, "baz": 3000}`) should remain the same | 2018/11/22 | [
"https://Stackoverflow.com/questions/53433285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483422/"
] | There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.
We will remove the *oldKey-oldValue* pair using [`Json_Remove()`](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-remove) function, and then [`Json_Insert()`](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-insert) the *newKey-oldValue* pair.
[`Json_Extract()`](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-extract) function is used to fetch value corresponding to an input key in the JSON document.
```
UPDATE `my_table`
SET `my_col` = JSON_INSERT(
JSON_REMOVE(my_col, '$.oldKeyValue'),
'$.newKeyValue',
JSON_EXTRACT(my_col, '$.oldKeyValue')
);
```
**[Demo](https://www.db-fiddle.com/f/kHywwDrV1acnxb3x6HkWrT/0)**
```
SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';
SET @new_col := JSON_INSERT(
JSON_REMOVE(@my_col, '$.oldKeyValue'),
'$.newKeyValue',
JSON_EXTRACT(@my_col,'$.oldKeyValue')
);
SELECT @new_col;
```
**Result**
```
| @new_col |
| ------------------------------------------------------------------------------------------------------------------------------- |
| {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |
```
---
As an alternative to `Json_Extract()`, we can also use `->` operator to access the Value corresponding to a given Key in the JSON doc.
```
UPDATE `my_table`
SET `my_col` = JSON_INSERT(
JSON_REMOVE(my_col, '$.oldKeyValue'),
'$.newKeyValue',
my_col->'$.oldKeyValue'
);
``` | I personally prefer another method:
```
UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')
```
This replaces directly the key name in the JSON string without destroying the JSON structure.
I am using the additional `:` in order to avoid an unintentional replacement in a value. |
53,433,285 | I'm having this json stored in db
```
{
"endDate": "2018-10-10",
"startDate": "2017-09-05",
"oldKeyValue": {
"foo": 1000,
"bar": 2000,
"baz": 3000
},
"anotherValue": 0
}
```
How can I rename `"oldKeyValue"` key to `"newKeyValue"` without knowing the index of the key in an `UPDATE` query? I'm looking for something like this
```
UPDATE `my_table` SET `my_col` = JSON()
```
NOTE: only the key needs to change, the values (i.e. `{"foo": 1000, "bar": 2000, "baz": 3000}`) should remain the same | 2018/11/22 | [
"https://Stackoverflow.com/questions/53433285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483422/"
] | There is no straightforward JSON function to do the same. We can use a combination of some JSON functions.
We will remove the *oldKey-oldValue* pair using [`Json_Remove()`](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-remove) function, and then [`Json_Insert()`](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-insert) the *newKey-oldValue* pair.
[`Json_Extract()`](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-extract) function is used to fetch value corresponding to an input key in the JSON document.
```
UPDATE `my_table`
SET `my_col` = JSON_INSERT(
JSON_REMOVE(my_col, '$.oldKeyValue'),
'$.newKeyValue',
JSON_EXTRACT(my_col, '$.oldKeyValue')
);
```
**[Demo](https://www.db-fiddle.com/f/kHywwDrV1acnxb3x6HkWrT/0)**
```
SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}';
SET @new_col := JSON_INSERT(
JSON_REMOVE(@my_col, '$.oldKeyValue'),
'$.newKeyValue',
JSON_EXTRACT(@my_col,'$.oldKeyValue')
);
SELECT @new_col;
```
**Result**
```
| @new_col |
| ------------------------------------------------------------------------------------------------------------------------------- |
| {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} |
```
---
As an alternative to `Json_Extract()`, we can also use `->` operator to access the Value corresponding to a given Key in the JSON doc.
```
UPDATE `my_table`
SET `my_col` = JSON_INSERT(
JSON_REMOVE(my_col, '$.oldKeyValue'),
'$.newKeyValue',
my_col->'$.oldKeyValue'
);
``` | Plain text search & replace will only work if the JSON is stored in minified/compact format without extra whitespace in it. |
53,433,285 | I'm having this json stored in db
```
{
"endDate": "2018-10-10",
"startDate": "2017-09-05",
"oldKeyValue": {
"foo": 1000,
"bar": 2000,
"baz": 3000
},
"anotherValue": 0
}
```
How can I rename `"oldKeyValue"` key to `"newKeyValue"` without knowing the index of the key in an `UPDATE` query? I'm looking for something like this
```
UPDATE `my_table` SET `my_col` = JSON()
```
NOTE: only the key needs to change, the values (i.e. `{"foo": 1000, "bar": 2000, "baz": 3000}`) should remain the same | 2018/11/22 | [
"https://Stackoverflow.com/questions/53433285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483422/"
] | I personally prefer another method:
```
UPDATE my_table SET my_col = REPLACE(my_col, '"oldKeyValue":', '"newKeyValue":')
```
This replaces directly the key name in the JSON string without destroying the JSON structure.
I am using the additional `:` in order to avoid an unintentional replacement in a value. | Plain text search & replace will only work if the JSON is stored in minified/compact format without extra whitespace in it. |
10,950,356 | I have a quick question about Haskell. I've been following [Learn You a Haskell](http://learnyouahaskell.com/starting-out#tuples), and am just a bit confused as to the execution order / logic of the following snippet, used to calculate the side lengths of a triangle, when all sides are equal to or less than 10 and the total perimeter of the triangle is 24:
`[(a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c==24]`
The part that is confusing to me is the upper expansion bound on the `b` and `a` binding. From what I gather, the `..c` and `..b` are used to remove additional permutations (combinations?) of the same set of triangle sides.
When I run it with the `..c/b`, I get the answer:
`[(6,8,10)]`
When I don't have the `..c/b`:
`[(a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10], a^2 + b^2 == c^2, a+b+c==24]`
as I didn't when I initially typed it in, I got:
`[(8,6,10),(6,8,10)]`
Which is obviously representative of the same triangle, save for the `a` and `b` values have been swapped.
So, can someone walk me through the logic / execution / evaluation of what's going on here? | 2012/06/08 | [
"https://Stackoverflow.com/questions/10950356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420001/"
] | The original version considers all triplets (a,b,c) where c is a number between 1 and 10, b is a number between 1 and c and a is a number between 1 and b. (6,8,10) fits that criteria, (8,6,10) doesn't (because here a is 8 and b is 6, so a isn't between 0 and 6).
In your version you consider all triplets (a,b,c) where a, b and c are between 1 and 10. You make no restrictions on how a, b and c relate to each other, so (8, 6, 10) is not excluded since all numbers in it are indeed between 1 and 10.
If you think of it in terms of imperative for-loops, your version does this:
```
for c from 1 to 10:
for b from 1 to 10:
for a from 1 to 10:
if a^2 + b^2 == c^2 and a+b+c==24:
add (a,b,c) to the result
```
while the original version does this:
```
for c from 1 to 10:
for b from 1 to c:
for c from 1 to b:
if a^2 + b^2 == c^2 and a+b+c==24:
add (a,b,c) to the result
``` | It's not about execution order. In the first example you don't see the degenerate solution
```
[(8,6,10)]
```
since `a <= b <= c`. In the second case `a > b` is included in the list comprehension. |
10,950,356 | I have a quick question about Haskell. I've been following [Learn You a Haskell](http://learnyouahaskell.com/starting-out#tuples), and am just a bit confused as to the execution order / logic of the following snippet, used to calculate the side lengths of a triangle, when all sides are equal to or less than 10 and the total perimeter of the triangle is 24:
`[(a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c==24]`
The part that is confusing to me is the upper expansion bound on the `b` and `a` binding. From what I gather, the `..c` and `..b` are used to remove additional permutations (combinations?) of the same set of triangle sides.
When I run it with the `..c/b`, I get the answer:
`[(6,8,10)]`
When I don't have the `..c/b`:
`[(a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10], a^2 + b^2 == c^2, a+b+c==24]`
as I didn't when I initially typed it in, I got:
`[(8,6,10),(6,8,10)]`
Which is obviously representative of the same triangle, save for the `a` and `b` values have been swapped.
So, can someone walk me through the logic / execution / evaluation of what's going on here? | 2012/06/08 | [
"https://Stackoverflow.com/questions/10950356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420001/"
] | The original version considers all triplets (a,b,c) where c is a number between 1 and 10, b is a number between 1 and c and a is a number between 1 and b. (6,8,10) fits that criteria, (8,6,10) doesn't (because here a is 8 and b is 6, so a isn't between 0 and 6).
In your version you consider all triplets (a,b,c) where a, b and c are between 1 and 10. You make no restrictions on how a, b and c relate to each other, so (8, 6, 10) is not excluded since all numbers in it are indeed between 1 and 10.
If you think of it in terms of imperative for-loops, your version does this:
```
for c from 1 to 10:
for b from 1 to 10:
for a from 1 to 10:
if a^2 + b^2 == c^2 and a+b+c==24:
add (a,b,c) to the result
```
while the original version does this:
```
for c from 1 to 10:
for b from 1 to c:
for c from 1 to b:
if a^2 + b^2 == c^2 and a+b+c==24:
add (a,b,c) to the result
``` | List comprehensions can be written in terms of other functions like `concatMap`, which clarifies the scope of the bindings. As a one-liner, your example becomes something like this:
```
concatMap (\c -> concatMap (\b -> concatMap (\a -> if a^2 + b^2 == c^2 then (if a+b+c == 24 then [(a,b,c)] else []) else []) (enumFromTo 1 b)) (enumFromTo 1 c)) (enumFromTo 1 10)
```
Yeah, that looks ugly, but it's similar to what Haskell desugars your comprehensions into. The scope of each of the variables `a`, `b` and `c`, should be obvious from this.
Or alternatively, this can be written with the `List` monad:
```
import Control.Monad
example = do c <- [1..10]
b <- [1..c]
a <- [1..b]
guard (a^2 + b^2 == c^2)
guard (a+b+c == 24)
return (a,b,c)
```
This is actually very similar as the one-liner above, given the definition of the `List` Monad and `guard`:
```
instance Monad [] where
return x = [x]
xs >>= f = concatMap f xs
instance MonadPlus [] where
mzero = []
mconcat = (++)
guard bool = if bool then return () else mzero
``` |
28,879,751 | so here is the situation i currently am having trouble with.
I want to check if a user has permission to view a page, with one single function.
So I have an array with key/values where i store permissions in.
```
{"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
```
Stored in `service.currentUser`, which can be called by using `service.currentUser.authorities`.
I have a function:
```
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test === role)
{
return (!!(service.currentUser) && true);
}
}
return false;
}
```
I created the `test` variable to debug its value. And the `permission` parameter has the value 'gebruikersbeheer'.
Now i want to compare the value of the `perm` key with the `role` and check if it is true.
Now i have searched along the internet to do so, and i only found solutions which are not viable for me nor implementable.
When i start debugging my `perm` has an integer value. Why is it not the name of the key? (Which must be "role")
Also, when i use Watch on the `role` and `test` variables they are completely the same but still i cant compare them and get a `true`.
(Dont mind the return statement at this point.)
Also i cannot modify the array. It is returned by spring security this way.
Is there any (nicer) way to check if `authorities` contains `role`?
It might be duplicate, but i couldnt find anything for my specific situation.
Cheers. | 2015/03/05 | [
"https://Stackoverflow.com/questions/28879751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1863487/"
] | You currently are check a object with another object, is best check the string with the string, below show an little example of the same function but using the **some** method from arrays;
```js
var currentUser = {"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
function hasPermission(permission) {
return currentUser.authorities.some(function(v){
return v.role === permission;
});
}
alert("Have permission? "+ hasPermission("gebruikersbeheer"))
``` | `service.currentUser.authorities` is an array this is why you're getting an integer for `perm` in `for(perm in service.currentUser.authorities)`.
The other problem is that you can't compare all the properties in the object using `===` (including prototype properties), so you need to compare explicit the values for the properties... or create a custom function to compare your objects.
You can try with:
```
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test["role"] === role["role"])
{
return (!!(service.currentUser) && true);
}
}
return false;
}
```
Hope this helps, |
28,879,751 | so here is the situation i currently am having trouble with.
I want to check if a user has permission to view a page, with one single function.
So I have an array with key/values where i store permissions in.
```
{"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
```
Stored in `service.currentUser`, which can be called by using `service.currentUser.authorities`.
I have a function:
```
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test === role)
{
return (!!(service.currentUser) && true);
}
}
return false;
}
```
I created the `test` variable to debug its value. And the `permission` parameter has the value 'gebruikersbeheer'.
Now i want to compare the value of the `perm` key with the `role` and check if it is true.
Now i have searched along the internet to do so, and i only found solutions which are not viable for me nor implementable.
When i start debugging my `perm` has an integer value. Why is it not the name of the key? (Which must be "role")
Also, when i use Watch on the `role` and `test` variables they are completely the same but still i cant compare them and get a `true`.
(Dont mind the return statement at this point.)
Also i cannot modify the array. It is returned by spring security this way.
Is there any (nicer) way to check if `authorities` contains `role`?
It might be duplicate, but i couldnt find anything for my specific situation.
Cheers. | 2015/03/05 | [
"https://Stackoverflow.com/questions/28879751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1863487/"
] | You currently are check a object with another object, is best check the string with the string, below show an little example of the same function but using the **some** method from arrays;
```js
var currentUser = {"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
function hasPermission(permission) {
return currentUser.authorities.some(function(v){
return v.role === permission;
});
}
alert("Have permission? "+ hasPermission("gebruikersbeheer"))
``` | Since you are just concerned with whether something exists or not, you can use the [Array.Some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) function. It still loops through the array, but will stop upon hitting the first instance that is true. Your method is basically doing the same thing already, but this way it a bit cleaner, since it uses the actual elements of the array (instead of an index).
```
hasPermission: function (permission) {
var authArray = service.currentUser.authorities;
var hasAuth = authArray.some(function(kvp) {
return kvp.role == permission; //function to determine a match
});
return hasAuth;
}
``` |
28,879,751 | so here is the situation i currently am having trouble with.
I want to check if a user has permission to view a page, with one single function.
So I have an array with key/values where i store permissions in.
```
{"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
```
Stored in `service.currentUser`, which can be called by using `service.currentUser.authorities`.
I have a function:
```
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test === role)
{
return (!!(service.currentUser) && true);
}
}
return false;
}
```
I created the `test` variable to debug its value. And the `permission` parameter has the value 'gebruikersbeheer'.
Now i want to compare the value of the `perm` key with the `role` and check if it is true.
Now i have searched along the internet to do so, and i only found solutions which are not viable for me nor implementable.
When i start debugging my `perm` has an integer value. Why is it not the name of the key? (Which must be "role")
Also, when i use Watch on the `role` and `test` variables they are completely the same but still i cant compare them and get a `true`.
(Dont mind the return statement at this point.)
Also i cannot modify the array. It is returned by spring security this way.
Is there any (nicer) way to check if `authorities` contains `role`?
It might be duplicate, but i couldnt find anything for my specific situation.
Cheers. | 2015/03/05 | [
"https://Stackoverflow.com/questions/28879751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1863487/"
] | `service.currentUser.authorities` is an array this is why you're getting an integer for `perm` in `for(perm in service.currentUser.authorities)`.
The other problem is that you can't compare all the properties in the object using `===` (including prototype properties), so you need to compare explicit the values for the properties... or create a custom function to compare your objects.
You can try with:
```
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test["role"] === role["role"])
{
return (!!(service.currentUser) && true);
}
}
return false;
}
```
Hope this helps, | Since you are just concerned with whether something exists or not, you can use the [Array.Some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) function. It still loops through the array, but will stop upon hitting the first instance that is true. Your method is basically doing the same thing already, but this way it a bit cleaner, since it uses the actual elements of the array (instead of an index).
```
hasPermission: function (permission) {
var authArray = service.currentUser.authorities;
var hasAuth = authArray.some(function(kvp) {
return kvp.role == permission; //function to determine a match
});
return hasAuth;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.