qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
8,737,854 |
I have a string in php formatted like this:
```
http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb
```
where aaa... and bbb.... represent random characters and are random in length.
I would like to parse the string so that I am left with this:
```
http://bbbbbbbbbbbbbbb
```
|
2012/01/05
|
['https://Stackoverflow.com/questions/8737854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/657818/']
|
Hi This would help you to get the address:
```
$str = 'http://www.example.com/*http://www.another.org/';
$pattern = '/^http:\/\/[\.\w\-]+\/\*(http:\/\/.+)$/';
//$result = preg_replace($pattern, '$1', $str);
$found = preg_match_all($pattern, $str, $result);
$url = (!$found==0) ? $result[1][0] : '';
echo $str . '<br />' . $url;
```
|
Here is a clean solution: grab everything after the last occurrence of "http://".
```
$start = strrpos($input, 'http://');
$output = substr($input, $start);
```
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
You can order by ascending both column in separate and then merge it using [with clauses](https://oracle-base.com/articles/misc/with-clause), `rownum` **EDIT** using @Kaushik Nayak Tip in comments
```
with a as
(select rownum as r,a1.* from (select col1, col3 from Hakuna_matata order by col1 asc ) a1)
, b as
(select rownum as r,a2.* from (select col2 from Hakuna_matata order by col2 asc ) a2)
select a.col1, b.col2, a.col3 from a ,b where a.r=b.r;
```
col3 is example of adding more columns to select
|
Appropriate to use `ascii` function in your case :
```
SQL> select col1, ( ascii(col1) - 64 ) col2 from Hakuna_matata;
```
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
As there is no explanation given on how `col2` should be generated (e.g. swapping the values or just re-numbering them), I'd go for:
```
select col1,
row_number() over (order by col1) as col2
from Hakuna_matata;
```
Which produces the desired output - but it's unclear if that is the desired *solution*.
|
Appropriate to use `ascii` function in your case :
```
SQL> select col1, ( ascii(col1) - 64 ) col2 from Hakuna_matata;
```
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
You can order by ascending both column in separate and then merge it using [with clauses](https://oracle-base.com/articles/misc/with-clause), `rownum` **EDIT** using @Kaushik Nayak Tip in comments
```
with a as
(select rownum as r,a1.* from (select col1, col3 from Hakuna_matata order by col1 asc ) a1)
, b as
(select rownum as r,a2.* from (select col2 from Hakuna_matata order by col2 asc ) a2)
select a.col1, b.col2, a.col3 from a ,b where a.r=b.r;
```
col3 is example of adding more columns to select
|
Maybe there is another way, but I think that you have to update table data:
```
update Hakuna_matata set col2=1 where col1='A';
update Hakuna_matata set col2=2 where col1='B';
```
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
As there is no explanation given on how `col2` should be generated (e.g. swapping the values or just re-numbering them), I'd go for:
```
select col1,
row_number() over (order by col1) as col2
from Hakuna_matata;
```
Which produces the desired output - but it's unclear if that is the desired *solution*.
|
Maybe there is another way, but I think that you have to update table data:
```
update Hakuna_matata set col2=1 where col1='A';
update Hakuna_matata set col2=2 where col1='B';
```
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
You can order by ascending both column in separate and then merge it using [with clauses](https://oracle-base.com/articles/misc/with-clause), `rownum` **EDIT** using @Kaushik Nayak Tip in comments
```
with a as
(select rownum as r,a1.* from (select col1, col3 from Hakuna_matata order by col1 asc ) a1)
, b as
(select rownum as r,a2.* from (select col2 from Hakuna_matata order by col2 asc ) a2)
select a.col1, b.col2, a.col3 from a ,b where a.r=b.r;
```
col3 is example of adding more columns to select
|
As there is no explanation given on how `col2` should be generated (e.g. swapping the values or just re-numbering them), I'd go for:
```
select col1,
row_number() over (order by col1) as col2
from Hakuna_matata;
```
Which produces the desired output - but it's unclear if that is the desired *solution*.
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
You can order by ascending both column in separate and then merge it using [with clauses](https://oracle-base.com/articles/misc/with-clause), `rownum` **EDIT** using @Kaushik Nayak Tip in comments
```
with a as
(select rownum as r,a1.* from (select col1, col3 from Hakuna_matata order by col1 asc ) a1)
, b as
(select rownum as r,a2.* from (select col2 from Hakuna_matata order by col2 asc ) a2)
select a.col1, b.col2, a.col3 from a ,b where a.r=b.r;
```
col3 is example of adding more columns to select
|
Interesting. All the other answers seem so complicated. I would do:
```
select col1, row_number() over (order by col1) as seqnum
from Hakuna_matata
order by col1;
```
But the interviewer probably wants you to ask questions about what the ordering means, not simply come up with a solution that makes assumptions.
|
49,217,832 |
This was the question asked to me in interview :
Input:
```
SQL> select col1,col2 from Hakuna_matata;
COL1 ~ COL2
--------------------------------------------------~
A ~ 2
B ~ 1
C ~ 3
```
I want output as
```
COL1 ~ COL2
--------------------------------------------------~---
A ~ 1
B ~ 2
C ~ 3
```
How you will do in SQL?
Please help me with the queries/way how this can be done .
|
2018/03/11
|
['https://Stackoverflow.com/questions/49217832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9474466/']
|
As there is no explanation given on how `col2` should be generated (e.g. swapping the values or just re-numbering them), I'd go for:
```
select col1,
row_number() over (order by col1) as col2
from Hakuna_matata;
```
Which produces the desired output - but it's unclear if that is the desired *solution*.
|
Interesting. All the other answers seem so complicated. I would do:
```
select col1, row_number() over (order by col1) as seqnum
from Hakuna_matata
order by col1;
```
But the interviewer probably wants you to ask questions about what the ordering means, not simply come up with a solution that makes assumptions.
|
53,771,718 |
`__FILE__` returns the path of the current Ruby script file.
One potentially significant problem is that, if using `binding.pry`, `__FILE__` evaluates to `(pry)`. It is potentially problematic to have `__FILE__` evaluate to different values depending on whether it is evaluated in the context of `binding.pry`. For example,
```
$stdout.print "****************************************\n\n"
$stdout.print "FILE: #{__FILE__}\n\n"
$stdout.print "****************************************\n\n"
binding.pry
```
When the script pauses at `binding.pry`, I get:
```
__FILE__
# >> (pry)
```
Does anyone know any mechanism to get the path of the current file even in the context of `binding.pry`?
|
2018/12/13
|
['https://Stackoverflow.com/questions/53771718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6572871/']
|
Use `_file_` instead of `__FILE__`. For example, given two files:
```
# foo.rb
require 'pry'
require './bar'
binding.pry
b = Bar.new
```
and:
```
# bar.rb
require 'pry'
class Bar
def initialize
binding.pry
end
end
```
Run them with `ruby foo.rb`:
```
ruby foo.rb
From: /Users/username/foo.rb @ line 3 :
1: require 'pry'
2: require './bar'
=> 3: binding.pry
4: b = Bar.new
(main):1 ⇒ _file_
=> "/Users/username/foo.rb"
(main):2 ⇒ exit
From: /Users/username/bar.rb @ line 4 Bar#initialize:
3: def initialize
=> 4: binding.pry
5: end
(#<Bar:0x00007fbb6caaff08>):1 ⇒ _file_
=> "/Users/username/bar.rb"
```
`_file_` and any other local variable names can be found in [`binding.local_variables`](https://ruby-doc.org/core-2.5.3/Binding.html#method-i-local_variables).
|
Sergio Tulentsev made a simple suggestion, assign `__FILE__` to a variable before invoking `binding.pry`.
anothermh, mentioned `_file_` which is available in binding pry.
In the end, I combined the two answers:
```
# When in the context of binding.pry, __FILE__ resolves to '(pry)',
# binding contains the local variable _file_ which always resolves to
# the current file, even when being evaluated in the context of binding.pry .
# _file_ is only available, in binding. This does the trick:
current_file = __FILE__.downcase == '(pry)' ? _file_ : __FILE__
```
|
8,034,656 |
For example:
```
<div style="background-color:black;width:20px;height:20px;" > </div>
<div style="background-color:red;width:20px;height:20px; margin:50px;" > </div>
```
<http://jsfiddle.net/TLLup/>
Here is two bars red and black.
I want to stick black bar to red and black bar must follow to red if it changes coordinates and it doesn't matter what we are doing changes DOM or just using jquery function `$(element).position()`.
|
2011/11/07
|
['https://Stackoverflow.com/questions/8034656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290082/']
|
I had a somewhat similar issue because I was performing my calculations in ViewDidLoad. I was able to work around the issue by creating a bool flag in the view's code and only performing the calculations in ViewDidAppear if the flag was not set (and, of course setting the flag so that the logic wasn't repeated each time).
|
On iOS 5 and up, sizeThatFits on a UITableView gives the correct result when called within the viewDidLayoutSubviews UIViewController method.
|
2,891,472 |
I was wondering if there is a (webbased) way to scale down a whole website and put it into an iframe. [including images etc], so that a user would get a fully functional preview of the website (only for websites without frame busting methods of course).
|
2010/05/23
|
['https://Stackoverflow.com/questions/2891472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253387/']
|
Have you tried the following with css?
```
body {
zoom: 10%;
}
```
|
Thats up to javascript or css although it really depends about the browser and its behavior to certain commands.
|
2,891,472 |
I was wondering if there is a (webbased) way to scale down a whole website and put it into an iframe. [including images etc], so that a user would get a fully functional preview of the website (only for websites without frame busting methods of course).
|
2010/05/23
|
['https://Stackoverflow.com/questions/2891472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253387/']
|
No, there isn't.
The Microsoft propriety `zoom` property could probably do it, but not in most browsers, and not in pages you can't edit the CSS for.
If you want to provide a preview, provide a thumbnail graphic (which would probably be a lot faster for the user to download in most cases anyway)
|
Thats up to javascript or css although it really depends about the browser and its behavior to certain commands.
|
2,891,472 |
I was wondering if there is a (webbased) way to scale down a whole website and put it into an iframe. [including images etc], so that a user would get a fully functional preview of the website (only for websites without frame busting methods of course).
|
2010/05/23
|
['https://Stackoverflow.com/questions/2891472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253387/']
|
Have you tried the following with css?
```
body {
zoom: 10%;
}
```
|
You can use javascript to specify the iframe src.
`document.getElementById('myiframe').src = 'my url';`
|
2,891,472 |
I was wondering if there is a (webbased) way to scale down a whole website and put it into an iframe. [including images etc], so that a user would get a fully functional preview of the website (only for websites without frame busting methods of course).
|
2010/05/23
|
['https://Stackoverflow.com/questions/2891472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253387/']
|
No, there isn't.
The Microsoft propriety `zoom` property could probably do it, but not in most browsers, and not in pages you can't edit the CSS for.
If you want to provide a preview, provide a thumbnail graphic (which would probably be a lot faster for the user to download in most cases anyway)
|
You can use javascript to specify the iframe src.
`document.getElementById('myiframe').src = 'my url';`
|
2,891,472 |
I was wondering if there is a (webbased) way to scale down a whole website and put it into an iframe. [including images etc], so that a user would get a fully functional preview of the website (only for websites without frame busting methods of course).
|
2010/05/23
|
['https://Stackoverflow.com/questions/2891472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253387/']
|
No, there isn't.
The Microsoft propriety `zoom` property could probably do it, but not in most browsers, and not in pages you can't edit the CSS for.
If you want to provide a preview, provide a thumbnail graphic (which would probably be a lot faster for the user to download in most cases anyway)
|
Have you tried the following with css?
```
body {
zoom: 10%;
}
```
|
22,243 |
I know that $G\_t = R\_{t+1} + G\_{t+1}$.
Suppose $\gamma = 0.9$ and the reward sequence is $R\_1 = 2$ followed by an infinite sequence of $7$s. What is the value of $G\_0$?
As it's infinite, how can we deduce the value of $G\_0$? I don't see the solution. It's just $G\_0 = 5 + 0.9\*G\_1$. And we don't know $G\_1$ value, and we don't know $R\_2, R\_3, R\_4, ...$
|
2020/06/29
|
['https://ai.stackexchange.com/questions/22243', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/38264/']
|
You know all the rewards. They're 5, 7, 7, 7, and 7s forever. The problem now boils down to essentially a geometric series computation.
$$
G\_0 = R\_0 + \gamma G\_1
$$
$$
G\_0 = 5 + \gamma\sum\_{k=0}^\infty 7\gamma^k
$$
$$
G\_0 = 5 + 7\gamma\sum\_{k=0}^\infty\gamma^k
$$
$$
G\_0 = 5 + \frac{7\gamma}{1-\gamma} = \frac{5 + 2\gamma}{1-\gamma}
$$
|
There are a few ways to resolve values of infinite sums. In this case, we can use a simple technique of self-reference to create a solvable equation.
I will show how to do it for the generic case here of an MDP with same reward $r$ on each timestep:
$$G\_t = \sum\_{k=0}^{\infty} \gamma^k r$$
We can "pop off" the first item:
$$G\_t = r + \sum\_{k=1}^{\infty} \gamma^k r$$
Then we can note that the second term is just $\gamma$ times the orginal term:
$$G\_t = r + \gamma G\_t$$
(There are situations where this won't work, such as when $\gamma \ge 1$ - essentially we are taking advantage that the high order terms are arbitrarily close to zero, so can be ignored)
Re-arrange it again:
$$G\_t = \frac{r}{1 - \gamma}$$
This means that you can get the value for a return for the discounted sum of repeating rewards. Which allows you to calculate your $G\_1$. I will leave that last part as an execrise for you, as you already figured the first part out.
|
48,735,135 |
I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3
Where a1,a2,a3 are random generated numbers and x,y are parameters.
But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert this function to tensorflow tensor.Here is my code, string with "##" dont work.
```
import tensorflow as tf
from random import random, seed
import numpy as np
def mypolyval(x, min_point, min_value):
res = min_value
for i in range(len(min_point)):
res += (x[i] - min_point[i]) ** 2
return res
class FunGen:
def __init__(self, dim, n):
self.dim = dim
self.n = n
self.functions = []
self.x = []
def c2(self):
seed(10)
for _ in range(self.n):
min_point = [random() for _ in range(self.dim)]
min_value = random()
f = np.vectorize(mypolyval, excluded=['x'])
##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
self.functions.append((f, min_point, min_value))
return self.functions
functions = FunGen(2, 1).c2()
for i in functions:
print(type(i[0]))
f=i[0]
## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
##a=tf.convert_to_tensor(f,dtype=np.float32)
```
|
2018/02/11
|
['https://Stackoverflow.com/questions/48735135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8895598/']
|
Please note that as of November of 2018, there has been a [breaking change to MetaMask](https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8) where MetaMask will no longer automatically inject web3 into the browser. Instead users must grant the DApp access to their accounts via accepting a prompt dialog created by window.ethereum.enable(). See the below code for handling MetaMask in both modern DApp browsers as well as legacy DApp browsers.
```js
// Modern DApp Browsers
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
window.ethereum.enable().then(function() {
// User has allowed account access to DApp...
});
} catch(e) {
// User has denied account access to DApp...
}
}
// Legacy DApp Browsers
else if (window.web3) {
web3 = new Web3(window.web3.currentProvider);
}
// Non-DApp Browsers
else {
alert('You have to install MetaMask !');
}
```
|
You should use web3 provider like MetaMask in browser.
This is script that I use for web3 detection:
```
window.addEventListener('load', function () {
if (typeof web3 !== 'undefined') {
window.web3 = new Web3(window.web3.currentProvider)
if (window.web3.currentProvider.isMetaMask === true) {
window.web3.eth.getAccounts((error, accounts) => {
if (accounts.length == 0) {
// there is no active accounts in MetaMask
}
else {
// It's ok
}
});
} else {
// Another web3 provider
}
} else {
// No web 3 provider
}
});
```
|
48,735,135 |
I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3
Where a1,a2,a3 are random generated numbers and x,y are parameters.
But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert this function to tensorflow tensor.Here is my code, string with "##" dont work.
```
import tensorflow as tf
from random import random, seed
import numpy as np
def mypolyval(x, min_point, min_value):
res = min_value
for i in range(len(min_point)):
res += (x[i] - min_point[i]) ** 2
return res
class FunGen:
def __init__(self, dim, n):
self.dim = dim
self.n = n
self.functions = []
self.x = []
def c2(self):
seed(10)
for _ in range(self.n):
min_point = [random() for _ in range(self.dim)]
min_value = random()
f = np.vectorize(mypolyval, excluded=['x'])
##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
self.functions.append((f, min_point, min_value))
return self.functions
functions = FunGen(2, 1).c2()
for i in functions:
print(type(i[0]))
f=i[0]
## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
##a=tf.convert_to_tensor(f,dtype=np.float32)
```
|
2018/02/11
|
['https://Stackoverflow.com/questions/48735135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8895598/']
|
You should use web3 provider like MetaMask in browser.
This is script that I use for web3 detection:
```
window.addEventListener('load', function () {
if (typeof web3 !== 'undefined') {
window.web3 = new Web3(window.web3.currentProvider)
if (window.web3.currentProvider.isMetaMask === true) {
window.web3.eth.getAccounts((error, accounts) => {
if (accounts.length == 0) {
// there is no active accounts in MetaMask
}
else {
// It's ok
}
});
} else {
// Another web3 provider
}
} else {
// No web 3 provider
}
});
```
|
To new readers that want to fix this issue, as of [January 2021, Metamask has removed it's injected `window.web3` API](https://docs.metamask.io/guide/provider-migration.html#provider-migration-guide). To use connect your app to Metamask, I'd try something like this
```
export const connectWallet = async () => {
if (window.ethereum) { //check if Metamask is installed
try {
const address = await window.ethereum.enable(); //connect Metamask
const obj = {
connectedStatus: true,
status: "",
address: address
}
return obj;
} catch (error) {
return {
connectedStatus: false,
status: " Connect to Metamask using the button on the top right."
}
}
} else {
return {
connectedStatus: false,
status: " You must install Metamask into your browser: https://metamask.io/download.html"
}
}
};
```
In [this tutorial on creating an NFT Minter with React](https://docs.alchemyapi.io/alchemy/tutorials/nft-minter), you can also learn how to call smart contract functions and sign transactions via Metamask! Best of luck :)
|
48,735,135 |
I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3
Where a1,a2,a3 are random generated numbers and x,y are parameters.
But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert this function to tensorflow tensor.Here is my code, string with "##" dont work.
```
import tensorflow as tf
from random import random, seed
import numpy as np
def mypolyval(x, min_point, min_value):
res = min_value
for i in range(len(min_point)):
res += (x[i] - min_point[i]) ** 2
return res
class FunGen:
def __init__(self, dim, n):
self.dim = dim
self.n = n
self.functions = []
self.x = []
def c2(self):
seed(10)
for _ in range(self.n):
min_point = [random() for _ in range(self.dim)]
min_value = random()
f = np.vectorize(mypolyval, excluded=['x'])
##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
self.functions.append((f, min_point, min_value))
return self.functions
functions = FunGen(2, 1).c2()
for i in functions:
print(type(i[0]))
f=i[0]
## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
##a=tf.convert_to_tensor(f,dtype=np.float32)
```
|
2018/02/11
|
['https://Stackoverflow.com/questions/48735135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8895598/']
|
You should use web3 provider like MetaMask in browser.
This is script that I use for web3 detection:
```
window.addEventListener('load', function () {
if (typeof web3 !== 'undefined') {
window.web3 = new Web3(window.web3.currentProvider)
if (window.web3.currentProvider.isMetaMask === true) {
window.web3.eth.getAccounts((error, accounts) => {
if (accounts.length == 0) {
// there is no active accounts in MetaMask
}
else {
// It's ok
}
});
} else {
// Another web3 provider
}
} else {
// No web 3 provider
}
});
```
|
Thanks for the other answers in this question. I refer to them to create this hook in my project.
```
export function useCheckMetaMaskInstalled() {
const [installed, setInstalled] = useState(false);
useEffect(() => {
if (window.ethereum) {
setInstalled(true);
}
}, []);
return installed;
}
```
|
48,735,135 |
I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3
Where a1,a2,a3 are random generated numbers and x,y are parameters.
But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert this function to tensorflow tensor.Here is my code, string with "##" dont work.
```
import tensorflow as tf
from random import random, seed
import numpy as np
def mypolyval(x, min_point, min_value):
res = min_value
for i in range(len(min_point)):
res += (x[i] - min_point[i]) ** 2
return res
class FunGen:
def __init__(self, dim, n):
self.dim = dim
self.n = n
self.functions = []
self.x = []
def c2(self):
seed(10)
for _ in range(self.n):
min_point = [random() for _ in range(self.dim)]
min_value = random()
f = np.vectorize(mypolyval, excluded=['x'])
##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
self.functions.append((f, min_point, min_value))
return self.functions
functions = FunGen(2, 1).c2()
for i in functions:
print(type(i[0]))
f=i[0]
## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
##a=tf.convert_to_tensor(f,dtype=np.float32)
```
|
2018/02/11
|
['https://Stackoverflow.com/questions/48735135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8895598/']
|
Please note that as of November of 2018, there has been a [breaking change to MetaMask](https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8) where MetaMask will no longer automatically inject web3 into the browser. Instead users must grant the DApp access to their accounts via accepting a prompt dialog created by window.ethereum.enable(). See the below code for handling MetaMask in both modern DApp browsers as well as legacy DApp browsers.
```js
// Modern DApp Browsers
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
window.ethereum.enable().then(function() {
// User has allowed account access to DApp...
});
} catch(e) {
// User has denied account access to DApp...
}
}
// Legacy DApp Browsers
else if (window.web3) {
web3 = new Web3(window.web3.currentProvider);
}
// Non-DApp Browsers
else {
alert('You have to install MetaMask !');
}
```
|
To new readers that want to fix this issue, as of [January 2021, Metamask has removed it's injected `window.web3` API](https://docs.metamask.io/guide/provider-migration.html#provider-migration-guide). To use connect your app to Metamask, I'd try something like this
```
export const connectWallet = async () => {
if (window.ethereum) { //check if Metamask is installed
try {
const address = await window.ethereum.enable(); //connect Metamask
const obj = {
connectedStatus: true,
status: "",
address: address
}
return obj;
} catch (error) {
return {
connectedStatus: false,
status: " Connect to Metamask using the button on the top right."
}
}
} else {
return {
connectedStatus: false,
status: " You must install Metamask into your browser: https://metamask.io/download.html"
}
}
};
```
In [this tutorial on creating an NFT Minter with React](https://docs.alchemyapi.io/alchemy/tutorials/nft-minter), you can also learn how to call smart contract functions and sign transactions via Metamask! Best of luck :)
|
48,735,135 |
I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3
Where a1,a2,a3 are random generated numbers and x,y are parameters.
But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert this function to tensorflow tensor.Here is my code, string with "##" dont work.
```
import tensorflow as tf
from random import random, seed
import numpy as np
def mypolyval(x, min_point, min_value):
res = min_value
for i in range(len(min_point)):
res += (x[i] - min_point[i]) ** 2
return res
class FunGen:
def __init__(self, dim, n):
self.dim = dim
self.n = n
self.functions = []
self.x = []
def c2(self):
seed(10)
for _ in range(self.n):
min_point = [random() for _ in range(self.dim)]
min_value = random()
f = np.vectorize(mypolyval, excluded=['x'])
##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
self.functions.append((f, min_point, min_value))
return self.functions
functions = FunGen(2, 1).c2()
for i in functions:
print(type(i[0]))
f=i[0]
## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
##a=tf.convert_to_tensor(f,dtype=np.float32)
```
|
2018/02/11
|
['https://Stackoverflow.com/questions/48735135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8895598/']
|
Please note that as of November of 2018, there has been a [breaking change to MetaMask](https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8) where MetaMask will no longer automatically inject web3 into the browser. Instead users must grant the DApp access to their accounts via accepting a prompt dialog created by window.ethereum.enable(). See the below code for handling MetaMask in both modern DApp browsers as well as legacy DApp browsers.
```js
// Modern DApp Browsers
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
window.ethereum.enable().then(function() {
// User has allowed account access to DApp...
});
} catch(e) {
// User has denied account access to DApp...
}
}
// Legacy DApp Browsers
else if (window.web3) {
web3 = new Web3(window.web3.currentProvider);
}
// Non-DApp Browsers
else {
alert('You have to install MetaMask !');
}
```
|
Thanks for the other answers in this question. I refer to them to create this hook in my project.
```
export function useCheckMetaMaskInstalled() {
const [installed, setInstalled] = useState(false);
useEffect(() => {
if (window.ethereum) {
setInstalled(true);
}
}, []);
return installed;
}
```
|
48,735,135 |
I am trying to create function using numpy something like f=(x-a1)^2+(y-a2)^2+a3
Where a1,a2,a3 are random generated numbers and x,y are parameters.
But I cant work with it, I want to find f(0,0) where [0,0] is [x,y] and [a1,a2,a3] were set before,but my code doesnt work.
And then I want to convert this function to tensorflow tensor.Here is my code, string with "##" dont work.
```
import tensorflow as tf
from random import random, seed
import numpy as np
def mypolyval(x, min_point, min_value):
res = min_value
for i in range(len(min_point)):
res += (x[i] - min_point[i]) ** 2
return res
class FunGen:
def __init__(self, dim, n):
self.dim = dim
self.n = n
self.functions = []
self.x = []
def c2(self):
seed(10)
for _ in range(self.n):
min_point = [random() for _ in range(self.dim)]
min_value = random()
f = np.vectorize(mypolyval, excluded=['x'])
##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
self.functions.append((f, min_point, min_value))
return self.functions
functions = FunGen(2, 1).c2()
for i in functions:
print(type(i[0]))
f=i[0]
## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
##a=tf.convert_to_tensor(f,dtype=np.float32)
```
|
2018/02/11
|
['https://Stackoverflow.com/questions/48735135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8895598/']
|
To new readers that want to fix this issue, as of [January 2021, Metamask has removed it's injected `window.web3` API](https://docs.metamask.io/guide/provider-migration.html#provider-migration-guide). To use connect your app to Metamask, I'd try something like this
```
export const connectWallet = async () => {
if (window.ethereum) { //check if Metamask is installed
try {
const address = await window.ethereum.enable(); //connect Metamask
const obj = {
connectedStatus: true,
status: "",
address: address
}
return obj;
} catch (error) {
return {
connectedStatus: false,
status: " Connect to Metamask using the button on the top right."
}
}
} else {
return {
connectedStatus: false,
status: " You must install Metamask into your browser: https://metamask.io/download.html"
}
}
};
```
In [this tutorial on creating an NFT Minter with React](https://docs.alchemyapi.io/alchemy/tutorials/nft-minter), you can also learn how to call smart contract functions and sign transactions via Metamask! Best of luck :)
|
Thanks for the other answers in this question. I refer to them to create this hook in my project.
```
export function useCheckMetaMaskInstalled() {
const [installed, setInstalled] = useState(false);
useEffect(() => {
if (window.ethereum) {
setInstalled(true);
}
}, []);
return installed;
}
```
|
62,387,623 |
```
df_clean['message'] = df_clean['message'].apply(lambda x: gensim.parsing.preprocessing.remove_stopwords(x))
```
I tried this on a dataframe's column 'message' but I get the error:
```
TypeError: decoding to str: need a bytes-like object, list found
```
|
2020/06/15
|
['https://Stackoverflow.com/questions/62387623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10608841/']
|
Apparently, the `df_clean["message"]` column contains a list of words, not a string, hence the error saying that `need a bytes-like object, list found`.
To fix this issue, you need to convert it to string again using `join()` method like so:
```
df_clean['message'] = df_clean['message'].apply(lambda x: gensim.parsing.preprocessing.remove_stopwords(" ".join(x)))
```
Notice that the `df_clean["message"]` will contain string objects after applying the previous code.
|
This is not a `gensim` problem, the error is raised by `pandas`: there is a value in your column `message` that is of type `list` instead of `string`. Here's a minimal `pandas` example:
```
import pandas as pd
from gensim.parsing.preprocessing import remove_stopwords
df = pd.DataFrame([['one', 'two'], ['three', ['four']]], columns=['A', 'B'])
df.A.apply(remove_stopwords) # works fine
df.B.apply(remove_stopwords)
TypeError: decoding to str: need a bytes-like object, list found
```
|
62,387,623 |
```
df_clean['message'] = df_clean['message'].apply(lambda x: gensim.parsing.preprocessing.remove_stopwords(x))
```
I tried this on a dataframe's column 'message' but I get the error:
```
TypeError: decoding to str: need a bytes-like object, list found
```
|
2020/06/15
|
['https://Stackoverflow.com/questions/62387623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10608841/']
|
Apparently, the `df_clean["message"]` column contains a list of words, not a string, hence the error saying that `need a bytes-like object, list found`.
To fix this issue, you need to convert it to string again using `join()` method like so:
```
df_clean['message'] = df_clean['message'].apply(lambda x: gensim.parsing.preprocessing.remove_stopwords(" ".join(x)))
```
Notice that the `df_clean["message"]` will contain string objects after applying the previous code.
|
What the error is saying is that *remove\_stopwords* needs **string** type object and you are passing a **list**, So before removing *stop words* check that all the values in column are of string type. [See the Docs](https://radimrehurek.com/gensim/parsing/preprocessing.html#gensim.parsing.preprocessing.remove_stopwords)
|
18,160,456 |
I would like to know if there is an API I can use to get a LinkShare merchant domain URL.
The merchant search endpoint only returns their `uid` and `name`.
|
2013/08/10
|
['https://Stackoverflow.com/questions/18160456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83475/']
|
According to the Linkshare help docs you can get a list of default URLs for all advertisers in your program (by joining data from two APIs), but those will still be affiliate links on Linkshare redirect domains. You would then need to write a script to visit those links and return the final destination URL, then grab the root domain of the URL.
Steps:
1. Follow the instructions here: <http://helpcenter.linkshare.com/publisher/questions.php?questionid=1030>
2. Write a script in your language of choice to cURL the affiliate link and grab `curl_getinfo(curl_init(), CURLINFO_EFFECTIVE_URL);` to see where it's redirecting to.
3. Parse the response with a RegExp to grab just the root domain like `http[s]?://([^/]+)`
|
This is a duplicate of [this Stack Overflow question](https://stackoverflow.com/questions/16973780/how-to-programmatically-get-a-list-of-my-linkshare-merchants-from-linkshare/16973781#16973781) this is what worked for me:
The following URL will allow you to get a list of merchants with data that you have permission to access without the need to login. It will return an XML list of your merchants:
```
http://findadvertisers.linksynergy.com/merchantsearch?token=YOUR_LINKSHARE_ACCESS_TOKEN
```
|
6,669,596 |
I'm trying to map certain routes so that auto generated Urls will look like
`Admin/controller/action/param` for both of these code blocks,
`@Url.Action("action","controller",new{id="param"})` and
`@Url.Action("action","controller",new{type="param"})`
What I did was the following in the area registration,
```
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index",
type = UrlParameter.Optional },
new string[] { "namespaces" });
```
when parameter name is `id`, url generated is as expected, but when parameter name is `type`, instead of `controller/action/typevalue`, it generates something like `controller/action/?type=typevalue`
Is there a way to generate the url something like `controller/action/typevalue` keeping the generator behaviour for `Admin_default` route intact?
|
2011/07/12
|
['https://Stackoverflow.com/questions/6669596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219933/']
|
Have you tried removing the Optional default value on id ? In this case, the first route shouldn't match when providing only the type parameter.
EDIT: After reading again your question, my solution doesn't keep your first route intact ...
|
You only need the one route.
```
context.MapRoute("Admin_default",
"Admin/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
```
in your controller you
URLs:
<http://website/Admin/index/hello>
<http://website/Admin/type/342>
```
public class AdminController()
{
public ActionResult Index(string id)
{
// do whatever
returne View();
}
public ActionResult type(string id)
{
// do whatever
returne View();
}
}
```
|
6,669,596 |
I'm trying to map certain routes so that auto generated Urls will look like
`Admin/controller/action/param` for both of these code blocks,
`@Url.Action("action","controller",new{id="param"})` and
`@Url.Action("action","controller",new{type="param"})`
What I did was the following in the area registration,
```
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index",
type = UrlParameter.Optional },
new string[] { "namespaces" });
```
when parameter name is `id`, url generated is as expected, but when parameter name is `type`, instead of `controller/action/typevalue`, it generates something like `controller/action/?type=typevalue`
Is there a way to generate the url something like `controller/action/typevalue` keeping the generator behaviour for `Admin_default` route intact?
|
2011/07/12
|
['https://Stackoverflow.com/questions/6669596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219933/']
|
>
> when parameter name is id, url generated is as expected, but when
> parameter name is type, instead of controller/action/typevalue, it
> generates something like controller/action/?type=typevalue
>
>
>
That happens because first route is used to map the url (id is optional).
You could try adding some constraints to your routes. I'm guessing your id parameter is an integer and type parameter is a string. In that case you can try with this routes:
```
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new { id = @"\d+" },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index", type = UrlParameter.Optional },
new string[] { "namespaces" });
```
You can find more info on route constraints [here](http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs).
|
Have you tried removing the Optional default value on id ? In this case, the first route shouldn't match when providing only the type parameter.
EDIT: After reading again your question, my solution doesn't keep your first route intact ...
|
6,669,596 |
I'm trying to map certain routes so that auto generated Urls will look like
`Admin/controller/action/param` for both of these code blocks,
`@Url.Action("action","controller",new{id="param"})` and
`@Url.Action("action","controller",new{type="param"})`
What I did was the following in the area registration,
```
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index",
type = UrlParameter.Optional },
new string[] { "namespaces" });
```
when parameter name is `id`, url generated is as expected, but when parameter name is `type`, instead of `controller/action/typevalue`, it generates something like `controller/action/?type=typevalue`
Is there a way to generate the url something like `controller/action/typevalue` keeping the generator behaviour for `Admin_default` route intact?
|
2011/07/12
|
['https://Stackoverflow.com/questions/6669596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219933/']
|
>
> when parameter name is id, url generated is as expected, but when
> parameter name is type, instead of controller/action/typevalue, it
> generates something like controller/action/?type=typevalue
>
>
>
That happens because first route is used to map the url (id is optional).
You could try adding some constraints to your routes. I'm guessing your id parameter is an integer and type parameter is a string. In that case you can try with this routes:
```
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new { id = @"\d+" },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index", type = UrlParameter.Optional },
new string[] { "namespaces" });
```
You can find more info on route constraints [here](http://www.asp.net/mvc/tutorials/creating-a-route-constraint-cs).
|
You only need the one route.
```
context.MapRoute("Admin_default",
"Admin/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
```
in your controller you
URLs:
<http://website/Admin/index/hello>
<http://website/Admin/type/342>
```
public class AdminController()
{
public ActionResult Index(string id)
{
// do whatever
returne View();
}
public ActionResult type(string id)
{
// do whatever
returne View();
}
}
```
|
18,378,506 |
I need to get an appropriate table size according to a text in a header. It contains abbreviations of czech names of days like: "Po", "Út", "St", atc. but instead of this three dots are displayed.
I have this code:
`width`, `height` - max of all minimum row/column sizes
`allWidth`,`allHeight` - should be the total width, height of the whole table
```
//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
for (int col = 0; col < table.getColumnCount(); col++) {
TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(table,
tableColumn.getHeaderValue(), false, false, -1, col);
width = Math.max(component.getPreferredSize().width, width);
table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = table.getColumnCount() * width;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = table.getRowCount() * height;
//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
```
I'm using GridBagLayout with this settings, I think this is ok:
```
this.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 1; //position x=0, y=0 is for JSpinners, months and years
gbc.weighty = 0;
gbc.weightx = 0;
add(scrollPane,gbc);//add table in a custom Calendar component
```
Also I changed the look and feel and this is causing those three dots. Otherwise the names are correctly displayed.
```
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
```
And this is how I initialize JTable and JScrollPane, I have a feeling like this could be ok too.
```
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
```
Problems:
If I don't set the scrollPane with gbc to resize itself, it gets the minimum possible size unless I calculate and set the minimum sizes of `table` and `scrollPane` by hand. (the left picture)
Using this settings, I got the result in the middle pic, but also too small. (no names of days and the height is also somewhat smaller.)
I don't know of any other better approach to do this, nothing I've found helped me so far.
When I considered some padding, e.g 2 pixels and adjusted the calculation of allWidth,allHeight like this:
```
allHeight = (1+table.getRowCount()+pady) * height; //plus one line of header
allWidth = table.getColumnCount() * width;
```
I got the picture on the right.



Here is a simple complete compilable class that demonstrates the problem:
```
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Main {
public static void main(String[] args) {
new Main().start();
}
private void start() {
JFrame f = new JFrame();
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
initTable();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
JPanel calendar = new JPanel();
calendar.setLayout(new GridBagLayout());
calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
calendar.add(scrollPane, gbc);
f.add(calendar,gbc);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
JTable table;
JScrollPane scrollPane;
CalendarTableModel tableModel;
private void initTable() {
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
int padx = 2,pady = 2;
for (int col = 0; col < table.getColumnCount(); col++) {
TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(table,
tableColumn.getHeaderValue(), false, false, -1, col);
width = Math.max(component.getPreferredSize().width, width);
table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = (table.getColumnCount()+padx) * width;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = (1+table.getRowCount()+pady) * height;
//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
}
private void setTable(JTable jTable) {
this.table = jTable;
}
private JTable getTable() {
return this.table;
}
private class CalendarTableModel extends AbstractTableModel {
private String[] daysData = {"Po", "Út", "St", "Čt", "Pá", "So", "Ne"};
private int[][] values;
public CalendarTableModel() {
values = new int[7][6];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
values[j][i] = 7;
}
}
}
@Override
public int getRowCount() {
return 6;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public String getColumnName(int column) {
return daysData[column];
}
@Override
public Object getValueAt(int row, int column) {
return this.values[column][row];
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
}
```
|
2013/08/22
|
['https://Stackoverflow.com/questions/18378506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2158784/']
|
you can to get this one

by
* `f.pack()` before `f.setVisible(true);`
* desired widht should be at 22 / 23 pixelx but `component.getPreferredSize(`) or `SwingUtilities#computeStringWidth(FontMetrics fm, String str)` returns only 17 / 18 and plus `table.getIntercellSpacing().width` only one pixel for Po - Ne
* note real workaround could be based on [TableColumnAdjuster by @camickr](http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/)
from code
```
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.JTextComponent;
public class Main {
public static void main(String[] args) {
new Main().start();
}
private void start() {
JFrame f = new JFrame();
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
initTable();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
JPanel calendar = new JPanel();
calendar.setLayout(new GridBagLayout());
calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
calendar.add(scrollPane, gbc);
f.add(calendar, gbc);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
JTable table;
JScrollPane scrollPane;
CalendarTableModel tableModel;
private void initTable() {
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
TableColumnModel columnModel = table.getColumnModel();
for (int col = 0; col < table.getColumnCount(); col++) {
int maxWidth = 0;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer rend = table.getCellRenderer(row, col);
Object value = table.getValueAt(row, col);
Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
maxWidth = Math.max(comp.getPreferredSize().width, maxWidth);
}
TableColumn column = columnModel.getColumn(col);
TableCellRenderer headerRenderer = column.getHeaderRenderer();
if (headerRenderer == null) {
headerRenderer = table.getTableHeader().getDefaultRenderer();
}
Object headerValue = column.getHeaderValue();
Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);
maxWidth = Math.max(maxWidth, headerComp.getPreferredSize().width);
// note some extra padding
column.setPreferredWidth(maxWidth + 6);//IntercellSpacing * 2 + 2 * 2 pixel instead of taking this value from Borders
}
DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
}
private void setTable(JTable jTable) {
this.table = jTable;
}
private JTable getTable() {
return this.table;
}
private class CalendarTableModel extends AbstractTableModel {
private String[] daysData = {"Pondelok", "Út", "St", "Čt", "Pá", "Sobota", "Ne"};
private int[][] values;
public CalendarTableModel() {
values = new int[7][6];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
values[j][i] = 30;
}
}
}
@Override
public int getRowCount() {
return 6;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public String getColumnName(int column) {
return daysData[column];
}
@Override
public Object getValueAt(int row, int column) {
return this.values[column][row];
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
}
```
|
I came to solution :-)
I had to change the look and feel before I calculated appropriate column widths. When I did it the other way around, the calculation was out of date.
So I only needed to set the correct widths like this:
```
table.getColumnModel().getColumn(col).setPreferredWidth(width);
```
And then change the size of the viewPort like this, because the table's prefered size is now correct.
```
table.setPreferredScrollableViewportSize(table.getPreferredSize());
```
Thanks! ;)
|
18,378,506 |
I need to get an appropriate table size according to a text in a header. It contains abbreviations of czech names of days like: "Po", "Út", "St", atc. but instead of this three dots are displayed.
I have this code:
`width`, `height` - max of all minimum row/column sizes
`allWidth`,`allHeight` - should be the total width, height of the whole table
```
//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
for (int col = 0; col < table.getColumnCount(); col++) {
TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(table,
tableColumn.getHeaderValue(), false, false, -1, col);
width = Math.max(component.getPreferredSize().width, width);
table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = table.getColumnCount() * width;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = table.getRowCount() * height;
//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
```
I'm using GridBagLayout with this settings, I think this is ok:
```
this.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 1; //position x=0, y=0 is for JSpinners, months and years
gbc.weighty = 0;
gbc.weightx = 0;
add(scrollPane,gbc);//add table in a custom Calendar component
```
Also I changed the look and feel and this is causing those three dots. Otherwise the names are correctly displayed.
```
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
```
And this is how I initialize JTable and JScrollPane, I have a feeling like this could be ok too.
```
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
```
Problems:
If I don't set the scrollPane with gbc to resize itself, it gets the minimum possible size unless I calculate and set the minimum sizes of `table` and `scrollPane` by hand. (the left picture)
Using this settings, I got the result in the middle pic, but also too small. (no names of days and the height is also somewhat smaller.)
I don't know of any other better approach to do this, nothing I've found helped me so far.
When I considered some padding, e.g 2 pixels and adjusted the calculation of allWidth,allHeight like this:
```
allHeight = (1+table.getRowCount()+pady) * height; //plus one line of header
allWidth = table.getColumnCount() * width;
```
I got the picture on the right.



Here is a simple complete compilable class that demonstrates the problem:
```
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Main {
public static void main(String[] args) {
new Main().start();
}
private void start() {
JFrame f = new JFrame();
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
initTable();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
JPanel calendar = new JPanel();
calendar.setLayout(new GridBagLayout());
calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
calendar.add(scrollPane, gbc);
f.add(calendar,gbc);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
JTable table;
JScrollPane scrollPane;
CalendarTableModel tableModel;
private void initTable() {
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
int padx = 2,pady = 2;
for (int col = 0; col < table.getColumnCount(); col++) {
TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(table,
tableColumn.getHeaderValue(), false, false, -1, col);
width = Math.max(component.getPreferredSize().width, width);
table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = (table.getColumnCount()+padx) * width;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = (1+table.getRowCount()+pady) * height;
//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
}
private void setTable(JTable jTable) {
this.table = jTable;
}
private JTable getTable() {
return this.table;
}
private class CalendarTableModel extends AbstractTableModel {
private String[] daysData = {"Po", "Út", "St", "Čt", "Pá", "So", "Ne"};
private int[][] values;
public CalendarTableModel() {
values = new int[7][6];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
values[j][i] = 7;
}
}
}
@Override
public int getRowCount() {
return 6;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public String getColumnName(int column) {
return daysData[column];
}
@Override
public Object getValueAt(int row, int column) {
return this.values[column][row];
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
}
```
|
2013/08/22
|
['https://Stackoverflow.com/questions/18378506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2158784/']
|
you can to get this one

by
* `f.pack()` before `f.setVisible(true);`
* desired widht should be at 22 / 23 pixelx but `component.getPreferredSize(`) or `SwingUtilities#computeStringWidth(FontMetrics fm, String str)` returns only 17 / 18 and plus `table.getIntercellSpacing().width` only one pixel for Po - Ne
* note real workaround could be based on [TableColumnAdjuster by @camickr](http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/)
from code
```
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.JTextComponent;
public class Main {
public static void main(String[] args) {
new Main().start();
}
private void start() {
JFrame f = new JFrame();
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
initTable();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
JPanel calendar = new JPanel();
calendar.setLayout(new GridBagLayout());
calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
calendar.add(scrollPane, gbc);
f.add(calendar, gbc);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
JTable table;
JScrollPane scrollPane;
CalendarTableModel tableModel;
private void initTable() {
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
TableColumnModel columnModel = table.getColumnModel();
for (int col = 0; col < table.getColumnCount(); col++) {
int maxWidth = 0;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer rend = table.getCellRenderer(row, col);
Object value = table.getValueAt(row, col);
Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
maxWidth = Math.max(comp.getPreferredSize().width, maxWidth);
}
TableColumn column = columnModel.getColumn(col);
TableCellRenderer headerRenderer = column.getHeaderRenderer();
if (headerRenderer == null) {
headerRenderer = table.getTableHeader().getDefaultRenderer();
}
Object headerValue = column.getHeaderValue();
Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);
maxWidth = Math.max(maxWidth, headerComp.getPreferredSize().width);
// note some extra padding
column.setPreferredWidth(maxWidth + 6);//IntercellSpacing * 2 + 2 * 2 pixel instead of taking this value from Borders
}
DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
}
private void setTable(JTable jTable) {
this.table = jTable;
}
private JTable getTable() {
return this.table;
}
private class CalendarTableModel extends AbstractTableModel {
private String[] daysData = {"Pondelok", "Út", "St", "Čt", "Pá", "Sobota", "Ne"};
private int[][] values;
public CalendarTableModel() {
values = new int[7][6];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
values[j][i] = 30;
}
}
}
@Override
public int getRowCount() {
return 6;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public String getColumnName(int column) {
return daysData[column];
}
@Override
public Object getValueAt(int row, int column) {
return this.values[column][row];
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
}
```
|
This is fantastic code to auto-fit your header and cell content in the JTable:
```
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < jTable1.getColumnCount(); column++){
TableColumn tableColumn = jTable1.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = 0;
TableCellRenderer rend = jTable1.getTableHeader().getDefaultRenderer();
TableCellRenderer rendCol = tableColumn.getHeaderRenderer();
if (rendCol == null) rendCol = rend;
Component header = rendCol.getTableCellRendererComponent(jTable1, tableColumn.getHeaderValue(), false, false, 0, column);
maxWidth = header.getPreferredSize().width;
System.out.println("maxWidth :"+maxWidth);
for (int row = 0; row < jTable1.getRowCount(); row++){
TableCellRenderer cellRenderer = jTable1.getCellRenderer(row, column);
Component c = jTable1.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + jTable1.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
System.out.println("preferredWidth :"+preferredWidth);
System.out.println("Width :"+width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth <= maxWidth){
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth(preferredWidth);
}
```
|
18,378,506 |
I need to get an appropriate table size according to a text in a header. It contains abbreviations of czech names of days like: "Po", "Út", "St", atc. but instead of this three dots are displayed.
I have this code:
`width`, `height` - max of all minimum row/column sizes
`allWidth`,`allHeight` - should be the total width, height of the whole table
```
//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
for (int col = 0; col < table.getColumnCount(); col++) {
TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(table,
tableColumn.getHeaderValue(), false, false, -1, col);
width = Math.max(component.getPreferredSize().width, width);
table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = table.getColumnCount() * width;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = table.getRowCount() * height;
//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
```
I'm using GridBagLayout with this settings, I think this is ok:
```
this.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 1; //position x=0, y=0 is for JSpinners, months and years
gbc.weighty = 0;
gbc.weightx = 0;
add(scrollPane,gbc);//add table in a custom Calendar component
```
Also I changed the look and feel and this is causing those three dots. Otherwise the names are correctly displayed.
```
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
```
And this is how I initialize JTable and JScrollPane, I have a feeling like this could be ok too.
```
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
```
Problems:
If I don't set the scrollPane with gbc to resize itself, it gets the minimum possible size unless I calculate and set the minimum sizes of `table` and `scrollPane` by hand. (the left picture)
Using this settings, I got the result in the middle pic, but also too small. (no names of days and the height is also somewhat smaller.)
I don't know of any other better approach to do this, nothing I've found helped me so far.
When I considered some padding, e.g 2 pixels and adjusted the calculation of allWidth,allHeight like this:
```
allHeight = (1+table.getRowCount()+pady) * height; //plus one line of header
allWidth = table.getColumnCount() * width;
```
I got the picture on the right.



Here is a simple complete compilable class that demonstrates the problem:
```
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Main {
public static void main(String[] args) {
new Main().start();
}
private void start() {
JFrame f = new JFrame();
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
initTable();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
JPanel calendar = new JPanel();
calendar.setLayout(new GridBagLayout());
calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
calendar.add(scrollPane, gbc);
f.add(calendar,gbc);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
JTable table;
JScrollPane scrollPane;
CalendarTableModel tableModel;
private void initTable() {
setTable(new JTable());
getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
getTable().setAutoscrolls(false);
getTable().getTableHeader().setResizingAllowed(false);
getTable().getTableHeader().setReorderingAllowed(false);
getTable().setColumnSelectionAllowed(true);
getTable().setRowSelectionAllowed(true);
getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableModel = new CalendarTableModel(); //my class extended from AbstractTableModel
getTable().setModel(tableModel);
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setAutoscrolls(false);
//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
int padx = 2,pady = 2;
for (int col = 0; col < table.getColumnCount(); col++) {
TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
TableCellRenderer renderer = tableColumn.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component component = renderer.getTableCellRendererComponent(table,
tableColumn.getHeaderValue(), false, false, -1, col);
width = Math.max(component.getPreferredSize().width, width);
table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = (table.getColumnCount()+padx) * width;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, 0);
Component comp = table.prepareRenderer(renderer, row, 0);
height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = (1+table.getRowCount()+pady) * height;
//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
}
private void setTable(JTable jTable) {
this.table = jTable;
}
private JTable getTable() {
return this.table;
}
private class CalendarTableModel extends AbstractTableModel {
private String[] daysData = {"Po", "Út", "St", "Čt", "Pá", "So", "Ne"};
private int[][] values;
public CalendarTableModel() {
values = new int[7][6];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
values[j][i] = 7;
}
}
}
@Override
public int getRowCount() {
return 6;
}
@Override
public int getColumnCount() {
return 7;
}
@Override
public String getColumnName(int column) {
return daysData[column];
}
@Override
public Object getValueAt(int row, int column) {
return this.values[column][row];
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
}
```
|
2013/08/22
|
['https://Stackoverflow.com/questions/18378506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2158784/']
|
This is fantastic code to auto-fit your header and cell content in the JTable:
```
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < jTable1.getColumnCount(); column++){
TableColumn tableColumn = jTable1.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = 0;
TableCellRenderer rend = jTable1.getTableHeader().getDefaultRenderer();
TableCellRenderer rendCol = tableColumn.getHeaderRenderer();
if (rendCol == null) rendCol = rend;
Component header = rendCol.getTableCellRendererComponent(jTable1, tableColumn.getHeaderValue(), false, false, 0, column);
maxWidth = header.getPreferredSize().width;
System.out.println("maxWidth :"+maxWidth);
for (int row = 0; row < jTable1.getRowCount(); row++){
TableCellRenderer cellRenderer = jTable1.getCellRenderer(row, column);
Component c = jTable1.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + jTable1.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
System.out.println("preferredWidth :"+preferredWidth);
System.out.println("Width :"+width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth <= maxWidth){
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth(preferredWidth);
}
```
|
I came to solution :-)
I had to change the look and feel before I calculated appropriate column widths. When I did it the other way around, the calculation was out of date.
So I only needed to set the correct widths like this:
```
table.getColumnModel().getColumn(col).setPreferredWidth(width);
```
And then change the size of the viewPort like this, because the table's prefered size is now correct.
```
table.setPreferredScrollableViewportSize(table.getPreferredSize());
```
Thanks! ;)
|
9,320,027 |
I have an applet (Applet, not JApplet) that has a lot of classes organized into packages, including the applet itself. I have looked everywhere for how to use that jar as an applet. It is not runnable and has a manifest file like such:
```
Manifest-Version: 1.0
Class-Path: AppletSource.jar
```
I put it in an html (Game.html), as such:
```
<applet code="Game/Game.class" archive="Game.jar" width=800 height=600>
Your browser needs JAVA!!!
</applet>
```
As you can see the class is called Game.class, Package Game and the jar Game.jar.
The manifest is in Game.jar/META-INF
When I use the `appletviewer Game.html` I get an error (java.security.AccessControlException: access denied) and if I open the .html I get a `ClassNotFoundException: Game.Game.class`. What can I do?
|
2012/02/16
|
['https://Stackoverflow.com/questions/9320027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/920628/']
|
try
```
<applet code="Game.Game" archive="Game.jar" width=800 height=600>
Your browser needs JAVA!!!
</applet>
```
Also check that the package name is really **Game** and not **game**.
|
The format for the applet code attribute is from oracle doc "The value appletFile can be of the form classname.class or of the form packagename.classname.class.".
This file is relative to the base URL of the applet. It cannot be absolute.
Also try adding the jar in the same directory as the html.
For some further information see this doc
<http://docs.oracle.com/javase/1.4.2/docs/guide/misc/applet.html>
|
7,017,809 |
i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
```
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
```
the function :
```
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
```
|
2011/08/10
|
['https://Stackoverflow.com/questions/7017809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/888300/']
|
The inner foreach loop seems to be entirely redundant. Try something like:
```
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
```
Doing a `print_r($names)` afterwards should show you the results of the loop, assuming your getNames function is working properly.
|
Depending of the content of the `$receivers` array try either
```
foreach ($receivers as $value){
echo getName($value) ;
}
```
or
```
foreach ($receivers as $key => $value){
echo getName($key) ;
}
```
|
48,310,337 |
I am completing the 57 programming exercises book by Brian P. Hogan.
With most of these exercises, I've tried to develop a GUI.
In the following exercise, I want to calculate the Simple Interest of a Principal value over a period of years. Simply put:
```
var yearlyInterest = Principal * (Percentage(whole number) /= 100)
(yearlyInterest * numberOfYears) + Principal
// outputs total amount at the end of investment over a period of however many years
```
As you can see in the example above, there are three core inputs - Principal, Percentage and Time.
When creating the graphical user interface, I am struggling to get all of these core inputs to calculate the result simultaneously.
The following code only manages to calculate the result once I enter the number for the Time input. (excuse my poor coding skills i.e. global variables, I'm only up to exercise 12!)
**HTML**
```
<!DOCTYPE html>
<html lang="en">
<body>
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;">
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;">
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;">
<div id="result"></div>
</body>
<script src="simpleInterest.js"></script>
</html>
```
**JS**
```
var principal = document.getElementsByClassName("principal");
var percentage = document.getElementsByClassName("percentage");
var time = document.getElementsByClassName("time");
var output = document.querySelector("#result");
var result;
var newResult;
var finalOutput;
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
var newPrincipal = principal[0].value;
result = newPrincipal;
}
if ( event.target.classList.contains( 'percentage' ) ) {
var newPercentage = percentage[0].value;
newResult = result * (newPercentage / 100);
}
if ( event.target.classList.contains( 'time' ) ) {
var newTime = time[0].value;
finalOutput = (newResult * newTime) + Number(result);
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
```
Could somebody please show me an effective way to simultaneously calculate something based on each input event and output it using the .innerHTML method?
Thanks!
|
2018/01/17
|
['https://Stackoverflow.com/questions/48310337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5527137/']
|
You need to get the values of all the inputs, not just the one that the user is currently typing in. Define a single function that does this, and add it as an event listener for all 3 inputs.
```js
var principal = document.querySelector(".principal");
var percentage = document.querySelector(".percentage");
var time = document.querySelector(".time");
var output = document.querySelector("#result");
function calcInterest() {
var newPrincipal = parseFloat(principal.value);
var newPercentage = parseFloat(percentage.value);
var newTime = parseFloat(time.value);
if (!isNaN(newPrincipal) && !isNaN(newPercentage) && !isNaN(newTime)) {
var result = newPrincipal + newTime * newPrincipal * newPercentage / 100;
output.textContent = result;
}
}
principal.addEventListener("input", calcInterest);
percentage.addEventListener("input", calcInterest);
time.addEventListener("input", calcInterest);
```
```html
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;"><br>
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;"><br>
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;"><br> Result:
<div id="result"></div>
```
|
Create function to calculate, and call this function instead of just executing some code. Something like that:
```js
var principal = document.getElementsByClassName("principal")
var percentage = document.getElementsByClassName("percentage")
var time = document.getElementsByClassName("time")
var output = document.querySelector("#result")
var result
var newResult
var finalOutput
var calculate = () => {
var newPrincipal = principal[0].value;
result = newPrincipal
var newPercentage = percentage[0].value
newResult = result * (newPercentage / 100)
var newTime = time[0].value
finalOutput = (newResult * newTime) + Number(result)
}
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
calculate();
}
if ( event.target.classList.contains( 'percentage' ) ) {
calculate();
}
if ( event.target.classList.contains( 'time' ) ) {
calculate();
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
```
|
94,754 |
I need to join a vertex to edge, with *snap to edge* i can snap my vertex on the edge but i don't know how to join it.
Now my solution is:
1. snap vertex to edge
2. subdivide edge (this creates a new vertex on the edge)
3. merge the two vertices
But i think is too elaborate, so i look for a simpler solution.
[](https://i.stack.imgur.com/iwxC8.jpg)
|
2017/11/19
|
['https://blender.stackexchange.com/questions/94754', 'https://blender.stackexchange.com', 'https://blender.stackexchange.com/users/48600/']
|
Subdivide is a bad option in your situation because you get more verticals than you need.
The fastest way, in my opinion, is to manage this with a loop cut.
1. Loop Cut `CTRL`+`R` and slide to the position where you want to connect your vertex
2. Select your vertices and merge `ALT`+`M` them
[](https://i.stack.imgur.com/vGrqD.gif)
You could the same with the knife tool (`K`). However you can't guarantee for a good mesh flow if you do so.
With Loop Cuts you are most of the time on the good side.
|
If i understood the question maybe a quick solution.
Download the [addon Snap utilities](https://github.com/Mano-Wii/Addon-Snap-Utilities-Line/blob/master/mesh_snap_utilities_line.py)
Press `T` in toolshelf -> Snap utilities ->
Select the single verts and click on the line from the addon and draw the line from verts to edge. You will get a edge and a new verts.
To confirm the operation press `Enter` To Exit `Esc`
[](https://i.stack.imgur.com/AIyN1.gif)
|
30,438,899 |
I have a service implemented using Jersey that write/read from a JSON file and I have a test file extending JerseyTest class for testing that service.
What I am trying to do is when running the test it write/read in a different file (with '\_test' in name). That way I don't have the values changed from the main file.
The file is being instanced in the @PostConstruct method like that:
```java
@PostConstruct
public void init() {
try {
jsonFile = new NewsJson(); // Need to have a different behavior for testing
} catch (IOException ioe) {
LOGGER.error("Error creating file: " + ioe.getMessage());
}
}
```
What I have tried is to call a @POST method that modify the jsonFile variable, activating writting in a different file. The problem in that solution is the @PostConstruct method being called every request.
How can I change that behavior? Is there a different annotation for initializing services using Jersey?
|
2015/05/25
|
['https://Stackoverflow.com/questions/30438899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2249074/']
|
**1. HomeController.cs**
```
public class HomeController : Controller
{
MVCDbContext _db = new MVCDbContext();
public ActionResult Index()
{
return View(_db.Model1.ToList());
}
[HttpGet]
public ActionResult add(Model1 objmo,int?id)
{
if (id == null)
{
return View();
}
else
{
Model1 objdata = _db.Model1.Find(id);
objmo.fname = objdata.fname;
objmo.lname = objdata.lname;
return View(objdata);
}
}
[HttpPost]
public ActionResult add(Model1 obj)
{
if (obj.Aref == 0)
{
_db.Model1.Add(obj);
}
else
{
Model1 objdata = _db.Model1.Where(x => x.Aref == obj.Aref).FirstOrDefault();
objdata.fname = obj.fname;
objdata.lname = obj.lname;
}
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult delete(int? id)
{
_db.Model1.Remove(_db.Model1.Find(id));
_db.SaveChanges();
return RedirectToAction("Index");
}
}
```
```html
2. Index.cshtml
@model IEnumerable<mvc_crud_dropdown.Models.Model1>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "add")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Aref)
</th>
<th>
@Html.DisplayNameFor(model => model.fname)
</th>
<th>
@Html.DisplayNameFor(model => model.lname)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Aref)
</td>
<td>
@Html.DisplayFor(modelItem => item.fname)
</td>
<td>
@Html.DisplayFor(modelItem => item.lname)
</td>
<td>
@Html.ActionLink("Edit", "add", new { id=item.Aref }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Aref })
</td>
</tr>
}
</table>
```
|
You can start with sample project from codeproject
<http://www.codeproject.com/Articles/875859/Insert-Update-and-Delete-MVC-WebGrid-Data-using-JQ>
|
30,438,899 |
I have a service implemented using Jersey that write/read from a JSON file and I have a test file extending JerseyTest class for testing that service.
What I am trying to do is when running the test it write/read in a different file (with '\_test' in name). That way I don't have the values changed from the main file.
The file is being instanced in the @PostConstruct method like that:
```java
@PostConstruct
public void init() {
try {
jsonFile = new NewsJson(); // Need to have a different behavior for testing
} catch (IOException ioe) {
LOGGER.error("Error creating file: " + ioe.getMessage());
}
}
```
What I have tried is to call a @POST method that modify the jsonFile variable, activating writting in a different file. The problem in that solution is the @PostConstruct method being called every request.
How can I change that behavior? Is there a different annotation for initializing services using Jersey?
|
2015/05/25
|
['https://Stackoverflow.com/questions/30438899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2249074/']
|
**1. HomeController.cs**
```
public class HomeController : Controller
{
MVCDbContext _db = new MVCDbContext();
public ActionResult Index()
{
return View(_db.Model1.ToList());
}
[HttpGet]
public ActionResult add(Model1 objmo,int?id)
{
if (id == null)
{
return View();
}
else
{
Model1 objdata = _db.Model1.Find(id);
objmo.fname = objdata.fname;
objmo.lname = objdata.lname;
return View(objdata);
}
}
[HttpPost]
public ActionResult add(Model1 obj)
{
if (obj.Aref == 0)
{
_db.Model1.Add(obj);
}
else
{
Model1 objdata = _db.Model1.Where(x => x.Aref == obj.Aref).FirstOrDefault();
objdata.fname = obj.fname;
objdata.lname = obj.lname;
}
_db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult delete(int? id)
{
_db.Model1.Remove(_db.Model1.Find(id));
_db.SaveChanges();
return RedirectToAction("Index");
}
}
```
```html
2. Index.cshtml
@model IEnumerable<mvc_crud_dropdown.Models.Model1>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "add")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Aref)
</th>
<th>
@Html.DisplayNameFor(model => model.fname)
</th>
<th>
@Html.DisplayNameFor(model => model.lname)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Aref)
</td>
<td>
@Html.DisplayFor(modelItem => item.fname)
</td>
<td>
@Html.DisplayFor(modelItem => item.lname)
</td>
<td>
@Html.ActionLink("Edit", "add", new { id=item.Aref }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Aref })
</td>
</tr>
}
</table>
```
|
Read this article : [How to Implement Insert, Update, Delete Functionality in Single View of ASP.Net MVC?](http://www.c-sharpcorner.com/UploadFile/bd8b0b/how-to-implement-insert-update-delete-functionality-in-singl/)
|
38,881,314 |
Trying to put the last 24hrs of data into a CSV file and getting using tweepy for python
```
Traceback (most recent call last):
File "**", line 74, in <module>
get_all_tweets("BQ")
File "**", line 66, in get_all_tweets
writer.writerows(outtweets)
File "C:\Users\Barry\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 6-7: character maps to <undefined>
```
as an error, can anyone see what is wrong as this was working in some capacity before today.
Code:
def get\_all\_tweets(screen\_name):
```
# authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
# initialize a list to hold all the tweepy Tweets
alltweets = []
# make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.home_timeline (screen_name=screen_name, count=200)
# save most recent tweets
alltweets.extend(new_tweets)
# save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
outtweets = []
page = 1
deadend = False
print ("getting tweets before %s" % (oldest))
# all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.home_timeline(screen_name=screen_name, count=200, max_id=oldest, page=page)
# save most recent tweets
alltweets.extend(new_tweets)
# update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print ("...%s tweets downloaded so far" % (len(alltweets)))
for tweet in alltweets:
if (datetime.datetime.now() - tweet.created_at).days < 1:
# transform the tweepy tweets into a 2D array that will populate the csv
outtweets.append([tweet.user.name, tweet.created_at, tweet.text.encode("utf-8")])
else:
deadend = True
return
if not deadend:
page += 1
# write the csv
with open('%s_tweets.csv' % screen_name, 'w') as f:
writer = csv.writer(f)
writer.writerow(["name", "created_at", "text"])
writer.writerows(outtweets)
pass
print ("CSV written")
if __name__ == '__main__':
# pass in the username of the account you want to download
get_all_tweets("BQ")
```
\*\* EDIT 1 \*\*
```
with open('%s_tweets.csv' % screen_name, 'w', encode('utf-8')) as f:
TypeError: an integer is required (got type bytes)
```
\*\* EDIT 2\*\*
```
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 6-7: character maps to <undefined>
```
|
2016/08/10
|
['https://Stackoverflow.com/questions/38881314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6230786/']
|
Your problem is with the characters in some tweets. You're not able to write them to the file you open.
If you replace this line
```
with open('%s_tweets.csv' % screen_name, 'w') as f:
```
with this:
```
with open('%s_tweets.csv' % screen_name, mode='w', encoding='utf-8') as f:
```
it should work. Please note that this will only work with python 3.x
|
It seems that the character is something that cannot be encoded into utf-8. While it may be useful to view the tweet in question that triggered the error, you can prevent such an error in the future by changing `tweet.text.encode("utf-8")` to either `tweet.text.encode("utf-8", "ignore")`, `tweet.text.encode("utf-8", "replace")`, or `tweet.text.encode("utf-8", "backslashreplace")`. `ignore` removes anything that cannot be encoded; `replace` replaces the infringing character with `\ufff`; and `backslashreplace` adds a backslash to the infringing character `\x00` would become `\\x00`.
For more on this: <https://docs.python.org/3/howto/unicode.html#converting-to-bytes>
|
13,756,162 |
PLease help!
This is what I have so far: <http://beauxlent.com/nicole>
When you click "one" "two" or "three", it takes you to a div that is still on the same page. However, I would like the div to stay within the right div and still on the same page used #tags. I've seen this done before.
```
<style type="text/css">
{
padding: 0;
margin: 0;
}
body {
text-align: justify;
overflow: hidden;
background: #F8F8F8;
font: -blocked- arial;
}
table, p {
display: none;
}
div {
width: 100%;
}
.container {width: 800px; display:block; margin:0px auto}
.left {width:200px; float:left; background: #eee; display:block; height:200px;
line- height:2}
.right {width:600px; float:right; background: #808080; display:block; height: 200px;
line-height:2; }
#o {position:absolute; right: 2000px;}
.blog {
background: 0;
position: absolute;
top: 150px;
left: 500px;
width: 290px;
height: 140px;
}
#omg {
z-index: 7;
position: absolute;
top: 1000px;
right: 0;
color: #000;
height: 1000px;
}
#plz {
z-index: 7;
position: absolute;
top: 9000px;
right: 0;
color: #000;
height: 9000px;
}
}
#nande a:hover {
color: #000;
}
#nande {
z-index: 7;
position: absolute;
top: 7000px;
right: 0;
color: #000;
height: 1000px;
}
body, table {
color: #fff;
}
font, table, tr, td, br, p {
font: -blocked- franklin gothic medium;
color: #fff;
}
#content {
width: 100%;
}
#main, #content {
border: 0px none;
background: #fff;
}
}
.framed {
background: #fff;
padding: 5px;
overflow: auto;
position: absolute;
top: 20px;
left: 0px;
}
</style>
<div id="boxed">
<div class="container">
<div class="left">
<a href="#uno" class="big">1</a>
<a href="#dos" class="big">2</a>
<a href="#tres" class="big">3</a>
</div>
<div class="right">
<div id="omg">
<a name="uno"></a>
<div class="framed">
one
</div>
</div>
<div id="nande">
<a name="dos"></a>
<div class="framed">
two
</div>
</div>
<div id="plz">
<a name="tres"></a>
<div class="framed">
three
</div>
</div>
</div>
```
|
2012/12/07
|
['https://Stackoverflow.com/questions/13756162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880756/']
|
Tabbings you mean. This can be done too in CSS. Try to check it here -> <http://css-tricks.com/functional-css-tabs-revisited/>
HTML code:
```
<div class="tab">
<input type="radio" id="tab-1" name="tab-group-1" checked>
<label for="tab-1">Tab One</label>
<div class="content">
stuff
</div>
</div>
<div class="tab">
<input type="radio" id="tab-2" name="tab-group-1">
<label for="tab-2">Tab Two</label>
<div class="content">
stuff
</div>
</div>
<div class="tab">
<input type="radio" id="tab-3" name="tab-group-1">
<label for="tab-3">Tab Three</label>
<div class="content">
stuff
</div>
</div>
</div>
```
CSS code:
```
.tabs {
position: relative;
min-height: 200px; /* This part sucks */
clear: both;
margin: 25px 0;
}
.tab {
float: left;
}
.tab label {
background: #eee;
padding: 10px;
border: 1px solid #ccc;
margin-left: -1px;
position: relative;
left: 1px;
}
.tab [type=radio] {
display: none;
}
.content {
position: absolute;
top: 28px;
left: 0;
background: white;
right: 0;
bottom: 0;
padding: 20px;
border: 1px solid #ccc;
}
[type=radio]:checked ~ label {
background: white;
border-bottom: 1px solid white;
z-index: 2;
}
[type=radio]:checked ~ label ~ .content {
z-index: 1;
}
```
|
Take a look at [jQuery UI Tabs](http://jqueryui.com/tabs/) - very easy to implement.
**Include**
```
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
```
**The jQuery**
```
$(function() {
$( "#tabs" ).tabs();
});
```
**The HTML**
```
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>
```
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
(Not an answer but I cannot add comments)
If you are checking `.bash_history` because you just want delete a specific command (e.g. containing a password in clear), you can directly delete the entry in memory by `history -d <entry_id>`.
For example, supposing an output like:
```
$ history
926 ll
927 cd ..
928 export --password=super_secret
929 ll
```
and you want purge the `export` line, you can simply achieve it by:
```
history -d 928
```
|
Commands are saved in memory (RAM) while your session is active. As soon as you close the shell, the commands list gets written to `.bash_history` before shutdown.
Thus, you won't see history of current session in `.bash_history`.
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
(Not an answer but I cannot add comments)
If you are checking `.bash_history` because you just want delete a specific command (e.g. containing a password in clear), you can directly delete the entry in memory by `history -d <entry_id>`.
For example, supposing an output like:
```
$ history
926 ll
927 cd ..
928 export --password=super_secret
929 ll
```
and you want purge the `export` line, you can simply achieve it by:
```
history -d 928
```
|
bash keeps it in working memory, bash can be configured to save it when bash closes or after each command, and to be loaded when bash starts or on request.
If you configure to save after each command, then consider the implications of having multiple bash running at same time. (command lines will be interleaved)
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
Bash maintains the list of commands internally in memory while it's running. They are written into [`.bash_history` on exit](https://www.gnu.org/software/bash/manual/bashref.html#Bash-History-Facilities):
>
> When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to the file named by $HISTFILE
>
>
>
If you want to force the command history to be written out, you can use the [`history -a`](https://www.gnu.org/software/bash/manual/bashref.html#index-history) command, which will:
>
> Append the new history lines (history lines entered since the beginning of the current Bash session) to the history file.
>
>
>
There is also a `-w` option:
>
> Write out the current history to the history file.
>
>
>
which may suit you more depending on exactly how you use your history.
If you want to make sure that they're always written immediately, you can put that command into your `PROMPT_COMMAND` variable:
```
export PROMPT_COMMAND='history -a'
```
|
(Not an answer but I cannot add comments)
If you are checking `.bash_history` because you just want delete a specific command (e.g. containing a password in clear), you can directly delete the entry in memory by `history -d <entry_id>`.
For example, supposing an output like:
```
$ history
926 ll
927 cd ..
928 export --password=super_secret
929 ll
```
and you want purge the `export` line, you can simply achieve it by:
```
history -d 928
```
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
bash keeps it in working memory, bash can be configured to save it when bash closes or after each command, and to be loaded when bash starts or on request.
If you configure to save after each command, then consider the implications of having multiple bash running at same time. (command lines will be interleaved)
|
Commands are saved in memory (RAM) while your session is active. As soon as you close the shell, the commands list gets written to `.bash_history` before shutdown.
Thus, you won't see history of current session in `.bash_history`.
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
Commands are saved in memory (RAM) while your session is active. As soon as you close the shell, the commands list gets written to `.bash_history` before shutdown.
Thus, you won't see history of current session in `.bash_history`.
|
The easiest way to find where your bash history is stored is with this:
`echo $HISTFILE`
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
While running, the history is kept only in memory (by default) if:
* set -o history (an `H` in `echo "$-"`) is set.
* HISTSIZE is not `0` **and**
* HISTIGNORE is not `*` (or some other very restrictive pattern).
If any of the above fail, no history is stored in memory and consequently no history could or will be written to disk.
History in memory is written to disk if:
* HISTFILESIZE is not 0 **and**
* HISTFILE is not unset.
But only when the shell exits or if the commands `history -a` (append) or `history -w` (write) are executed.
To trigger an immediate write to disk you can use the variable:
```
PROMPT_COMMAND='history -a'
```
which will `append` the `new` history lines to the history file. These are history lines entered since the beginning of the current bash session, but not already appended to the history file.
Or:
```
PROMPT_COMMAND='history -w'
```
To **overwrite** the history in the HISTFILE with the list from memory.
So, you can remove a command from the history in memory:
```
$ history 5
6359 ls
6360 cd ..
6361 comand --private-password='^%^&$@#)!@*'
6362 top
6363 set +o | less
$ history -d 6361
$ history 5
6359 ls
6360 cd ..
6361 top
6362 set +o | less
$ history -w
```
And write it to disk with the last command:
```
history -w # with `shopt -u histappend` unset
```
|
The easiest way to find where your bash history is stored is with this:
`echo $HISTFILE`
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
Bash maintains the list of commands internally in memory while it's running. They are written into [`.bash_history` on exit](https://www.gnu.org/software/bash/manual/bashref.html#Bash-History-Facilities):
>
> When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to the file named by $HISTFILE
>
>
>
If you want to force the command history to be written out, you can use the [`history -a`](https://www.gnu.org/software/bash/manual/bashref.html#index-history) command, which will:
>
> Append the new history lines (history lines entered since the beginning of the current Bash session) to the history file.
>
>
>
There is also a `-w` option:
>
> Write out the current history to the history file.
>
>
>
which may suit you more depending on exactly how you use your history.
If you want to make sure that they're always written immediately, you can put that command into your `PROMPT_COMMAND` variable:
```
export PROMPT_COMMAND='history -a'
```
|
The easiest way to find where your bash history is stored is with this:
`echo $HISTFILE`
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
Bash maintains the list of commands internally in memory while it's running. They are written into [`.bash_history` on exit](https://www.gnu.org/software/bash/manual/bashref.html#Bash-History-Facilities):
>
> When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to the file named by $HISTFILE
>
>
>
If you want to force the command history to be written out, you can use the [`history -a`](https://www.gnu.org/software/bash/manual/bashref.html#index-history) command, which will:
>
> Append the new history lines (history lines entered since the beginning of the current Bash session) to the history file.
>
>
>
There is also a `-w` option:
>
> Write out the current history to the history file.
>
>
>
which may suit you more depending on exactly how you use your history.
If you want to make sure that they're always written immediately, you can put that command into your `PROMPT_COMMAND` variable:
```
export PROMPT_COMMAND='history -a'
```
|
While running, the history is kept only in memory (by default) if:
* set -o history (an `H` in `echo "$-"`) is set.
* HISTSIZE is not `0` **and**
* HISTIGNORE is not `*` (or some other very restrictive pattern).
If any of the above fail, no history is stored in memory and consequently no history could or will be written to disk.
History in memory is written to disk if:
* HISTFILESIZE is not 0 **and**
* HISTFILE is not unset.
But only when the shell exits or if the commands `history -a` (append) or `history -w` (write) are executed.
To trigger an immediate write to disk you can use the variable:
```
PROMPT_COMMAND='history -a'
```
which will `append` the `new` history lines to the history file. These are history lines entered since the beginning of the current bash session, but not already appended to the history file.
Or:
```
PROMPT_COMMAND='history -w'
```
To **overwrite** the history in the HISTFILE with the list from memory.
So, you can remove a command from the history in memory:
```
$ history 5
6359 ls
6360 cd ..
6361 comand --private-password='^%^&$@#)!@*'
6362 top
6363 set +o | less
$ history -d 6361
$ history 5
6359 ls
6360 cd ..
6361 top
6362 set +o | less
$ history -w
```
And write it to disk with the last command:
```
history -w # with `shopt -u histappend` unset
```
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
(Not an answer but I cannot add comments)
If you are checking `.bash_history` because you just want delete a specific command (e.g. containing a password in clear), you can directly delete the entry in memory by `history -d <entry_id>`.
For example, supposing an output like:
```
$ history
926 ll
927 cd ..
928 export --password=super_secret
929 ll
```
and you want purge the `export` line, you can simply achieve it by:
```
history -d 928
```
|
The easiest way to find where your bash history is stored is with this:
`echo $HISTFILE`
|
145,250 |
If I run `history`, I can see my latest executed commands.
But if I do `tail -f $HISTFILE` or `tail -f ~/.bash_history`, they do not get listed.
Does the file get locked, is there a temporary location or something similar?
|
2014/07/18
|
['https://unix.stackexchange.com/questions/145250', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/57143/']
|
Bash maintains the list of commands internally in memory while it's running. They are written into [`.bash_history` on exit](https://www.gnu.org/software/bash/manual/bashref.html#Bash-History-Facilities):
>
> When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to the file named by $HISTFILE
>
>
>
If you want to force the command history to be written out, you can use the [`history -a`](https://www.gnu.org/software/bash/manual/bashref.html#index-history) command, which will:
>
> Append the new history lines (history lines entered since the beginning of the current Bash session) to the history file.
>
>
>
There is also a `-w` option:
>
> Write out the current history to the history file.
>
>
>
which may suit you more depending on exactly how you use your history.
If you want to make sure that they're always written immediately, you can put that command into your `PROMPT_COMMAND` variable:
```
export PROMPT_COMMAND='history -a'
```
|
Commands are saved in memory (RAM) while your session is active. As soon as you close the shell, the commands list gets written to `.bash_history` before shutdown.
Thus, you won't see history of current session in `.bash_history`.
|
320,377 |
I was moving a couple of physical volumes from my lvm. I managed to successfully pvmove and pvremove them. After this i was moving some files from the lvm to one of the removed pvs. Now during this my system hang up and i had to reboot. But once i rebooted i find that the superblock is corrupted on the lvm. Here is the actual error message:
```
bad geometry: block count 35651584 exceeds size of device (19922944 blocks)
```
e2fsck fails with message:
```
The filesystem size (according to the superblock) is 35651584 blocks
The physical size of the device is 19922944 blocks
Either the superblock or the partition table is likely to be corrupt!
Abort<y>? yes
```
I tried e2fsck -b 8193 and that failed too.
What is going on? Is there anyway i can recover the data or is it lost?
EDIT:
Oh, i have already done vgcfgrestore. it doesn't help.
EDIT1:
Trying to open the device from debugfs gives the error message
```
/dev/home/lvol0: Can't read an inode bitmap while reading inode bitmap
```
EDIT2:
Adding a blog post link.<http://anandjeyahar.wordpress.com/2011/08/09/lvm/>
|
2011/08/08
|
['https://superuser.com/questions/320377', 'https://superuser.com', 'https://superuser.com/users/71178/']
|
Take a look at [TestDisk](http://www.cgsecurity.org/wiki/TestDisk). You can get it pre-installed with several live rescue cds, or install it from the repo while running a normal live-cd.
|
Try the below url, hope this will help you
<http://www.digitalinux.com/2010/11/lvm-logical-volume-manager.html>
|
27,884,209 |
I am attempting to use PHP's `printf` function to print out a user's storage capacity. The full formula looks something like this:
```
echo printf("%.02f", ($size/(1024*1024))) . " GB";
```
Given that `$size == (10 * 1024 * 1024)`, this should print out
>
> 10.00 GB
>
>
>
But it doesn't. It prints `10.04 GB`. Furthermore,
```
echo printf("%.02f", 10)
```
results in
>
> 10.04
>
>
>
---
What?! In giving it an integer to convert to a float, it converts 10 to 10.00000009.
How can this be remedied? Obviously, one solution would be to print it out as an integer, but the value will not always be an integer; it may be 5.57 GB, in which case the accuracy of this script is very important.
---
And umm...
```
echo printf("%d", 10)
```
results in
>
> 102
>
>
>
Something is very wrong here.
|
2015/01/11
|
['https://Stackoverflow.com/questions/27884209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892629/']
|
So apparently `printf` is not meant to be echoed. At all.
Simply changing the instances of `printf` to `sprintf` fixed that problem.
---
Furthermore, removing the echo, and just running the command as `printf("%.02f", 10)` does, in fact, print `10.00`, however, it should be noted that you cannot append strings to printf like you can with echoing.
---
If you ask me, PHP should've thrown a syntax error, unexpected T\_FUNCTION or something, but I digress.
|
This is to deep, But I will try to explain:
```
echo printf("%d", 10)
```
TL>TR: When `echo` is called with an expression, it first evaluate all of the params, then displays the result on the screen.
If some of the expressions print something on the screen when evaluated, you get a this mess.
First thing that happens is `printf()` it is executed, to get its value.
This result in IMMEDIATELY printing "10" on the screen/output.
Then, the **return** result of `printf()` is echo-ed, in this case it is "2".
If you check the [docs](http://php.net/manual/en/function.printf.php) `printf` returns the **length** of the result string.
So on the screen you see "10","2"
You should really not use **Print()** and similar function together with **Echo**.
P.S
Here is another gem:
`echo 1. print(2) + 3;` // result: 214
|
247,136 |
How do I add a class to the form element of the search block form?
I mean, add a class to this element:
```
<form action="/search/node" method="get" id="search-block-form" accept-charset="UTF-8" data-drupal-form-fields="edit-keys"></form>
```
I've tried:
```
function mytheme_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'search_block_form') {
$form['#attributes'] = array('class' => array('abc'));
}
}
```
and
```
function mytheme_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'search_block_form') {
$form['#attributes']['class'][] = 'abc';
}
}
```
I've tried:
```
function mytheme_preprocess_form(&$variables) {
if ($variables['element']['#form_id'] == 'search_block_form') {
$variables['element']['#attributes'] = array('class' => array('xyz'));
}
}
```
I've looked into altering `core/modules/system/templates/form.html.twig`, which does not look like the way to go.
I'm using the Bootstrap theme as my base.
|
2017/10/01
|
['https://drupal.stackexchange.com/questions/247136', 'https://drupal.stackexchange.com', 'https://drupal.stackexchange.com/users/14968/']
|
Just tested this and `$node->access('update');` works for me. I let the optional $account parameter out so that it would check the currently logged in user.
The only difference was that I loaded my node with:
```
\Drupal\node\Entity\Node::load($nid);
```
To just use `Node::load($nid);` Make sure to include:
```
use Drupal\node\Entity\Node;
```
at the top of your file.
|
As Rubix05 mentions, the issue is that you are testing "edit" access when you should be testing "update" access.
```
$node = Node::load(1);
$account = User::load(1);
$check = $node->access('update', $account);
```
|
36,906,926 |
I am using the below code in which I am clearing the data inside datatable. And now I need to attach a new data to existing datatable.
```
var dataTable = $('#mytable').DataTable();
dataTable.clear().draw();
var dtt = $('#mytable').DataTable({
"aaData": GlobalTable,
paging: false,
searching: false,
"columns": [
{"data": "name"},
{"data": "position"},
{"data": "office"},
{"data": "extn"},
{"data": "start_date"},
{"data": "end_date"},
{"data": "salary"}
]
});
```
What should I use? It is giving me error Reinitialize is not allowed for the datatable.
|
2016/04/28
|
['https://Stackoverflow.com/questions/36906926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2696717/']
|
Using the [DATEDIFF](https://msdn.microsoft.com/en-us/library/ms189794.aspx) function you will get the difference of two dates/time in Year/Month/Day/Hour/Min/Sec as you required.
Eg:- `DATEDIFF ( MINUTE , startdate , enddate )` --will return the diff in minutes
|
You can try to use the [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794.aspx) function like this:
```
where DATEDIFF(HH,StartWork, EndWork)
```
|
36,906,926 |
I am using the below code in which I am clearing the data inside datatable. And now I need to attach a new data to existing datatable.
```
var dataTable = $('#mytable').DataTable();
dataTable.clear().draw();
var dtt = $('#mytable').DataTable({
"aaData": GlobalTable,
paging: false,
searching: false,
"columns": [
{"data": "name"},
{"data": "position"},
{"data": "office"},
{"data": "extn"},
{"data": "start_date"},
{"data": "end_date"},
{"data": "salary"}
]
});
```
What should I use? It is giving me error Reinitialize is not allowed for the datatable.
|
2016/04/28
|
['https://Stackoverflow.com/questions/36906926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2696717/']
|
```
DECLARE @END_DATE TIME = '' ,
@START_DATE TIME = ''
SELECT CONVERT(TIME,DATEADD(MS,DATEDIFF(SS, @START_DATE, @END_DATE )*1000,0),114)
```
|
You can try to use the [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794.aspx) function like this:
```
where DATEDIFF(HH,StartWork, EndWork)
```
|
19,778,292 |
I'm making a wordpress template from scratch.
I've eliminated many of the files and kept in just the header.php, footer.php, index.php, and style.css to rule out many of my potential problems.
I've played with the code, looked up questions, googled for my solution, but I'm not sure why my style isn't being recognized when i go to my site
the following are my 4 files:
**style.css**
```
/* Eric Meyer's Reset CSS v2.0 - http://cssreset.com */
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:none}table{border-collapse:collapse;border-spacing:0}
/* MAIN STYLE */
html {
font-size: 20px;
}
body {
}
#bodywrapper {
background: gray;
font-family: arial, sans-serif;
font-size: 5em;
}
header {
height:20em;
background: #000;
color: #fff;
margin: 0 auto;
}
#nav {
}
#nav ul {
list-style-type: none;
}
#nav ul li {
display: inline-block;
padding: 1em;
}
#nav ul li a{
padding: 1em;
text-align: center;
text-decoration:none;
}
#nav ul li a div{
height: 5em;
width: auto;
padding: 1em;
background-color: black;
}
#sandwichwrapper {
margin: 2em;
border: 1em solid black;
}
#sidebar {
float: right;
width: 15em;
margin: 2em;
border: 1em solid green;
}
#main {
float: right;
width: 15em;
margin: 2em;
border: 1em solid blue;
}
#comments{
clear: both;
margin: 2em;
border: 1em solid yellow;
}
#comment-form{
}
footer {
clear: both;
margin: 0 auto;
padding: 1em;
background: #000;
color: #fff;
}
/* BUNDLED STYLES */
header, footer{
width:100%;
margin:0 auto;
padding: 5em;
overflow:auto;
}
nav #sandwich {
width: 50em;
}
/* TEXT RULES */
h1 {
size: 10em;
color: green;
}
h2 {
size: 8em;
}
h3 {
size: 6em;
}
h4 {
size: 4em;
}
h5 {
size: 2em;
}
```
**header.php**
```
<!doctype html>
<html>
<head>
<title>The Logic Spot</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<meta charset="utf-8" />
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
header("Content-type: text/css");
</head>
<body>
<div id="bodywrapper">
<header>
<h1><a href="<?php echo home_url('/')?>"><?php bloginfo('name')?></a></h1>
</header>
<div id="nav">
<?php wp_nav_menu();?>
</div>
<div id="sandwichwrapper">
```
**index.php**
```
<?php get_header()?>
<!--div#bodywrapper contained in header.php-->
<!--div#sandwich contained in header.php-->
<?php get_sidebar()?>
<div id="main">
<?php while(have_posts()): the_post()?>
<h2><a href="<?php the_permalink()?>"><?php the_title()?></a></h2>
<p>By <?php echo get_the_author_link();?></p>
<?php the_content(__('Continue Reading'))?>
<?php endwhile?>
</div>
<!--div#sandwich contained in footer.php-->
<!--div#bodywrapper contained in header.php-->
<?php get_footer()?>
```
**footer.php**
```
</div> <!-- close div#sandwichwrapper-->
<footer>
<?=date('Y')?> Copyright
</footer>
</div> <!-- close div#bodywrapper-->
</body>
</html>
```
|
2013/11/04
|
['https://Stackoverflow.com/questions/19778292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2951835/']
|
Add this line in the `<head>` tag
```
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
```
|
Hey you need to specify absolute path to the stylesheets, for example
```
<link type="text/css" rel="stylesheet" href="http://www.yourwebsite.com/wp-content/themes/yourtheme/style.css" />
```
Also as Matt stated, you can use functions like [get\_stylesheet\_directory\_url()](http://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri) or [get\_stylesheet\_uri()](http://codex.wordpress.org/Function_Reference/get_stylesheet_uri) to make your path more dynamic.
|
70,638,185 |
I'm trying to migrate from the now dead Tachyons framework to Tailwindcss. However, there's one block I haven't figured out how to overcome.
I use the [jekyll-postscss](https://github.com/mhanberg/jekyll-postcss) Gem to enable postscss processing during `jekyll build`. Things appear to work well with the following setup:
`assets/css/styles.css`:
```
---
---
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
```
`postcss.config.js`:
```
module.exports = {
parser: 'postcss-scss',
plugins: [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
...(process.env.JEKYLL_ENV == "production"
? [require('cssnano')({ preset: 'default' })]
: [])
]
};
```
`tailwind.config.js`:
```
module.exports = {
purge: [
'./_includes/**/*.html',
'./_layouts/**/*.html',
'./_posts/*.md',
'./*.html',
],
darkMode: false,
theme: {
extend: {},
},
variants: {},
plugins: [
require('@tailwindcss/typography'),
],
}
```
With a `jekyll build` command, I can see the correctly generated styles.css file under `_site/assets/css`.
However, it doesn't work when I try to import other css or scss files. For example, if I modify the `styles.css` file into the following
`assets/css/styles.scss`:
```
---
---
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
@import "test.css"
```
where `test.css` is in the same directory as `styles.scss` (`assets/css/`), `postcss-import` throws an exception
```
Error: Failed to find './test.css'
in [
/project
]
at /project/node_modules/postcss-import/lib/resolve-id.js:35:13
at async LazyResult.runAsync (/project/node_modules/postcss/lib/lazy-result.js:396:11)
```
I'm a bit confused as to why `postcss-import` does not see this file.
|
2022/01/09
|
['https://Stackoverflow.com/questions/70638185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2719660/']
|
Because the css resource you imported is not in the resolved path, the default resolved path includes: root directory, node\_modules, etc. Other paths can refer to the official documentation [link](https://github.com/postcss/postcss-import).
You can try the following methods to solve this problem:
1. Modify the postcss configuration file `postcss.config.js`
```
module.exports = {
...
require('postcss-import')({
addModulesDirectories: ["assets/css"]
}),
...
};
```
2. Modify the main style file `assets/css/styles.css`
```
@import "assets/css/test.css"
```
|
I used a similar solution to what [Donnie](https://stackoverflow.com/a/73348640/3402925) suggests, but I set the `path` instead of the `addModulesDirectories`, which resolved the issue for me. I didn't try the `addModulesDirectories`, so I don't know whether that might have also worked.
```
module.exports = {
...
require('postcss-import')({
path: ["assets/css"]
}),
...
};
```
|
4,211,509 |
I created a new xml file, and had an errant ? in it that prevented R.java from regenerating. I tried Cleaning the Project, and Fixing the Project Properties but no luck.
Then I realized the XML was creating the R.java from recreating itself, so I deleted the XML file and the R.java was back.
Now though, I am getting an error on all the calls to R.*.* calls saying that :
* cannot be resolved or is not a field
So, for instance I have
```
setContentView(R.layout.detectlayout);
```
ERROR: detectlayout cannot be resolved or is not a field
for all of my calls to 'R.'. Any ideas?
I have tried all of the suggestions on SO already to no luck =/
|
2010/11/18
|
['https://Stackoverflow.com/questions/4211509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496686/']
|
Look at the 'import' section of your code. Since you deleted your original R, chances is Eclipse help you to fill in the R as com.android.R instead of com.yourproject.R
I also sometimes have problem in Eclipse Resource stuff, sometimes I found turning off and on the "auto buiild" function may help, or simply restarting Eclipse may sometimes help. It's kind of buggy under Mac OS.
|
This can happen if .R is imported. Eclipse will automatically add it sometimes when you have difficulty with with R.java
|
4,211,509 |
I created a new xml file, and had an errant ? in it that prevented R.java from regenerating. I tried Cleaning the Project, and Fixing the Project Properties but no luck.
Then I realized the XML was creating the R.java from recreating itself, so I deleted the XML file and the R.java was back.
Now though, I am getting an error on all the calls to R.*.* calls saying that :
* cannot be resolved or is not a field
So, for instance I have
```
setContentView(R.layout.detectlayout);
```
ERROR: detectlayout cannot be resolved or is not a field
for all of my calls to 'R.'. Any ideas?
I have tried all of the suggestions on SO already to no luck =/
|
2010/11/18
|
['https://Stackoverflow.com/questions/4211509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496686/']
|
Look at the 'import' section of your code. Since you deleted your original R, chances is Eclipse help you to fill in the R as com.android.R instead of com.yourproject.R
I also sometimes have problem in Eclipse Resource stuff, sometimes I found turning off and on the "auto buiild" function may help, or simply restarting Eclipse may sometimes help. It's kind of buggy under Mac OS.
|
first don't bother deleting the R file it not going to make things better only worst lol
as you said you some times need to clean the project
when you start modifying resources its good to select the root of your project and do a alt+shift+o to reload all ressources
then f5 to refresh the tree
then clean the project
you also have to check that eclipse is set to build automatically (Project->build automatically).
|
63,737,381 |
I intended to coding" when Listview items appearing and Items appearing " items appearing from **top** or **bottom**. ( using TranslateTo )
but When Listview Viewcell Appearing, or itemsAppearing, i tried to Apply animations.
but, higher index of items hiding lower index of items animation.
so, lower index items animation is only show shortly. ( cropped by other layout)
[Please Check Image Description \_ Animation Cropped by items](https://i.stack.imgur.com/1SSkI.png)
in Xamarin Forms(C#)
```
private async void ItemsListView_ItemAppearing_1(object sender, ItemVisibilityEventArgs e)
{
int i = e.ItemIndex;
int y;
y = 400;
for (int d = 0; d < i; d++)
{
int z = d + 1;
y = y + (400 / (z * z));
}
uint x = uint.Parse(y.ToString());
IEnumerable<PropertyInfo> pInfos = (ItemsListView as ItemsView<Cell>).GetType().GetRuntimeProperties();
var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");
if (templatedItems != null)
{
var cells = templatedItems.GetValue(ItemsListView);
var cell = (cells as Xamarin.Forms.ITemplatedItemsList<Xamarin.Forms.Cell>)[e.ItemIndex] as ViewCell;
//cell.View.Opacity = 0;
cell.View.TranslationY = Var.Device_Height / Var.Device_Scale;
await cell.View.TranslateTo(0, 0, x, Easing.CubicOut);
}
}
```
In XAML
```
<ListView x:Name="ItemsListView" BackgroundColor="Transparent" VerticalOptions="Fill" ItemsSource="{Binding Items}" Margin="0" SeparatorVisibility="None" RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="True" HasUnevenRows="True" IsRefreshing="{Binding IsBusy, Mode=OneWay}" ItemAppearing="ItemsListView_ItemAppearing_1"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Appearing="ViewCell_Appearing">
<ViewCell.View>
<Frame IsClippedToBounds="False"
Margin="0,5"
CornerRadius="10"
Padding="0"
HasShadow="False"
BorderColor="#f0f0f0"
BackgroundColor="Transparent" >
<StackLayout Padding="0" Spacing="0" MinimumHeightRequest="0">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" Margin="13,12,5,0" FontAttributes="Bold" FontSize="18" TextColor="#222222">
</Label>
<Frame MinimumHeightRequest="0" VerticalOptions="EndAndExpand" Padding="7,2,7,2" CornerRadius="100" BackgroundColor="Accent" HasShadow="False">
<Label Text="{Binding Sequence}" TextColor="White" FontSize="Micro"/>
</Frame>
</StackLayout>
<Label Text="{Binding Mail}" Margin="13,6,0,12">
</Label>
</StackLayout>
</Frame>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
it is same result, when **ViewCell\_appearing** or **items\_Appearing**
|
2020/09/04
|
['https://Stackoverflow.com/questions/63737381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10910681/']
|
The following worked. Sorry, I cannot provide info on all details since I don't know them :( Maybe somebody else can.
deployment.yaml
```
apiVersion: apps/v1
kind: Deployment
metadata:
name: zipkin
labels:
app.kubernetes.io/name: zipkin
app.kubernetes.io/instance: zipkin
app: zipkin
spec:
replicas: 1
selector:
matchLabels:
app: zipkin
template:
metadata:
name: zipkin
labels:
app: zipkin
spec:
containers:
- name: zipkin
image: openzipkin/zipkin:2.21
imagePullPolicy: Always
ports:
- containerPort: 9411
protocol: TCP
env:
- name: STORAGE_TYPE
value: elasticsearch
- name: ES_HOSTS
value: https://my-es-host:9243
- name: ES_USERNAME
value: myUser
- name: ES_PASSWORD
value: myPassword
- name: ES_HTTP_LOGGING
value: HEADERS
readinessProbe:
httpGet:
path: /api/v2/services
port: 9411
initialDelaySeconds: 5
timeoutSeconds: 3
```
service.yaml
```
apiVersion: v1
kind: Service
metadata:
name: zipkin
labels:
app.kubernetes.io/name: zipkin
app.kubernetes.io/instance: zipkin
app: zipkin
spec:
type: ClusterIP
ports:
- port: 9411
targetPort: 9411
protocol: TCP
name: http <-- DELETED
selector:
app.kubernetes.io/name: zipkin <-- DELETED
app.kubernetes.io/instance: zipkin <-- DELETED
app: zipkin
```
ingress.yaml
```
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: zipkin
labels:
app.kubernetes.io/name: zipkin
app.kubernetes.io/instance: zipkin
app.kubernetes.io/managed-by: zipkin
annotations:
kubernetes.io/ingress.class: nginx
kubernetes.io/tls-acme: "true"
nginx.ingress.kubernetes.io/rewrite-target: /$1 <-- DELETED
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/proxy-body-size: "0"
nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE"
nginx.ingress.kubernetes.io/cors-allow-origin: "*"
nginx.ingress.kubernetes.io/enable-cors: "true"
spec:
tls:
- hosts:
- ns-zipkin.my-host
secretName: .my-host
rules:
- host: ns-zipkin.my-host
http:
paths:
- path: / <-- CHANGED
backend:
serviceName: zipkin
servicePort: 9411 <-- CHANGED
```
|
Your service is expecting following labels on pod:
```
selector:
app.kubernetes.io/name: zipkin
app.kubernetes.io/instance: zipkin
app: zipkin
```
Although it looks like you have only one label on zipkin pods:
```
labels:
app: zipkin
```
Label selector uses logical AND (&&), and this means that all labels specified must be on pod to match it.
|
267,134 |
To demonstrate that a set is open, you can show that any element of it is an interior point. That is, for any element $x$ of an open set $S$ there exists some ball of center $x$ and positive radius. Likewise, if you find that all elements of a set are interior points, you can figure that the set is open.
What property can be used to show that a set is closed? By a definition of closed sets you could show that its complement is open, but that method involves elements outside of the set.
Are there any properties specific to elements of closed sets?
|
2012/12/29
|
['https://math.stackexchange.com/questions/267134', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17622/']
|
You can’t limit yourself entirely to points of the closed set, because whether a set is closed depends on how it interacts with the surrounding space. For example, $\Bbb Q\times\{0\}$ is a closed subset of $\Bbb Q^2$ but not of $\Bbb R^2$. You don’t, however, have to look just at the complement.
>
> Let $X$ be a topological space and $F\subseteq X$. Then the following are equivalent:
>
>
> * $F$ is closed in $X$.
> * If $\nu$ is a [net](http://en.wikipedia.org/wiki/Net_%28mathematics%29) in $F$ that converges to some $x\in X$, then $x\in F$.
> * If $\mathscr{F}$ is a [filter](http://en.wikipedia.org/wiki/Filter_%28mathematics%29) on $F$ that converges to $x\in X$, then $x\in F$.
>
>
>
Note that both the net and the filter versions deal specifically with points of $F$, though they (necessarily) also refer to points that may be outside $F$, namely, the limit points of the nets or filters.
[This PDF](http://www.math.tamu.edu/~saichu/netsfilters.pdf) is a good introduction to nets and filters in topology.
|
Well, point-set topology is hardly my métier, but it seems to me that when one speaks of a set being closed, one always has in mind its setting within a larger space. One says (or ought to say), “$K$ is closed in $X$”, because the property of being closed is not intrinsic.
Once you understand that, you see that the property of being open is not intrinsic, either. Here's an example. In the space $X=[0,1]$, that is, $X$ is the closed unit interval, the subset $U=\langle1/2,0]$, that is the half-open interval from $1/2$ to $1$, is open. But it is not open in $\mathbb R$. About the point $1\in X$, the “$X$-ball” of radius $1/4$ is wholly contained in $U$, because the $X$-ball of radius $1/4$ contains no points to the right of $1$.
There is a *far deeper* result that says that an open subset of $\mathbb R^n$, when mapped continuously and in one-to-one fashion into another $\mathbb R^n$ (same dimension), has image that is necessarily open. This is “Invariance of Domain”, which you can google, and it *does* say that in this restricted sense, openness in $\mathbb R^n$ is intrinsic. But as I say, that is a deep theorem.
|
267,134 |
To demonstrate that a set is open, you can show that any element of it is an interior point. That is, for any element $x$ of an open set $S$ there exists some ball of center $x$ and positive radius. Likewise, if you find that all elements of a set are interior points, you can figure that the set is open.
What property can be used to show that a set is closed? By a definition of closed sets you could show that its complement is open, but that method involves elements outside of the set.
Are there any properties specific to elements of closed sets?
|
2012/12/29
|
['https://math.stackexchange.com/questions/267134', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17622/']
|
You can’t limit yourself entirely to points of the closed set, because whether a set is closed depends on how it interacts with the surrounding space. For example, $\Bbb Q\times\{0\}$ is a closed subset of $\Bbb Q^2$ but not of $\Bbb R^2$. You don’t, however, have to look just at the complement.
>
> Let $X$ be a topological space and $F\subseteq X$. Then the following are equivalent:
>
>
> * $F$ is closed in $X$.
> * If $\nu$ is a [net](http://en.wikipedia.org/wiki/Net_%28mathematics%29) in $F$ that converges to some $x\in X$, then $x\in F$.
> * If $\mathscr{F}$ is a [filter](http://en.wikipedia.org/wiki/Filter_%28mathematics%29) on $F$ that converges to $x\in X$, then $x\in F$.
>
>
>
Note that both the net and the filter versions deal specifically with points of $F$, though they (necessarily) also refer to points that may be outside $F$, namely, the limit points of the nets or filters.
[This PDF](http://www.math.tamu.edu/~saichu/netsfilters.pdf) is a good introduction to nets and filters in topology.
|
There is no "intrinsic" property of closedness for sets or spaces $A$. Closedness is *not* a property of sets or of topological spaces, but a property of pairs $(A,X)$ where $X$ is a topological space and $A$ is an arbitrary subset of $X$. The set $A$ is *closed in* $X$ if the properties mentioned in Brian Scott's answer hold.
Given an arbitrary subset $A$ of some topological space $X$ this set may be closed in $X$ or not. Assume $A$ is not closed (and there are very strange subsets of $X$). Nevertheless the set $A$ inherits topological information from $X$, and you can consider $A$ as a topological subspace of $X$, equipped with the so-called relative topology. Looking at the pair $(A,A)$, the full relative space $A$ is trivially a closed set in $A$, even though $A$ may be the strangest subset of $X$ you can think of.
Contrasting the above, *compactness* is an "unary" property of topological spaces and of their subsets, the latter considered as spaces in their own right, using the relative topology. I won't go into this here.
|
48,644,114 |
I am trying to follow this example in order to understand the join() method:
```
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
```
I understood that T1.join() for example makes the main thread wait for T1 to finish in order to continue with its flow. Am I correct here?
So, I modified the code like this:
```
System.out.println("1");
T1.start();
System.out.println("2");
T2.start();
// wait for threads to end
try {
System.out.println("3");
T1.join();
System.out.println("4");
T2.join();
System.out.println("5");
} catch (Exception e) {
System.out.println("Interrupted");
}
```
in order to try and follow the complete flow.
And this is what I get every time:
```
1
Starting Thread - 1
2
Starting Thread - 2
3
4
5
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
```
and I cannot explain it...
How come the counter prints were printed after the "5" character???
I probably don't understand well the join issue...
|
2018/02/06
|
['https://Stackoverflow.com/questions/48644114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2875641/']
|
You start a thread (A) which starts another thread (B).
You wait for thread A to finish - which is almost immediate as it barely does anything besides kick off thread B - but thread B is still running independently.
|
>
> I am trying ... to understand the join() method
>
>
>
`t.join()` is trivially easy to understand. All it does is wait for thread `t` to die. It doesn't do anything else. Most especially, it does not do anything to thread `t`.
A call to `t.join()` will do nothing, and return immediately if `t` has already finished. Otherwise it will do nothing, and it will not return until `t` *is* finished.
|
48,644,114 |
I am trying to follow this example in order to understand the join() method:
```
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
```
I understood that T1.join() for example makes the main thread wait for T1 to finish in order to continue with its flow. Am I correct here?
So, I modified the code like this:
```
System.out.println("1");
T1.start();
System.out.println("2");
T2.start();
// wait for threads to end
try {
System.out.println("3");
T1.join();
System.out.println("4");
T2.join();
System.out.println("5");
} catch (Exception e) {
System.out.println("Interrupted");
}
```
in order to try and follow the complete flow.
And this is what I get every time:
```
1
Starting Thread - 1
2
Starting Thread - 2
3
4
5
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
```
and I cannot explain it...
How come the counter prints were printed after the "5" character???
I probably don't understand well the join issue...
|
2018/02/06
|
['https://Stackoverflow.com/questions/48644114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2875641/']
|
As @Micheal said, your main thread are not joinning to "desire" thread, perhaps this code can help you to clarify. It helps Main thread to join with the inside threads.
```
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
public void joinInsideThread() throws InterruptedException {
if (t != null){
t.join();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);
System.out.println("1");
T1.start();
System.out.println("2");
T2.start();
// wait for threads to end
try {
System.out.println("3");
T1.joinInsideThread();
System.out.println("4");
T2.joinInsideThread();
System.out.println("5");
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
```
|
>
> I am trying ... to understand the join() method
>
>
>
`t.join()` is trivially easy to understand. All it does is wait for thread `t` to die. It doesn't do anything else. Most especially, it does not do anything to thread `t`.
A call to `t.join()` will do nothing, and return immediately if `t` has already finished. Otherwise it will do nothing, and it will not return until `t` *is* finished.
|
69,727,170 |
I am actually trying to do surface defect detection for the images (checking for defects on the walls like cracks…) when I try to fit the model it throws an error logits and labels must be `broadcastable: logits_size=[32,198] labels_size=[32,3]`
I tried a few ways but nothing worked. How do I overcome the error or is there something wrong with the approach I chose?
The data I am working with is unlabelled image data (all the images are in a single folder )
```
from keras.preprocessing.image import ImageDataGenerator
train_model = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_model = ImageDataGenerator(rescale = 1./255)
training_data = train_model.flow_from_directory('/Users/nm2/Public/ai-dataset-training-100/5/23_463_DISTACCO_DEL_COPRIFERRO_Q100_training_dataset',
target_size = (224, 224),
batch_size = 32,
class_mode = 'categorical')
testing_data = test_model.flow_from_directory('/Users/nm2/Public/ai-dataset-training-100/5/23_463_DISTACCO_DEL_COPRIFERRO_Q100_training_dataset',
target_size = (224, 224),
batch_size = 32,
class_mode = 'categorical')
IMAGE_SIZE = [224, 224]
#Import the Vgg 16 and add the preprocessing layer to front of the VGG16 Here we will use ImageNet PreTrained Weights
vgg_model = VGG16(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)
for layer in vgg_model.layers:
layer.trainable = False
x = Flatten()(vgg_model.output)
#We use glob function to find out how many files are there in the working directory and count the number of classes they belong to.
folder_count = glob('/Users/nm2/Public/ai-dataset-training-`100/5/23_493_PANORAMICA_LIVELLO_BASE_ISPEZIONE_Q100_training_dataset/*')`
prediction = Dense(len(folder_count), activation='softmax')(x)
#Create a Model
model = Model(inputs=vgg_model.input, outputs=prediction)
model.summary()
model.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
post_run = model.fit(training_data,
validation_data=testing_data,
epochs=10,
steps_per_epoch=len(training_data),
validation_steps=len(testing_data))
InvalidArgumentError: logits and labels must be broadcastable: logits_size=[32,198] labels_size=[32,3]
[[node categorical_crossentropy/softmax_cross_entropy_with_logits (defined at var/folders/3b/tfwxbsyd41j64kbrjghzrvcm0000gq/T/ipykernel_1068/3441923959.py:5) ]] [Op:__inference_train_function_1205]
Function call stack:
train_function
```
|
2021/10/26
|
['https://Stackoverflow.com/questions/69727170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16297417/']
|
you have this code as your model top layer
```
prediction = Dense(len(folder_count), activation='softmax')(x)
```
the number of neurons in this layer should be the same as the number of classes you have. Also in model.fit you have
```
steps_per_epoch=len(training_data), validation_steps=len(testing_data))
```
this should be
```
batch_size=32
steps_per_epoch=len(training_data)/batch_size
validation_steps=len(testing_data)/batch_size
```
or alternatively do not specify these values and model.fit will determine the right values internally. Also you have code
```
vgg_model = VGG16(input_shape=IMAGE_SIZE + [3]
```
change this to
```
vgg_model = VGG16(input_shape=[224,224,3]
```
|
Here is the full code that should work for you.
```
import tensorflow as tf
import tensorflow as tf
from tensorflow import keras
from keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Activation,Dropout
data_dir=r'C:\Temp\DATA' # directory where the image files are stored change to your directory
vsplit=.2 #percentage of data to be used for validation
IMAGE_SIZE = [224, 224]
IMAGE_SHAPE=[224,224,3]
train_model = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2,
horizontal_flip = True, validation_split=vsplit)
test_model = ImageDataGenerator(rescale = 1./255, validation_split=vsplit)
training_data = train_model.flow_from_directory(data_dir, target_size = IMAGE_SIZE,batch_size = 32,
class_mode = 'categorical', subset='training',
shuffle = True, seed=123)
testing_data = test_model.flow_from_directory(data_dir, target_size = IMAGE_SIZE, batch_size = 32,
class_mode = 'categorical', subset='validation',
shuffle=True, seed=123)
class_dict=training_data.class_indices
classes=list(class_dict.keys())
print ('LIST OF CLASSES ', classes)
print ('CLASS DICTIONARY ',class_dict)
number_of_classes=len(classes) # this is the number of neurons in your top layer of the model
print ('Number of classes = ', number_of_classes)
base_model=tf.keras.applications.VGG19(include_top=False, weights="imagenet",input_shape=IMAGE_SHAPE, pooling='max')
# Note setting pooling='max' eliminates the need for a flatten layer
# I do not recommend using VGG it is a very large model I recommend using EfficientNetB3- note do not rescale
# the pixel for Efficient net.
x=base_model.output
base_model.trainable=False
x = Dense(256, activation='relu')(x)
x=Dropout(rate=.45, seed=123)(x)
output=Dense(number_of_classes, activation='softmax')(x)
model=Model(inputs=base_model.input, outputs=output)
model.compile(Adam(learning_rate=.001), loss='categorical_crossentropy', metrics=['accuracy'])
epochs=5
# I recommend the use of callbacks to control the learning rate and early stopping
rlronp=tf.keras.callbacks.ReduceLROnPlateau( monitor="val_loss", factor=0.5, patience=1, verbose=1)
estop=tf.keras.callbacks.EarlyStopping( monitor="val_loss", patience=3, verbose=1, restore_best_weights=True)
history=model.fit(x=training_data, epochs=epochs, verbose=1, validation_data=testing_data,
callbacks=[rlronp, estop], validation_steps=None, shuffle=True, initial_epoch=0)
# Fine Tune the model
base_model.trainable=True # make the base model trainable
epochs=5
history=model.fit(x=training_data, epochs=epochs, verbose=1, validation_data=testing_data,
callbacks=[rlronp, estop], validation_steps=None, shuffle=True, initial_epoch=0)
```
|
30,723,972 |
I have an int array called `doubledNumbers` and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in `doubledNumbers`:
```
12 14 16 17
```
I want to change the `doubledNumbers` to:
```
3 5 7 8
```
I'm unsure how to do this for an int array as I get the error
>
> invalid types 'int[int]' for array subscript
>
>
>
This is the code I have (thrown in a `for` loop):
```
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
```
|
2015/06/09
|
['https://Stackoverflow.com/questions/30723972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681431/']
|
There is nothing like decimal digits in an `int`. There are (mostly 32 or 64) *binary* digits (bits) and the base of 2 is not commensurable with the base of 10. You’ll need to divide your numbers by 10 to get decimal digits.
```
unsigned int DigitSum(unsigned int input, unsigned int base = 10)
{
unsigned int sum = 0;
while(input >= base)
{
sum += input % base;
input /= base;
}
sum += input;
return sum;
}
```
I used `unsigned int`. The example cannot be directly used for negative numbers but the modification is not difficult.
|
```
int A[2];
A[0] = 2;
A[1] = 10;
for (int i=0;i<2;i++) {
if (a[i] > 9) {
int b = a[i]%10;
int c = a[i]/10;
int d = b+c;
cout << d;
}
}
```
It's only for two digit numbers(10 -99) and for more than that (after 99) we will have to change logic.
|
30,723,972 |
I have an int array called `doubledNumbers` and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in `doubledNumbers`:
```
12 14 16 17
```
I want to change the `doubledNumbers` to:
```
3 5 7 8
```
I'm unsure how to do this for an int array as I get the error
>
> invalid types 'int[int]' for array subscript
>
>
>
This is the code I have (thrown in a `for` loop):
```
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
```
|
2015/06/09
|
['https://Stackoverflow.com/questions/30723972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681431/']
|
You can use something like this
```
#include <iostream>
using namespace std;
int sumofdigits(int);
int main()
{
// your code goes here
int a[5] ={12,14,15,16,17};
for(int i=0;i<5;i++)
{
int m=sumofdigits(a[i]);
cout <<m<<" ";
}
return 0;
}
int sumofdigits(int n)
{
int sum=0;
while(n!=0)
{
int d=n%10;
sum=sum+d;
n=n/10;
}
return sum;
}
```
// % operator is used for calculating remainder.
|
```
int A[2];
A[0] = 2;
A[1] = 10;
for (int i=0;i<2;i++) {
if (a[i] > 9) {
int b = a[i]%10;
int c = a[i]/10;
int d = b+c;
cout << d;
}
}
```
It's only for two digit numbers(10 -99) and for more than that (after 99) we will have to change logic.
|
30,723,972 |
I have an int array called `doubledNumbers` and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in `doubledNumbers`:
```
12 14 16 17
```
I want to change the `doubledNumbers` to:
```
3 5 7 8
```
I'm unsure how to do this for an int array as I get the error
>
> invalid types 'int[int]' for array subscript
>
>
>
This is the code I have (thrown in a `for` loop):
```
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
```
|
2015/06/09
|
['https://Stackoverflow.com/questions/30723972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681431/']
|
```
You can do like this,
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a[5]={1,2,5,11,12};
int length = sizeof(a)/sizeof(int);
for(int i=0;i<length;i++)
{
if ( a[i] >9 )
{
stringstream ss;
ss << a[i];
string a1 = ss.str();
const char * s = a1.c_str();
int sum=0;
while (*s !='\0')
{
cout<<*s<<endl;
sum += (*s - '0');
s++;
}
cout<<"num:"<< sum <<"\n";
}
}
}
```
|
```
int A[2];
A[0] = 2;
A[1] = 10;
for (int i=0;i<2;i++) {
if (a[i] > 9) {
int b = a[i]%10;
int c = a[i]/10;
int d = b+c;
cout << d;
}
}
```
It's only for two digit numbers(10 -99) and for more than that (after 99) we will have to change logic.
|
30,723,972 |
I have an int array called `doubledNumbers` and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in `doubledNumbers`:
```
12 14 16 17
```
I want to change the `doubledNumbers` to:
```
3 5 7 8
```
I'm unsure how to do this for an int array as I get the error
>
> invalid types 'int[int]' for array subscript
>
>
>
This is the code I have (thrown in a `for` loop):
```
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
```
|
2015/06/09
|
['https://Stackoverflow.com/questions/30723972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681431/']
|
There is nothing like decimal digits in an `int`. There are (mostly 32 or 64) *binary* digits (bits) and the base of 2 is not commensurable with the base of 10. You’ll need to divide your numbers by 10 to get decimal digits.
```
unsigned int DigitSum(unsigned int input, unsigned int base = 10)
{
unsigned int sum = 0;
while(input >= base)
{
sum += input % base;
input /= base;
}
sum += input;
return sum;
}
```
I used `unsigned int`. The example cannot be directly used for negative numbers but the modification is not difficult.
|
You can use something like this
```
#include <iostream>
using namespace std;
int sumofdigits(int);
int main()
{
// your code goes here
int a[5] ={12,14,15,16,17};
for(int i=0;i<5;i++)
{
int m=sumofdigits(a[i]);
cout <<m<<" ";
}
return 0;
}
int sumofdigits(int n)
{
int sum=0;
while(n!=0)
{
int d=n%10;
sum=sum+d;
n=n/10;
}
return sum;
}
```
// % operator is used for calculating remainder.
|
30,723,972 |
I have an int array called `doubledNumbers` and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in `doubledNumbers`:
```
12 14 16 17
```
I want to change the `doubledNumbers` to:
```
3 5 7 8
```
I'm unsure how to do this for an int array as I get the error
>
> invalid types 'int[int]' for array subscript
>
>
>
This is the code I have (thrown in a `for` loop):
```
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
```
|
2015/06/09
|
['https://Stackoverflow.com/questions/30723972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681431/']
|
There is nothing like decimal digits in an `int`. There are (mostly 32 or 64) *binary* digits (bits) and the base of 2 is not commensurable with the base of 10. You’ll need to divide your numbers by 10 to get decimal digits.
```
unsigned int DigitSum(unsigned int input, unsigned int base = 10)
{
unsigned int sum = 0;
while(input >= base)
{
sum += input % base;
input /= base;
}
sum += input;
return sum;
}
```
I used `unsigned int`. The example cannot be directly used for negative numbers but the modification is not difficult.
|
```
You can do like this,
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a[5]={1,2,5,11,12};
int length = sizeof(a)/sizeof(int);
for(int i=0;i<length;i++)
{
if ( a[i] >9 )
{
stringstream ss;
ss << a[i];
string a1 = ss.str();
const char * s = a1.c_str();
int sum=0;
while (*s !='\0')
{
cout<<*s<<endl;
sum += (*s - '0');
s++;
}
cout<<"num:"<< sum <<"\n";
}
}
}
```
|
30,723,972 |
I have an int array called `doubledNumbers` and if a number in this array is greater than 9, I want to add the digits together. (example, 16 would become 1+6=7, 12 would become 3, 14 would become 5, etc)
Lets say I had the following numbers in `doubledNumbers`:
```
12 14 16 17
```
I want to change the `doubledNumbers` to:
```
3 5 7 8
```
I'm unsure how to do this for an int array as I get the error
>
> invalid types 'int[int]' for array subscript
>
>
>
This is the code I have (thrown in a `for` loop):
```
if (doubledNumbers[i]>9) {
doubledNumbers[i]=doubledNumbers[i][0]+doubledNumbers[i][1];
```
|
2015/06/09
|
['https://Stackoverflow.com/questions/30723972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681431/']
|
You can use something like this
```
#include <iostream>
using namespace std;
int sumofdigits(int);
int main()
{
// your code goes here
int a[5] ={12,14,15,16,17};
for(int i=0;i<5;i++)
{
int m=sumofdigits(a[i]);
cout <<m<<" ";
}
return 0;
}
int sumofdigits(int n)
{
int sum=0;
while(n!=0)
{
int d=n%10;
sum=sum+d;
n=n/10;
}
return sum;
}
```
// % operator is used for calculating remainder.
|
```
You can do like this,
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a[5]={1,2,5,11,12};
int length = sizeof(a)/sizeof(int);
for(int i=0;i<length;i++)
{
if ( a[i] >9 )
{
stringstream ss;
ss << a[i];
string a1 = ss.str();
const char * s = a1.c_str();
int sum=0;
while (*s !='\0')
{
cout<<*s<<endl;
sum += (*s - '0');
s++;
}
cout<<"num:"<< sum <<"\n";
}
}
}
```
|
15,446,397 |
I am adding nested (reddit-like) comments to my app; so far I'm just using `comment` divs, where in my CSS I do this:
```
.comment {
margin-left: 40px;
}
```
This works fine for displaying comments. My question is what is the cleanest way to now add reply forms to each comment (and only show it when the user clicks a reply button of some sort)?
Is this usually done by adding all the input boxes for the comments right away, hiding them at first, and then only showing them if the user clicks on a reply button? Or perhaps should I only append the relevant `<form>` HTML code to a given div once the user clicks reply for that comment?
What is the cleanest way to do this?
|
2013/03/16
|
['https://Stackoverflow.com/questions/15446397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363078/']
|
You can do that by having one form field hidden somewhere in the html and when ever user clicks on the commect clone the form element and append it to the comment div
checkout this jsFiddle [example](http://jsfiddle.net/jskswamy/p6qFB/) below is the code snippet
```
<div class="comment">
comment1
</div>
<div class="comment">
comment2
</div>
<div style="display:none">
<form id="commentForm">
<textarea name="comment"></textarea>
</form>
</div>
var Comment = {
init: function() {
$(".comment").bind('click', $.proxy(this.handleClick, this));
},
handleClick: function(evt) {
var form = $('#commentForm').clone();
var target = $(evt.target);
var isFormAvailable = $("#commentForm", target).length > 0;
if(!isFormAvailable) {
$(evt.target).append(form);
}
}
};
$(function() {
Comment.init();
});
```
|
Keep a template of the form somewhere in your document and keep it hidden. On click of reply next to any comment, do following.
1. Clone the template (you can jquery clone function)
2. Set a hidden field in the template to the id of the comment for which reply is been clicked
3. append it next to comment that need to be replied
I'll go with this.
Keep the input boxes with each comment right away doesn't make sense. It's unnecessarily increasing the size of the page.
|
61,545,026 |
I've been banging my head on this issue! I have a variable called `repDate` which today is equal to `"5/1/2020"` as a string. I've tried this formula to convert it to a `Long` so I can compare it to a date in the file `rDtLng = CLng(repDate)`. I'm getting error "Type Mismatch" which I am not sure why there would be one. This is where I am doing the comparing the rest works great, just the report date as long doesn't want to work.
```
'repDate equals "5/1/2020", currently
rDtLng = CLng(repDate)
.
.
.
'Delete charge offs
For w = rwCnt To 3 Step -1
Do While .Cells(w, napbRng.Column).Value2 <= 0 And .Cells(w, apbRng.Column).Value2 <= 0
If .Cells(w, matDtRng.Column).Value2 = "" Then Exit Do
If .Cells(w, matDtRng.Column).Value2 < rDtLng Then
.Rows(w).Delete shift:=xlShiftUp
Else: Exit Do
End If
Loop
Next w
```
Thanks in advance!
|
2020/05/01
|
['https://Stackoverflow.com/questions/61545026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8396248/']
|
`CLng` expects a numeric input, which the *text-that-looks-like-a-date* `"5/1/2020"` is not.
You can convert that to an actual date using `CDate` and then perform mathematical operations on it, including the existing `<` comparison.
Though if I understand what your end goal is, you might consider `Range.AutoFilter` with a date filter, and then deleting visible rows, instead of your current `Do` loop approach.
*Side note*: you could `CLng(CDate("5/1/2020"))` and the result would be `43952`, but that's an unnecessary step, as you can do math with dates directly.
|
Use DateValue() Function.
```
Sub test()
Dim myDate As Long
Dim str As String
str = "5/1/2020"
myDate = DateValue(str)
If myDate = DateSerial(2020, 5, 1) Then
MsgBox "OK"
End If
End Sub
```
|
51,322,445 |
I have a large dataset of which I would like to drop columns that contain `null` values and return a new dataframe. How can I do that?
The following only drops a single column or rows containing `null`.
```
df.where(col("dt_mvmt").isNull()) #doesnt work because I do not have all the columns names or for 1000's of columns
df.filter(df.dt_mvmt.isNotNull()) #same reason as above
df.na.drop() #drops rows that contain null, instead of columns that contain null
```
For example
```
a | b | c
1 | | 0
2 | 2 | 3
```
In the above case it will drop the whole column `B` because one of its values is empty.
|
2018/07/13
|
['https://Stackoverflow.com/questions/51322445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10020360/']
|
Here is one possible approach for dropping all columns that have NULL values: See [here](https://stackoverflow.com/questions/44627386/how-to-find-count-of-null-and-nan-values-for-each-column-in-a-pyspark-dataframe) for the source on the code of counting NULL values per column.
```
import pyspark.sql.functions as F
# Sample data
df = pd.DataFrame({'x1': ['a', '1', '2'],
'x2': ['b', None, '2'],
'x3': ['c', '0', '3'] })
df = sqlContext.createDataFrame(df)
df.show()
def drop_null_columns(df):
"""
This function drops all columns which contain null values.
:param df: A PySpark DataFrame
"""
null_counts = df.select([F.count(F.when(F.col(c).isNull(), c)).alias(c) for c in df.columns]).collect()[0].asDict()
to_drop = [k for k, v in null_counts.items() if v > 0]
df = df.drop(*to_drop)
return df
# Drops column b2, because it contains null values
drop_null_columns(df).show()
```
Before:
```
+---+----+---+
| x1| x2| x3|
+---+----+---+
| a| b| c|
| 1|null| 0|
| 2| 2| 3|
+---+----+---+
```
After:
```
+---+---+
| x1| x3|
+---+---+
| a| c|
| 1| 0|
| 2| 3|
+---+---+
```
Hope this helps!
|
If we need to keep only the rows having at least one inspected column not null then use this. Execution time is very less.
```
from operator import or_
from functools import reduce
inspected = df.columns
df = df.where(reduce(or_, (F.col(c).isNotNull() for c in inspected ), F.lit(False)))```
```
|
48,661,858 |
I am working with asp .net. I want to send an authentication code to user's email when he sign up. I'm using this code to send email. I'm adding a html file to send. How can I add the authentication code to this HTML file?
This is the code which I used to send the html file via Email. So how can I add a `string(authenticationCode)` to HTML file to send it to the user for authentication.
```
var fromAddress = new MailAddress("[email protected]", "From Hamza");
var toAddress = new MailAddress("[email protected]", "To Usama");
const string fromPassword = "****";
const string subject = "email";
const string body = "hello world";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.BodyEncoding = Encoding.UTF8;
String plainBody = "Title";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
message.AlternateViews.Add(plainView);
MailDefinition msg = new MailDefinition();
msg.BodyFileName = "~/newsletter.html";
msg.IsBodyHtml = true;
msg.From = "[email protected]";
msg.Subject = "Subject";
ListDictionary replacements = new ListDictionary();
MailMessage msgHtml = msg.CreateMailMessage("[email protected]", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
logo.ContentId = "logo";
htmlView.LinkedResources.Add(logo);
LinkedResource cover = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/cover.jpg"), MediaTypeNames.Image.Jpeg);
cover.ContentId = "cover";
htmlView.LinkedResources.Add(cover);
message.AlternateViews.Add(htmlView);
smtp.Send(message);
```
|
2018/02/07
|
['https://Stackoverflow.com/questions/48661858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
How about this:
If your service is based off of the *microsoft/dotnet* Docker image, create a new dockerfile based on the same image, and install the debugger, ssh and unzip.
```
FROM microsoft/dotnet
RUN apt-get update && apt-get -y install openssh-server unzip
RUN mkdir /var/run/sshd && chmod 0755 /var/run/sshd
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin without-password/g' /etc/ssh/sshd_config
RUN sed -i 's/#StrictModes yes/StrictModes no/g' /etc/ssh/sshd_config
RUN service ssh restart
RUN mkdir /root/.vs-debugger && chmod 0755 /root/.vs-debugger
RUN curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v vs2017u1 -l /root/.vs-debugger/
EXPOSE 22
```
Build and push this to your registry.
```
docker build -t myregistry/dotnetdebugger .
docker push myregistry/dotnetdebugger
```
Next ensure that your service's build is outputting the [PDB](https://en.wikipedia.org/wiki/Program_database) files as portable PDB files -
*[Offroad Debugging of .NET Core on Linux and OS X from Visual Studio](https://github.com/Microsoft/MIEngine/wiki/Offroad-Debugging-of-.NET-Core-on-Linux---OSX-from-Visual-Studio)*
And ensure that the PDB files are included with the DLL files when you build your service's Docker image.
Then when your container is running and you decide that you need to debug it, you can attach the debugger container as a side car container to the service:
```
docker run -d -p 10222:22 --pid container:<container name> - myregistry/dotnetdebugger
```
Then in Visual Studio, go to menu *Tools* → *Options* → *Crossplatform* → *Connection Manager* - and add a new connection. Specify the IP address or hostname of the container, 10222 as the port (the one in the `docker run` command), and root as the user with no password.
|
As of May 2018, if you are using Visual Studio, you can use their [official support](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/docker/visual-studio-tools-for-docker?view=aspnetcore-2.1).
You just need to have installed Docker and add the support for Docker projects menu *Project* → *Docker support*.
This creates a new project with a Docker compose and a *dockerfile* to your project, and then Visual Studio links this and allows debugging!
|
111,196 |
I am designing a form for a tablet. Typically forms are filled out vertically, but in landscape some fields could be represented on one line to save scrolling. For example: height and weight, or first and last name.
My questions are:
* Would too many groupings be confusing to users (e.g. gender and birthdate)?
* How should the multi-field design respond to both portrait and landscape layouts?
|
2017/08/23
|
['https://ux.stackexchange.com/questions/111196', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/97187/']
|
Putting input fields next to each other makes them hard to scan for users.
Since users like to scan instead of reading putting them below each other makes it far better in terms of usability.
There are many articles and studies regarding that, for example you could read: <https://uxplanet.org/designing-more-efficient-forms-structure-inputs-labels-and-actions-e3a47007114f>
Its a pretty decent summary of do's and dont's.
|
I think the main scenario where multiple fields on the same line would be where there is a very strong relationship between them. Eg blood pressure.
Blood pressure is measured as 2 values that go together Systolic/Diastolic, and both values are small numbers eg 120/80. I could see this being displayed on a single line grouped together... but only because they are so tightly related and it would be odd to split them apart.
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
I'll try to hint on the answer. This is *not* an answer, only an introductory illustration. @jk's answer points to the real thing, zippers.
Imagine you have an immutable tree structure. You want to alter one node by inserting a child. As a result, you get a whole new tree.
But most of the new tree is exactly the same as old tree. [A clever implementation](http://en.wikipedia.org/wiki/Persistent_data_structure#Trees) would reuse most of the tree fragments, routing pointers around the altered node:

[Okasaki's book](http://rads.stackoverflow.com/amzn/click/0521663504) is full of examples like this.
So I suppose you could reasonably alter small parts of your game world each move (pick up a coin), and only actually change small parts of your world data structure (the cell where the coin was picked up). Parts that only belong to past states will be garbage-collected in time.
This probably takes some consideration in designing the data game world structure in an appropriate way. Unfortunately, I'm no expert in these matters. Definitely it must be something else than a NxM matrix one would use as a mutable data structure. Probably it should consist of smaller pieces (corridors? individual cells?) that point to each other, as tree nodes do.
|
[9000's answer](https://softwareengineering.stackexchange.com/a/195730/31260) is half the answer, persistent data structures allow you to reuse unchanged parts.
You may already be thinking however "hey what if I want to change the root of the tree?" as it stands with the example given that now means changing all the nodes. This is where [Zippers](http://en.wikipedia.org/wiki/Zipper_%28data_structure%29) come to the rescue. They allow element at a focus to be changed in O(1), and the focus can be moved anywhere in the structure.
The other point with zippers is that a [Zipper exists for pretty much any data type you want](http://en.wikibooks.org/wiki/Haskell/Zippers#Differentiation_of_data_types)
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
I'll try to hint on the answer. This is *not* an answer, only an introductory illustration. @jk's answer points to the real thing, zippers.
Imagine you have an immutable tree structure. You want to alter one node by inserting a child. As a result, you get a whole new tree.
But most of the new tree is exactly the same as old tree. [A clever implementation](http://en.wikipedia.org/wiki/Persistent_data_structure#Trees) would reuse most of the tree fragments, routing pointers around the altered node:

[Okasaki's book](http://rads.stackoverflow.com/amzn/click/0521663504) is full of examples like this.
So I suppose you could reasonably alter small parts of your game world each move (pick up a coin), and only actually change small parts of your world data structure (the cell where the coin was picked up). Parts that only belong to past states will be garbage-collected in time.
This probably takes some consideration in designing the data game world structure in an appropriate way. Unfortunately, I'm no expert in these matters. Definitely it must be something else than a NxM matrix one would use as a mutable data structure. Probably it should consist of smaller pieces (corridors? individual cells?) that point to each other, as tree nodes do.
|
Functional style programs create lots of opportunities like that to use concurrency. Anytime you transform or filter or aggregate a collection, and everything is pure or immutable, there's an opportunity for the operation to be sped up by concurrency.
For example, suppose you perform AI decisions independently of each other and in no particular order. They don't take turns, they all make a decision simultaneously and then the world advances. The code might look like this:
```
func MakeMonsterDecision curWorldState monster =
...
...
return monsterDecision
func NextWorldState curWorldState =
...
let monsterMakeDecisionForCurrentState = MakeMonsterDecision curWorldState
let monsterDecisions = List.map monsterMakeDecisionForCurrentState activeMonsters
...
return newWorldState
```
You have a function to compute what a monster will do given a world state, and apply it to every monster as part of computing the next world state. This is a natural thing to do in a functional language, and the compiler is free to perform the 'apply it to every monster' step in parallel.
In an imperative language you'd be more likely to iterate over every monster, applying their effects to the world. It's just easier to do it that way, because you don't want to deal with cloning or complicated aliasing. The compiler *can't* perform the monster computations in parallel in that case, because early monster decisions affect later monster decisions.
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
I'll try to hint on the answer. This is *not* an answer, only an introductory illustration. @jk's answer points to the real thing, zippers.
Imagine you have an immutable tree structure. You want to alter one node by inserting a child. As a result, you get a whole new tree.
But most of the new tree is exactly the same as old tree. [A clever implementation](http://en.wikipedia.org/wiki/Persistent_data_structure#Trees) would reuse most of the tree fragments, routing pointers around the altered node:

[Okasaki's book](http://rads.stackoverflow.com/amzn/click/0521663504) is full of examples like this.
So I suppose you could reasonably alter small parts of your game world each move (pick up a coin), and only actually change small parts of your world data structure (the cell where the coin was picked up). Parts that only belong to past states will be garbage-collected in time.
This probably takes some consideration in designing the data game world structure in an appropriate way. Unfortunately, I'm no expert in these matters. Definitely it must be something else than a NxM matrix one would use as a mutable data structure. Probably it should consist of smaller pieces (corridors? individual cells?) that point to each other, as tree nodes do.
|
>
> FP proponents have claimed that concurrency is easy because their
> paradigm avoids mutable state. I don't get it.
>
>
>
I wanted to pitch in about this general question as someone who is a functional neophyte but has been up to my eyeballs in side effects over the years and would like to mitigate them, for all kinds of reasons, including easier (or specifically "safer, less error-prone") concurrency. When I glance over at my functional peers and what they're doing, the grass seems a bit greener and smells nicer, at least in this regard.
**Serial Algorithms**
That said, about your specific example, if your problem is serial in nature and B cannot be executed until A is finished, conceptually you can't run A and B in parallel no matter what. You have to find a way to break the order dependency like in your answer based on making parallel moves using old game state, or use a data structure which allows parts of it to be independently modified to eliminate the order dependency as proposed in the other answers, or something of this sort. But there are definitely a share of conceptual design problems like this where you can't necessarily just multithread everything so easily because things are immutable. Some things are just going to be serial in nature until you find some smart way to break the order dependency, if that's even possible.
**Easier Concurrency**
That said, there are many cases where we fail to parallelize programs that involve side effects in places that could potentially significantly improve performance simply because of the possibility that it *might* not be thread-safe. One of the cases where eliminating the mutable state (or more specifically, external side effects) helps a lot as I see it is that it turns *"may or may not be thread-safe"* into *"definitely thread-safe"*.
To make that statement a bit more concrete, consider that I give you a task to implement a sorting function in C which accepts a comparator and uses that to sort an array of elements. It's meant to be quite generalized but I'll give you an easy assumption that it will be used against inputs of such a scale (millions of elements or more) that it will doubtlessly be beneficial to always use a multithreaded implementation. Can you multithread your sorting function?
The problem is that you cannot because the comparators your sorting function calls *may* cause side effects unless you know how they are implemented (or at the very least documented) for all possible cases which is kind of impossible without degeneralizing the function. A comparator could do something disgusting like modify a global variable inside in a non-atomic way. 99.9999% of comparators may not do this, but we still can't multithread this generalized function simply because of the 0.00001% of cases that might cause side effects. As a result you might have to offer both a single-threaded and multithreaded sort function and pass the responsibility to the programmers using it to decide which one to use based on thread safety. And people might still use the single-threaded version and miss opportunities to multithread because they might also be unsure whether the comparator is thread-safe, or whether it will always remain as such in the future.
There's a whole lot of brainpower that can be involved in just rationalizing about the thread safety of things without throwing locks everywhere which can go away if we just had hard guarantees that functions won't cause side effects for now and the future. And there's fear: practical fear, because anyone who has had to debug a race condition a few too many times would probably be hesitant about multithreading anything that they can't be 110% sure is thread-safe and will remain as such. Even for the most paranoid (of which I am probably at least borderline), the pure function provides that sense of relief and confidence that we can safely call it in parallel.
And that's one of the main cases where I see it as so beneficial if you can get a hard guarantee that such functions are thread-safe which you get with pure functional languages. The other is that functional languages often promote creating functions free of side effects in the first place. For example, they might provide you with persistent data structures where it's reasonably quite efficient to input a massive data structure and then output a brand new one with only a small part of it changed from the original without touching the original. Those working without such data structures might want to modify them directly and lose some thread safety along the way.
**Side Effects**
That said, I disagree with one part with all due respect to my functional friends (who I think are super cool):
>
> [...] because their paradigm avoids mutable state.
>
>
>
It's not necessarily immutability that makes concurrency so practical as I see it. It's functions that avoid causing side effects. If a function inputs an array to sort, copies it, and then mutates the copy to sort its contents and outputs the copy, it's still just as thread-safe as one working with some immutable array type even if you're passing the same input array to it from multiple threads. So I think there's still a place for mutable types in creating very concurrency-friendly code, so to speak, though there are a lot of additional benefits to immutable types, including persistent data structures which I use not so much for their immutable properties but to eliminate the expense of having to deep copy everything in order to create functions free of side effects.
And there's often overhead to making functions free of side effects in the form of shuffling and copying some additional data, maybe an extra level of indirection, and possibly some GC on parts of a persistent data structure, but I look at one my buddies who has a 32-core machine and I'm thinking the exchange is probably worth it if we can more confidently do more things in parallel.
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
Listening to a few Rich Hickey talks -- [this one](http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey) in particular -- alleviated my confusion. In one he indicated that it is okay that concurrent processes may not have the most current state. I needed to hear that. What I was having trouble digesting was that programs would actually be okay with basing decisions on snapshots of the world that have since been superseded by newer ones. I kept wondering how concurrent FP got around the issue of basing decisions on old state.
In a banking application we would never want to base a decision on a snapshot of state that has since been superseded by a newer one (a withdrawal occurred).
That concurrency is easy because the FP paradigm avoids mutable state is a technical claim that doesn't attempt to say anything about the logical merits of basing decisions on potentially old state. FP still ultimately models state change. There's no getting around this.
|
[9000's answer](https://softwareengineering.stackexchange.com/a/195730/31260) is half the answer, persistent data structures allow you to reuse unchanged parts.
You may already be thinking however "hey what if I want to change the root of the tree?" as it stands with the example given that now means changing all the nodes. This is where [Zippers](http://en.wikipedia.org/wiki/Zipper_%28data_structure%29) come to the rescue. They allow element at a focus to be changed in O(1), and the focus can be moved anywhere in the structure.
The other point with zippers is that a [Zipper exists for pretty much any data type you want](http://en.wikibooks.org/wiki/Haskell/Zippers#Differentiation_of_data_types)
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
[9000's answer](https://softwareengineering.stackexchange.com/a/195730/31260) is half the answer, persistent data structures allow you to reuse unchanged parts.
You may already be thinking however "hey what if I want to change the root of the tree?" as it stands with the example given that now means changing all the nodes. This is where [Zippers](http://en.wikipedia.org/wiki/Zipper_%28data_structure%29) come to the rescue. They allow element at a focus to be changed in O(1), and the focus can be moved anywhere in the structure.
The other point with zippers is that a [Zipper exists for pretty much any data type you want](http://en.wikibooks.org/wiki/Haskell/Zippers#Differentiation_of_data_types)
|
>
> FP proponents have claimed that concurrency is easy because their
> paradigm avoids mutable state. I don't get it.
>
>
>
I wanted to pitch in about this general question as someone who is a functional neophyte but has been up to my eyeballs in side effects over the years and would like to mitigate them, for all kinds of reasons, including easier (or specifically "safer, less error-prone") concurrency. When I glance over at my functional peers and what they're doing, the grass seems a bit greener and smells nicer, at least in this regard.
**Serial Algorithms**
That said, about your specific example, if your problem is serial in nature and B cannot be executed until A is finished, conceptually you can't run A and B in parallel no matter what. You have to find a way to break the order dependency like in your answer based on making parallel moves using old game state, or use a data structure which allows parts of it to be independently modified to eliminate the order dependency as proposed in the other answers, or something of this sort. But there are definitely a share of conceptual design problems like this where you can't necessarily just multithread everything so easily because things are immutable. Some things are just going to be serial in nature until you find some smart way to break the order dependency, if that's even possible.
**Easier Concurrency**
That said, there are many cases where we fail to parallelize programs that involve side effects in places that could potentially significantly improve performance simply because of the possibility that it *might* not be thread-safe. One of the cases where eliminating the mutable state (or more specifically, external side effects) helps a lot as I see it is that it turns *"may or may not be thread-safe"* into *"definitely thread-safe"*.
To make that statement a bit more concrete, consider that I give you a task to implement a sorting function in C which accepts a comparator and uses that to sort an array of elements. It's meant to be quite generalized but I'll give you an easy assumption that it will be used against inputs of such a scale (millions of elements or more) that it will doubtlessly be beneficial to always use a multithreaded implementation. Can you multithread your sorting function?
The problem is that you cannot because the comparators your sorting function calls *may* cause side effects unless you know how they are implemented (or at the very least documented) for all possible cases which is kind of impossible without degeneralizing the function. A comparator could do something disgusting like modify a global variable inside in a non-atomic way. 99.9999% of comparators may not do this, but we still can't multithread this generalized function simply because of the 0.00001% of cases that might cause side effects. As a result you might have to offer both a single-threaded and multithreaded sort function and pass the responsibility to the programmers using it to decide which one to use based on thread safety. And people might still use the single-threaded version and miss opportunities to multithread because they might also be unsure whether the comparator is thread-safe, or whether it will always remain as such in the future.
There's a whole lot of brainpower that can be involved in just rationalizing about the thread safety of things without throwing locks everywhere which can go away if we just had hard guarantees that functions won't cause side effects for now and the future. And there's fear: practical fear, because anyone who has had to debug a race condition a few too many times would probably be hesitant about multithreading anything that they can't be 110% sure is thread-safe and will remain as such. Even for the most paranoid (of which I am probably at least borderline), the pure function provides that sense of relief and confidence that we can safely call it in parallel.
And that's one of the main cases where I see it as so beneficial if you can get a hard guarantee that such functions are thread-safe which you get with pure functional languages. The other is that functional languages often promote creating functions free of side effects in the first place. For example, they might provide you with persistent data structures where it's reasonably quite efficient to input a massive data structure and then output a brand new one with only a small part of it changed from the original without touching the original. Those working without such data structures might want to modify them directly and lose some thread safety along the way.
**Side Effects**
That said, I disagree with one part with all due respect to my functional friends (who I think are super cool):
>
> [...] because their paradigm avoids mutable state.
>
>
>
It's not necessarily immutability that makes concurrency so practical as I see it. It's functions that avoid causing side effects. If a function inputs an array to sort, copies it, and then mutates the copy to sort its contents and outputs the copy, it's still just as thread-safe as one working with some immutable array type even if you're passing the same input array to it from multiple threads. So I think there's still a place for mutable types in creating very concurrency-friendly code, so to speak, though there are a lot of additional benefits to immutable types, including persistent data structures which I use not so much for their immutable properties but to eliminate the expense of having to deep copy everything in order to create functions free of side effects.
And there's often overhead to making functions free of side effects in the form of shuffling and copying some additional data, maybe an extra level of indirection, and possibly some GC on parts of a persistent data structure, but I look at one my buddies who has a 32-core machine and I'm thinking the exchange is probably worth it if we can more confidently do more things in parallel.
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
Listening to a few Rich Hickey talks -- [this one](http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey) in particular -- alleviated my confusion. In one he indicated that it is okay that concurrent processes may not have the most current state. I needed to hear that. What I was having trouble digesting was that programs would actually be okay with basing decisions on snapshots of the world that have since been superseded by newer ones. I kept wondering how concurrent FP got around the issue of basing decisions on old state.
In a banking application we would never want to base a decision on a snapshot of state that has since been superseded by a newer one (a withdrawal occurred).
That concurrency is easy because the FP paradigm avoids mutable state is a technical claim that doesn't attempt to say anything about the logical merits of basing decisions on potentially old state. FP still ultimately models state change. There's no getting around this.
|
Functional style programs create lots of opportunities like that to use concurrency. Anytime you transform or filter or aggregate a collection, and everything is pure or immutable, there's an opportunity for the operation to be sped up by concurrency.
For example, suppose you perform AI decisions independently of each other and in no particular order. They don't take turns, they all make a decision simultaneously and then the world advances. The code might look like this:
```
func MakeMonsterDecision curWorldState monster =
...
...
return monsterDecision
func NextWorldState curWorldState =
...
let monsterMakeDecisionForCurrentState = MakeMonsterDecision curWorldState
let monsterDecisions = List.map monsterMakeDecisionForCurrentState activeMonsters
...
return newWorldState
```
You have a function to compute what a monster will do given a world state, and apply it to every monster as part of computing the next world state. This is a natural thing to do in a functional language, and the compiler is free to perform the 'apply it to every monster' step in parallel.
In an imperative language you'd be more likely to iterate over every monster, applying their effects to the world. It's just easier to do it that way, because you don't want to deal with cloning or complicated aliasing. The compiler *can't* perform the monster computations in parallel in that case, because early monster decisions affect later monster decisions.
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
Functional style programs create lots of opportunities like that to use concurrency. Anytime you transform or filter or aggregate a collection, and everything is pure or immutable, there's an opportunity for the operation to be sped up by concurrency.
For example, suppose you perform AI decisions independently of each other and in no particular order. They don't take turns, they all make a decision simultaneously and then the world advances. The code might look like this:
```
func MakeMonsterDecision curWorldState monster =
...
...
return monsterDecision
func NextWorldState curWorldState =
...
let monsterMakeDecisionForCurrentState = MakeMonsterDecision curWorldState
let monsterDecisions = List.map monsterMakeDecisionForCurrentState activeMonsters
...
return newWorldState
```
You have a function to compute what a monster will do given a world state, and apply it to every monster as part of computing the next world state. This is a natural thing to do in a functional language, and the compiler is free to perform the 'apply it to every monster' step in parallel.
In an imperative language you'd be more likely to iterate over every monster, applying their effects to the world. It's just easier to do it that way, because you don't want to deal with cloning or complicated aliasing. The compiler *can't* perform the monster computations in parallel in that case, because early monster decisions affect later monster decisions.
|
>
> FP proponents have claimed that concurrency is easy because their
> paradigm avoids mutable state. I don't get it.
>
>
>
I wanted to pitch in about this general question as someone who is a functional neophyte but has been up to my eyeballs in side effects over the years and would like to mitigate them, for all kinds of reasons, including easier (or specifically "safer, less error-prone") concurrency. When I glance over at my functional peers and what they're doing, the grass seems a bit greener and smells nicer, at least in this regard.
**Serial Algorithms**
That said, about your specific example, if your problem is serial in nature and B cannot be executed until A is finished, conceptually you can't run A and B in parallel no matter what. You have to find a way to break the order dependency like in your answer based on making parallel moves using old game state, or use a data structure which allows parts of it to be independently modified to eliminate the order dependency as proposed in the other answers, or something of this sort. But there are definitely a share of conceptual design problems like this where you can't necessarily just multithread everything so easily because things are immutable. Some things are just going to be serial in nature until you find some smart way to break the order dependency, if that's even possible.
**Easier Concurrency**
That said, there are many cases where we fail to parallelize programs that involve side effects in places that could potentially significantly improve performance simply because of the possibility that it *might* not be thread-safe. One of the cases where eliminating the mutable state (or more specifically, external side effects) helps a lot as I see it is that it turns *"may or may not be thread-safe"* into *"definitely thread-safe"*.
To make that statement a bit more concrete, consider that I give you a task to implement a sorting function in C which accepts a comparator and uses that to sort an array of elements. It's meant to be quite generalized but I'll give you an easy assumption that it will be used against inputs of such a scale (millions of elements or more) that it will doubtlessly be beneficial to always use a multithreaded implementation. Can you multithread your sorting function?
The problem is that you cannot because the comparators your sorting function calls *may* cause side effects unless you know how they are implemented (or at the very least documented) for all possible cases which is kind of impossible without degeneralizing the function. A comparator could do something disgusting like modify a global variable inside in a non-atomic way. 99.9999% of comparators may not do this, but we still can't multithread this generalized function simply because of the 0.00001% of cases that might cause side effects. As a result you might have to offer both a single-threaded and multithreaded sort function and pass the responsibility to the programmers using it to decide which one to use based on thread safety. And people might still use the single-threaded version and miss opportunities to multithread because they might also be unsure whether the comparator is thread-safe, or whether it will always remain as such in the future.
There's a whole lot of brainpower that can be involved in just rationalizing about the thread safety of things without throwing locks everywhere which can go away if we just had hard guarantees that functions won't cause side effects for now and the future. And there's fear: practical fear, because anyone who has had to debug a race condition a few too many times would probably be hesitant about multithreading anything that they can't be 110% sure is thread-safe and will remain as such. Even for the most paranoid (of which I am probably at least borderline), the pure function provides that sense of relief and confidence that we can safely call it in parallel.
And that's one of the main cases where I see it as so beneficial if you can get a hard guarantee that such functions are thread-safe which you get with pure functional languages. The other is that functional languages often promote creating functions free of side effects in the first place. For example, they might provide you with persistent data structures where it's reasonably quite efficient to input a massive data structure and then output a brand new one with only a small part of it changed from the original without touching the original. Those working without such data structures might want to modify them directly and lose some thread safety along the way.
**Side Effects**
That said, I disagree with one part with all due respect to my functional friends (who I think are super cool):
>
> [...] because their paradigm avoids mutable state.
>
>
>
It's not necessarily immutability that makes concurrency so practical as I see it. It's functions that avoid causing side effects. If a function inputs an array to sort, copies it, and then mutates the copy to sort its contents and outputs the copy, it's still just as thread-safe as one working with some immutable array type even if you're passing the same input array to it from multiple threads. So I think there's still a place for mutable types in creating very concurrency-friendly code, so to speak, though there are a lot of additional benefits to immutable types, including persistent data structures which I use not so much for their immutable properties but to eliminate the expense of having to deep copy everything in order to create functions free of side effects.
And there's often overhead to making functions free of side effects in the form of shuffling and copying some additional data, maybe an extra level of indirection, and possibly some GC on parts of a persistent data structure, but I look at one my buddies who has a 32-core machine and I'm thinking the exchange is probably worth it if we can more confidently do more things in parallel.
|
195,718 |
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.
Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.
To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.
Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).
I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.
Can someone better represent this claim?
|
2013/04/22
|
['https://softwareengineering.stackexchange.com/questions/195718', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88091/']
|
Listening to a few Rich Hickey talks -- [this one](http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey) in particular -- alleviated my confusion. In one he indicated that it is okay that concurrent processes may not have the most current state. I needed to hear that. What I was having trouble digesting was that programs would actually be okay with basing decisions on snapshots of the world that have since been superseded by newer ones. I kept wondering how concurrent FP got around the issue of basing decisions on old state.
In a banking application we would never want to base a decision on a snapshot of state that has since been superseded by a newer one (a withdrawal occurred).
That concurrency is easy because the FP paradigm avoids mutable state is a technical claim that doesn't attempt to say anything about the logical merits of basing decisions on potentially old state. FP still ultimately models state change. There's no getting around this.
|
>
> FP proponents have claimed that concurrency is easy because their
> paradigm avoids mutable state. I don't get it.
>
>
>
I wanted to pitch in about this general question as someone who is a functional neophyte but has been up to my eyeballs in side effects over the years and would like to mitigate them, for all kinds of reasons, including easier (or specifically "safer, less error-prone") concurrency. When I glance over at my functional peers and what they're doing, the grass seems a bit greener and smells nicer, at least in this regard.
**Serial Algorithms**
That said, about your specific example, if your problem is serial in nature and B cannot be executed until A is finished, conceptually you can't run A and B in parallel no matter what. You have to find a way to break the order dependency like in your answer based on making parallel moves using old game state, or use a data structure which allows parts of it to be independently modified to eliminate the order dependency as proposed in the other answers, or something of this sort. But there are definitely a share of conceptual design problems like this where you can't necessarily just multithread everything so easily because things are immutable. Some things are just going to be serial in nature until you find some smart way to break the order dependency, if that's even possible.
**Easier Concurrency**
That said, there are many cases where we fail to parallelize programs that involve side effects in places that could potentially significantly improve performance simply because of the possibility that it *might* not be thread-safe. One of the cases where eliminating the mutable state (or more specifically, external side effects) helps a lot as I see it is that it turns *"may or may not be thread-safe"* into *"definitely thread-safe"*.
To make that statement a bit more concrete, consider that I give you a task to implement a sorting function in C which accepts a comparator and uses that to sort an array of elements. It's meant to be quite generalized but I'll give you an easy assumption that it will be used against inputs of such a scale (millions of elements or more) that it will doubtlessly be beneficial to always use a multithreaded implementation. Can you multithread your sorting function?
The problem is that you cannot because the comparators your sorting function calls *may* cause side effects unless you know how they are implemented (or at the very least documented) for all possible cases which is kind of impossible without degeneralizing the function. A comparator could do something disgusting like modify a global variable inside in a non-atomic way. 99.9999% of comparators may not do this, but we still can't multithread this generalized function simply because of the 0.00001% of cases that might cause side effects. As a result you might have to offer both a single-threaded and multithreaded sort function and pass the responsibility to the programmers using it to decide which one to use based on thread safety. And people might still use the single-threaded version and miss opportunities to multithread because they might also be unsure whether the comparator is thread-safe, or whether it will always remain as such in the future.
There's a whole lot of brainpower that can be involved in just rationalizing about the thread safety of things without throwing locks everywhere which can go away if we just had hard guarantees that functions won't cause side effects for now and the future. And there's fear: practical fear, because anyone who has had to debug a race condition a few too many times would probably be hesitant about multithreading anything that they can't be 110% sure is thread-safe and will remain as such. Even for the most paranoid (of which I am probably at least borderline), the pure function provides that sense of relief and confidence that we can safely call it in parallel.
And that's one of the main cases where I see it as so beneficial if you can get a hard guarantee that such functions are thread-safe which you get with pure functional languages. The other is that functional languages often promote creating functions free of side effects in the first place. For example, they might provide you with persistent data structures where it's reasonably quite efficient to input a massive data structure and then output a brand new one with only a small part of it changed from the original without touching the original. Those working without such data structures might want to modify them directly and lose some thread safety along the way.
**Side Effects**
That said, I disagree with one part with all due respect to my functional friends (who I think are super cool):
>
> [...] because their paradigm avoids mutable state.
>
>
>
It's not necessarily immutability that makes concurrency so practical as I see it. It's functions that avoid causing side effects. If a function inputs an array to sort, copies it, and then mutates the copy to sort its contents and outputs the copy, it's still just as thread-safe as one working with some immutable array type even if you're passing the same input array to it from multiple threads. So I think there's still a place for mutable types in creating very concurrency-friendly code, so to speak, though there are a lot of additional benefits to immutable types, including persistent data structures which I use not so much for their immutable properties but to eliminate the expense of having to deep copy everything in order to create functions free of side effects.
And there's often overhead to making functions free of side effects in the form of shuffling and copying some additional data, maybe an extra level of indirection, and possibly some GC on parts of a persistent data structure, but I look at one my buddies who has a 32-core machine and I'm thinking the exchange is probably worth it if we can more confidently do more things in parallel.
|
2,442,017 |
I'm new to the Measure Theory. I was wondering can we always find a measure for a measurable space? It would be better to explain in details.
|
2017/09/23
|
['https://math.stackexchange.com/questions/2442017', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/439544/']
|
There's always the measure that maps every subset to $0$.
If you mean a probability measure then it also exists, pick $x\in X$ and define $f(A)=1$ if $x\in A$ and $0$ otherwise. This is called a Dirac measure.
|
A *measurable space* is just a pair $(X,\mathcal{M})$, where $X$ is a set and $\mathcal{M}\subseteq\mathscr{P}(X)$ is a $\sigma$-algebra on $X$. The purpose of this definition is just to identify a $\sigma$-algebra on $X$, which is the collection of all measurable subsets of $X$.
For any given set $X$, there are several ways in which we can define a measure $\mu:\mathscr{P}(X)\to[0,\infty]$. (See examples below.) For any such measure, the restriction $\mu|\_{\mathcal{M}}$ will turn the measurable space $(X,\mathcal{M})$ into the measure space $(X,\mathcal{M},\mu|\_{\mathcal{M}})$.
In fact, it's worth proving the following easy exercise.
>
> If $(X,\mathcal{M},\mu)$ is a measure space and $\mathcal{N}\subseteq \mathcal{M}$ is a $\sigma$-algebra, then $\mu|\_{\mathcal{N}}$ is a measure on the measurable space $(X,\mathcal{N})$.
>
>
>
Some important examples of measures $\mu:\mathscr{P}(X)\to[0,\infty]$:
1. The zero measure: $\mu(A)=0$ for every $A\subseteq X$.
2. The infinite measure: $\mu(A)=\infty$ for $A\ne\emptyset$ and $\mu(\emptyset)=0$.
3. The counting measure:
$$
\mu(A) = \begin{cases}
|A| & \text{if $A$ is finite}, \\
\infty & \text{otherwise}.
\end{cases}
$$
4. Point mass measure (or Dirac measure) of a fixed point $x\in X$:
$$\mu(A) = \begin{cases}
1 & \text{if $x\in A$}, \\
0 & \text{otherwise}.
\end{cases}$$
5. $\mu(A)=\infty$ if $A$ is infinite, and $\mu(A)=0$ otherwise.
|
2,442,017 |
I'm new to the Measure Theory. I was wondering can we always find a measure for a measurable space? It would be better to explain in details.
|
2017/09/23
|
['https://math.stackexchange.com/questions/2442017', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/439544/']
|
There's always the measure that maps every subset to $0$.
If you mean a probability measure then it also exists, pick $x\in X$ and define $f(A)=1$ if $x\in A$ and $0$ otherwise. This is called a Dirac measure.
|
To construct a probability measure on any measurable space $(\Omega,\tau)$, consider the Dirac measure P:
For any $A\in \tau$
$$P(A) = \begin{cases}
1 & \text{$A\ni x$}, \\
0 & \text{otherwise}.
\end{cases}$$
Choice $x\in \Omega$ such that: $\exists B\in \tau, B\ni x $. Then $(\Omega,\tau,P)$ is a probability space, P is a probability measure.
|
2,442,017 |
I'm new to the Measure Theory. I was wondering can we always find a measure for a measurable space? It would be better to explain in details.
|
2017/09/23
|
['https://math.stackexchange.com/questions/2442017', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/439544/']
|
A *measurable space* is just a pair $(X,\mathcal{M})$, where $X$ is a set and $\mathcal{M}\subseteq\mathscr{P}(X)$ is a $\sigma$-algebra on $X$. The purpose of this definition is just to identify a $\sigma$-algebra on $X$, which is the collection of all measurable subsets of $X$.
For any given set $X$, there are several ways in which we can define a measure $\mu:\mathscr{P}(X)\to[0,\infty]$. (See examples below.) For any such measure, the restriction $\mu|\_{\mathcal{M}}$ will turn the measurable space $(X,\mathcal{M})$ into the measure space $(X,\mathcal{M},\mu|\_{\mathcal{M}})$.
In fact, it's worth proving the following easy exercise.
>
> If $(X,\mathcal{M},\mu)$ is a measure space and $\mathcal{N}\subseteq \mathcal{M}$ is a $\sigma$-algebra, then $\mu|\_{\mathcal{N}}$ is a measure on the measurable space $(X,\mathcal{N})$.
>
>
>
Some important examples of measures $\mu:\mathscr{P}(X)\to[0,\infty]$:
1. The zero measure: $\mu(A)=0$ for every $A\subseteq X$.
2. The infinite measure: $\mu(A)=\infty$ for $A\ne\emptyset$ and $\mu(\emptyset)=0$.
3. The counting measure:
$$
\mu(A) = \begin{cases}
|A| & \text{if $A$ is finite}, \\
\infty & \text{otherwise}.
\end{cases}
$$
4. Point mass measure (or Dirac measure) of a fixed point $x\in X$:
$$\mu(A) = \begin{cases}
1 & \text{if $x\in A$}, \\
0 & \text{otherwise}.
\end{cases}$$
5. $\mu(A)=\infty$ if $A$ is infinite, and $\mu(A)=0$ otherwise.
|
To construct a probability measure on any measurable space $(\Omega,\tau)$, consider the Dirac measure P:
For any $A\in \tau$
$$P(A) = \begin{cases}
1 & \text{$A\ni x$}, \\
0 & \text{otherwise}.
\end{cases}$$
Choice $x\in \Omega$ such that: $\exists B\in \tau, B\ni x $. Then $(\Omega,\tau,P)$ is a probability space, P is a probability measure.
|
36,372,912 |
I want to convert my date in to **MM/dd/yyyy** format.i use following code for converting date
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM/dd/yyyy", englishCulture);
```
but the result is comes like this **04-02-2016**
i want to having result in **04/02/2016** in string variable.
|
2016/04/02
|
['https://Stackoverflow.com/questions/36372912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4776191/']
|
Try using single quotes around the [delimiters](https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx#dateSeparator)
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM'/'dd'/'yyyy", englishCulture);
```
Alternatively,
```
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-UK");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
dtfi.DateSeparator = "/";
string NewDateFormat = Convert.ToDateTime(MyDate,dtfi).ToString("MM/dd/yyyy", dtfi);
```
|
Use DateSeparator property of DateTimeFormatInfo. For more details: <https://msdn.microsoft.com/en-us/library/ms130987(v=vs.110).aspx>
```
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-UK");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
dtfi.DateSeparator = "/";
string NewDateFormat = Convert.ToDateTime(MyDate,dtfi).ToString("MM/dd/yyyy", dtfi);
```
|
36,372,912 |
I want to convert my date in to **MM/dd/yyyy** format.i use following code for converting date
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM/dd/yyyy", englishCulture);
```
but the result is comes like this **04-02-2016**
i want to having result in **04/02/2016** in string variable.
|
2016/04/02
|
['https://Stackoverflow.com/questions/36372912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4776191/']
|
try this..
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);
```
|
Try using single quotes around the [delimiters](https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx#dateSeparator)
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM'/'dd'/'yyyy", englishCulture);
```
Alternatively,
```
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-UK");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
dtfi.DateSeparator = "/";
string NewDateFormat = Convert.ToDateTime(MyDate,dtfi).ToString("MM/dd/yyyy", dtfi);
```
|
36,372,912 |
I want to convert my date in to **MM/dd/yyyy** format.i use following code for converting date
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM/dd/yyyy", englishCulture);
```
but the result is comes like this **04-02-2016**
i want to having result in **04/02/2016** in string variable.
|
2016/04/02
|
['https://Stackoverflow.com/questions/36372912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4776191/']
|
try this..
```
string NewDateFormat = Convert.ToDateTime(Mydate, englishCulture).ToString("MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);
```
|
Use DateSeparator property of DateTimeFormatInfo. For more details: <https://msdn.microsoft.com/en-us/library/ms130987(v=vs.110).aspx>
```
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-UK");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;
dtfi.DateSeparator = "/";
string NewDateFormat = Convert.ToDateTime(MyDate,dtfi).ToString("MM/dd/yyyy", dtfi);
```
|
35,144,056 |
I've problem to click event on Kendo bar chart (seriesClick). I got undefined. Previously, I've do like e.category and its works because of categoryAxis: not in array. But now my code categoryAxis:is in array to avoid overlapping label with bar chart. Actually how do I call if categoryAxis in array. Below is my script:
```
var series = [{
"name": "Total",
"colorField": "valueColor",
"gap": 0.5,
"data": [{value: aa, valueColor: "#ff0000"},{value: bb, valueColor: "#9966ff"},{value: cc, valueColor: "#66ff66"},{value: dd, valueColor: "#ffff00"},
{value: ee, valueColor: "#ff8080"},{value: ff, valueColor: "#ff9933"},{value: gg, valueColor: "#ccccb3"},{value: hh, valueColor: "#4dffff"}]
}];
$("#chart_div2").kendoChart({
title: {
text: "Emotion Result"
},
legend: {
visible: false
},
seriesDefaults: {
type: "bar",
height: 150
},
series: series,
valueAxis: {
line: {
visible: false
},
minorGridLines: {
visible: true
},
axisCrossingValue: [0, -Infinity]
},
categoryAxis: [{
labels:{
visible:false
}
},{
categories: ["Anger", "Calm(+) / Agitated(-)", "Fear", "Happy(+) / Sad(-)", "Like(+) / Dislike(-)", "Shame", "Sure(+) / Unsure(-)", "Surprise"],
majorGridLines: {
visible: false
}
}],
tooltip: {
visible: true,
template: "#= series.name #: #= value #"
},
seriesClick: function(e){
var emo=e.category;
alert("You Click : "+emo)
clickBar(emo);
}
});
```
Thank you for helping
|
2016/02/02
|
['https://Stackoverflow.com/questions/35144056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5676150/']
|
Clearly this relates to your [earlier question](https://stackoverflow.com/questions/35103336/maple-how-to-insert-a-command-to-force-my-code-to-choose-random-integer-values). So I'll try to address both here.
You may be get the idea that a "thorough" search grid does better at finding most (or sometimes all) roots, but that a random process can often be faster at finding a smaller subset. However as more and more roots are found by the random method then the chances grow are that each newly generated random starting point will converge to a root already found.
You mentioned Maple 15 in one of your questions, so I ran the code below in 64bit Maple 15.01 for Windows.
I wrapped your basic steps inside a proc, to make things easier to use and (hopefully) understand.
I did not change your iteration scheme (which may be homework), but notice that it requires an initial point. Note that X\_\_0 displays similarly to X[0] as pretty-printed 2D Math output, but they are not the same. This was a problem for your code on the Question, and also for the transcribed code on one of the examples in your other Question. I suggest you use 1D Maple Notation for your input mode if that is not entirely clear to you.
There's no need to use linalg[jacobian] which is deprecated. I adjusted to use VectorCalculus:-Jacobian.
```
restart;
f := (x-7)^4+(y-2)^2-100:
g := (x-11)^2+(y-5)^2-75:
G := unapply(convert(Vector([x,y])
-1/VectorCalculus:-Jacobian([f, g],[x, y]).Vector([f,g]),
list),x,y):
p := proc(X0::[complex(numeric),complex(numeric)], G)
local X, K;
X[0]:=X0;
for K to 30 while evalf[Digits+5](abs(X[K-1][1]-X[K-2][1])) <> 0
and evalf[Digits+5](abs(X[K-1][2]-X[K-2][2])) <> 0 do
X[K] := evalf[Digits+5](G(X[K-1][1], X[K-1][2]));
end do;
if not type(X[K-1],[complex(numeric),complex(numeric)]) then
error "nonnumeric results"; end if;
if K<29 then map(simplify@fnormal, evalf(X[K-1]));
else error "did not converge"; end if;
end proc:
p( [17, -2], G );
[9.879819419, -3.587502283]
p( [5, 11], G );
[5.127257522, 11.36481703]
p( [-1.0-11.*I, -2.0*I], G );
[7.144643342 - 2.930435630 I, -3.398413328 + 1.345239163 I]
Digits := 20:
p( [-1.0-11.*I, -2.0*I], G );
[7.1446433421702820770 - 2.9304356302329792484 I,
-3.3984133281207314618 + 1.3452391631560967251 I]
Equate([x,y],%);
[x = 7.1446433421702820770 - 2.9304356302329792484 I,
y = -3.3984133281207314618 + 1.3452391631560967251 I]
eval( [f,g], % );
[ -18 -18 -18 ]
[1 10 + 2 10 I, -1 10 + 0. I]
Digits := 10:
NN:=2: # This attempts (NN+1)^4 iterates
incx,incy:=5.0,5.0:
Sols:={}:
count:=0:
st := time():
for a from -NN to NN do
for b from -NN to NN do
for c from -NN to NN do
for d from -NN to NN do
count:=count+1;
try
cand := p( [a*incx+b*incy*I, c*incx+d*incy*I], G );
if not member(cand,{Sols}) then
Sols := Sols union {cand}; end if;
catch:
end try;
end do;
end do;
end do;
end do;
(time() - st)*'seconds', count*'attempts';
34.695 seconds, 625 attempts
nops( Sols );
8
sort( Sols );
{[3.867005122, 0.08874923598], [5.127257522, 11.36481703],
[5.721021477, 11.86530303], [9.879819419, -3.587502283],
[7.144643342 - 2.930435630 I, -3.398413328 + 1.345239163 I],
[7.144643342 + 2.930435630 I, -3.398413328 - 1.345239163 I],
[8.557804888 - 1.867139097 I, 13.53272982 - 0.5344031829 I],
[8.557804888 + 1.867139097 I, 13.53272982 + 0.5344031829 I]}
seq( eval( max(abs(f),abs(g)), Equate([x,y],xypoint) ), xypoint=Sols );
-8 -7 -8 -8 -8 -8
3 10 , 1 10 , 9 10 , 4 10 , 3.162277660 10 , 3.162277660 10 ,
-7 -7
1.019803903 10 , 1.019803903 10
randomize():
fgen := proc(a::numeric,b::numeric,i::nonnegint:=1)
seq(RandomTools:-Generate(float('range'=a..b,'digits'=5)),
ii=1..i);
end proc:
fgen(-100.0, 100.0); # Usage example, a random point
-26.41
randSols := {}:
A,B := 15, 15:
numattempts:=100:
st := time():
for s from 1 to numattempts do
try
cand := p( [fgen(-A,A)+fgen(-B,B)*I, fgen(-A,A)+fgen(-B,B)*I], G );
if not member(cand,{randSols}) then
randSols := randSols union {cand}; end if;
catch:
end try;
end do;
(time() - st)*'seconds', numattempts*'attempts';
5.756 seconds, 100 attempts
nops(randSols);
5
sort( randSols );
{[3.867005122, 0.08874923598],
[7.144643342 - 2.930435630 I, -3.398413328 + 1.345239163 I],
[7.144643342 + 2.930435630 I, -3.398413328 - 1.345239163 I],
[8.557804888 - 1.867139097 I, 13.53272982 - 0.5344031829 I],
[8.557804888 + 1.867139097 I, 13.53272982 + 0.5344031829 I]}
seq( eval( max(abs(f),abs(g)), Equate([x,y],xypoint) ), xypoint=randSols );
-8 -8 -8 -7 -7
3 10 , 3.162277660 10 , 3.162277660 10 , 1.019803903 10 , 1.019803903 10
```
|
For each 'do' statement (i.e. loop) you need a corresponding 'end do', you only have one. Also you need to terminate statements (e.g. X\_\_0:=[i+j*I,m+n*I]) with a colon or semicolon. E.g.,
```
for i from -100.0 to 100.0 do
for j from -100.0 to 100.0 do
for m from -100.0 to 100.0 do
for n from -100.0 to 100.0 do
X__0:=[i+j*I, m+n*I];
for K from 1 to 20 while evalf(abs(X[K-1][1]-X[K-2][1]),25)<>0 and evalf(abs(X[K-1][2]-X[K-2][2]),25) <>0 do
X[K]:=evalf(G(X[K-1][1], X[K-1][2]), 25);
end do;
end do;
end do;
end do;
end do;
```
end do;
Your code doesn't provide an initial definition of X[0] or define G, so it's hard otherwise to know what to suggest to improve things.
|
4,132,955 |
I have a `Logger` class which is implemented singleton. The class is simple and there are few methods and one `static` property, `Instance`. Like all singleton classes, I access the unique instance via `Logger.Instance` property.
I extracted an interface from `Logger` class (using Visual Studio refactor context menu). After extraction, interface contains signature for those few methods, and since the `Instance` property is `static`, it is not included in `ILogger` interface.
After all of this, I cannot cast a `Logger.Instance` into `ILogger` at run-time. What is wrong with my approach ?
|
2010/11/09
|
['https://Stackoverflow.com/questions/4132955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313421/']
|
Did you actually declare that `Logger` implements `ILogger`?
```
public sealed class Logger : ILogger
{
...
}
```
If so, it should be fine. Please post some code so we can try to diagnose the issue.
If not, that's the problem, and it's easily fixed :)
|
The example you described works fine for me. I made a small example, maybe you see some differences:
```
class Program
{
static void Main(string[] args)
{
ILogger logger = Logger.GetLogger();
logger.LogMessage("Hello");
}
}
public interface ILogger
{
void LogMessage(string message);
}
public class Logger : ILogger
{
private static Logger instance;
public static Logger GetLogger()
{
return instance ?? (instance = new Logger());
}
public void LogMessage(string message)
{
Console.WriteLine(message);
}
}
```
|
430,943 |
У того спортсмена был номер "4".
Спортсмен под номером "4" первым достиг цели.
Номер "4", подойдите, пожалуйста, к стойке регистрации.
|
2017/03/28
|
['https://rus.stackexchange.com/questions/430943', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/185870/']
|
В каких случаях нужны кавычки?
В современном русском языке кавычки выполняют следующие функции:
1. Выделение безабзацной прямой речи и цитат.
2. Выделение условных (собственных) наименований.
3. Выделение слов, которые употребляются в необычном, ироническом, особом значении.
([Грамота.ру](http://new.gramota.ru/spravka/letters/53-kav1)).
**Номер 4** из Вашего вопроса не относится ни к одному из перечисленных пунктов, поэтому кавычки не нужны.
|
Кавычки не нужны. Иначе все номера писались бы в кавычках. Чем отличается номер спортсмена от номера дома или квартиры?
|
54,812 |
On May 28, 1754, a young Lt. Colonel named George Washington [ambushed a French force at Jumonville Glen](https://en.wikipedia.org/wiki/Battle_of_Jumonville_Glen) with assistance from a Iroquois leader named Tanacharison. One of the casualties was the French expedition's leader, [Joseph Coulon de Villiers, Sieur de Jumonville](https://en.wikipedia.org/wiki/Joseph_Coulon_de_Jumonville).
When word reached Fort Duquesne about the incident, Jumonville's half brother, Captain Louis Coulon de Villiers, vowed revenge. He attacked Washington's troops garrisoned at [Fort Necessity](https://en.wikipedia.org/wiki/Battle_of_Fort_Necessity) and forced them to surrender on July 3, 1754. In the surrender document, written in French, Coulon de Villiers inserted a clause describing Jumonville's death as an "assassination".
Then a 22 year old Lt. Colonel, Washington could neither read nor speak French. He signed the surrender document without reading it. This was his first and only surrender during his entire life. It led many British army officers to question whether command should be given to young colonials.
This incident set into a motion a chain of events that quickly spiraled into the Seven Year's War; this conflagration involved 15 nations in combat on five continents. It was the first global war.
Why didn't George Washington simply agree to surrender Fort Necessity without signing the document? Why not offer to write up a surrender agreement in English, a language that both Washington and Captain Louis Coulon de Villiers both read? **Why would he sign such an important document if he could not read it?**
Please provide answers based on historical documents.
|
2019/09/30
|
['https://history.stackexchange.com/questions/54812', 'https://history.stackexchange.com', 'https://history.stackexchange.com/users/16866/']
|
**Short answer**
**George Washington relied on the translation of a mercenary he knew well and who had previously acted as his translator, [Jacob Van Braam](https://en.wikipedia.org/wiki/Jacob_Van_Braam), and did not think he was signing a document in which (the French later claimed) he admitted *assassinating* a French military officer. Further, the claim that the officer killed had been on a diplomatic mission, was not mentioned in the document he signed.**
Washington was actually more concerned with the part of the document which required that he and his men had to leave their arms behind and march though hostile territory; he requested that they be allowed to keep their guns to defend themselves against hostile Indians, and this request was granted. He then signed the document ([copy here in French and English](https://founders.archives.gov/?q=%20assassination%20Author%3A%22Washington%2C%20George%22&s=1111311111&sa=&r=1&sr=)) and surrendered.
---
**Details**
Concerning the mistranslation and Washington's belief that he was admitting to killing a French officer (i.e. not a diplomat):
>
> the French commander offered Washington written articles of
> capitulation. He read them aloud to Van Braam so there would be no
> question what the blurred, water-blotched handwriting said. The
> preamble stated that the French intended "only to avenge" the death of
> Jumonville. Van Braam could not translate the next word. In the
> guttering candlelight of Washington's makeshift command post, it
> looked as if it were Passailir. Witnesses later had trouble
> remembering whether Van Braam translated it as "death" or "loss" or
> "killing." What the French later contended they had written had only
> one possible meaning: assassination. If Washington signed his name to
> such an admission, he was taking full responsibility, on behalf of
> Virginia and the English, for the murder of a French diplomat.
> Washington later said that what came next was what made him willing to
> sign: *un de nos officiers*. That was easy, "one of our officers."
>
>
>
*Source: Willard Sterne Randall, '[George Washington: A Life](https://archive.org/details/georgewashington00rand)' (1997)*
Washington considered the document "honourable" except for one part:
>
> What concerned Washington more at the moment was that, after
> guaranteeing the Virginians' safe passage, the French wanted to
> "reserve" to themselves all his artillery "and munitions of war." This
> meant that Washington and his men would have to leave behind their
> guns and gunpowder and walk fifty miles through forests swarming with
> hostile Indians whom Villiers could only promise to restrain....he refused to sign. The French commander ended the impasse
> with a single stroke of his pen through the offending words.
>
>
>
*Source: Randall*
Ron Chernow, in *[Washington: A Life](https://books.google.com.ph/books/about/Washington.html?id=Wnc3V5m9kqgC&redir_esc=y)*, has a broadly similar account, but emphasizes Washington's unawareness of the word 'assassination' in the document.
>
> How could this profound misunderstanding have arisen? The night of the
> negotiation was dark and rainy, and when Van Braam brought back the
> terms of surrender, Washington and the other officers strained to read
> the blurry words in a dim light. “We could scarcely keep the
> candlelight to read them,” recalled one officer *[see note 1 below]*. “They were wrote in a
> bad hand, on wet and blotted paper, so that no person could read them
> but Van Braam, who had heard them from the mouth of the French
> officer.” Not expert in English, Van Braam might have used death or
> loss interchangeably with assassination, yet it’s hard to imagine that
> he botched the translation deliberately. What is clear is that
> Washington was adamant that he never consented to the loaded word
> assassination. “That we were willfully, or ignorantly, deceived by our
> interpreter in regard to the word assassination, I do aver and will to
> my dying moment,” Washington insisted.
>
>
>
On this last statement by Washington, [more can be found here](https://founders.archives.gov/documents/Washington/02-01-02-0076-0004). He disputes much of his adversary's version of events, but also makes a fairly wild claim as to how many French were killed. Washington also disputed claims by the prisoners captured from Joseph Coulon de Villiers, Sieur de Jumonville's force (claims later re-iterated by the French) that they had been on a diplomatic mission when de Jumonville was killed *[see note 2]*.
As to why Washington signed a document at all, the terms offered by the French essentially required that the conditions be put in writing; there were wider issues at stake which commanders of both sides would need to see. Further, Washington was not in a good position: the British were running low on supplies, they were outnumbered, their gunpowder was damp, the terrain favoured the French due to the poor location of the fort, and the fort itself was too small to provide shelter from the wet weather for all the soldiers. Under the circumstances, Washington negotiated the best he could *[see Note 3 below]*. The French commander Louis Coulon de Villiers' final offer was:
>
> If the English were now prepared to sign articles of capitulation, to
> withdraw from the Ohio Country and pledge not to return within the
> space of a year, to repatriate the prisoners they had taken, and to
> leave two officers as hostages at Fort Duquesne to guarantee the
> fulfillment of the surrender terms, he would allow them to march off
> the next day carrying their personal possessions, their arms, and
> their colors. But if the English did not agree to these terms, Coulon
> assured the Dutchman [Van Braam], he would destroy them.
>
>
>
*Source: Fred Anderson, 'Crucible of War: The Seven Years War and the Fate of Empire in British North America, 1754-1766*
Added to this, Washington was young and inexperienced, and he was relying on someone (Van Braam) who had previously served with his older half-brother. Van Braam had already acted successfully as an interpreter and Washington would have had no good reason not to trust him (Van Braam was [later cleared of charges of treason](https://www.mountvernon.org/library/digitalhistory/digital-encyclopedia/article/jacob-van-braam/) in mistranslating the French terms).
As *Evargalo* has noted in a comment, this incident should not be overestimated with regard to the [Seven Years War](https://en.wikipedia.org/wiki/Seven_Years%27_War); there were many causes and states involved, and territorial disputes were widespread.
---
**Notes**
Note 1: The officer mentioned is [Adam Stephen](https://en.wikipedia.org/wiki/Adam_Stephen), a Scottish doctor and military officer who was with Washington. This *National Archives* footnote for the page [II., 3 July 1754](https://founders.archives.gov/?q=%20assassination%20Author%3A%22Washington%2C%20George%22&s=1111311111&sa=&r=1&sr=) has more:
>
> In his discussion of the terms of capitulation Adam Stephen stated
> that when Van Braam “returned with the French Proposals, we were
> obliged to take the Sense of them by Word of Mouth: It rained so
> heavily that he could not give us a written Translation of them; we
> could scarcely keep the Candle light to read them; they were wrote in
> a bad Hand, on wet and blotted Paper, so that no Person could read
> them but Van Braam, who had heard them from the Mouth of the French
> Officer. Every Officer, then present, is willing to declare, that
> there was no such Word as Assassination mentioned; the Terms expressed
> to us, were ‘the Death of Jumonville.’ If it had been mentioned, we
> could have got it altered, as the French seemed very condescending,
> and willing to bring Things to a Conclusion, during the whole Course
> of the Interview” (Maryland Gazette [Annapolis], 29 Aug. 1754).
>
>
>
Note 2: The following is from Washington's *[Expedition to the Ohio, 1754: Narrative](https://founders.archives.gov/documents/Washington/01-01-02-0004-0002)*:
>
> They [the French prisoners] informed me that they had been sent with a Summons to order me to
> depart. A plausible Pretence to discover our Camp, and to obtain the
> Knowledge of our Forces and our Situation! It was so clear that they
> were come to reconnoitre what we were, that I admired at their
> Assurance, when they told me they were come as an Embassy; for their
> Instructions mentioned that they should get what Knowledge they could
> of the Roads, Rivers, and of all the Country as far as Potowmack: And
> instead of coming as an Embassador, publickly, and in an open Manner,
> they came secretly,...
>
>
>
Note 3: The National archives has [this footnote](https://founders.archives.gov/documents/Washington/02-01-02-0076-0002):
>
> As Adam Stephen pointed out, GW had little option but to surrender,
> and the fact that the French were willing to offer terms was “no
> disagreeable News to us, who had received no Intelligence of the
> Approach of our Convoys or Reinforcements, and who had only a Couple
> of Bags of Flour and a little Bacon left for the Support of 300 Men.”
> Most of the arms were out of order, and the powder was wet from
> exposure to the incessant rain. “But what was still worse, it was no
> sooner dark, than one half of our Men got drunk” (Maryland Gazette, 29
> Aug. 1754). The men had broken into the fort’s liquor supply.
> According to GW’s later testimony on the capitulation of the fort to
> the French, he “absolutely refused their first and second proposals
> and would consent to capitulate on no other terms than such as we
> obtained.”
>
>
>
|
>
> **Question:**
>
> Why did a young George Washington sign a document admitting to assassinating a French military officer?
>
>
>
Because he really had no choice. Fort Necessity was a hastily assembled wooden structure placed in the middle of a meadow. Unfortunately Necessity was built within rifle range of the nearby woods so the French could remain in relative safety and fire directly into Washington's outnumbered concentrated force. Washington was significantly outnumbered, 700 french and their native allies to his 160 Virginia militia men. As you say, Washington's inability to read the document which was presented to him outside in the rain probable played a significant role in Washington's decision.
>
> **Question**:
>
> On May 28, 1754, a young Lt. Colonel named George Washington ambushed a French force at Jumonville Glen with assistance from a Iroquois leader named Tanacharison.
>
>
>
I know you are quoting the wikipedia article here but that doesn't really accurately describe what happened. Washington's 50 odd troops marched all night to get to the French camp. The French didn't walk into an ambush, but were caught off guard after a larger French force had attacked and destroyed several British Fortresses. It wasn't like Washington didn't have provocation and authority to attack the French.
>
> [Jumonville Glen Skirmish](https://www.mountvernon.org/library/digitalhistory/digital-encyclopedia/article/jumonville-glen-skirmish/)
>
> On May 27th, reports came into Washington’s camp of a force of fifty French soldiers less than fifteen miles from his position. Washington met with Tanacharison, and the two of them decided to take a portion of their troops and meet the French. Throughout the night, the column of roughly fifty men traveled single file through the inky wilderness, with seven Virginians getting lost along the way. The next morning, they discovered the French in a sheltered glen hidden from the main trail. Tanacharison’s took his Mingos behind the French position, while Washington’s Virginias advanced towards the front of the glen. With Washington in the lead, the Virginians swiftly moved on the French position and the resulting engagement lasted only fifteen minutes before the French surrendered.6
>
>
>
Washington in March 1754 had been ordered back to the Ohio Valley (previously there delivering a rebuffed diplomatic message to the French to cease harassing British settlers and to Leave the Ohio Valley in Oct-Dec 1753) to link up with previously dispatched forces under **[Captain William Trent](https://en.wikipedia.org/wiki/William_Trent)** building fortresses at the fork of the Monongahela and Allegheny rivers. When Washington arrived the forces he was to rendezvous with had been attacked and run off by the French who had destroyed the British fortifications and were establishing their own fortress on same location, Fort Duquesne where modern day Pittsburgh sits.
>
> [William Trent](https://en.wikipedia.org/wiki/William_Trent)
>
> Trent and his men had not completed Fort Prince George when a large French military expedition of 600 soldiers, led by Sieur de Contrecoeur, surrounded the English colonists. They forced Trent to surrender and return with his men to Virginia. The French force included engineers. After demolishing Fort St. George, they began building the larger, more complex Fort Duquesne (at present-day Pittsburgh).
>
>
>
This was just prior to Washington Arriving with his force and just prior to Jumonville Glen Skirmish in question.
The reason why both the British and French desired this strategic area was all about the rivers. The French fortress at Duquesne sat at the junction of 3 rivers, Monongahela and Allegheny rivers converge into the Ohio River. The Ohio River converges into the Mississippi river. Whoever controls the rivers controls a highway connecting not just France's two major population centers, Quebec and New Orleans, but also runs across the fertile American mid west and south. Given the stakes both countries were gearing up for a fight and young Major Washington and his small force was sent into the middle of it.
>
> **Thoughts:**
>
>
>
In 1749, The British Crown granted the **[Ohio Company](https://en.wikipedia.org/wiki/Ohio_Company)**, 500,000 acres of land in Ohio. This Ohio company included George Washington's half brother Lawrence Washington along with future founding father George Mason, along with George Washington benefactor Lord Fairfax. What I think is especially interesting is how these important accomplished men had so very much at stake in Ohio, and yet they entrusted George Washington to lead the effort to safeguard their interests. George Washington was 21 years old in 1753 when he first traveled to the Ohio Valley to deliver his diplomatic warning to the French. He had a 3rd or 4th grade education. He spoke no french nor any native american dialects; and he had no military experience. I found that the most amazing thing about this story.
|
1,645,315 |
>
> For two sequences $a\_n$ and $b\_n$, “If $\{a\_n\}$ and $\{b\_n\}$ are increasing, then $\{a\_nb\_n\}$ is increasing.” Show this is false, make the hypothesis on $\{b\_n\}$ stronger, and prove the amended statement.
>
>
>
I was thinking to let both $a\_n$ and $b\_n$ be positive, but it only let me change the hypothesis on $b\_n$, how do I proceed?
|
2016/02/07
|
['https://math.stackexchange.com/questions/1645315', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/309006/']
|
Suppose that $\{a\_n\}$ is increasing, $\{b\_n\}$ is positive and increasing, and that $\{b\_n\}$ also has the following property:
>
> for all $n$, if $a\_{n+1}<0$ then $b\_{n+1}\le a\_nb\_n/a\_{n+1}$.
>
>
>
First check that the conditions on $\{b\_n\}$ are not inconsistent: if $a\_{n+1}<0$ then $a\_n\le a\_{n+1}<0$, so $a\_nb\_n/a\_{n+1}\ge b\_n$ and hence it is possible to choose $b\_{n+1}$ satisfying $b\_n\le b\_{n+1}\le a\_nb\_n/a\_{n+1}$.
Now if $a\_{n+1}<0$ then this condition clearly gives
$$a\_{n+1}b\_{n+1}\ge a\_nb\_n\ ;$$
if on the other hand $a\_{n+1}\ge0$ then
$$a\_{n+1}b\_{n+1}-a\_nb\_n=a\_{n+1}(b\_{n+1}-b\_n)+b\_n(a\_{n+1}-a\_n)\ge0\ .$$
|
It's possible that there may be an error in the exercise; if you require that the new condition on $b\_n$ be independent of $a\_n$, then you have a problem: For all increasing sequences $b\_n$, there exists a sequence $a\_n$ such that $a\_nb\_n$ is not increasing. One can prove this by cases: If $b\_1$ and $b\_2$ are positive, then set $a\_1=-1$ and $a\_2=-\frac{1}2\left(\frac{b\_1}{b\_2}+1\right)$. If both $b\_1$ and $b\_2$ are negative, set $a\_1=1$ and $a\_2=\frac{b\_1}{b\_2}+1.$ If $b\_1$ is negative and $b\_2$ is positive, set $a\_1=-1$ and $a\_2=0$.
If we weaken the condition on the sequences to be "non-decreasing" then at least we could use "$b\_n$ is constant and non-negative". If we allow $b\_n$ to depend on $a\_n$, then we get trivial conditions like "$b\_n$ is such that $a\_nb\_n$ is increasing". None of these conditions seem terribly natural though.
|
59,319,987 |
>
>
> ```
> id user_id name qty datetime
> --- --------- ---- ---- -----------
> 1 1 a 5 2019-12-01 12:26:01
> 2 2 b 3 2019-12-13 12:26:02
> 3 1 c 4 2019-12-13 12:26:03
> 4 2 a 2 2019-12-25 12:26:04
> 5 1 c 2 2019-12-21 12:26:06
>
> ```
>
>
i Want the this data
>
>
> ```
> id user_id name qty datetime
> --- --------- ---- ---- -----------
> 5 1 c 2 2019-12-21 12:26:06
> 4 2 a 2 2019-12-25 12:26:04
>
> ```
>
>
using laravel and also if possible then what will be the sql query for it
|
2019/12/13
|
['https://Stackoverflow.com/questions/59319987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11195843/']
|
**Models:**
*Users:* id, name, email, etc...
*Orders:* user\_id, qty, name, datetime etc..
**Model Query:**
```
Orders::orderBy('datetime', 'desc')->get()->unique('user_id');
```
**DB Query**
```
DB::table('orders')->orderBy('datetime', 'desc')->get()->unique('user_id');
```
|
In pure SQL, you can filter with a correlated subquery:
```
select t.*
from mytable t
where t.datetime = (
select max(t1.datetime) from mytable t1 where t1.user_id = t.user_id
)
```
|
59,319,987 |
>
>
> ```
> id user_id name qty datetime
> --- --------- ---- ---- -----------
> 1 1 a 5 2019-12-01 12:26:01
> 2 2 b 3 2019-12-13 12:26:02
> 3 1 c 4 2019-12-13 12:26:03
> 4 2 a 2 2019-12-25 12:26:04
> 5 1 c 2 2019-12-21 12:26:06
>
> ```
>
>
i Want the this data
>
>
> ```
> id user_id name qty datetime
> --- --------- ---- ---- -----------
> 5 1 c 2 2019-12-21 12:26:06
> 4 2 a 2 2019-12-25 12:26:04
>
> ```
>
>
using laravel and also if possible then what will be the sql query for it
|
2019/12/13
|
['https://Stackoverflow.com/questions/59319987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11195843/']
|
**Models:**
*Users:* id, name, email, etc...
*Orders:* user\_id, qty, name, datetime etc..
**Model Query:**
```
Orders::orderBy('datetime', 'desc')->get()->unique('user_id');
```
**DB Query**
```
DB::table('orders')->orderBy('datetime', 'desc')->get()->unique('user_id');
```
|
or an uncorrelated subquery...
```
select x.*
from mytable x
join (
select user_id, max(t1.datetime) datetime from mytable group by user_id
) y
on y.user_id = x.user_id
and y.datetime = x.datetime
```
|
293,885 |
Please note that I asked the same question on [stackoverflow](https://stackoverflow.com/questions/32049022/application-logic-vs-business-logic) but they directed me to ask here.
While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them.
[Here](http://encyclopedia2.thefreedictionary.com/application+logic) they say that they are the same but the answer [here](https://stackoverflow.com/questions/1456425/business-and-application-logic) is totally different.
For me I understand it in the following way:
If we look up for the definition of the `Logic` word in Google we will get
>
> system or set of principles underlying the arrangements of elements in
> a computer or electronic device so as to perform a specified task.
>
>
>
So, if the logic is `set of principles underlying the arrangements of elements` then the business logic should be `set of principles underlying the arrangements of the business rules`, in other words it means the rules that should be followed to get a system reflects your business needs.
And for me the application logic is `the principles that the application based on`, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?.
So please could anybody help me to get rid of confusion about the difference between the application and the business logic.
|
2015/08/17
|
['https://softwareengineering.stackexchange.com/questions/293885', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/192185/']
|
I agree with SO's LoztInSpace that this is quite opinionated answer and that everyone can have slightly different definitions. Especially if historical influences are involved. This is how I would define the terms:
Business logic is logic, that is created with collaboration and agreement with business experts. If business expert says that "Customer cannot withdraw more money than he has in his account.", then this is a business rule. In ideal world, this logic would be in some kind of library or service, so it can be either reused across multiple applications or changed in all relevant applications at once.
Application logic is simply everything else. Example can be "clicking this button opens window to add new customer". It has nothing to do with business, but it is still logic that needs to be implemented. In ideal world, application logic will use library or service, that is implementing the business rules. Multiple application, each with different application logic, can reuse one business logic. Imagine web app, web service and mobile app all operating using one business logic, but each clearly need different application logics.
The reason why I think those two get mixed up, is that keeping them separate is extremely hard. Even if you do your most to keep them separate, use cases surface where you have to mix them up. If for example you have all your business logic in service, it keeps it separate. But having some business logic in local application that is using the service might increase responsiveness or user comfort, because the local application doesn't need to call service for every small change.
Another reason why they are mixed together is that for many non-technical people. UI is "the application", so anything reflected in the UI is important. In the ideal "business logic" case, there is no UI. There would probably be suite of automated tests to verify the logic, but nothing that can be shown to business people. So to business people, everything is same kind of "logic". IMO.
|
Na, they're just different terms for the same thing - the "middle tier" of program code that does the things you want your program to perform. Like many things in software, there are no hard-and-fast terminology for pieces of a system, as there are no single formal definitions for building systems.
So sometimes people will call it business logic, others application logic, others will call it program logic, its all much of a muchness. Don't bother trying to define this so rigidly, nearly every system varies in how its built so be glad there's only this minor level of vagueness in terminology!
|
293,885 |
Please note that I asked the same question on [stackoverflow](https://stackoverflow.com/questions/32049022/application-logic-vs-business-logic) but they directed me to ask here.
While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them.
[Here](http://encyclopedia2.thefreedictionary.com/application+logic) they say that they are the same but the answer [here](https://stackoverflow.com/questions/1456425/business-and-application-logic) is totally different.
For me I understand it in the following way:
If we look up for the definition of the `Logic` word in Google we will get
>
> system or set of principles underlying the arrangements of elements in
> a computer or electronic device so as to perform a specified task.
>
>
>
So, if the logic is `set of principles underlying the arrangements of elements` then the business logic should be `set of principles underlying the arrangements of the business rules`, in other words it means the rules that should be followed to get a system reflects your business needs.
And for me the application logic is `the principles that the application based on`, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?.
So please could anybody help me to get rid of confusion about the difference between the application and the business logic.
|
2015/08/17
|
['https://softwareengineering.stackexchange.com/questions/293885', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/192185/']
|
I agree with SO's LoztInSpace that this is quite opinionated answer and that everyone can have slightly different definitions. Especially if historical influences are involved. This is how I would define the terms:
Business logic is logic, that is created with collaboration and agreement with business experts. If business expert says that "Customer cannot withdraw more money than he has in his account.", then this is a business rule. In ideal world, this logic would be in some kind of library or service, so it can be either reused across multiple applications or changed in all relevant applications at once.
Application logic is simply everything else. Example can be "clicking this button opens window to add new customer". It has nothing to do with business, but it is still logic that needs to be implemented. In ideal world, application logic will use library or service, that is implementing the business rules. Multiple application, each with different application logic, can reuse one business logic. Imagine web app, web service and mobile app all operating using one business logic, but each clearly need different application logics.
The reason why I think those two get mixed up, is that keeping them separate is extremely hard. Even if you do your most to keep them separate, use cases surface where you have to mix them up. If for example you have all your business logic in service, it keeps it separate. But having some business logic in local application that is using the service might increase responsiveness or user comfort, because the local application doesn't need to call service for every small change.
Another reason why they are mixed together is that for many non-technical people. UI is "the application", so anything reflected in the UI is important. In the ideal "business logic" case, there is no UI. There would probably be suite of automated tests to verify the logic, but nothing that can be shown to business people. So to business people, everything is same kind of "logic". IMO.
|
Every system or application is going to have its own definitions of what is business logic and what is application logic. It will either be explicit or implicit.
In my experience data driven applications (e.g. DBs etc.) tend to have a more formal definition of what the business logic is.
The application logic tends to focus on getting information from point A to point B, the business logic centres around what the information is - and the language of the business logic is usually domain specific. Put another way, the application logic is focused on the question "how does it work?", the business logic on "what does it do?" - again, the distinction can be very fuzzy and is more often that not domain specific.
|
293,885 |
Please note that I asked the same question on [stackoverflow](https://stackoverflow.com/questions/32049022/application-logic-vs-business-logic) but they directed me to ask here.
While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them.
[Here](http://encyclopedia2.thefreedictionary.com/application+logic) they say that they are the same but the answer [here](https://stackoverflow.com/questions/1456425/business-and-application-logic) is totally different.
For me I understand it in the following way:
If we look up for the definition of the `Logic` word in Google we will get
>
> system or set of principles underlying the arrangements of elements in
> a computer or electronic device so as to perform a specified task.
>
>
>
So, if the logic is `set of principles underlying the arrangements of elements` then the business logic should be `set of principles underlying the arrangements of the business rules`, in other words it means the rules that should be followed to get a system reflects your business needs.
And for me the application logic is `the principles that the application based on`, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?.
So please could anybody help me to get rid of confusion about the difference between the application and the business logic.
|
2015/08/17
|
['https://softwareengineering.stackexchange.com/questions/293885', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/192185/']
|
I agree with SO's LoztInSpace that this is quite opinionated answer and that everyone can have slightly different definitions. Especially if historical influences are involved. This is how I would define the terms:
Business logic is logic, that is created with collaboration and agreement with business experts. If business expert says that "Customer cannot withdraw more money than he has in his account.", then this is a business rule. In ideal world, this logic would be in some kind of library or service, so it can be either reused across multiple applications or changed in all relevant applications at once.
Application logic is simply everything else. Example can be "clicking this button opens window to add new customer". It has nothing to do with business, but it is still logic that needs to be implemented. In ideal world, application logic will use library or service, that is implementing the business rules. Multiple application, each with different application logic, can reuse one business logic. Imagine web app, web service and mobile app all operating using one business logic, but each clearly need different application logics.
The reason why I think those two get mixed up, is that keeping them separate is extremely hard. Even if you do your most to keep them separate, use cases surface where you have to mix them up. If for example you have all your business logic in service, it keeps it separate. But having some business logic in local application that is using the service might increase responsiveness or user comfort, because the local application doesn't need to call service for every small change.
Another reason why they are mixed together is that for many non-technical people. UI is "the application", so anything reflected in the UI is important. In the ideal "business logic" case, there is no UI. There would probably be suite of automated tests to verify the logic, but nothing that can be shown to business people. So to business people, everything is same kind of "logic". IMO.
|
As others have pointed out, these terms do not have one universally accepted meaning. I will describe the definitions I have encountered more often, i.e. in several projects with different companies.
The **business logic** defines a normalized, general-purpose model of the business domain for which an application is written, e.g.
* Classes like `Customer`, `Order`, `OrderLine`, and associations like `customer-order`, and so on.
* General-purpose operations such as `registerCustomer`, `cancelOrder`
Very often this class model is mapped to a database model and the mapping is implemented using ORM. The operations are normally performed each in their own transaction and provide the basic API for modifying the database, i.e. the persistent state of the application.
The **application logic** is a layer built on top of the business logic and serves to implement specific use cases. Application logic modules may use ad-hoc data representation, e.g. a CustomerSummary class without any association to `Order` if you want to list customers only. Such ad-hoc data representation must be mapped to the underlying normalized representation provided by the business model. For example, `CustomerSummary` can be defined as a view on top of `Customer`.
Note that the boundary between the two layers may not be so clearly-defined. E.g. after implementing several use cases one might notice similar data structures in the application logic and decide to unify (normalize) them and move them to the business logic.
|
293,885 |
Please note that I asked the same question on [stackoverflow](https://stackoverflow.com/questions/32049022/application-logic-vs-business-logic) but they directed me to ask here.
While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them.
[Here](http://encyclopedia2.thefreedictionary.com/application+logic) they say that they are the same but the answer [here](https://stackoverflow.com/questions/1456425/business-and-application-logic) is totally different.
For me I understand it in the following way:
If we look up for the definition of the `Logic` word in Google we will get
>
> system or set of principles underlying the arrangements of elements in
> a computer or electronic device so as to perform a specified task.
>
>
>
So, if the logic is `set of principles underlying the arrangements of elements` then the business logic should be `set of principles underlying the arrangements of the business rules`, in other words it means the rules that should be followed to get a system reflects your business needs.
And for me the application logic is `the principles that the application based on`, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?.
So please could anybody help me to get rid of confusion about the difference between the application and the business logic.
|
2015/08/17
|
['https://softwareengineering.stackexchange.com/questions/293885', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/192185/']
|
Every system or application is going to have its own definitions of what is business logic and what is application logic. It will either be explicit or implicit.
In my experience data driven applications (e.g. DBs etc.) tend to have a more formal definition of what the business logic is.
The application logic tends to focus on getting information from point A to point B, the business logic centres around what the information is - and the language of the business logic is usually domain specific. Put another way, the application logic is focused on the question "how does it work?", the business logic on "what does it do?" - again, the distinction can be very fuzzy and is more often that not domain specific.
|
Na, they're just different terms for the same thing - the "middle tier" of program code that does the things you want your program to perform. Like many things in software, there are no hard-and-fast terminology for pieces of a system, as there are no single formal definitions for building systems.
So sometimes people will call it business logic, others application logic, others will call it program logic, its all much of a muchness. Don't bother trying to define this so rigidly, nearly every system varies in how its built so be glad there's only this minor level of vagueness in terminology!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.