qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
25,164,869 | I have a requirement to be able to dynamically add/remove rows to a Tabel in an MVC 5 Application I am working on. I have also included knockout in my project as I use it to post back to preform calculation on my viewModel.
What I have done so far is created a List on my User Model to hold the details of the AdditionalUsers:
```
public List<AdditionalUser> AdditionalUsers { get; set; }
```
Additional User class defined as:
```
public class AdditionalUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public double Cost { get; set; }
}
```
I then created a EditorTemplates folder and created a partial view \_AdditionalUser.cshtml as below:
```
@model MyProject.Models.AdditionalUser
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
```
Where I need this rendered on my User View I have done the following:
```
<tr>
@Html.EditorFor(model => model.AdditionalUsers)
</tr>
```
Each other on the view has 3 . Doing this then in my controller where I new my User model I did:
```
model.AdditionalUsers = new List<AdditionalUser>(2);
```
I would have thought that would have created two blank rows in the tr where I called EditorFor but nothing is rendered? This was just for my first test to get the EditorTemplate working. I want to then wire this up to knockout to Add and remove the rows dynamically but first I am wondering why the EditorTemplate is not rendering as expected? | 2014/08/06 | [
"https://Stackoverflow.com/questions/25164869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | Your editor template is named incorrectly. There are two ways for MVC to pick it up:
**By Name**
Name the template with the exact same name as the data type:
```
DateTime.cshtml
String.cshtml
AdditionalUser.cshtml
```
**Explicitly**
In the property of your model, use the `UIHint` attribute:
```
public class MyModel
{
public SomeObject TheObject { get; set; }
[UIHint("SomeObject")]
public SomeObject AnotherObject { get; set; }
}
```
Additionally your code is not quite correct to get the rows rendered. You should first add the `tr` tag to the view:
```
@model MyProject.Models.AdditionalUser
<tr>
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
</tr>
```
Next change your parent view to something like this (note I've added table header row for clarity):
```
<table>
<tr>
<th>@Html.DisplayNameFor(m => m.FirstName)</th>
<th>@Html.DisplayNameFor(m => m.Surname)</th>
<th>@Html.DisplayNameFor(m => m.Cost)</th>
</tr>
@Html.EditorFor(model => model.AdditionalUsers)
</table>
``` | In your GET action method, you need to return some item in the `AdditionalUsers` collection. Try this.
```
var yourViewModel=new YourViewModel();
var userList = new List<AdditionalUser>();
userList.Add(new AdditionalUser { FirstName ="A"} );
userList.Add(new AdditionalUser{ FirstName ="B"});
yourViewModel.AdditionalUsers =userList();
return view(yourViewModel);
```
Also your **editor template name should be same as the class name** which is strongly typed to the editor template razor view, which is `AdditionalUser.cshtml` |
25,164,869 | I have a requirement to be able to dynamically add/remove rows to a Tabel in an MVC 5 Application I am working on. I have also included knockout in my project as I use it to post back to preform calculation on my viewModel.
What I have done so far is created a List on my User Model to hold the details of the AdditionalUsers:
```
public List<AdditionalUser> AdditionalUsers { get; set; }
```
Additional User class defined as:
```
public class AdditionalUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public double Cost { get; set; }
}
```
I then created a EditorTemplates folder and created a partial view \_AdditionalUser.cshtml as below:
```
@model MyProject.Models.AdditionalUser
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
```
Where I need this rendered on my User View I have done the following:
```
<tr>
@Html.EditorFor(model => model.AdditionalUsers)
</tr>
```
Each other on the view has 3 . Doing this then in my controller where I new my User model I did:
```
model.AdditionalUsers = new List<AdditionalUser>(2);
```
I would have thought that would have created two blank rows in the tr where I called EditorFor but nothing is rendered? This was just for my first test to get the EditorTemplate working. I want to then wire this up to knockout to Add and remove the rows dynamically but first I am wondering why the EditorTemplate is not rendering as expected? | 2014/08/06 | [
"https://Stackoverflow.com/questions/25164869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | Your editor template is named incorrectly. There are two ways for MVC to pick it up:
**By Name**
Name the template with the exact same name as the data type:
```
DateTime.cshtml
String.cshtml
AdditionalUser.cshtml
```
**Explicitly**
In the property of your model, use the `UIHint` attribute:
```
public class MyModel
{
public SomeObject TheObject { get; set; }
[UIHint("SomeObject")]
public SomeObject AnotherObject { get; set; }
}
```
Additionally your code is not quite correct to get the rows rendered. You should first add the `tr` tag to the view:
```
@model MyProject.Models.AdditionalUser
<tr>
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
</tr>
```
Next change your parent view to something like this (note I've added table header row for clarity):
```
<table>
<tr>
<th>@Html.DisplayNameFor(m => m.FirstName)</th>
<th>@Html.DisplayNameFor(m => m.Surname)</th>
<th>@Html.DisplayNameFor(m => m.Cost)</th>
</tr>
@Html.EditorFor(model => model.AdditionalUsers)
</table>
``` | here is the rules
1- the name of the template must be same. in your case it must be AdditionalUser.cshtml
2- MVC first looks if a folder **EditorTemplates** exists in the parent folder of the view (which has controller name) then looks at Shared folder.
But in your case `@Html.EditorFor(model => model.AdditionalUsers)` is would not work as the type is List and as far as I know there is no way to do that so use a foreach loop;
```
@foreach (var u in model.AdditionalUsers) {
@Html.EditorFor(model => u)
}
```
should do the trick. |
25,164,869 | I have a requirement to be able to dynamically add/remove rows to a Tabel in an MVC 5 Application I am working on. I have also included knockout in my project as I use it to post back to preform calculation on my viewModel.
What I have done so far is created a List on my User Model to hold the details of the AdditionalUsers:
```
public List<AdditionalUser> AdditionalUsers { get; set; }
```
Additional User class defined as:
```
public class AdditionalUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public double Cost { get; set; }
}
```
I then created a EditorTemplates folder and created a partial view \_AdditionalUser.cshtml as below:
```
@model MyProject.Models.AdditionalUser
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
```
Where I need this rendered on my User View I have done the following:
```
<tr>
@Html.EditorFor(model => model.AdditionalUsers)
</tr>
```
Each other on the view has 3 . Doing this then in my controller where I new my User model I did:
```
model.AdditionalUsers = new List<AdditionalUser>(2);
```
I would have thought that would have created two blank rows in the tr where I called EditorFor but nothing is rendered? This was just for my first test to get the EditorTemplate working. I want to then wire this up to knockout to Add and remove the rows dynamically but first I am wondering why the EditorTemplate is not rendering as expected? | 2014/08/06 | [
"https://Stackoverflow.com/questions/25164869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | Your editor template is named incorrectly. There are two ways for MVC to pick it up:
**By Name**
Name the template with the exact same name as the data type:
```
DateTime.cshtml
String.cshtml
AdditionalUser.cshtml
```
**Explicitly**
In the property of your model, use the `UIHint` attribute:
```
public class MyModel
{
public SomeObject TheObject { get; set; }
[UIHint("SomeObject")]
public SomeObject AnotherObject { get; set; }
}
```
Additionally your code is not quite correct to get the rows rendered. You should first add the `tr` tag to the view:
```
@model MyProject.Models.AdditionalUser
<tr>
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
</tr>
```
Next change your parent view to something like this (note I've added table header row for clarity):
```
<table>
<tr>
<th>@Html.DisplayNameFor(m => m.FirstName)</th>
<th>@Html.DisplayNameFor(m => m.Surname)</th>
<th>@Html.DisplayNameFor(m => m.Cost)</th>
</tr>
@Html.EditorFor(model => model.AdditionalUsers)
</table>
``` | You can drop the "\_" character from the name, or there is an overload, that takes a template name as the second argument.
```
@Html.EditorFor(model => model.AdditionalUsers, "_AdditionalUsers")
``` |
25,164,869 | I have a requirement to be able to dynamically add/remove rows to a Tabel in an MVC 5 Application I am working on. I have also included knockout in my project as I use it to post back to preform calculation on my viewModel.
What I have done so far is created a List on my User Model to hold the details of the AdditionalUsers:
```
public List<AdditionalUser> AdditionalUsers { get; set; }
```
Additional User class defined as:
```
public class AdditionalUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public double Cost { get; set; }
}
```
I then created a EditorTemplates folder and created a partial view \_AdditionalUser.cshtml as below:
```
@model MyProject.Models.AdditionalUser
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
```
Where I need this rendered on my User View I have done the following:
```
<tr>
@Html.EditorFor(model => model.AdditionalUsers)
</tr>
```
Each other on the view has 3 . Doing this then in my controller where I new my User model I did:
```
model.AdditionalUsers = new List<AdditionalUser>(2);
```
I would have thought that would have created two blank rows in the tr where I called EditorFor but nothing is rendered? This was just for my first test to get the EditorTemplate working. I want to then wire this up to knockout to Add and remove the rows dynamically but first I am wondering why the EditorTemplate is not rendering as expected? | 2014/08/06 | [
"https://Stackoverflow.com/questions/25164869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | You can drop the "\_" character from the name, or there is an overload, that takes a template name as the second argument.
```
@Html.EditorFor(model => model.AdditionalUsers, "_AdditionalUsers")
``` | In your GET action method, you need to return some item in the `AdditionalUsers` collection. Try this.
```
var yourViewModel=new YourViewModel();
var userList = new List<AdditionalUser>();
userList.Add(new AdditionalUser { FirstName ="A"} );
userList.Add(new AdditionalUser{ FirstName ="B"});
yourViewModel.AdditionalUsers =userList();
return view(yourViewModel);
```
Also your **editor template name should be same as the class name** which is strongly typed to the editor template razor view, which is `AdditionalUser.cshtml` |
25,164,869 | I have a requirement to be able to dynamically add/remove rows to a Tabel in an MVC 5 Application I am working on. I have also included knockout in my project as I use it to post back to preform calculation on my viewModel.
What I have done so far is created a List on my User Model to hold the details of the AdditionalUsers:
```
public List<AdditionalUser> AdditionalUsers { get; set; }
```
Additional User class defined as:
```
public class AdditionalUser
{
public string FirstName { get; set; }
public string Surname { get; set; }
public double Cost { get; set; }
}
```
I then created a EditorTemplates folder and created a partial view \_AdditionalUser.cshtml as below:
```
@model MyProject.Models.AdditionalUser
<td>
@Html.TextBoxFor(model => model.FirstName)
</td>
<td>
@Html.TextBoxFor(model => model.Surname)
</td>
<td>
@Html.TextBoxFor(model => model.Cost)
</td>
```
Where I need this rendered on my User View I have done the following:
```
<tr>
@Html.EditorFor(model => model.AdditionalUsers)
</tr>
```
Each other on the view has 3 . Doing this then in my controller where I new my User model I did:
```
model.AdditionalUsers = new List<AdditionalUser>(2);
```
I would have thought that would have created two blank rows in the tr where I called EditorFor but nothing is rendered? This was just for my first test to get the EditorTemplate working. I want to then wire this up to knockout to Add and remove the rows dynamically but first I am wondering why the EditorTemplate is not rendering as expected? | 2014/08/06 | [
"https://Stackoverflow.com/questions/25164869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | You can drop the "\_" character from the name, or there is an overload, that takes a template name as the second argument.
```
@Html.EditorFor(model => model.AdditionalUsers, "_AdditionalUsers")
``` | here is the rules
1- the name of the template must be same. in your case it must be AdditionalUser.cshtml
2- MVC first looks if a folder **EditorTemplates** exists in the parent folder of the view (which has controller name) then looks at Shared folder.
But in your case `@Html.EditorFor(model => model.AdditionalUsers)` is would not work as the type is List and as far as I know there is no way to do that so use a foreach loop;
```
@foreach (var u in model.AdditionalUsers) {
@Html.EditorFor(model => u)
}
```
should do the trick. |
8,514,067 | Just for instance, this code is working
```
import urllib
image = urllib.URLopener()
file_ = 1
name = 1
for i in range(1,1000):
try:
image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
print "save file %s" %file_
name += 1
file_ += 1
except IOError:
file_ += 1
```
How could I make it stop after some time was spent, even if the code is still being ran? Please, help me to figure it out. | 2011/12/15 | [
"https://Stackoverflow.com/questions/8514067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981877/"
] | I would use the [`multiprocessing`](http://docs.python.org/dev/library/multiprocessing) module, which generates new processes (not threads) for parallelizing tasks.
How to do it? First, the actual download code should be put in a function:
```
import urllib
import multiprocessing
import time
def download_images():
image = urllib.URLopener()
file_ = 1
name = 1
for i in range(1,1000):
try:
image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
print "save file %s" %file_
name += 1
file_ += 1
except IOError:
file_ += 1
```
Now, we create a new `multiprocessing.Process` object, passing the function above as its target. This object will start a process just to execute this function:
```
downloader = multiprocessing.Process(target=download_images)
```
Once we have created the process object, just call its `start()` method. This will start a process that will run in parallel:
```
downloader.start()
```
Since it is running in parallel, the main program keeps executing. Now, we define a timeout and sleep for the time of this timeout. In the example below, the timeout is 15 seconds:
```
timeout = 15
time.sleep(timeout)
```
Once the timeout ends, just terminate the downloader process:
```
downloader.terminate()
```
The full program can be found [here](http://pastebin.com/u9VGUiMj). | Not the best but a usable way:
You can spawn a child thread using `threading` module to do this, and, set an time.sleep in your main thread, so when time is out, you can kill the child thread.
**EDIT**: just something like this:
```
import threading
import urllib
def child(file_, name):
try:
image = urllib.URLopener()
image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
print "save file %s" % file_
except IOError:
pass
file_ = 1
name = 1
for i in range(1,1000):
t = threading.Thread(target = child, args = (file_, name))
t.daemon = True
t.start()
t.join(timeout = 10)
file_ += 1
name += 1
``` |
8,514,067 | Just for instance, this code is working
```
import urllib
image = urllib.URLopener()
file_ = 1
name = 1
for i in range(1,1000):
try:
image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
print "save file %s" %file_
name += 1
file_ += 1
except IOError:
file_ += 1
```
How could I make it stop after some time was spent, even if the code is still being ran? Please, help me to figure it out. | 2011/12/15 | [
"https://Stackoverflow.com/questions/8514067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981877/"
] | I would use the [`multiprocessing`](http://docs.python.org/dev/library/multiprocessing) module, which generates new processes (not threads) for parallelizing tasks.
How to do it? First, the actual download code should be put in a function:
```
import urllib
import multiprocessing
import time
def download_images():
image = urllib.URLopener()
file_ = 1
name = 1
for i in range(1,1000):
try:
image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
print "save file %s" %file_
name += 1
file_ += 1
except IOError:
file_ += 1
```
Now, we create a new `multiprocessing.Process` object, passing the function above as its target. This object will start a process just to execute this function:
```
downloader = multiprocessing.Process(target=download_images)
```
Once we have created the process object, just call its `start()` method. This will start a process that will run in parallel:
```
downloader.start()
```
Since it is running in parallel, the main program keeps executing. Now, we define a timeout and sleep for the time of this timeout. In the example below, the timeout is 15 seconds:
```
timeout = 15
time.sleep(timeout)
```
Once the timeout ends, just terminate the downloader process:
```
downloader.terminate()
```
The full program can be found [here](http://pastebin.com/u9VGUiMj). | This one really works for me and it is very simple. Suppose that we want stop after 25 seconds.
```
import timeit #we will need the command default_timer() that checks the actual time
start = timeit.default_timer()
while timeit.default_timer()-start<=25:
"you code here"
``` |
226,456 | The following
```
SELECT ARRAY[a,b,c,d]
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
Returns `{foo,bar,foo,baz}` of type `text[]`. I would like to get `{foo,bar,baz}` of type `text[]` **with one of the duplicate `foo` elements removed**? Does PostgreSQL have a unique function that works on a text-array, or an `anyarray` of `anyelement`? | 2019/01/06 | [
"https://dba.stackexchange.com/questions/226456",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2639/"
] | While there is no function to accomplish that, you can use
1. `unnest()` to convert an array of elements, to a table of rows of one-column,
2. `DISTINCT` to remove duplicates
3. `ARRAY(query)` to recreate the row.
That idiom looks like,
```
ARRAY( SELECT DISTINCT ... FROM unnest(arr) )
```
And in practice is applied like this,
```
SELECT ARRAY(SELECT DISTINCT e FROM unnest(ARRAY[a,b,c,d]) AS a(e))
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
If you want it sorted you can do,
```
SELECT ARRAY(SELECT DISTINCT e FROM unnest(ARRAY[a,b,c,d]) AS a(e) ORDER BY e)
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
And that can all can be written with `CROSS JOIN LATERAL` which is **much** cleaner,
```
SELECT ARRAY(
SELECT DISTINCT e
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d)
CROSS JOIN LATERAL unnest(ARRAY[a,b,c,d]) AS a(e)
-- ORDER BY e; -- if you want it sorted
);
```
---
* Answer inspired by RhodiumToad on irc.freenode.net/#postgresql | Perhaps more of a question / comment.
This code below preserves the original ordering. How can it be improved / made more efficient.
In essence, I believe it will also accomplish the set task.
```
select e
from
(
select array_agg(e) over (order by wf_rn) as e, row_number() over (order by wf_rn DESC) as wf_rn
from
(
select *, row_number() over (partition by e order by wf_rn) as wf_rn_e
from
(
SELECT *, row_number() over () as wf_rn
FROM
(
select unnest(ARRAY['foo', 'bar', 'foo', 'baz']) as e
) AS t
) as A
) as A
where wf_rn_e = 1
) as A
where wf_rn = 1
```
I have to say thank you for the "lateral join" pointer - that makes it super easy to execute this without having to wrap it as a function :-) |
226,456 | The following
```
SELECT ARRAY[a,b,c,d]
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
Returns `{foo,bar,foo,baz}` of type `text[]`. I would like to get `{foo,bar,baz}` of type `text[]` **with one of the duplicate `foo` elements removed**? Does PostgreSQL have a unique function that works on a text-array, or an `anyarray` of `anyelement`? | 2019/01/06 | [
"https://dba.stackexchange.com/questions/226456",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2639/"
] | While there is no function to accomplish that, you can use
1. `unnest()` to convert an array of elements, to a table of rows of one-column,
2. `DISTINCT` to remove duplicates
3. `ARRAY(query)` to recreate the row.
That idiom looks like,
```
ARRAY( SELECT DISTINCT ... FROM unnest(arr) )
```
And in practice is applied like this,
```
SELECT ARRAY(SELECT DISTINCT e FROM unnest(ARRAY[a,b,c,d]) AS a(e))
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
If you want it sorted you can do,
```
SELECT ARRAY(SELECT DISTINCT e FROM unnest(ARRAY[a,b,c,d]) AS a(e) ORDER BY e)
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
And that can all can be written with `CROSS JOIN LATERAL` which is **much** cleaner,
```
SELECT ARRAY(
SELECT DISTINCT e
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d)
CROSS JOIN LATERAL unnest(ARRAY[a,b,c,d]) AS a(e)
-- ORDER BY e; -- if you want it sorted
);
```
---
* Answer inspired by RhodiumToad on irc.freenode.net/#postgresql | If the input values are in one column (essentially an array in relational terms), then the unique array can also be obtained using the stock `array_agg()` function with a `DISTINCT` keyword:
```sql
SELECT array_agg(DISTINCT v)
FROM ( VALUES
('foo'), ('bar'), ('foo'), ('baz')
) AS t(v);
```
Output:
```
array_agg
---------------
{bar,baz,foo}
(1 row)
```
If the input is an array, an `unnest()` can be used to turn the input into a one-column table first, and then `array_agg(DISTINCT ...)`. |
226,456 | The following
```
SELECT ARRAY[a,b,c,d]
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
Returns `{foo,bar,foo,baz}` of type `text[]`. I would like to get `{foo,bar,baz}` of type `text[]` **with one of the duplicate `foo` elements removed**? Does PostgreSQL have a unique function that works on a text-array, or an `anyarray` of `anyelement`? | 2019/01/06 | [
"https://dba.stackexchange.com/questions/226456",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2639/"
] | While there is no function to accomplish that, you can use
1. `unnest()` to convert an array of elements, to a table of rows of one-column,
2. `DISTINCT` to remove duplicates
3. `ARRAY(query)` to recreate the row.
That idiom looks like,
```
ARRAY( SELECT DISTINCT ... FROM unnest(arr) )
```
And in practice is applied like this,
```
SELECT ARRAY(SELECT DISTINCT e FROM unnest(ARRAY[a,b,c,d]) AS a(e))
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
If you want it sorted you can do,
```
SELECT ARRAY(SELECT DISTINCT e FROM unnest(ARRAY[a,b,c,d]) AS a(e) ORDER BY e)
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
And that can all can be written with `CROSS JOIN LATERAL` which is **much** cleaner,
```
SELECT ARRAY(
SELECT DISTINCT e
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d)
CROSS JOIN LATERAL unnest(ARRAY[a,b,c,d]) AS a(e)
-- ORDER BY e; -- if you want it sorted
);
```
---
* Answer inspired by RhodiumToad on irc.freenode.net/#postgresql | A simple function based on @Evan Carroll's answer
```sql
create or replace function array_unique (a text[]) returns text[] as $$
select array (
select distinct v from unnest(a) as b(v)
)
$$ language sql;
```
with that in place you can
```
select internal.array_unique(array['foo','bar'] || array['foo'])
=> {'foo','bar'}
``` |
226,456 | The following
```
SELECT ARRAY[a,b,c,d]
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
Returns `{foo,bar,foo,baz}` of type `text[]`. I would like to get `{foo,bar,baz}` of type `text[]` **with one of the duplicate `foo` elements removed**? Does PostgreSQL have a unique function that works on a text-array, or an `anyarray` of `anyelement`? | 2019/01/06 | [
"https://dba.stackexchange.com/questions/226456",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2639/"
] | If the input values are in one column (essentially an array in relational terms), then the unique array can also be obtained using the stock `array_agg()` function with a `DISTINCT` keyword:
```sql
SELECT array_agg(DISTINCT v)
FROM ( VALUES
('foo'), ('bar'), ('foo'), ('baz')
) AS t(v);
```
Output:
```
array_agg
---------------
{bar,baz,foo}
(1 row)
```
If the input is an array, an `unnest()` can be used to turn the input into a one-column table first, and then `array_agg(DISTINCT ...)`. | Perhaps more of a question / comment.
This code below preserves the original ordering. How can it be improved / made more efficient.
In essence, I believe it will also accomplish the set task.
```
select e
from
(
select array_agg(e) over (order by wf_rn) as e, row_number() over (order by wf_rn DESC) as wf_rn
from
(
select *, row_number() over (partition by e order by wf_rn) as wf_rn_e
from
(
SELECT *, row_number() over () as wf_rn
FROM
(
select unnest(ARRAY['foo', 'bar', 'foo', 'baz']) as e
) AS t
) as A
) as A
where wf_rn_e = 1
) as A
where wf_rn = 1
```
I have to say thank you for the "lateral join" pointer - that makes it super easy to execute this without having to wrap it as a function :-) |
226,456 | The following
```
SELECT ARRAY[a,b,c,d]
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
Returns `{foo,bar,foo,baz}` of type `text[]`. I would like to get `{foo,bar,baz}` of type `text[]` **with one of the duplicate `foo` elements removed**? Does PostgreSQL have a unique function that works on a text-array, or an `anyarray` of `anyelement`? | 2019/01/06 | [
"https://dba.stackexchange.com/questions/226456",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2639/"
] | A simple function based on @Evan Carroll's answer
```sql
create or replace function array_unique (a text[]) returns text[] as $$
select array (
select distinct v from unnest(a) as b(v)
)
$$ language sql;
```
with that in place you can
```
select internal.array_unique(array['foo','bar'] || array['foo'])
=> {'foo','bar'}
``` | Perhaps more of a question / comment.
This code below preserves the original ordering. How can it be improved / made more efficient.
In essence, I believe it will also accomplish the set task.
```
select e
from
(
select array_agg(e) over (order by wf_rn) as e, row_number() over (order by wf_rn DESC) as wf_rn
from
(
select *, row_number() over (partition by e order by wf_rn) as wf_rn_e
from
(
SELECT *, row_number() over () as wf_rn
FROM
(
select unnest(ARRAY['foo', 'bar', 'foo', 'baz']) as e
) AS t
) as A
) as A
where wf_rn_e = 1
) as A
where wf_rn = 1
```
I have to say thank you for the "lateral join" pointer - that makes it super easy to execute this without having to wrap it as a function :-) |
226,456 | The following
```
SELECT ARRAY[a,b,c,d]
FROM ( VALUES
('foo', 'bar', 'foo', 'baz' )
) AS t(a,b,c,d);
```
Returns `{foo,bar,foo,baz}` of type `text[]`. I would like to get `{foo,bar,baz}` of type `text[]` **with one of the duplicate `foo` elements removed**? Does PostgreSQL have a unique function that works on a text-array, or an `anyarray` of `anyelement`? | 2019/01/06 | [
"https://dba.stackexchange.com/questions/226456",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/2639/"
] | A simple function based on @Evan Carroll's answer
```sql
create or replace function array_unique (a text[]) returns text[] as $$
select array (
select distinct v from unnest(a) as b(v)
)
$$ language sql;
```
with that in place you can
```
select internal.array_unique(array['foo','bar'] || array['foo'])
=> {'foo','bar'}
``` | If the input values are in one column (essentially an array in relational terms), then the unique array can also be obtained using the stock `array_agg()` function with a `DISTINCT` keyword:
```sql
SELECT array_agg(DISTINCT v)
FROM ( VALUES
('foo'), ('bar'), ('foo'), ('baz')
) AS t(v);
```
Output:
```
array_agg
---------------
{bar,baz,foo}
(1 row)
```
If the input is an array, an `unnest()` can be used to turn the input into a one-column table first, and then `array_agg(DISTINCT ...)`. |
259,071 | Can anyone explain to me the difference between *content type* and *custom content type*? | 2018/04/03 | [
"https://drupal.stackexchange.com/questions/259071",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/84216/"
] | *Custom content type* can be used with two different meanings:
* Any node type ([bundle](https://www.drupal.org/docs/8/api/entity-api/bundles), or entity bundle, in Drupal 8 terminology) created from the user interface (admin/structure/types/add in Drupal 7 and Drupal 8) from users with the right permissions
* Any node type implemented from third-party modules
What is not a custom content type is a content type created from a Drupal core module, or a Drupal core profile. For example, the [*Forum topic*](https://cgit.drupalcode.org/drupal/tree/core/modules/forum/config/optional/node.type.forum.yml) content type is created from the Forum module, while the [*Article*](https://cgit.drupalcode.org/drupal/tree/core/profiles/standard/config/install/node.type.article.yml) content type is created from the Standard profile.
For the rest, there isn't much difference between a custom content type and a content type: Both can be extended with fields.
There could be a difference between a content type created from a module (core module or third-party module) and a content type created through the user interface: the content type fields that aren't created from the user interface made available from the [*Field UI*](https://www.drupal.org/docs/8/core/modules/field-ui) module. For example, the Forum module adds to the *Forum topic* content type a [reference field for a vocabulary the module created](https://cgit.drupalcode.org/drupal/tree/core/modules/forum/config/optional/field.field.node.forum.taxonomy_forums.yml). Similarly, the Standard profile adds [a field to attach an image](https://cgit.drupalcode.org/drupal/tree/core/profiles/standard/config/install/field.field.node.article.field_image.yml) to nodes of the *Article* content type. | A content type is a type of node. Node types (aka content types) are generally created through the browser UI. However, they can also be created through code, which people refer generally refer to as a custom content type. |
61,972,632 | Currently I am trying to have volume persistence for my MYSQL database using Kubernetes with Kubeadm.
The environment is based on an amazon EC2 instance using EBS storage disks.
As you can see below a storage class, a persistent volume as well as a persistent volume claim have been implemented in order to have a mysql persistence.
However an error occurs when I try to deploy the mysql pod (on the attached image).
**mysql-pv.yml:**
```
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
name: standard
provisioner: kubernetes.io/aws-ebs
parameters:
type: gp2
reclaimPolicy: Retain
mountOptions:
- debug
volumeBindingMode: Immediate
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: mysql-pv
labels:
type: amazonEBS
spec:
capacity:
storage: 5Gi
storageClassName: standard
accessModes:
- ReadWriteOnce
awsElasticBlockStore:
volumeID: vol-ID
fsType: ext4
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql-pv-claim
spec:
storageClassName: standard
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
```
**mysql.yml**:
```
apiVersion: apps/v1
kind: Deployment
metadata:
name: mysql
spec:
selector:
matchLabels:
app: mysql
strategy:
type: Recreate
template:
metadata:
labels:
app: mysql
spec:
containers:
- image: mysql:5.7.30
name: mysql
env:
- name: MYSQL_ROOT_PASSWORD
value: MYPASSWORD
ports:
- containerPort: 3306
name: mysql
volumeMounts:
- name: mysql-persistent-storage
mountPath: /var/lib/mysql
volumes:
- name: mysql-persistent-storage
persistentVolumeClaim:
claimName: mysql-pv-claim
---
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
type: NodePort
ports:
- port: 3306
targetPort: 3306
nodePort: 31306
selector:
app: mysql
```
This is my mysql pod description:
```
Name: mysql-5c9788fc65-jq2nh
Namespace: default
Priority: 0
Node: ip-172-31-31-210/172.31.31.210
Start Time: Sat, 23 May 2020 12:19:24 +0000
Labels: app=mysql
pod-template-hash=5c9788fc65
Annotations: <none>
Status: Pending
IP:
IPs: <none>
Controlled By: ReplicaSet/mysql-5c9788fc65
Containers:
mysql:
Container ID:
Image: mysql:5.7.30
Image ID:
Port: 3306/TCP
Host Port: 0/TCP
State: Waiting
Reason: ContainerCreating
Ready: False
Restart Count: 0
Environment:
MYSQL_ROOT_PASSWORD: MYPASS
Mounts:
/data/ from mysql-persistent-storage (rw)
/var/run/secrets/kubernetes.io/serviceaccount from default-token-cshk2 (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
mysql-persistent-storage:
Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
ClaimName: mysql-pv-claim
ReadOnly: false
default-token-cshk2:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-cshk2
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
```
Here is the error I get:
```
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled <unknown> default-scheduler
Successfully assigned default/mysql-5c9788fc65-jq2nh to ip-172-31-31-210
Warning FailedMount 39m kubelet, ip-172-31-31-210 MountVolume.SetUp failed for volume "mysql-pv" : mount failed: exit status 32
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/29d5cee7-da11-4a0c-b5aa-e262f919d1ba/volumes/kubernetes.io~aws-ebs/mysql-pv --scope -- mount -o bind /var/lib/kubelet/plugins/kubernetes.io/aws-ebs/mounts/vol-06212746d87534157 /var/lib/kubelet/pods/29d5cee7-da11-4a0c-b5aa-e262f919d1ba/volumes/kubernetes.io~aws-ebs/mysql-pv
Output: Running scope as unit: run-r11fefbbda1d241c2985931d3adaaa969.scope
mount: /var/lib/kubelet/pods/29d5cee7-da11-4a0c-b5aa-e262f919d1ba/volumes/kubernetes.io~aws-ebs/mysql-pv: special device /var/lib/kubelet/plugins/kubernetes.io/aws-ebs/mounts/vol-06212746d87534157 does not exist.
Warning FailedMount 39m kubelet, ip-172-31-31-210 MountVolume.SetUp failed for volume "mysql-pv" : mount failed: exit status 32
```
Someone can help me ? | 2020/05/23 | [
"https://Stackoverflow.com/questions/61972632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13289397/"
] | Check for the state of PV and PVC if the PVC is in bounded state or not.
`kubectl describe pvc mysql-pv-claim`
`kubectl describe pv mysql-pv`
Do you have the [EBS CSI driver](https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html) installed?
Other reason can be, I think you missed adding the option of **--cloud-provider=aws**, this is required by CCM for the nodes. Check out the similar [issue](https://github.com/kubernetes/kubernetes/issues/70921).
The following link has all the IAM permissions and a working example on how to create and mount an EBS volume in Kubernetes from docs on [cluster configuration](https://docs.docker.com/ee/ucp/kubernetes/storage/configure-aws-storage/#cluster-configuration) for using EBS.
With a kubeadm configuration, configuration is defined in: **/var/lib/kubelet/config.yaml** and **/var/lib/kubelet/kubeadm-flags.env**
If the cluster was deployed using **kubeadm** then, define environment variable on all nodes in `kubeadm-flags.env`
To resolve this manually you need to add the [--cloud-provider=aws](https://github.com/kubernetes/cloud-provider-aws#readme) tag to the `kubeadm-flags.env` and restarted the services, which will resolve the issue:
`systemctl daemon-reload && systemctl restart kubelet`
or provide the following [configuration](https://kubernetes.io/docs/concepts/cluster-administration/cloud-providers/#kubeadm) for kubeadm. Change openstack to AWS in your case.
Check the following [blog](https://www.nebulaworks.com/blog/2019/08/27/leveraging-aws-ebs-for-kubernetes-persistent-volumes/) for better understanding.
```
kind: InitConfiguration
nodeRegistration:
kubeletExtraArgs:
cloud-provider: "aws"
cloud-config: "/etc/kubernetes/cloud.conf"
---
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
apiServer:
extraArgs:
cloud-provider: "aws"
#cloud-config: "/etc/kubernetes/cloud.conf"
extraVolumes:
- name: cloud
hostPath: "/etc/kubernetes/cloud.conf"
mountPath: "/etc/kubernetes/cloud.conf"
controllerManager:
extraArgs:
cloud-provider: "aws"
#cloud-config: "/etc/kubernetes/cloud.conf"
extraVolumes:
- name: cloud
hostPath: "/etc/kubernetes/cloud.conf"
mountPath: "/etc/kubernetes/cloud.conf"```
``` | Here is some additional information:
**kubectl describe pvc mysql-pv-claim** :
```
Name: mysql-pv-claim
Namespace: default
StorageClass: standard
Status: Bound
Volume: mysql-pv
Labels: <none>
Annotations: pv.kubernetes.io/bind-completed: yes
pv.kubernetes.io/bound-by-controller: yes
Finalizers: [kubernetes.io/pvc-protection]
Capacity: 5Gi
Access Modes: RWO
VolumeMode: Filesystem
Mounted By: mysql-5c9788fc65-jq2nh
Events: <none>
```
**kubectl describe pv mysql-pv** :
```
Name: mysql-pv
Labels: type=amazonEBS
Annotations: pv.kubernetes.io/bound-by-controller: yes
Finalizers: [kubernetes.io/pv-protection]
StorageClass: standard
Status: Bound
Claim: default/mysql-pv-claim
Reclaim Policy: Retain
Access Modes: RWO
VolumeMode: Filesystem
Capacity: 5Gi
Node Affinity: <none>
Message:
Source:
Type: AWSElasticBlockStore (a Persistent Disk resource in AWS)
VolumeID: vol-06212746d87534157
FSType: ext4
Partition: 0
ReadOnly: false
Events: <none>
```
**lsblk** :
```
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 18M 1 loop /snap/amazon-ssm-agent/1566
loop1 7:1 0 93.9M 1 loop /snap/core/9066
loop2 7:2 0 93.8M 1 loop /snap/core/8935
nvme0n1 259:0 0 10G 0 disk
nvme1n1 259:1 0 15G 0 disk
└─nvme1n1p1 259:2 0 15G 0 part /
```
I want to use nvme0n1.
I don't have kubelet and kube-controller-manager.log file log. |
6,524,703 | I am wondering if I am using blocks as shown in the code below
```
__block Loader *loader = [[Loader alloc]initWithResourcePath:self.resourcePath];
[loader setCompletionHandler:^(NSArray *anArray){
self.answerArray=anArray;
[self reloadData];
}];
[loader getObjects];
```
My question is with regards to memory management. The analyzer tells me that there is a potential leak (since I did an alloc/init for my loader). How can I stop the leak here? I tried to release the loader at the end but that causes my app to stop functioning. Any advise is appreciated here | 2011/06/29 | [
"https://Stackoverflow.com/questions/6524703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | Several issues:
* there is no reason for `loader` to be declared `__block`; you aren't re-assigning in the block and, thus, the `__block` is pointless.
* the leak is because you `alloc/init` the loader, but never release it
* do not name methods `getSomething`; the `get` prefix is reserved for methods that return stuff by reference. Just call it `objects`. If it is supposed to trigger the load, then call it `load` or `performLoad`.
If it is asynchronous, then `getObjects` is pointless. If synchronous, then the completion block is pointless.
If `loader` is to be used synchronously, `release` it at the end of the method. If it is `asynchronous`, then the completion block could release it. Note that the use of `__block` in this case is still pointless; while referring to `loader` in the completion block will create a retain cycle, it will be broken when you explicitly Block\_release() the block in your `loader` (because you *must* have done a `Block_copy()` when setting the completion handler if it is to be used asynchronously in the first place). | If you plan to use `loader` outside of the function calling your block, it is highly possible that you need to store it in a ivar of your controller (I guess, it is a controller, but I don't know what kind of class owns the code you shows). Once you do that, you can release it in your `dealloc`.
The reasoning is that `loader` should live across several methods and runloop cycles, so a local variable will not do.
Otherwise, just release it at the end of the block, once you have done with it.
If this does not seem right to you, then possibly more code is needed. |
6,524,703 | I am wondering if I am using blocks as shown in the code below
```
__block Loader *loader = [[Loader alloc]initWithResourcePath:self.resourcePath];
[loader setCompletionHandler:^(NSArray *anArray){
self.answerArray=anArray;
[self reloadData];
}];
[loader getObjects];
```
My question is with regards to memory management. The analyzer tells me that there is a potential leak (since I did an alloc/init for my loader). How can I stop the leak here? I tried to release the loader at the end but that causes my app to stop functioning. Any advise is appreciated here | 2011/06/29 | [
"https://Stackoverflow.com/questions/6524703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | Several issues:
* there is no reason for `loader` to be declared `__block`; you aren't re-assigning in the block and, thus, the `__block` is pointless.
* the leak is because you `alloc/init` the loader, but never release it
* do not name methods `getSomething`; the `get` prefix is reserved for methods that return stuff by reference. Just call it `objects`. If it is supposed to trigger the load, then call it `load` or `performLoad`.
If it is asynchronous, then `getObjects` is pointless. If synchronous, then the completion block is pointless.
If `loader` is to be used synchronously, `release` it at the end of the method. If it is `asynchronous`, then the completion block could release it. Note that the use of `__block` in this case is still pointless; while referring to `loader` in the completion block will create a retain cycle, it will be broken when you explicitly Block\_release() the block in your `loader` (because you *must* have done a `Block_copy()` when setting the completion handler if it is to be used asynchronously in the first place). | I'm going to make some assumptions: 1) The completion handler (block) is used by method getObjects. 2) getObjects is asynchronous (it returns to the caller right away though it continues to process).
With these assumptions you can't send release after sending getObjects because getObjects is still using the completion handler.
Try sending a release or autorelease at the end of the completion handler. That should free loader provided reloadData is not also asynchronous. |
41,795 | I was reading [Do Stars Vanish Into a Black Hole or Crash Against a Surface? A New Test Answers](https://www.space.com/37075-how-stars-fall-into-black-holes.html) on space.com.
It says the following:
>
> Another proposed alternative to event horizons is the "hard surface
> theory," which suggests that matter within a black hole is destroyed
> by smashing into a solid surface. Instead of a singularity with no
> surface area, the black hole is a giant mass with a hard surface, and
> material being pulled closer — such as a star — would not actually
> fall into a black hole, but hit this hard surface and be destroyed. If
> that were the case, the collision should create a large burst of
> light.
>
>
>
If we focus on the last sentence:
>
> If that were the case, the collision should create a large burst of
> light.
>
>
>
If the escape velocity of black hole becomes at certain altitude above the say solid surface of a blackhole more than that of speed of light, would we still see a large burst of light when the collision happens? Black holes are incredibly dense wouldn't it make more sense from them to be solid?
Something like a [dark star](https://en.wikipedia.org/wiki/Dark_star_(Newtonian_mechanics)).
No one really knows what happens to the matter at the singularity. Wouldn't it make sense that the reason that a black hole gets larger is due to more matter being smashed into the singularity making it gain mass. It also seems that black holes can be hurled out their galaxies, it must be in some form of matter that it stays together even when hurled out? | 2021/03/04 | [
"https://astronomy.stackexchange.com/questions/41795",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/33956/"
] | The idea of a hard surface on a black hole is very much a minority theory, bordering on a fringe theory. The reason is that general relativity is fairly well tested, and does not just predict event horizons around black holes but also the [Buchdahl bound](https://en.wikipedia.org/wiki/Buchdahl%27s_theorem) on how small objects in hydrostatic equilibrium can be. Still, it is always worth testing the theory, [which is what the paper proposes](https://arxiv.org/abs/1703.00023).
If you drop an object from infinity onto an object of radius $R$ the Newtonian kinetic energy at that moment would be $GM/R$ J/kg, much of which would be released as a flash. This is why accretion onto white dwarfs and neutron stars produce a lot of radiation beside the accretion disk: for white dwarfs about 0.0003 of the mass-energy would be released, while for a neutron star 0.147 of the mass energy would be released. For a black hole-radius object this crude estimate produces 50% efficiency of converting mass into energy.
However, the energy of that flash is reduced by the [gravitational redshift](https://en.wikipedia.org/wiki/Gravitational_redshift). At the Buchdahl limit the redshift is z=2, halving the energy received (for neutron stars you only get 74% of the energy). But for a black hole horizon general relativity gives infinite redshift, making the flash disappear altogether.
It does not make sense to see black holes as solid objects since the structure of spacetime inside the event horizon makes the inward direction behave like time does outside: you can only move inward, just as you can only move forward in time. Thinking of the singularity as a material object with mass is very misleading: [it is not even point-like](https://arxiv.org/abs/1907.05292). Hence talk about the density of a black hole or imagining it as a sphere of something dense tends to end in confusion. Similarly talking about escape velocity is also tricky: it does not define the horizon as people usually say. The horizon is defined by being a trapped surface that can only be crossed in one direction. | To answer your questions: citing the same article you refer to:
>
> But if event horizons do exist, there wouldn't be flash of light. Instead, matter would just completely vanish when pulled in.
>
>
>
So, the existence of an event horizon (where even light can not escape the gravitational pull) would avoid seeing any burst of light on this theoretical collision with a surface.
>
> Black holes are incredibly dense wouldn't it make more sense from them to be solid?
>
>
>
It would not. Take as an example neutron stars, which are surely more dense than anything in our solar system. The star is so dense, that matter becomes *neutron-degenerate*. This is a special kind of plasma state, a ultra compressed one where the fermions are the closest possible without breaking the Pauli Exclusion Principle. The rules that govern this state are determined by quantum mechanics rather than classic mechanics. I am just giving you this example to show that, under extreme densities, "normal" rules (such as the ones that follow for solids) no longer apply and things become more complex. |
41,795 | I was reading [Do Stars Vanish Into a Black Hole or Crash Against a Surface? A New Test Answers](https://www.space.com/37075-how-stars-fall-into-black-holes.html) on space.com.
It says the following:
>
> Another proposed alternative to event horizons is the "hard surface
> theory," which suggests that matter within a black hole is destroyed
> by smashing into a solid surface. Instead of a singularity with no
> surface area, the black hole is a giant mass with a hard surface, and
> material being pulled closer — such as a star — would not actually
> fall into a black hole, but hit this hard surface and be destroyed. If
> that were the case, the collision should create a large burst of
> light.
>
>
>
If we focus on the last sentence:
>
> If that were the case, the collision should create a large burst of
> light.
>
>
>
If the escape velocity of black hole becomes at certain altitude above the say solid surface of a blackhole more than that of speed of light, would we still see a large burst of light when the collision happens? Black holes are incredibly dense wouldn't it make more sense from them to be solid?
Something like a [dark star](https://en.wikipedia.org/wiki/Dark_star_(Newtonian_mechanics)).
No one really knows what happens to the matter at the singularity. Wouldn't it make sense that the reason that a black hole gets larger is due to more matter being smashed into the singularity making it gain mass. It also seems that black holes can be hurled out their galaxies, it must be in some form of matter that it stays together even when hurled out? | 2021/03/04 | [
"https://astronomy.stackexchange.com/questions/41795",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/33956/"
] | This seems to be a fringe idea that appears inconsistent with General Relativity. For a spherically symmetric mass distribution it is easy to show, from the Schwarzschild metric, that it is impossible for anything (with or without mass) to avoid moving towards smaller values of $r$ if $r$ is less than the Schwarzschild radius.
Whilst GR breaks down as a theory as $r \rightarrow 0$, it is safe to say that anything "odd" that happens will be well inside the Schwarzschild radius and so evidence of it in the form of a burst of light can never reach an outside observer.
A solid surface cannot exist outside, but close-to (within about 1.2 times), the Schwarzschild radius either. This is because of the self-defeating nature of pressure in General Relativity, which contributes to the curvature of spacetime. Any self-supporting structure close to the event horizon cannot be in equilibrium because of the increase in spacetime curvature that its internal pressure would cause. | To answer your questions: citing the same article you refer to:
>
> But if event horizons do exist, there wouldn't be flash of light. Instead, matter would just completely vanish when pulled in.
>
>
>
So, the existence of an event horizon (where even light can not escape the gravitational pull) would avoid seeing any burst of light on this theoretical collision with a surface.
>
> Black holes are incredibly dense wouldn't it make more sense from them to be solid?
>
>
>
It would not. Take as an example neutron stars, which are surely more dense than anything in our solar system. The star is so dense, that matter becomes *neutron-degenerate*. This is a special kind of plasma state, a ultra compressed one where the fermions are the closest possible without breaking the Pauli Exclusion Principle. The rules that govern this state are determined by quantum mechanics rather than classic mechanics. I am just giving you this example to show that, under extreme densities, "normal" rules (such as the ones that follow for solids) no longer apply and things become more complex. |
1,457,884 | Original equation $$y^4=Cx^5$$
Ok my issue is that i am not sure how I would continue after taking the derivative. $$\frac{y^4}{x^5}=C$$
$$\frac{4y^3x^5\frac{dy}{dx}-5y^4x^4}{x^{10}}dx$$ I am not sure how I would continue to seperate the variable to be able to take the integral to the find the orthogonal trjectory. | 2015/09/30 | [
"https://math.stackexchange.com/questions/1457884",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272342/"
] | For the family of curves $y(x, C)$ where
$$
y^4 = C \, x^5
$$
and $C$ is a constant, we want to find the orthogonal curves $z(x, C)$.
$y$ and $z$ should intersect at $x\_0$, thus
$$
y(x\_0) = z(x\_0) \quad (\*)
$$
and if $y$ has the tangent
$$
T(x) = y(x\_0) + y'(x\_0)\, x
$$
at the point $x\_0$ then $z$ should have an orthogonal tangent there
$$
U(x) = z(x\_0) + z'(x\_0)\, x
$$
Using the scalar product we get the condition for orthogonal tangent vectors
$$
0 = (1, T'(x\_0)) \cdot (1, U'(x\_0)) = 1 + T'(x\_0) U'(x\_0) \Rightarrow \\
U'(x\_0) = - \frac{1}{T'(x\_0)}
$$
and this means
$$
z'(x\_0) = - \frac{1}{y'(x\_0)} \quad (\*\*)
$$
Solving for $y$ and differentiating, we get
$$
y = (C \, x^5)^{1/4} \Rightarrow \\
y' = \frac{5}{4} (C \, x)^{1/4}
$$
and therefore
$$
z' = - \frac{4}{5} (C \, x)^{-1/4}
$$
Integrating gives
$$
z = -\frac{16}{15} C^{-1/4} \, x^{3/4} + D
$$
with an integration constant $D$ such that equation $(\*)$ holds:
$$
(C \, x\_0^5)^{1/4} = -\frac{16}{15} C^{-1/4} \, x\_0^{3/4} + D \Rightarrow \\
D = (C \, x\_0^5)^{1/4} + \frac{16}{15} C^{-1/4} \, x\_0^{3/4}
$$
which gives
$$
z = -\frac{16}{15} C^{-1/4} \, (x^{3/4} - x\_0^{3/4}) + (C \, x\_0^5)^{1/4}
$$
Here is the positive part of the curve for $C=1$ (green) and $C=2$ (cyan) and the orthogonal curves at $x\_0 \in \{ 0.5, 1, 1.5, 2 \}$.
[](https://i.stack.imgur.com/Du6aU.png) | You have $\frac{4y^3x^5\frac{dy}{dx}- 5y^4x^4}{x^{10}}dx$. This is wrong. There should be no "dx" at the end and it should be an equation, equal to 0:
$\frac{4y^3x^5\frac{dy}{dx}- 5y^4x^4}{x^{10}}= 0$
Multiplying both sides by the $x^{10}$, $4y^3x^5\frac{dy}{dx}- 5y^4x^4= 0$ so $4y^3x^5\frac{dy}{dx}= 5y^4x^4$ and $\frac{dy}{dx}= \frac{5y^4x^4}{4y^3x^5}= \frac{5y}{4x}$.
The orthogonal complement is then given by $\frac{dy}{dx}= -\frac{4x}{5y}$. |
1,457,884 | Original equation $$y^4=Cx^5$$
Ok my issue is that i am not sure how I would continue after taking the derivative. $$\frac{y^4}{x^5}=C$$
$$\frac{4y^3x^5\frac{dy}{dx}-5y^4x^4}{x^{10}}dx$$ I am not sure how I would continue to seperate the variable to be able to take the integral to the find the orthogonal trjectory. | 2015/09/30 | [
"https://math.stackexchange.com/questions/1457884",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272342/"
] | For the family of curves $y(x, C)$ where
$$
y^4 = C \, x^5
$$
and $C$ is a constant, we want to find the orthogonal curves $z(x, C)$.
$y$ and $z$ should intersect at $x\_0$, thus
$$
y(x\_0) = z(x\_0) \quad (\*)
$$
and if $y$ has the tangent
$$
T(x) = y(x\_0) + y'(x\_0)\, x
$$
at the point $x\_0$ then $z$ should have an orthogonal tangent there
$$
U(x) = z(x\_0) + z'(x\_0)\, x
$$
Using the scalar product we get the condition for orthogonal tangent vectors
$$
0 = (1, T'(x\_0)) \cdot (1, U'(x\_0)) = 1 + T'(x\_0) U'(x\_0) \Rightarrow \\
U'(x\_0) = - \frac{1}{T'(x\_0)}
$$
and this means
$$
z'(x\_0) = - \frac{1}{y'(x\_0)} \quad (\*\*)
$$
Solving for $y$ and differentiating, we get
$$
y = (C \, x^5)^{1/4} \Rightarrow \\
y' = \frac{5}{4} (C \, x)^{1/4}
$$
and therefore
$$
z' = - \frac{4}{5} (C \, x)^{-1/4}
$$
Integrating gives
$$
z = -\frac{16}{15} C^{-1/4} \, x^{3/4} + D
$$
with an integration constant $D$ such that equation $(\*)$ holds:
$$
(C \, x\_0^5)^{1/4} = -\frac{16}{15} C^{-1/4} \, x\_0^{3/4} + D \Rightarrow \\
D = (C \, x\_0^5)^{1/4} + \frac{16}{15} C^{-1/4} \, x\_0^{3/4}
$$
which gives
$$
z = -\frac{16}{15} C^{-1/4} \, (x^{3/4} - x\_0^{3/4}) + (C \, x\_0^5)^{1/4}
$$
Here is the positive part of the curve for $C=1$ (green) and $C=2$ (cyan) and the orthogonal curves at $x\_0 \in \{ 0.5, 1, 1.5, 2 \}$.
[](https://i.stack.imgur.com/Du6aU.png) | Using Quotient Rule to benefit
$$ \dfrac{y^4}{x^5} = \dfrac{4 y^3 y^{'}}{5 x^4}
\rightarrow \dfrac{y}{x} = \dfrac{4 y^{'}}{5} $$
To obtain orthogonal trajectory differential equation we replace the derivative by its negative reciprocal
$$ \dfrac{y}{x} = \dfrac{-4 }{5y^{'}} $$ Re-arrange
$$ 5 \,y\, dy + 4\ x \,dx =0 $$ Integrate
$$ \dfrac {5 y^2}{2} + 2 x^2 = c^2. $$
It is convenient to handle $ \dfrac{P}{Q} =\dfrac{P'}{Q'} $ for quotients. In fact also useful as $ \dfrac{P}{Q} =-\dfrac{P'}{Q'} $ for products. |
28,164,626 | How layout of a data in memory effects on algorithm performance?
For example merge sort is know for it computational complexity of O(n log n).
But in real world machine that processing algorithm will load/unload blocks of memory into CPU caches / CPU registers and spend auxiliary time on it.
Elements of collection to be sorted could be very scattered throughout the memory, and I wonder it will cause in slower performance vs sorting over gathered together elements.
Is in necessary to take into account how collections are really stores the data in memory? | 2015/01/27 | [
"https://Stackoverflow.com/questions/28164626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/675096/"
] | 1. In terms of big O notation - no. The time you read each block from
RAM to cpu cache is bounded by some constant, let it be `C`, so even
if you need to load each element in every iteration from RAM to
cache, you are going to need `O(C*nlogn)` time, but since `C` is
constant - it remains `O(nlogn)` time complexity.
2. In real world applications, especially when dealing with real-time apps, cache performance could be indeed a factor, and should be considered, so the order of accessing data, could matter. This is one of the reasons why quicksort is usually regarded as "faster" - it tends to have nice cache performance.
In addition - there are some algorithms that are developed to enjoy the "best of two worlds" - both `O(nlogn)` worst case with better constants, such as [Timsort](http://en.wikipedia.org/wiki/Timsort).
However, as rule of thumb, you should usually first implement the "easy way", then benchmark to see if it's fast enough, profile if it's not - and optimize the bottleneck. If you'll try to optimize every piece of your code for best cache performance - you will probably never finish writing it. | Profiling, profiling, profiling.
Modern computer architectures have become so complicated that accurate predictions on the running time have become impossible. You should prefer an experimental approach.
Also note that running times are no more deterministic and you should resort to statistical methods.
Architecture killed the algorithmician. |
28,164,626 | How layout of a data in memory effects on algorithm performance?
For example merge sort is know for it computational complexity of O(n log n).
But in real world machine that processing algorithm will load/unload blocks of memory into CPU caches / CPU registers and spend auxiliary time on it.
Elements of collection to be sorted could be very scattered throughout the memory, and I wonder it will cause in slower performance vs sorting over gathered together elements.
Is in necessary to take into account how collections are really stores the data in memory? | 2015/01/27 | [
"https://Stackoverflow.com/questions/28164626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/675096/"
] | 1. In terms of big O notation - no. The time you read each block from
RAM to cpu cache is bounded by some constant, let it be `C`, so even
if you need to load each element in every iteration from RAM to
cache, you are going to need `O(C*nlogn)` time, but since `C` is
constant - it remains `O(nlogn)` time complexity.
2. In real world applications, especially when dealing with real-time apps, cache performance could be indeed a factor, and should be considered, so the order of accessing data, could matter. This is one of the reasons why quicksort is usually regarded as "faster" - it tends to have nice cache performance.
In addition - there are some algorithms that are developed to enjoy the "best of two worlds" - both `O(nlogn)` worst case with better constants, such as [Timsort](http://en.wikipedia.org/wiki/Timsort).
However, as rule of thumb, you should usually first implement the "easy way", then benchmark to see if it's fast enough, profile if it's not - and optimize the bottleneck. If you'll try to optimize every piece of your code for best cache performance - you will probably never finish writing it. | >
> How layout of a data in memory effects on algorithm performance?
>
>
>
Layout is very important especially for large amount of data because access to the main memory is still expensive even for modern CPU:
<http://mechanical-sympathy.blogspot.ru/2013/02/cpu-cache-flushing-fallacy.html>
And your algo may spend much time on each cache miss:
<http://mechanical-sympathy.blogspot.ru/2012/08/memory-access-patterns-are-important.html>
Moreover, now there is a special area in Computer Science called Cache-friendly data structures and algos. See, for example, just googled:
<http://www.cc.gatech.edu/~bader/COURSES/UNM/ece637-Fall2003/papers/LFN02.pdf>
etc etc |
28,164,626 | How layout of a data in memory effects on algorithm performance?
For example merge sort is know for it computational complexity of O(n log n).
But in real world machine that processing algorithm will load/unload blocks of memory into CPU caches / CPU registers and spend auxiliary time on it.
Elements of collection to be sorted could be very scattered throughout the memory, and I wonder it will cause in slower performance vs sorting over gathered together elements.
Is in necessary to take into account how collections are really stores the data in memory? | 2015/01/27 | [
"https://Stackoverflow.com/questions/28164626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/675096/"
] | Profiling, profiling, profiling.
Modern computer architectures have become so complicated that accurate predictions on the running time have become impossible. You should prefer an experimental approach.
Also note that running times are no more deterministic and you should resort to statistical methods.
Architecture killed the algorithmician. | >
> How layout of a data in memory effects on algorithm performance?
>
>
>
Layout is very important especially for large amount of data because access to the main memory is still expensive even for modern CPU:
<http://mechanical-sympathy.blogspot.ru/2013/02/cpu-cache-flushing-fallacy.html>
And your algo may spend much time on each cache miss:
<http://mechanical-sympathy.blogspot.ru/2012/08/memory-access-patterns-are-important.html>
Moreover, now there is a special area in Computer Science called Cache-friendly data structures and algos. See, for example, just googled:
<http://www.cc.gatech.edu/~bader/COURSES/UNM/ece637-Fall2003/papers/LFN02.pdf>
etc etc |
2,515,706 | I'm trying to solve this problem:
You have two urns. The first urn contains a red ball and two white balls. The second urn contains five white balls. We draw one ball from each urn and exchange them. What is the probability that the red ball is in the first urn after $n$ times?
I think that I have to use the law of total probability. But I don't know how.
Thanks for any help you can provide. | 2017/11/11 | [
"https://math.stackexchange.com/questions/2515706",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/501853/"
] | \begin{align}
\lim\_{x\to\infty}\frac{(x^{\sqrt 2}+1)^{\sqrt 2}}{x^2+1} &=\lim\_{x\to\infty}\frac{x^2\left(1+x^{-\sqrt 2}\right)^{\sqrt 2}}{x^2 \left(1+\frac{1}{x^2}\right)}\\
& =\lim\_{x\to\infty}\frac{\left(1+\frac 1{x^{\sqrt 2}}\right)^{\sqrt 2}}{\left(1+\frac{1}{x^2}\right)}\\
&=1
\end{align}
Can you see how? | You shouldn't need to apply L'hopital's 4 times; after two applications the denominator will be a constant function and it should be easy to evaluate. |
2,515,706 | I'm trying to solve this problem:
You have two urns. The first urn contains a red ball and two white balls. The second urn contains five white balls. We draw one ball from each urn and exchange them. What is the probability that the red ball is in the first urn after $n$ times?
I think that I have to use the law of total probability. But I don't know how.
Thanks for any help you can provide. | 2017/11/11 | [
"https://math.stackexchange.com/questions/2515706",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/501853/"
] | \begin{align}
\lim\_{x\to\infty}\frac{(x^{\sqrt 2}+1)^{\sqrt 2}}{x^2+1} &=\lim\_{x\to\infty}\frac{x^2\left(1+x^{-\sqrt 2}\right)^{\sqrt 2}}{x^2 \left(1+\frac{1}{x^2}\right)}\\
& =\lim\_{x\to\infty}\frac{\left(1+\frac 1{x^{\sqrt 2}}\right)^{\sqrt 2}}{\left(1+\frac{1}{x^2}\right)}\\
&=1
\end{align}
Can you see how? | Set $x=1/t$ and compute instead
$$
\lim\_{t\to0^+}
\frac{\left(\dfrac{1}{\mathstrut t^{\sqrt{2}}}+1\right)^{\!\sqrt{2}}}{\dfrac{1}{t^2}+1}
=\lim\_{t\to0^+}\frac{(1+t^{\sqrt{2}})^{\sqrt{2}}}{1+t^2}
$$ |
73,415,016 | Suppose I have the following function that asks for 2 numbers and adds them.
```
def sum():
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
return a + b
```
Also I have two variables:
```
first_number = 2
second_number = 4
```
Considering that I can't copy paste the values of variable or change the function and the variables I want to fill in the values of these variables into the `sum` function. So, I was trying to do this by creating a function like `input_values` that could take the function and the variables as arguments and return the output of the function entered in it as an argument after imputing the variable values in it. I am working in a **jupyter notebook** and not able to understand how to build this function. Or is it possible even. Please help. The resultant function should be defined something like following:
```
def input_values(func,var1, var2):
#The computation should be held here.
```
It should be called like this:
```
input_values(func=sum(), var1=first_number,var2=second_number)
```
Again specifying, the **`input_values`** should follow the following algo.
1. Initiate the function given to it(in this case it is the `sum` function)
2. When the `sum` function ask to enter the first value from user, fill the value of `var1` in it and somehow proceed.
3. Again, when it asks to enter the other number, enter the value of `var2` in it and proceed.
4. When the given function(`sum`) is executed, return its value. | 2022/08/19 | [
"https://Stackoverflow.com/questions/73415016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17040733/"
] | Solution:
```
from bs4 import BeautifulSoup
html = """<h1 onclick="alert('Hello')">Click</h1>"""
a = BeautifulSoup(html,'html.parser')
for tag in a.find_all():
if 'onclick' in tag.attrs:
tag.attrs.pop('onclick')
print(a)
#<h1>Click</h1>
``` | I think you want something as follows:
```
from bs4 import BeautifulSoup
html = '<h1 onclick="alert(\'Hello\')">Click</h1>'
soup = BeautifulSoup(html)
print(soup)
# <html><body><h1 onclick="alert('Hello')">Click</h1></body></html>
# get h1
h1 = soup.h1
print(h1.attrs)
# {'onclick': "alert('Hello')"}
# so, we simply want to reset the attrs to an empty dict:
h1.attrs = {}
print(h1)
# <h1>Click</h1>
``` |
25,918,932 | I have a line that looks like the following, which I am viewing in vim.
```
0,0,0,1.791759,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5.278115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
```
It is from a feature vector file, each row is an instance and each column is the feature value for that feature number. I would like to figure out which feature number 5.27 corresponds to. I know the
```
s/,//gn
```
will count the number of commas in the line, but how do I restrict the command to count the number of commas in the line up to the columns with the number 5.27?
I have seen these two posts that seem relevant but cannot seem to piece them together: [How to compute the number of times word appeared in a file or in some range](https://stackoverflow.com/questions/1398989/vim-how-to-compute-the-number-of-times-word-appeared-in-a-file-or-in-some-range) and [Search and replace in a range of line and column](https://stackoverflow.com/questions/3847018/search-and-replace-in-a-range-of-line-and-column) | 2014/09/18 | [
"https://Stackoverflow.com/questions/25918932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2816571/"
] | ```
s/,\ze.*5\.27//gn
```
The interesting part is the `\ze` which sets the end of the match. See `:h /\ze` for more information | try this
```
s/,.\{-}5.27//gn
```
it should work. |
25,918,932 | I have a line that looks like the following, which I am viewing in vim.
```
0,0,0,1.791759,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5.278115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
```
It is from a feature vector file, each row is an instance and each column is the feature value for that feature number. I would like to figure out which feature number 5.27 corresponds to. I know the
```
s/,//gn
```
will count the number of commas in the line, but how do I restrict the command to count the number of commas in the line up to the columns with the number 5.27?
I have seen these two posts that seem relevant but cannot seem to piece them together: [How to compute the number of times word appeared in a file or in some range](https://stackoverflow.com/questions/1398989/vim-how-to-compute-the-number-of-times-word-appeared-in-a-file-or-in-some-range) and [Search and replace in a range of line and column](https://stackoverflow.com/questions/3847018/search-and-replace-in-a-range-of-line-and-column) | 2014/09/18 | [
"https://Stackoverflow.com/questions/25918932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2816571/"
] | Select the wanted area with visual mode and do
```
:s/\v%V%(,)//gn
```
`\v` enables us to escape less operators with `\`
`%V` limits the search to matches that start inside the visual selection
`%()` keeps the search together if you include alternations with `|`
It's not pretty but it works. See help files for `/\v`, `\%V` and `\%(`
There are also several versions of a plugin called vis.vim, which offers easier commands that aim to do just the above. However I haven't gotten any of them to work so I'll not comment on that further. | try this
```
s/,.\{-}5.27//gn
```
it should work. |
25,918,932 | I have a line that looks like the following, which I am viewing in vim.
```
0,0,0,1.791759,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5.278115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
```
It is from a feature vector file, each row is an instance and each column is the feature value for that feature number. I would like to figure out which feature number 5.27 corresponds to. I know the
```
s/,//gn
```
will count the number of commas in the line, but how do I restrict the command to count the number of commas in the line up to the columns with the number 5.27?
I have seen these two posts that seem relevant but cannot seem to piece them together: [How to compute the number of times word appeared in a file or in some range](https://stackoverflow.com/questions/1398989/vim-how-to-compute-the-number-of-times-word-appeared-in-a-file-or-in-some-range) and [Search and replace in a range of line and column](https://stackoverflow.com/questions/3847018/search-and-replace-in-a-range-of-line-and-column) | 2014/09/18 | [
"https://Stackoverflow.com/questions/25918932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2816571/"
] | ```
s/,\ze.*5\.27//gn
```
The interesting part is the `\ze` which sets the end of the match. See `:h /\ze` for more information | Select the wanted area with visual mode and do
```
:s/\v%V%(,)//gn
```
`\v` enables us to escape less operators with `\`
`%V` limits the search to matches that start inside the visual selection
`%()` keeps the search together if you include alternations with `|`
It's not pretty but it works. See help files for `/\v`, `\%V` and `\%(`
There are also several versions of a plugin called vis.vim, which offers easier commands that aim to do just the above. However I haven't gotten any of them to work so I'll not comment on that further. |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | Return a new [`ReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/ms132474.aspx):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
```
This is a wrapper for the list and the type is explicitly a read only type.
As @Freed notes, this is not thread safe, as it is only a wrapper and the list can change within the `Foo` class.
For better thread safety, make a copy before returning it (though if this is a requirement you should design the class for that to begin with):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
``` | how about
```
return new List<Bar>(_myList);
```
would that work?
**Sorry - too slow ;)** |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | If you want to make sure that a collection of elements cannot be modified, use a `ReadOnlyCollection` to communicate this intent.
Alternatively, you could instance a new list and return the elements in that new list. Then, your class does not have to care whether that list is modified or not. | You might want to consider `ReadOnlyCollection<T>` - see the answers to [Best practice when returning an array of values (.NET)](https://stackoverflow.com/questions/570083/best-practice-when-returning-an-array-of-values-net) |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | Return a new [`ReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/ms132474.aspx):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
```
This is a wrapper for the list and the type is explicitly a read only type.
As @Freed notes, this is not thread safe, as it is only a wrapper and the list can change within the `Foo` class.
For better thread safety, make a copy before returning it (though if this is a requirement you should design the class for that to begin with):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
``` | You might want to consider `ReadOnlyCollection<T>` - see the answers to [Best practice when returning an array of values (.NET)](https://stackoverflow.com/questions/570083/best-practice-when-returning-an-array-of-values-net) |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | Return a new [`ReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/ms132474.aspx):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
```
This is a wrapper for the list and the type is explicitly a read only type.
As @Freed notes, this is not thread safe, as it is only a wrapper and the list can change within the `Foo` class.
For better thread safety, make a copy before returning it (though if this is a requirement you should design the class for that to begin with):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
``` | If you want to make sure that a collection of elements cannot be modified, use a `ReadOnlyCollection` to communicate this intent.
Alternatively, you could instance a new list and return the elements in that new list. Then, your class does not have to care whether that list is modified or not. |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | If you want to make sure that a collection of elements cannot be modified, use a `ReadOnlyCollection` to communicate this intent.
Alternatively, you could instance a new list and return the elements in that new list. Then, your class does not have to care whether that list is modified or not. | how about
```
return new List<Bar>(_myList);
```
would that work?
**Sorry - too slow ;)** |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | If you want to make sure that a collection of elements cannot be modified, use a `ReadOnlyCollection` to communicate this intent.
Alternatively, you could instance a new list and return the elements in that new list. Then, your class does not have to care whether that list is modified or not. | You could use the [AsReadOnly](http://msdn.microsoft.com/en-us/library/e78dcd75.aspx) extension |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | the real problem is not about a copy of your private `_myList`, instead it would be: do you hand out a copy of the items as well?
for returning a copy of the list, you have several options
* `ReadOnlyCollection<T>`
* `IEnumerable<T>` (propably a real conversion, otherwise the attacker could cast back to a `List<T>` on the outside)
* a copy via `.ToList()`
* calling the ctor of `List<T>` with the private list
i'm not that fan of `ReadOnlyCollection<T>` as it just strips the ability for the consumer to add and delete something, but the connection to the private list is not cut. so when you change your private list, it affects the outhanded readonly-collection... which might be a bad thing!
i suggest to choose an option, where the return-value is fully isolated of your internal list and items! | You might want to consider `ReadOnlyCollection<T>` - see the answers to [Best practice when returning an array of values (.NET)](https://stackoverflow.com/questions/570083/best-practice-when-returning-an-array-of-values-net) |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | Return a new [`ReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/ms132474.aspx):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
```
This is a wrapper for the list and the type is explicitly a read only type.
As @Freed notes, this is not thread safe, as it is only a wrapper and the list can change within the `Foo` class.
For better thread safety, make a copy before returning it (though if this is a requirement you should design the class for that to begin with):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
``` | the real problem is not about a copy of your private `_myList`, instead it would be: do you hand out a copy of the items as well?
for returning a copy of the list, you have several options
* `ReadOnlyCollection<T>`
* `IEnumerable<T>` (propably a real conversion, otherwise the attacker could cast back to a `List<T>` on the outside)
* a copy via `.ToList()`
* calling the ctor of `List<T>` with the private list
i'm not that fan of `ReadOnlyCollection<T>` as it just strips the ability for the consumer to add and delete something, but the connection to the private list is not cut. so when you change your private list, it affects the outhanded readonly-collection... which might be a bad thing!
i suggest to choose an option, where the return-value is fully isolated of your internal list and items! |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | the real problem is not about a copy of your private `_myList`, instead it would be: do you hand out a copy of the items as well?
for returning a copy of the list, you have several options
* `ReadOnlyCollection<T>`
* `IEnumerable<T>` (propably a real conversion, otherwise the attacker could cast back to a `List<T>` on the outside)
* a copy via `.ToList()`
* calling the ctor of `List<T>` with the private list
i'm not that fan of `ReadOnlyCollection<T>` as it just strips the ability for the consumer to add and delete something, but the connection to the private list is not cut. so when you change your private list, it affects the outhanded readonly-collection... which might be a bad thing!
i suggest to choose an option, where the return-value is fully isolated of your internal list and items! | how about
```
return new List<Bar>(_myList);
```
would that work?
**Sorry - too slow ;)** |
4,104,838 | Are there any guidelines to return an object of a class? I have a class which has a List and a method which do something with the list and returns that list:
```
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
```
I don't think this is a good way to return the list, because now the calling method can modify the list and thus the list in the object Foo is updated. This can lead to unexpected and unwanted behaviour.
How do you handle this kind of situations? Do you make a copy of the object (in this case the list) and return that object, or.. ? Are there any best practices or tricks? | 2010/11/05 | [
"https://Stackoverflow.com/questions/4104838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] | Return a new [`ReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/ms132474.aspx):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
```
This is a wrapper for the list and the type is explicitly a read only type.
As @Freed notes, this is not thread safe, as it is only a wrapper and the list can change within the `Foo` class.
For better thread safety, make a copy before returning it (though if this is a requirement you should design the class for that to begin with):
```
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
``` | You could use the [AsReadOnly](http://msdn.microsoft.com/en-us/library/e78dcd75.aspx) extension |
62,148,036 | I'm trying to deploy a Laravel project to my server with this specs:
* OS: CentOS Linux release 7.8.2003
* Nodejs: 13.14.0
* npm: 6.14.5
* 1 CPU
* 4GB Ram
Everything was fine but a step, as I use ReactJS with Laravel I have to run npm run dev to let webpack build my assets files. (This is just the step to build the view, it run fine on my local machine and my friend's, with the different of os, MacOS and Ubuntu).
But when I run `npm run dev` the system either hang like this
```
[spyets@vultr current]$ npm run dev
> @ dev /home/spyets/public_html/yamlive/releases/3
> npm run development
> @ development /home/spyets/public_html/yamlive/releases/3
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
```
[](https://i.stack.imgur.com/wMmEa.jpg)
or show this error
```
Exit Code: 254 (Unknown error)
Host Name: development
================
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: Resource temporarily unavailable
```
[](https://i.stack.imgur.com/312gk.jpg)
I don't know if this give you more information, I run a vtop (a terminal management tool?) and every time I run the `npm run dev` command, `vtop` just crashed
**What I tried**:
1. reboot the server
2. reinstall nodejs ( I install nodejs directly with `yum` not using `nvm` )
3. upgrade nodejs from 12.20.2 to 13.14.0 ( as it currently in 13.14.0 )
I'm new to Centos and deployment.
**Edit**
* I also tried to make swapfile and add 3GB of swap
* I tried remove node\_modules and reinstall with npm install multiple times
* Running both `npm run dev` and `npm run prod` resulted in failed or crash | 2020/06/02 | [
"https://Stackoverflow.com/questions/62148036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5934288/"
] | There is no straight-forward migration path from Silverlight to any technology, despite probably to WPF to a degree, but as you mentioned that you want to run in the browser, probably the best way today is to use [Blazor](https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor), which just got its first official release, and Microsoft is heavily investing in it right now.
On top of that, the French company Userware [created](https://visualstudiomagazine.com/articles/2020/03/09/opensilver.aspx?m=1) the [OpenSilver](https://www.opensilver.net/) platform, which is a Silverlight replacement based on WebAssembly and Blazor, compatible with all major browsers. They even [provide](https://opensilver.net/announcements/introducing-opensilver.aspx) [professional migration services](https://opensilver.net/migrate/upload-xap.aspx) based on this approach.
There is also rich ecosystem already evolved, with a lot of third-party UI components vendors (like [Telerik](https://www.telerik.com/blazor-ui), [DevExpress](https://www.devexpress.com/blazor-razor-components/), [Radzen](https://blazor.radzen.com/), etc.). | At Mobilize.Net we have a migration tool that converts the client side XAML and C# to TypeScript using Angular, Kendo UI, HTML, and CSS. It supports C# constructs like generics and interfaces.
You can watch a [live stream from Twitch here](https://mobilize.wistia.com/medias/dosg7opq0) This is an approach most suitable for very large complex SL web apps that would be too time consuming or expensive to rewrite into a pure native approach. |
61,659,128 | I got an array like this:
```
rows: [
[
{ title: 'Test', value: 1 },
{ title: 'Test2', value: 2 },
{ title: 'Test3', value: 3 },
],
[
{ title: 'Test4', value: 4 },
{ title: 'Test5', value: 5 },
],
[
{ title: 'Test6', value: 6 },
{ title: 'Test7', value: 7 },
]
]
```
Now I'd like to unset the key `value` in each nested object.
At the moment I am doing:
```
rows.map(function(fields){
return fields.map(function(field){
field.value = '';
return field;
})
});
```
Do you see a better way to do this? | 2020/05/07 | [
"https://Stackoverflow.com/questions/61659128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7510971/"
] | Probably not modifying existing objects could be a better practice:
```
rows = rows.map(fields => {
return fields.map(field => {
return {...field, value: ''};
})
});
``` | You can use `delete` to explicitly remove a property and its value. No map needed:
```js
var ob = {foo:'bar',fizz:'buzz'};
console.log(ob); // Object { foo: "bar", fizz: "buzz" }
delete ob.fizz;
console.log(ob); // Object { foo: "bar" }
``` |
61,659,128 | I got an array like this:
```
rows: [
[
{ title: 'Test', value: 1 },
{ title: 'Test2', value: 2 },
{ title: 'Test3', value: 3 },
],
[
{ title: 'Test4', value: 4 },
{ title: 'Test5', value: 5 },
],
[
{ title: 'Test6', value: 6 },
{ title: 'Test7', value: 7 },
]
]
```
Now I'd like to unset the key `value` in each nested object.
At the moment I am doing:
```
rows.map(function(fields){
return fields.map(function(field){
field.value = '';
return field;
})
});
```
Do you see a better way to do this? | 2020/05/07 | [
"https://Stackoverflow.com/questions/61659128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7510971/"
] | ```js
function deleteKeyFromObject(inputObject) {
for (let[currentObjectKey,currentObjectValue] of Object.entries(inputObject)) {
if (currentObjectKey === 'value') {
delete inputObject.value;
} else if (Array.isArray(currentObjectValue)) {
deleteObjectFromArray(currentObjectValue);
} else if (typeof currentObjectValue === 'object') {
deleteKeyFromObject(currentObjectValue);
}
}
;
}
function deleteObjectFromArray(inputArray) {
for (let currentIndex = 0; currentIndex < inputArray.length; currentIndex++) {
let currentElement = inputArray[currentIndex];
if (Array.isArray(currentElement)) {
deleteObjectFromArray(currentElement);
} else if (typeof currentElement === 'object') {
deleteKeyFromObject(currentElement);
}
}
;
}
var data1 = {
rows: [[{
title: 'Test',
value: 1
}, {
title: 'Test2',
value: 2
}, {
title: 'Test3',
value: 3
}, ], [{
title: 'Test4',
value: 4
}, {
title: 'Test5',
value: 5
}, ], [{
title: 'Test6',
value: 6
}, {
title: 'Test7',
value: 7
}, ]]
}
deleteKeyFromObject(data1);
console.log(data1);
``` | You can use `delete` to explicitly remove a property and its value. No map needed:
```js
var ob = {foo:'bar',fizz:'buzz'};
console.log(ob); // Object { foo: "bar", fizz: "buzz" }
delete ob.fizz;
console.log(ob); // Object { foo: "bar" }
``` |
61,659,128 | I got an array like this:
```
rows: [
[
{ title: 'Test', value: 1 },
{ title: 'Test2', value: 2 },
{ title: 'Test3', value: 3 },
],
[
{ title: 'Test4', value: 4 },
{ title: 'Test5', value: 5 },
],
[
{ title: 'Test6', value: 6 },
{ title: 'Test7', value: 7 },
]
]
```
Now I'd like to unset the key `value` in each nested object.
At the moment I am doing:
```
rows.map(function(fields){
return fields.map(function(field){
field.value = '';
return field;
})
});
```
Do you see a better way to do this? | 2020/05/07 | [
"https://Stackoverflow.com/questions/61659128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7510971/"
] | ```js
function deleteKeyFromObject(inputObject) {
for (let[currentObjectKey,currentObjectValue] of Object.entries(inputObject)) {
if (currentObjectKey === 'value') {
delete inputObject.value;
} else if (Array.isArray(currentObjectValue)) {
deleteObjectFromArray(currentObjectValue);
} else if (typeof currentObjectValue === 'object') {
deleteKeyFromObject(currentObjectValue);
}
}
;
}
function deleteObjectFromArray(inputArray) {
for (let currentIndex = 0; currentIndex < inputArray.length; currentIndex++) {
let currentElement = inputArray[currentIndex];
if (Array.isArray(currentElement)) {
deleteObjectFromArray(currentElement);
} else if (typeof currentElement === 'object') {
deleteKeyFromObject(currentElement);
}
}
;
}
var data1 = {
rows: [[{
title: 'Test',
value: 1
}, {
title: 'Test2',
value: 2
}, {
title: 'Test3',
value: 3
}, ], [{
title: 'Test4',
value: 4
}, {
title: 'Test5',
value: 5
}, ], [{
title: 'Test6',
value: 6
}, {
title: 'Test7',
value: 7
}, ]]
}
deleteKeyFromObject(data1);
console.log(data1);
``` | Probably not modifying existing objects could be a better practice:
```
rows = rows.map(fields => {
return fields.map(field => {
return {...field, value: ''};
})
});
``` |
19,468,780 | I have 2 tables: `Income` (`InvoiceDate, TotalAmount`) and `Outcome` (`ExpenseDate, TotalAmount`).
Suppose that I have data for each column as below:
`Income`:
```
| INVOICEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-16 | 22000 |
| 2013-10-17 | 14400 |
| 2013-10-18 | 4488 |
```
`Outcome`:
```
| EXPENSEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-25 | 15 |
```
I want to merge these 2 tables to show as below:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| 2013-10-25 | 0 | 15 |
| 2013-10-16 | 22000 | 0 |
| 2013-10-17 | 14400 | 0 |
| 2013-10-18 | 4488 | 0 |
```
However when I run my T-SQL, It will show like this instead:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| (null) | (null) | 15 |
| 2013-10-16 | 22000 | (null) |
| 2013-10-17 | 14400 | (null) |
| 2013-10-18 | 4488 | (null) |
```
This is my T-SQL:
```
SELECT
CASE (income.InvoiceDate)
WHEN NULL THEN Outcome.expenseDate
ELSE income.InvoiceDate
END AS [Date],
CASE (income.TotalAmount)
WHEN NULL THEN 0
ELSE income.TotalAmount
END AS Income,
CASE (Outcome.TotalAmount)
WHEN NULL THEN 0
ELSE Outcome.TotalAmount
END AS Outcome
FROM
Outcome
FULL OUTER JOIN
income ON Outcome.expenseDate = income.InvoiceDate
WHERE
NOT (
Outcome.TotalAmount = 0
AND income.TotalAmount = 0
)
```
You can test this SQL at <http://sqlfiddle.com/#!6/3589f/1>
Does anyone know what's wrong with my T-SQL?
Thank You!
Pengan | 2013/10/19 | [
"https://Stackoverflow.com/questions/19468780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450738/"
] | `this.lexic` is evaluated to `null`. Note that `this.lexis` doesn't point to the constructor's local `lexic` variable, but to the instance's one.
*If you want to* add the String to the constructor's `lexic` variable, just get rid of the `this` keyword:
```
lexic.add(word);
``` | More than likely you have another variable named `lexic` as a class instance variable. (The above code would not compile if this is not the case)
Therefore its likely you're shadowing the `result` variable. Replace
```
Set<String> lexic = new TreeSet<String>();
```
with
```
lexic = new TreeSet<String>();
``` |
19,468,780 | I have 2 tables: `Income` (`InvoiceDate, TotalAmount`) and `Outcome` (`ExpenseDate, TotalAmount`).
Suppose that I have data for each column as below:
`Income`:
```
| INVOICEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-16 | 22000 |
| 2013-10-17 | 14400 |
| 2013-10-18 | 4488 |
```
`Outcome`:
```
| EXPENSEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-25 | 15 |
```
I want to merge these 2 tables to show as below:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| 2013-10-25 | 0 | 15 |
| 2013-10-16 | 22000 | 0 |
| 2013-10-17 | 14400 | 0 |
| 2013-10-18 | 4488 | 0 |
```
However when I run my T-SQL, It will show like this instead:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| (null) | (null) | 15 |
| 2013-10-16 | 22000 | (null) |
| 2013-10-17 | 14400 | (null) |
| 2013-10-18 | 4488 | (null) |
```
This is my T-SQL:
```
SELECT
CASE (income.InvoiceDate)
WHEN NULL THEN Outcome.expenseDate
ELSE income.InvoiceDate
END AS [Date],
CASE (income.TotalAmount)
WHEN NULL THEN 0
ELSE income.TotalAmount
END AS Income,
CASE (Outcome.TotalAmount)
WHEN NULL THEN 0
ELSE Outcome.TotalAmount
END AS Outcome
FROM
Outcome
FULL OUTER JOIN
income ON Outcome.expenseDate = income.InvoiceDate
WHERE
NOT (
Outcome.TotalAmount = 0
AND income.TotalAmount = 0
)
```
You can test this SQL at <http://sqlfiddle.com/#!6/3589f/1>
Does anyone know what's wrong with my T-SQL?
Thank You!
Pengan | 2013/10/19 | [
"https://Stackoverflow.com/questions/19468780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450738/"
] | More than likely you have another variable named `lexic` as a class instance variable. (The above code would not compile if this is not the case)
Therefore its likely you're shadowing the `result` variable. Replace
```
Set<String> lexic = new TreeSet<String>();
```
with
```
lexic = new TreeSet<String>();
``` | ```
this.lexic.add(word);
```
You are using this in constructor, that means, you are using the object during its creation. That is why you get NPE. remove this, it will work.
if you put filling part in a method also, that means
```
Set<String> lexic = new TreeSet<String>();
```
is also in same method, then also "this" will not work because "this" is not for local level variable. But in that case also, it will not give NPE but compiler error.
This code is working fine, you can check once :
```
public AnagramUserInput()
{
Set<String> result = new TreeSet<String>();
Set<String> lexic = new TreeSet<String>();
File lexicon = new File("output.txt");
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(lexicon));
String word;
while(((word = br.readLine()) != null)) {
lexic.add(word);//Exception is throwned right in this line
}
}catch(IOException exc) {
System.out.println(exc.toString());
System.exit(1);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(lexic);
}
```
just make sure, file is on proper location as required. |
19,468,780 | I have 2 tables: `Income` (`InvoiceDate, TotalAmount`) and `Outcome` (`ExpenseDate, TotalAmount`).
Suppose that I have data for each column as below:
`Income`:
```
| INVOICEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-16 | 22000 |
| 2013-10-17 | 14400 |
| 2013-10-18 | 4488 |
```
`Outcome`:
```
| EXPENSEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-25 | 15 |
```
I want to merge these 2 tables to show as below:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| 2013-10-25 | 0 | 15 |
| 2013-10-16 | 22000 | 0 |
| 2013-10-17 | 14400 | 0 |
| 2013-10-18 | 4488 | 0 |
```
However when I run my T-SQL, It will show like this instead:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| (null) | (null) | 15 |
| 2013-10-16 | 22000 | (null) |
| 2013-10-17 | 14400 | (null) |
| 2013-10-18 | 4488 | (null) |
```
This is my T-SQL:
```
SELECT
CASE (income.InvoiceDate)
WHEN NULL THEN Outcome.expenseDate
ELSE income.InvoiceDate
END AS [Date],
CASE (income.TotalAmount)
WHEN NULL THEN 0
ELSE income.TotalAmount
END AS Income,
CASE (Outcome.TotalAmount)
WHEN NULL THEN 0
ELSE Outcome.TotalAmount
END AS Outcome
FROM
Outcome
FULL OUTER JOIN
income ON Outcome.expenseDate = income.InvoiceDate
WHERE
NOT (
Outcome.TotalAmount = 0
AND income.TotalAmount = 0
)
```
You can test this SQL at <http://sqlfiddle.com/#!6/3589f/1>
Does anyone know what's wrong with my T-SQL?
Thank You!
Pengan | 2013/10/19 | [
"https://Stackoverflow.com/questions/19468780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450738/"
] | `this.lexic` is evaluated to `null`. Note that `this.lexis` doesn't point to the constructor's local `lexic` variable, but to the instance's one.
*If you want to* add the String to the constructor's `lexic` variable, just get rid of the `this` keyword:
```
lexic.add(word);
``` | The only problem I see here is
```
this.lexic.add(word); // this.lexic
```
Remove the `this`. Because the constructor instantiates the class. Even before the object is created, you're tryin to use `this`, which is wrong. |
19,468,780 | I have 2 tables: `Income` (`InvoiceDate, TotalAmount`) and `Outcome` (`ExpenseDate, TotalAmount`).
Suppose that I have data for each column as below:
`Income`:
```
| INVOICEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-16 | 22000 |
| 2013-10-17 | 14400 |
| 2013-10-18 | 4488 |
```
`Outcome`:
```
| EXPENSEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-25 | 15 |
```
I want to merge these 2 tables to show as below:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| 2013-10-25 | 0 | 15 |
| 2013-10-16 | 22000 | 0 |
| 2013-10-17 | 14400 | 0 |
| 2013-10-18 | 4488 | 0 |
```
However when I run my T-SQL, It will show like this instead:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| (null) | (null) | 15 |
| 2013-10-16 | 22000 | (null) |
| 2013-10-17 | 14400 | (null) |
| 2013-10-18 | 4488 | (null) |
```
This is my T-SQL:
```
SELECT
CASE (income.InvoiceDate)
WHEN NULL THEN Outcome.expenseDate
ELSE income.InvoiceDate
END AS [Date],
CASE (income.TotalAmount)
WHEN NULL THEN 0
ELSE income.TotalAmount
END AS Income,
CASE (Outcome.TotalAmount)
WHEN NULL THEN 0
ELSE Outcome.TotalAmount
END AS Outcome
FROM
Outcome
FULL OUTER JOIN
income ON Outcome.expenseDate = income.InvoiceDate
WHERE
NOT (
Outcome.TotalAmount = 0
AND income.TotalAmount = 0
)
```
You can test this SQL at <http://sqlfiddle.com/#!6/3589f/1>
Does anyone know what's wrong with my T-SQL?
Thank You!
Pengan | 2013/10/19 | [
"https://Stackoverflow.com/questions/19468780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450738/"
] | The only problem I see here is
```
this.lexic.add(word); // this.lexic
```
Remove the `this`. Because the constructor instantiates the class. Even before the object is created, you're tryin to use `this`, which is wrong. | ```
this.lexic.add(word);
```
You are using this in constructor, that means, you are using the object during its creation. That is why you get NPE. remove this, it will work.
if you put filling part in a method also, that means
```
Set<String> lexic = new TreeSet<String>();
```
is also in same method, then also "this" will not work because "this" is not for local level variable. But in that case also, it will not give NPE but compiler error.
This code is working fine, you can check once :
```
public AnagramUserInput()
{
Set<String> result = new TreeSet<String>();
Set<String> lexic = new TreeSet<String>();
File lexicon = new File("output.txt");
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(lexicon));
String word;
while(((word = br.readLine()) != null)) {
lexic.add(word);//Exception is throwned right in this line
}
}catch(IOException exc) {
System.out.println(exc.toString());
System.exit(1);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(lexic);
}
```
just make sure, file is on proper location as required. |
19,468,780 | I have 2 tables: `Income` (`InvoiceDate, TotalAmount`) and `Outcome` (`ExpenseDate, TotalAmount`).
Suppose that I have data for each column as below:
`Income`:
```
| INVOICEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-16 | 22000 |
| 2013-10-17 | 14400 |
| 2013-10-18 | 4488 |
```
`Outcome`:
```
| EXPENSEDATE | TOTALAMOUNT |
|-------------|-------------|
| 2013-10-25 | 15 |
```
I want to merge these 2 tables to show as below:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| 2013-10-25 | 0 | 15 |
| 2013-10-16 | 22000 | 0 |
| 2013-10-17 | 14400 | 0 |
| 2013-10-18 | 4488 | 0 |
```
However when I run my T-SQL, It will show like this instead:
```
| DATE | INCOME | OUTCOME |
|------------|--------|---------|
| (null) | (null) | 15 |
| 2013-10-16 | 22000 | (null) |
| 2013-10-17 | 14400 | (null) |
| 2013-10-18 | 4488 | (null) |
```
This is my T-SQL:
```
SELECT
CASE (income.InvoiceDate)
WHEN NULL THEN Outcome.expenseDate
ELSE income.InvoiceDate
END AS [Date],
CASE (income.TotalAmount)
WHEN NULL THEN 0
ELSE income.TotalAmount
END AS Income,
CASE (Outcome.TotalAmount)
WHEN NULL THEN 0
ELSE Outcome.TotalAmount
END AS Outcome
FROM
Outcome
FULL OUTER JOIN
income ON Outcome.expenseDate = income.InvoiceDate
WHERE
NOT (
Outcome.TotalAmount = 0
AND income.TotalAmount = 0
)
```
You can test this SQL at <http://sqlfiddle.com/#!6/3589f/1>
Does anyone know what's wrong with my T-SQL?
Thank You!
Pengan | 2013/10/19 | [
"https://Stackoverflow.com/questions/19468780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450738/"
] | `this.lexic` is evaluated to `null`. Note that `this.lexis` doesn't point to the constructor's local `lexic` variable, but to the instance's one.
*If you want to* add the String to the constructor's `lexic` variable, just get rid of the `this` keyword:
```
lexic.add(word);
``` | ```
this.lexic.add(word);
```
You are using this in constructor, that means, you are using the object during its creation. That is why you get NPE. remove this, it will work.
if you put filling part in a method also, that means
```
Set<String> lexic = new TreeSet<String>();
```
is also in same method, then also "this" will not work because "this" is not for local level variable. But in that case also, it will not give NPE but compiler error.
This code is working fine, you can check once :
```
public AnagramUserInput()
{
Set<String> result = new TreeSet<String>();
Set<String> lexic = new TreeSet<String>();
File lexicon = new File("output.txt");
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(lexicon));
String word;
while(((word = br.readLine()) != null)) {
lexic.add(word);//Exception is throwned right in this line
}
}catch(IOException exc) {
System.out.println(exc.toString());
System.exit(1);
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(lexic);
}
```
just make sure, file is on proper location as required. |
5,851 | I have a log file which contains a bunch of non visible control characters such as hex \u0003.
I would like to replace this using something like SED, but can't get the first part of the regex to match:
>
> /s/^E/some\_string
>
>
>
I am creating the ^E by pressing CTRL-V CTRL-0 CTRL-3 to create the special character, as read from the 'man ascii' page:
>
> 003 3 03 ETX
>
>
>
However, nothing matches this control character.
Any help appreciated! | 2011/01/14 | [
"https://unix.stackexchange.com/questions/5851",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/3793/"
] | This perl one-liner will do the job - beware, it will modify the file:
```
perl -i -pe 's#\x{0003}#some_string#g' /path/to/log/file
```
If you want to replace a number of characters with character codes between a specified range:
```
echo {A..Z} | perl -i -pe 's#[\x{0040}-\x{0047}]#P#g'
P P P P P P P H I J K L M N O P Q R S T U V W X Y Z
```
(*echo {A..Z}* produces a string of alphabetic characters in bash) | I'm not sure if I understand what you want, but if it is to substitute for occurrences of the successive hex bytes 0x00 0x03, this should work:
```
$ echo '0 61 20 00 03 0A' | xxd -r | sed 's/\x00\x03/test/g'
a test
``` |
5,851 | I have a log file which contains a bunch of non visible control characters such as hex \u0003.
I would like to replace this using something like SED, but can't get the first part of the regex to match:
>
> /s/^E/some\_string
>
>
>
I am creating the ^E by pressing CTRL-V CTRL-0 CTRL-3 to create the special character, as read from the 'man ascii' page:
>
> 003 3 03 ETX
>
>
>
However, nothing matches this control character.
Any help appreciated! | 2011/01/14 | [
"https://unix.stackexchange.com/questions/5851",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/3793/"
] | You can also use the `tr` command. For example:
To delete the control character:
```
tr -d '\033' < file
```
To replace the control character with another:
```
tr '\033' 'x' < file
```
If you are not sure what the value of the control character is, perform an octal dump and it will print it out:
```
$ cat file
hello
^[
world
$ od -b file
0000000 150 145 154 154 157 012 033 012 167 157 162 154 144 012
0000016
```
So the value of control character `^[` is `\033`. | I'm not sure if I understand what you want, but if it is to substitute for occurrences of the successive hex bytes 0x00 0x03, this should work:
```
$ echo '0 61 20 00 03 0A' | xxd -r | sed 's/\x00\x03/test/g'
a test
``` |
5,851 | I have a log file which contains a bunch of non visible control characters such as hex \u0003.
I would like to replace this using something like SED, but can't get the first part of the regex to match:
>
> /s/^E/some\_string
>
>
>
I am creating the ^E by pressing CTRL-V CTRL-0 CTRL-3 to create the special character, as read from the 'man ascii' page:
>
> 003 3 03 ETX
>
>
>
However, nothing matches this control character.
Any help appreciated! | 2011/01/14 | [
"https://unix.stackexchange.com/questions/5851",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/3793/"
] | This will replace all non-printable characters with a `#`
```
sed 's/[^[:print:]]/#/g' logfile
``` | I'm not sure if I understand what you want, but if it is to substitute for occurrences of the successive hex bytes 0x00 0x03, this should work:
```
$ echo '0 61 20 00 03 0A' | xxd -r | sed 's/\x00\x03/test/g'
a test
``` |
14,185,126 | Do you know any way / method to **take a photo in iOS** and saving it to camera Roll only with a simple button pressure without showing any preview?
I already know how to show the camera view but it show the preview of the image and the user need to click the take photo button to take the photo.
**In few Words:** the user click the button, the picture is taken, without previews nor double checks to take / save the photo.
I already found the `takePicture` method of `UIIMagePickerController` Class <http://developer.apple.com/library/ios/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/instm/UIImagePickerController/takePicture> | 2013/01/06 | [
"https://Stackoverflow.com/questions/14185126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531219/"
] | Set the `showsCameraControls`-Property to `NO`.
```
poc = [[UIImagePickerController alloc] init];
[poc setTitle:@"Take a photo."];
[poc setDelegate:self];
[poc setSourceType:UIImagePickerControllerSourceTypeCamera];
poc.showsCameraControls = NO;
```
You also have to add your own Controls as a custom view on the top of `poc.view`. But that is very simple and you can add your own UI-style by that way.
You receive the image-data as usually within the `imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:`
To take the photo, you call
```
[poc takePicture];
```
from your custom button.
Hope, that works for you. | Assuming you want a point-and-shoot method, you can create an AVSession and just call the UIImageWriteToSavedPhotosAlbum method.
Here is a link that goes into that exact process: <http://www.musicalgeometry.com/?p=1297>
It's also worth noting that your users need to have given the app access to their camera roll or you may experience issues saving the images. |
14,185,126 | Do you know any way / method to **take a photo in iOS** and saving it to camera Roll only with a simple button pressure without showing any preview?
I already know how to show the camera view but it show the preview of the image and the user need to click the take photo button to take the photo.
**In few Words:** the user click the button, the picture is taken, without previews nor double checks to take / save the photo.
I already found the `takePicture` method of `UIIMagePickerController` Class <http://developer.apple.com/library/ios/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/instm/UIImagePickerController/takePicture> | 2013/01/06 | [
"https://Stackoverflow.com/questions/14185126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531219/"
] | Assuming you want a point-and-shoot method, you can create an AVSession and just call the UIImageWriteToSavedPhotosAlbum method.
Here is a link that goes into that exact process: <http://www.musicalgeometry.com/?p=1297>
It's also worth noting that your users need to have given the app access to their camera roll or you may experience issues saving the images. | You need to design your own custom preview according to your size, on capture button pressed and call `buttonPressed` method and do stuff what you want
```
(void)buttonPressed:(UIButton *)sender {
NSLog(@" Capture Clicked");
[self.imagePicker takePicture];
//[NSTimer scheduledTimerWithTimeInterval:3.0f target:self
selector:@selector(timerFired:) userInfo:nil repeats:NO];
}
``` |
14,185,126 | Do you know any way / method to **take a photo in iOS** and saving it to camera Roll only with a simple button pressure without showing any preview?
I already know how to show the camera view but it show the preview of the image and the user need to click the take photo button to take the photo.
**In few Words:** the user click the button, the picture is taken, without previews nor double checks to take / save the photo.
I already found the `takePicture` method of `UIIMagePickerController` Class <http://developer.apple.com/library/ios/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/instm/UIImagePickerController/takePicture> | 2013/01/06 | [
"https://Stackoverflow.com/questions/14185126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531219/"
] | Assuming you want a point-and-shoot method, you can create an AVSession and just call the UIImageWriteToSavedPhotosAlbum method.
Here is a link that goes into that exact process: <http://www.musicalgeometry.com/?p=1297>
It's also worth noting that your users need to have given the app access to their camera roll or you may experience issues saving the images. | following is code that will take photo without showing preview screen. when i tried the accepted answer, which uses UIImagePickerController, the preview screen showed, then auto disappeared. with the code below, user taps 'takePhoto' button, and the devices takes photo with zero change to UI (in my app, i add a green check mark next to take photo button). the code below is from apple <https://developer.apple.com/LIBRARY/IOS/samplecode/AVCam/Introduction/Intro.html> with the 'extra functions' (that do not relate to taking still photo) commented out. thank you incmiko for suggesting this code in your answer [iOS take photo from camera without modalViewController](https://stackoverflow.com/questions/19386787/ios-take-photo-from-camera-without-modalviewcontroller).
updating code, 26 mar 2015:
to trigger snap photo:
```
[self snapStillImage:sender];
```
in .h file:
```
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
// include code below in header file, after #import and before @interface
// avfoundation copy paste code
static void * CapturingStillImageContext = &CapturingStillImageContext;
static void * RecordingContext = &RecordingContext;
static void * SessionRunningAndDeviceAuthorizedContext = &SessionRunningAndDeviceAuthorizedContext;
// avfoundation, include code below after @interface
// avf - Session management.
@property (nonatomic) dispatch_queue_t sessionQueue; // Communicate with the session and other session objects on this queue.
@property (nonatomic) AVCaptureSession *session;
@property (nonatomic) AVCaptureDeviceInput *videoDeviceInput;
@property (nonatomic) AVCaptureMovieFileOutput *movieFileOutput;
@property (nonatomic) AVCaptureStillImageOutput *stillImageOutput;
// avf - Utilities.
@property (nonatomic) UIBackgroundTaskIdentifier backgroundRecordingID;
@property (nonatomic, getter = isDeviceAuthorized) BOOL deviceAuthorized;
@property (nonatomic, readonly, getter = isSessionRunningAndDeviceAuthorized) BOOL sessionRunningAndDeviceAuthorized;
@property (nonatomic) BOOL lockInterfaceRotation;
@property (nonatomic) id runtimeErrorHandlingObserver;
```
in .m file:
```
#pragma mark - AV Foundation
- (BOOL)isSessionRunningAndDeviceAuthorized
{
return [[self session] isRunning] && [self isDeviceAuthorized];
}
+ (NSSet *)keyPathsForValuesAffectingSessionRunningAndDeviceAuthorized
{
return [NSSet setWithObjects:@"session.running", @"deviceAuthorized", nil];
}
// call following method from viewDidLoad
- (void)CreateAVCaptureSession
{
// Create the AVCaptureSession
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[self setSession:session];
// Check for device authorization
[self checkDeviceAuthorizationStatus];
// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue so that the main queue isn't blocked (which keeps the UI responsive).
dispatch_queue_t sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
[self setSessionQueue:sessionQueue];
dispatch_async(sessionQueue, ^{
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
NSError *error = nil;
AVCaptureDevice *videoDevice = [ViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionFront];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (error)
{
NSLog(@"%@", error);
}
if ([session canAddInput:videoDeviceInput])
{
[session addInput:videoDeviceInput];
[self setVideoDeviceInput:videoDeviceInput];
dispatch_async(dispatch_get_main_queue(), ^{
// Why are we dispatching this to the main queue?
// Because AVCaptureVideoPreviewLayer is the backing layer for AVCamPreviewView and UIView can only be manipulated on main thread.
// Note: As an exception to the above rule, it is not necessary to serialize video orientation changes on the AVCaptureVideoPreviewLayer’s connection with other session manipulation.
});
}
/* AVCaptureDevice *audioDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if (error)
{
NSLog(@"%@", error);
}
if ([session canAddInput:audioDeviceInput])
{
[session addInput:audioDeviceInput];
}
*/
AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
if ([session canAddOutput:movieFileOutput])
{
[session addOutput:movieFileOutput];
AVCaptureConnection *connection = [movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if ([connection isVideoStabilizationSupported])
[connection setEnablesVideoStabilizationWhenAvailable:YES];
[self setMovieFileOutput:movieFileOutput];
}
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
if ([session canAddOutput:stillImageOutput])
{
[stillImageOutput setOutputSettings:@{AVVideoCodecKey : AVVideoCodecJPEG}];
[session addOutput:stillImageOutput];
[self setStillImageOutput:stillImageOutput];
}
});
}
// call method below from viewWilAppear
- (void)AVFoundationStartSession
{
dispatch_async([self sessionQueue], ^{
[self addObserver:self forKeyPath:@"sessionRunningAndDeviceAuthorized" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:SessionRunningAndDeviceAuthorizedContext];
[self addObserver:self forKeyPath:@"stillImageOutput.capturingStillImage" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:CapturingStillImageContext];
[self addObserver:self forKeyPath:@"movieFileOutput.recording" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:RecordingContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:[[self videoDeviceInput] device]];
__weak ViewController *weakSelf = self;
[self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:[self session] queue:nil usingBlock:^(NSNotification *note) {
ViewController *strongSelf = weakSelf;
dispatch_async([strongSelf sessionQueue], ^{
// Manually restarting the session since it must have been stopped due to an error.
[[strongSelf session] startRunning];
});
}]];
[[self session] startRunning];
});
}
// call method below from viewDidDisappear
- (void)AVFoundationStopSession
{
dispatch_async([self sessionQueue], ^{
[[self session] stopRunning];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:[[self videoDeviceInput] device]];
[[NSNotificationCenter defaultCenter] removeObserver:[self runtimeErrorHandlingObserver]];
[self removeObserver:self forKeyPath:@"sessionRunningAndDeviceAuthorized" context:SessionRunningAndDeviceAuthorizedContext];
[self removeObserver:self forKeyPath:@"stillImageOutput.capturingStillImage" context:CapturingStillImageContext];
[self removeObserver:self forKeyPath:@"movieFileOutput.recording" context:RecordingContext];
});
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (BOOL)shouldAutorotate
{
// Disable autorotation of the interface when recording is in progress.
return ![self lockInterfaceRotation];
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// [[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] setVideoOrientation:(AVCaptureVideoOrientation)toInterfaceOrientation];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == CapturingStillImageContext)
{
BOOL isCapturingStillImage = [change[NSKeyValueChangeNewKey] boolValue];
if (isCapturingStillImage)
{
[self runStillImageCaptureAnimation];
}
}
else if (context == RecordingContext)
{
BOOL isRecording = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRecording)
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setTitle:NSLocalizedString(@"Stop", @"Recording button stop title") forState:UIControlStateNormal];
// [[self recordButton] setEnabled:YES];
}
else
{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setTitle:NSLocalizedString(@"Record", @"Recording button record title") forState:UIControlStateNormal];
// [[self recordButton] setEnabled:YES];
}
});
}
else if (context == SessionRunningAndDeviceAuthorizedContext)
{
BOOL isRunning = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRunning)
{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setEnabled:YES];
// [[self stillButton] setEnabled:YES];
}
else
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setEnabled:NO];
// [[self stillButton] setEnabled:NO];
}
});
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark Actions
- (IBAction)toggleMovieRecording:(id)sender
{
// [[self recordButton] setEnabled:NO];
dispatch_async([self sessionQueue], ^{
if (![[self movieFileOutput] isRecording])
{
[self setLockInterfaceRotation:YES];
if ([[UIDevice currentDevice] isMultitaskingSupported])
{
// Setup background task. This is needed because the captureOutput:didFinishRecordingToOutputFileAtURL: callback is not received until AVCam returns to the foreground unless you request background execution time. This also ensures that there will be time to write the file to the assets library when AVCam is backgrounded. To conclude this background execution, -endBackgroundTask is called in -recorder:recordingDidFinishToOutputFileURL:error: after the recorded file has been saved.
[self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]];
}
// Update the orientation on the movie file output video connection before starting recording.
// [[[self movieFileOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
// Turning OFF flash for video recording
[ViewController setFlashMode:AVCaptureFlashModeOff forDevice:[[self videoDeviceInput] device]];
// Start recording to a temporary file.
NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"movie" stringByAppendingPathExtension:@"mov"]];
[[self movieFileOutput] startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
}
else
{
[[self movieFileOutput] stopRecording];
}
});
}
- (IBAction)changeCamera:(id)sender
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setEnabled:NO];
// [[self stillButton] setEnabled:NO];
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *currentVideoDevice = [[self videoDeviceInput] device];
AVCaptureDevicePosition preferredPosition = AVCaptureDevicePositionUnspecified;
AVCaptureDevicePosition currentPosition = [currentVideoDevice position];
switch (currentPosition)
{
case AVCaptureDevicePositionUnspecified:
preferredPosition = AVCaptureDevicePositionBack;
break;
case AVCaptureDevicePositionBack:
preferredPosition = AVCaptureDevicePositionFront;
break;
case AVCaptureDevicePositionFront:
preferredPosition = AVCaptureDevicePositionBack;
break;
}
AVCaptureDevice *videoDevice = [ViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:preferredPosition];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
[[self session] beginConfiguration];
[[self session] removeInput:[self videoDeviceInput]];
if ([[self session] canAddInput:videoDeviceInput])
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:currentVideoDevice];
[ViewController setFlashMode:AVCaptureFlashModeAuto forDevice:videoDevice];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:videoDevice];
[[self session] addInput:videoDeviceInput];
[self setVideoDeviceInput:videoDeviceInput];
}
else
{
[[self session] addInput:[self videoDeviceInput]];
}
[[self session] commitConfiguration];
dispatch_async(dispatch_get_main_queue(), ^{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setEnabled:YES];
// [[self stillButton] setEnabled:YES];
});
});
}
- (IBAction)snapStillImage:(id)sender
{
dispatch_async([self sessionQueue], ^{
// Update the orientation on the still image output video connection before capturing.
// [[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
// Flash set to Auto for Still Capture
[ViewController setFlashMode:AVCaptureFlashModeAuto forDevice:[[self videoDeviceInput] device]];
// Capture a still image.
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
// do someting good with saved image
[self saveImageToParse:image];
}
}];
});
}
- (IBAction)focusAndExposeTap:(UIGestureRecognizer *)gestureRecognizer
{
// CGPoint devicePoint = [(AVCaptureVideoPreviewLayer *)[[self previewView] layer] captureDevicePointOfInterestForPoint:[gestureRecognizer locationInView:[gestureRecognizer view]]];
// [self focusWithMode:AVCaptureFocusModeAutoFocus exposeWithMode:AVCaptureExposureModeAutoExpose atDevicePoint:devicePoint monitorSubjectAreaChange:YES];
}
- (void)subjectAreaDidChange:(NSNotification *)notification
{
CGPoint devicePoint = CGPointMake(.5, .5);
[self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposeWithMode:AVCaptureExposureModeContinuousAutoExposure atDevicePoint:devicePoint monitorSubjectAreaChange:NO];
}
#pragma mark File Output Delegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
if (error)
NSLog(@"%@", error);
[self setLockInterfaceRotation:NO];
// Note the backgroundRecordingID for use in the ALAssetsLibrary completion handler to end the background task associated with this recording. This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's -isRecording is back to NO — which happens sometime after this method returns.
UIBackgroundTaskIdentifier backgroundRecordingID = [self backgroundRecordingID];
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
[[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error)
NSLog(@"%@", error);
[[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
if (backgroundRecordingID != UIBackgroundTaskInvalid)
[[UIApplication sharedApplication] endBackgroundTask:backgroundRecordingID];
}];
}
#pragma mark Device Configuration
- (void)focusWithMode:(AVCaptureFocusMode)focusMode exposeWithMode:(AVCaptureExposureMode)exposureMode atDevicePoint:(CGPoint)point monitorSubjectAreaChange:(BOOL)monitorSubjectAreaChange
{
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *device = [[self videoDeviceInput] device];
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode])
{
[device setFocusMode:focusMode];
[device setFocusPointOfInterest:point];
}
if ([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:exposureMode])
{
[device setExposureMode:exposureMode];
[device setExposurePointOfInterest:point];
}
[device setSubjectAreaChangeMonitoringEnabled:monitorSubjectAreaChange];
[device unlockForConfiguration];
}
else
{
NSLog(@"%@", error);
}
});
}
+ (void)setFlashMode:(AVCaptureFlashMode)flashMode forDevice:(AVCaptureDevice *)device
{
if ([device hasFlash] && [device isFlashModeSupported:flashMode])
{
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
[device setFlashMode:flashMode];
[device unlockForConfiguration];
}
else
{
NSLog(@"%@", error);
}
}
}
+ (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
AVCaptureDevice *captureDevice = [devices firstObject];
for (AVCaptureDevice *device in devices)
{
if ([device position] == position)
{
captureDevice = device;
break;
}
}
return captureDevice;
}
#pragma mark UI
- (void)runStillImageCaptureAnimation
{
/*
dispatch_async(dispatch_get_main_queue(), ^{
[[[self previewView] layer] setOpacity:0.0];
[UIView animateWithDuration:.25 animations:^{
[[[self previewView] layer] setOpacity:1.0];
}];
});
*/
}
- (void)checkDeviceAuthorizationStatus
{
NSString *mediaType = AVMediaTypeVideo;
[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
if (granted)
{
//Granted access to mediaType
[self setDeviceAuthorized:YES];
}
else
{
//Not granted access to mediaType
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc] initWithTitle:@"AVCam!"
message:@"AVCam doesn't have permission to use Camera, please change privacy settings"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
[self setDeviceAuthorized:NO];
});
}
}];
}
``` |
14,185,126 | Do you know any way / method to **take a photo in iOS** and saving it to camera Roll only with a simple button pressure without showing any preview?
I already know how to show the camera view but it show the preview of the image and the user need to click the take photo button to take the photo.
**In few Words:** the user click the button, the picture is taken, without previews nor double checks to take / save the photo.
I already found the `takePicture` method of `UIIMagePickerController` Class <http://developer.apple.com/library/ios/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/instm/UIImagePickerController/takePicture> | 2013/01/06 | [
"https://Stackoverflow.com/questions/14185126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531219/"
] | Set the `showsCameraControls`-Property to `NO`.
```
poc = [[UIImagePickerController alloc] init];
[poc setTitle:@"Take a photo."];
[poc setDelegate:self];
[poc setSourceType:UIImagePickerControllerSourceTypeCamera];
poc.showsCameraControls = NO;
```
You also have to add your own Controls as a custom view on the top of `poc.view`. But that is very simple and you can add your own UI-style by that way.
You receive the image-data as usually within the `imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:`
To take the photo, you call
```
[poc takePicture];
```
from your custom button.
Hope, that works for you. | You need to design your own custom preview according to your size, on capture button pressed and call `buttonPressed` method and do stuff what you want
```
(void)buttonPressed:(UIButton *)sender {
NSLog(@" Capture Clicked");
[self.imagePicker takePicture];
//[NSTimer scheduledTimerWithTimeInterval:3.0f target:self
selector:@selector(timerFired:) userInfo:nil repeats:NO];
}
``` |
14,185,126 | Do you know any way / method to **take a photo in iOS** and saving it to camera Roll only with a simple button pressure without showing any preview?
I already know how to show the camera view but it show the preview of the image and the user need to click the take photo button to take the photo.
**In few Words:** the user click the button, the picture is taken, without previews nor double checks to take / save the photo.
I already found the `takePicture` method of `UIIMagePickerController` Class <http://developer.apple.com/library/ios/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/instm/UIImagePickerController/takePicture> | 2013/01/06 | [
"https://Stackoverflow.com/questions/14185126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531219/"
] | Set the `showsCameraControls`-Property to `NO`.
```
poc = [[UIImagePickerController alloc] init];
[poc setTitle:@"Take a photo."];
[poc setDelegate:self];
[poc setSourceType:UIImagePickerControllerSourceTypeCamera];
poc.showsCameraControls = NO;
```
You also have to add your own Controls as a custom view on the top of `poc.view`. But that is very simple and you can add your own UI-style by that way.
You receive the image-data as usually within the `imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:`
To take the photo, you call
```
[poc takePicture];
```
from your custom button.
Hope, that works for you. | following is code that will take photo without showing preview screen. when i tried the accepted answer, which uses UIImagePickerController, the preview screen showed, then auto disappeared. with the code below, user taps 'takePhoto' button, and the devices takes photo with zero change to UI (in my app, i add a green check mark next to take photo button). the code below is from apple <https://developer.apple.com/LIBRARY/IOS/samplecode/AVCam/Introduction/Intro.html> with the 'extra functions' (that do not relate to taking still photo) commented out. thank you incmiko for suggesting this code in your answer [iOS take photo from camera without modalViewController](https://stackoverflow.com/questions/19386787/ios-take-photo-from-camera-without-modalviewcontroller).
updating code, 26 mar 2015:
to trigger snap photo:
```
[self snapStillImage:sender];
```
in .h file:
```
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
// include code below in header file, after #import and before @interface
// avfoundation copy paste code
static void * CapturingStillImageContext = &CapturingStillImageContext;
static void * RecordingContext = &RecordingContext;
static void * SessionRunningAndDeviceAuthorizedContext = &SessionRunningAndDeviceAuthorizedContext;
// avfoundation, include code below after @interface
// avf - Session management.
@property (nonatomic) dispatch_queue_t sessionQueue; // Communicate with the session and other session objects on this queue.
@property (nonatomic) AVCaptureSession *session;
@property (nonatomic) AVCaptureDeviceInput *videoDeviceInput;
@property (nonatomic) AVCaptureMovieFileOutput *movieFileOutput;
@property (nonatomic) AVCaptureStillImageOutput *stillImageOutput;
// avf - Utilities.
@property (nonatomic) UIBackgroundTaskIdentifier backgroundRecordingID;
@property (nonatomic, getter = isDeviceAuthorized) BOOL deviceAuthorized;
@property (nonatomic, readonly, getter = isSessionRunningAndDeviceAuthorized) BOOL sessionRunningAndDeviceAuthorized;
@property (nonatomic) BOOL lockInterfaceRotation;
@property (nonatomic) id runtimeErrorHandlingObserver;
```
in .m file:
```
#pragma mark - AV Foundation
- (BOOL)isSessionRunningAndDeviceAuthorized
{
return [[self session] isRunning] && [self isDeviceAuthorized];
}
+ (NSSet *)keyPathsForValuesAffectingSessionRunningAndDeviceAuthorized
{
return [NSSet setWithObjects:@"session.running", @"deviceAuthorized", nil];
}
// call following method from viewDidLoad
- (void)CreateAVCaptureSession
{
// Create the AVCaptureSession
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[self setSession:session];
// Check for device authorization
[self checkDeviceAuthorizationStatus];
// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue so that the main queue isn't blocked (which keeps the UI responsive).
dispatch_queue_t sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
[self setSessionQueue:sessionQueue];
dispatch_async(sessionQueue, ^{
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
NSError *error = nil;
AVCaptureDevice *videoDevice = [ViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionFront];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (error)
{
NSLog(@"%@", error);
}
if ([session canAddInput:videoDeviceInput])
{
[session addInput:videoDeviceInput];
[self setVideoDeviceInput:videoDeviceInput];
dispatch_async(dispatch_get_main_queue(), ^{
// Why are we dispatching this to the main queue?
// Because AVCaptureVideoPreviewLayer is the backing layer for AVCamPreviewView and UIView can only be manipulated on main thread.
// Note: As an exception to the above rule, it is not necessary to serialize video orientation changes on the AVCaptureVideoPreviewLayer’s connection with other session manipulation.
});
}
/* AVCaptureDevice *audioDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if (error)
{
NSLog(@"%@", error);
}
if ([session canAddInput:audioDeviceInput])
{
[session addInput:audioDeviceInput];
}
*/
AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
if ([session canAddOutput:movieFileOutput])
{
[session addOutput:movieFileOutput];
AVCaptureConnection *connection = [movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if ([connection isVideoStabilizationSupported])
[connection setEnablesVideoStabilizationWhenAvailable:YES];
[self setMovieFileOutput:movieFileOutput];
}
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
if ([session canAddOutput:stillImageOutput])
{
[stillImageOutput setOutputSettings:@{AVVideoCodecKey : AVVideoCodecJPEG}];
[session addOutput:stillImageOutput];
[self setStillImageOutput:stillImageOutput];
}
});
}
// call method below from viewWilAppear
- (void)AVFoundationStartSession
{
dispatch_async([self sessionQueue], ^{
[self addObserver:self forKeyPath:@"sessionRunningAndDeviceAuthorized" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:SessionRunningAndDeviceAuthorizedContext];
[self addObserver:self forKeyPath:@"stillImageOutput.capturingStillImage" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:CapturingStillImageContext];
[self addObserver:self forKeyPath:@"movieFileOutput.recording" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:RecordingContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:[[self videoDeviceInput] device]];
__weak ViewController *weakSelf = self;
[self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:[self session] queue:nil usingBlock:^(NSNotification *note) {
ViewController *strongSelf = weakSelf;
dispatch_async([strongSelf sessionQueue], ^{
// Manually restarting the session since it must have been stopped due to an error.
[[strongSelf session] startRunning];
});
}]];
[[self session] startRunning];
});
}
// call method below from viewDidDisappear
- (void)AVFoundationStopSession
{
dispatch_async([self sessionQueue], ^{
[[self session] stopRunning];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:[[self videoDeviceInput] device]];
[[NSNotificationCenter defaultCenter] removeObserver:[self runtimeErrorHandlingObserver]];
[self removeObserver:self forKeyPath:@"sessionRunningAndDeviceAuthorized" context:SessionRunningAndDeviceAuthorizedContext];
[self removeObserver:self forKeyPath:@"stillImageOutput.capturingStillImage" context:CapturingStillImageContext];
[self removeObserver:self forKeyPath:@"movieFileOutput.recording" context:RecordingContext];
});
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (BOOL)shouldAutorotate
{
// Disable autorotation of the interface when recording is in progress.
return ![self lockInterfaceRotation];
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// [[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] setVideoOrientation:(AVCaptureVideoOrientation)toInterfaceOrientation];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == CapturingStillImageContext)
{
BOOL isCapturingStillImage = [change[NSKeyValueChangeNewKey] boolValue];
if (isCapturingStillImage)
{
[self runStillImageCaptureAnimation];
}
}
else if (context == RecordingContext)
{
BOOL isRecording = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRecording)
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setTitle:NSLocalizedString(@"Stop", @"Recording button stop title") forState:UIControlStateNormal];
// [[self recordButton] setEnabled:YES];
}
else
{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setTitle:NSLocalizedString(@"Record", @"Recording button record title") forState:UIControlStateNormal];
// [[self recordButton] setEnabled:YES];
}
});
}
else if (context == SessionRunningAndDeviceAuthorizedContext)
{
BOOL isRunning = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRunning)
{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setEnabled:YES];
// [[self stillButton] setEnabled:YES];
}
else
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setEnabled:NO];
// [[self stillButton] setEnabled:NO];
}
});
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark Actions
- (IBAction)toggleMovieRecording:(id)sender
{
// [[self recordButton] setEnabled:NO];
dispatch_async([self sessionQueue], ^{
if (![[self movieFileOutput] isRecording])
{
[self setLockInterfaceRotation:YES];
if ([[UIDevice currentDevice] isMultitaskingSupported])
{
// Setup background task. This is needed because the captureOutput:didFinishRecordingToOutputFileAtURL: callback is not received until AVCam returns to the foreground unless you request background execution time. This also ensures that there will be time to write the file to the assets library when AVCam is backgrounded. To conclude this background execution, -endBackgroundTask is called in -recorder:recordingDidFinishToOutputFileURL:error: after the recorded file has been saved.
[self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]];
}
// Update the orientation on the movie file output video connection before starting recording.
// [[[self movieFileOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
// Turning OFF flash for video recording
[ViewController setFlashMode:AVCaptureFlashModeOff forDevice:[[self videoDeviceInput] device]];
// Start recording to a temporary file.
NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"movie" stringByAppendingPathExtension:@"mov"]];
[[self movieFileOutput] startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
}
else
{
[[self movieFileOutput] stopRecording];
}
});
}
- (IBAction)changeCamera:(id)sender
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setEnabled:NO];
// [[self stillButton] setEnabled:NO];
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *currentVideoDevice = [[self videoDeviceInput] device];
AVCaptureDevicePosition preferredPosition = AVCaptureDevicePositionUnspecified;
AVCaptureDevicePosition currentPosition = [currentVideoDevice position];
switch (currentPosition)
{
case AVCaptureDevicePositionUnspecified:
preferredPosition = AVCaptureDevicePositionBack;
break;
case AVCaptureDevicePositionBack:
preferredPosition = AVCaptureDevicePositionFront;
break;
case AVCaptureDevicePositionFront:
preferredPosition = AVCaptureDevicePositionBack;
break;
}
AVCaptureDevice *videoDevice = [ViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:preferredPosition];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
[[self session] beginConfiguration];
[[self session] removeInput:[self videoDeviceInput]];
if ([[self session] canAddInput:videoDeviceInput])
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:currentVideoDevice];
[ViewController setFlashMode:AVCaptureFlashModeAuto forDevice:videoDevice];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:videoDevice];
[[self session] addInput:videoDeviceInput];
[self setVideoDeviceInput:videoDeviceInput];
}
else
{
[[self session] addInput:[self videoDeviceInput]];
}
[[self session] commitConfiguration];
dispatch_async(dispatch_get_main_queue(), ^{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setEnabled:YES];
// [[self stillButton] setEnabled:YES];
});
});
}
- (IBAction)snapStillImage:(id)sender
{
dispatch_async([self sessionQueue], ^{
// Update the orientation on the still image output video connection before capturing.
// [[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
// Flash set to Auto for Still Capture
[ViewController setFlashMode:AVCaptureFlashModeAuto forDevice:[[self videoDeviceInput] device]];
// Capture a still image.
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
// do someting good with saved image
[self saveImageToParse:image];
}
}];
});
}
- (IBAction)focusAndExposeTap:(UIGestureRecognizer *)gestureRecognizer
{
// CGPoint devicePoint = [(AVCaptureVideoPreviewLayer *)[[self previewView] layer] captureDevicePointOfInterestForPoint:[gestureRecognizer locationInView:[gestureRecognizer view]]];
// [self focusWithMode:AVCaptureFocusModeAutoFocus exposeWithMode:AVCaptureExposureModeAutoExpose atDevicePoint:devicePoint monitorSubjectAreaChange:YES];
}
- (void)subjectAreaDidChange:(NSNotification *)notification
{
CGPoint devicePoint = CGPointMake(.5, .5);
[self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposeWithMode:AVCaptureExposureModeContinuousAutoExposure atDevicePoint:devicePoint monitorSubjectAreaChange:NO];
}
#pragma mark File Output Delegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
if (error)
NSLog(@"%@", error);
[self setLockInterfaceRotation:NO];
// Note the backgroundRecordingID for use in the ALAssetsLibrary completion handler to end the background task associated with this recording. This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's -isRecording is back to NO — which happens sometime after this method returns.
UIBackgroundTaskIdentifier backgroundRecordingID = [self backgroundRecordingID];
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
[[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error)
NSLog(@"%@", error);
[[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
if (backgroundRecordingID != UIBackgroundTaskInvalid)
[[UIApplication sharedApplication] endBackgroundTask:backgroundRecordingID];
}];
}
#pragma mark Device Configuration
- (void)focusWithMode:(AVCaptureFocusMode)focusMode exposeWithMode:(AVCaptureExposureMode)exposureMode atDevicePoint:(CGPoint)point monitorSubjectAreaChange:(BOOL)monitorSubjectAreaChange
{
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *device = [[self videoDeviceInput] device];
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode])
{
[device setFocusMode:focusMode];
[device setFocusPointOfInterest:point];
}
if ([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:exposureMode])
{
[device setExposureMode:exposureMode];
[device setExposurePointOfInterest:point];
}
[device setSubjectAreaChangeMonitoringEnabled:monitorSubjectAreaChange];
[device unlockForConfiguration];
}
else
{
NSLog(@"%@", error);
}
});
}
+ (void)setFlashMode:(AVCaptureFlashMode)flashMode forDevice:(AVCaptureDevice *)device
{
if ([device hasFlash] && [device isFlashModeSupported:flashMode])
{
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
[device setFlashMode:flashMode];
[device unlockForConfiguration];
}
else
{
NSLog(@"%@", error);
}
}
}
+ (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
AVCaptureDevice *captureDevice = [devices firstObject];
for (AVCaptureDevice *device in devices)
{
if ([device position] == position)
{
captureDevice = device;
break;
}
}
return captureDevice;
}
#pragma mark UI
- (void)runStillImageCaptureAnimation
{
/*
dispatch_async(dispatch_get_main_queue(), ^{
[[[self previewView] layer] setOpacity:0.0];
[UIView animateWithDuration:.25 animations:^{
[[[self previewView] layer] setOpacity:1.0];
}];
});
*/
}
- (void)checkDeviceAuthorizationStatus
{
NSString *mediaType = AVMediaTypeVideo;
[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
if (granted)
{
//Granted access to mediaType
[self setDeviceAuthorized:YES];
}
else
{
//Not granted access to mediaType
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc] initWithTitle:@"AVCam!"
message:@"AVCam doesn't have permission to use Camera, please change privacy settings"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
[self setDeviceAuthorized:NO];
});
}
}];
}
``` |
51,550,869 | If I have an string containing a JSONP response, for example`"jsonp([1,2,3])"`, and I want to retrieve the 3rd parameter `3`, how could I write a function that do that for me? I want to avoid using `eval`. My code (below) works fine on the debug line, but return `undefined` for some reason.
```
function unwrap(jsonp) {
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var f = new Function("jsonp", jsonp);
return f(unwrapper);
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
```
More info: I'm running this in a node.js scraper, using `request` library.
Here's a jsfiddle <https://jsfiddle.net/bortao/3nc967wd/> | 2018/07/27 | [
"https://Stackoverflow.com/questions/51550869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242076/"
] | Just `slice` the string to remove the `jsonp(` and `);`, and then you can `JSON.parse` it:
```js
function unwrap(jsonp) {
return JSON.parse(jsonp.slice(6, jsonp.length - 2));
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // returns the whole array
console.log(unwrap(j)[2]); // returns the third item in the array
```
Note that `new Function` is just as bad as `eval`. | Just a little changes and it'll work fine:
```
function unwrap(jsonp) {
var f = new Function("jsonp", `return ${jsonp}`);
console.log(f.toString())
return f(unwrapper);
}
function unwrapper(param) {
console.log(param[2]); // This works!
return param[2];
}
var j = 'jsonp([1,2,3]);'
console.log(unwrap(j)); // Return undefined
```
without return your anonymous function is like this :
```
function anonymous(jsonp) {
jsonp([1,2,3]);
}
```
because this function doesn't return so the output will be undefined. |
567,365 | I plan to charge a 12v LiFePO4 battery using a charger specifically designed for that purpose, but I would like to know alternative methods of charging this battery without a dedicated charger.
I understand that to charge this battery, the power source for charging must be near the correct voltage and within a safe range of amperage. I also realize charging will not be very efficient or cannot 'top off' the battery without a dedicated charger, because of how a dedicated charger varies voltage to charge at highest possible amperage first and then holds voltage constant and reduces amperage to top the battery off. Still, being able to bring a battery from say 11.5V back up to 13V would be useful.
How can a 12V LiFePO4 100Ah battery get a charge from common automotive or household electronics? For example, can it be hooked up to a car battery with jumper cables, then the car occasionally started and left to run for a bit to keep the car battery charged, using a multimeter to check charger and charging batteries' voltage? If not, for the sake of learning, could someone explain why this is not safe or doable? | 2021/05/28 | [
"https://electronics.stackexchange.com/questions/567365",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/108278/"
] | If you just hook the LiFePo up to a car battery, you'll get a lot of smoke from both the cables and the batteries involved, and it can also cause the LiFePo to ignite or explode.
The problem is that there's nothing to limit the current flowing into the LiFePo battery. A car battery can easily provide thousands of amperes of short-circuit current, and if you connect a LiFePo across it, you have created just such a short-circuit. Assuming that your LiFePo battery is fully discharged, which means it has a cell voltage of 2 Volts, the total voltage of the battery will be at 8 Volts (4 cells in series). The car battery, on the other hand, might have 13 Volts when fully charged. That's a difference of 5 Volts, which will cause a massive current to flow that's only limited by the circuit's total resistance (which is mostly in the wires connecting the batteries). If we now assume that you've connected the batteries using 1 meter of 10AWG wire, this will give us about 3.3 Milliohms of total resistance. 5 Volts across 3.3 Milliohms results in a massive 1500 Ampere current flowing into the LiFePo battery, for a total power dissipation of 7500 Watts (1500 Ampere at 5 Volts cable drop). In practice, it'll be slightly lower due to the batteries' internal resistance, but it won't change the fact that things will blow up almost instantly. It also won't be any better if the LiFePo battery isn't fully discharged, it'll still dump thousands of Watts into the cables and burn them (and the batteries too).
Even if you managed to limit the current, you still need a balancer to properly charge a LiFePo battery, otherwise individual cells might get over-charged and damaged.
**TL;DR: Don't do this, the batteries and cables will blow up. Always use a proper charger.** | Every time someone asks about this sort of thing, the overwhelming response is "only do it the proper way or your batteries will blow up and your house will burn down." You seem to understand that and specifically want to know what will happen or what your options are. In my opinion, that is a perfectly valid question.
I work with Lithium batteries a lot and also have read a lot of the manufacturer's literature. I am not a safety expert on the topic but I am not coming out of left field, either. LiFePO4 batteries are thermally much safer than Li-Ion/Li-polymer. But they still require proper charging for best battery life and for safety.
A car alternator can charge 4S LiFePO4 battery pack, but you need to monitor the current and voltage. If it is a small battery pack, the charge current could easily be too high for the battery. If it is a big battery, then it is very possible for the battery to overload the alternator, because the LiFePO4 batteries will accept very high currents without appreciable voltage rise. So there is danger that you will burn up your alternator.
Likewise, if the batteries are left on the alternator for a long time, they will get over-charged and lose capacity prematurely. Considering the expense of LiFePO4 batteries, this doesn't seem like a good idea other than some kind of emergency scenario. If possible, watch the voltage like a hawk and disconnect the LiFePO4 batteries when they get to the recommended maximum voltage.
Extreme caution is warranted if you are contemplating connecting a 4S LiFePO4 battery pack to a car battery. The voltages must be equal prior to making the connection to avoid excessive equalization currents. This is not a safe arrangement in the long term, and all previous comments about alternators apply if you run the engine.
One option for connecting different voltage batteries is to put a resistor between them to limit current. This is very inefficient, but may be workable in some cases. You have to do all the math to determine current and power dissipation in the resistor, etc. Most likely this would be done with a large power resistor. Once again, this would be something to do in an emergency only. |
567,365 | I plan to charge a 12v LiFePO4 battery using a charger specifically designed for that purpose, but I would like to know alternative methods of charging this battery without a dedicated charger.
I understand that to charge this battery, the power source for charging must be near the correct voltage and within a safe range of amperage. I also realize charging will not be very efficient or cannot 'top off' the battery without a dedicated charger, because of how a dedicated charger varies voltage to charge at highest possible amperage first and then holds voltage constant and reduces amperage to top the battery off. Still, being able to bring a battery from say 11.5V back up to 13V would be useful.
How can a 12V LiFePO4 100Ah battery get a charge from common automotive or household electronics? For example, can it be hooked up to a car battery with jumper cables, then the car occasionally started and left to run for a bit to keep the car battery charged, using a multimeter to check charger and charging batteries' voltage? If not, for the sake of learning, could someone explain why this is not safe or doable? | 2021/05/28 | [
"https://electronics.stackexchange.com/questions/567365",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/108278/"
] | If you just hook the LiFePo up to a car battery, you'll get a lot of smoke from both the cables and the batteries involved, and it can also cause the LiFePo to ignite or explode.
The problem is that there's nothing to limit the current flowing into the LiFePo battery. A car battery can easily provide thousands of amperes of short-circuit current, and if you connect a LiFePo across it, you have created just such a short-circuit. Assuming that your LiFePo battery is fully discharged, which means it has a cell voltage of 2 Volts, the total voltage of the battery will be at 8 Volts (4 cells in series). The car battery, on the other hand, might have 13 Volts when fully charged. That's a difference of 5 Volts, which will cause a massive current to flow that's only limited by the circuit's total resistance (which is mostly in the wires connecting the batteries). If we now assume that you've connected the batteries using 1 meter of 10AWG wire, this will give us about 3.3 Milliohms of total resistance. 5 Volts across 3.3 Milliohms results in a massive 1500 Ampere current flowing into the LiFePo battery, for a total power dissipation of 7500 Watts (1500 Ampere at 5 Volts cable drop). In practice, it'll be slightly lower due to the batteries' internal resistance, but it won't change the fact that things will blow up almost instantly. It also won't be any better if the LiFePo battery isn't fully discharged, it'll still dump thousands of Watts into the cables and burn them (and the batteries too).
Even if you managed to limit the current, you still need a balancer to properly charge a LiFePo battery, otherwise individual cells might get over-charged and damaged.
**TL;DR: Don't do this, the batteries and cables will blow up. Always use a proper charger.** | You can charge any (rechargeable) battery from any other battery or any other source provided that you can ensure that the charging current is within allowable limits for both batteries. There are a few ways to do this; the simplest is to use a resistor although a constant-current circuit would be better, and a switch-mode circuit better again since it would not require that the donor voltage be somewhat higher than the recipient.
Allowable limits includes not only current but minimum and maximum voltages too.
Other commentators have already indicated the hazards of going outside the operational limits. |
567,365 | I plan to charge a 12v LiFePO4 battery using a charger specifically designed for that purpose, but I would like to know alternative methods of charging this battery without a dedicated charger.
I understand that to charge this battery, the power source for charging must be near the correct voltage and within a safe range of amperage. I also realize charging will not be very efficient or cannot 'top off' the battery without a dedicated charger, because of how a dedicated charger varies voltage to charge at highest possible amperage first and then holds voltage constant and reduces amperage to top the battery off. Still, being able to bring a battery from say 11.5V back up to 13V would be useful.
How can a 12V LiFePO4 100Ah battery get a charge from common automotive or household electronics? For example, can it be hooked up to a car battery with jumper cables, then the car occasionally started and left to run for a bit to keep the car battery charged, using a multimeter to check charger and charging batteries' voltage? If not, for the sake of learning, could someone explain why this is not safe or doable? | 2021/05/28 | [
"https://electronics.stackexchange.com/questions/567365",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/108278/"
] | If you just hook the LiFePo up to a car battery, you'll get a lot of smoke from both the cables and the batteries involved, and it can also cause the LiFePo to ignite or explode.
The problem is that there's nothing to limit the current flowing into the LiFePo battery. A car battery can easily provide thousands of amperes of short-circuit current, and if you connect a LiFePo across it, you have created just such a short-circuit. Assuming that your LiFePo battery is fully discharged, which means it has a cell voltage of 2 Volts, the total voltage of the battery will be at 8 Volts (4 cells in series). The car battery, on the other hand, might have 13 Volts when fully charged. That's a difference of 5 Volts, which will cause a massive current to flow that's only limited by the circuit's total resistance (which is mostly in the wires connecting the batteries). If we now assume that you've connected the batteries using 1 meter of 10AWG wire, this will give us about 3.3 Milliohms of total resistance. 5 Volts across 3.3 Milliohms results in a massive 1500 Ampere current flowing into the LiFePo battery, for a total power dissipation of 7500 Watts (1500 Ampere at 5 Volts cable drop). In practice, it'll be slightly lower due to the batteries' internal resistance, but it won't change the fact that things will blow up almost instantly. It also won't be any better if the LiFePo battery isn't fully discharged, it'll still dump thousands of Watts into the cables and burn them (and the batteries too).
Even if you managed to limit the current, you still need a balancer to properly charge a LiFePo battery, otherwise individual cells might get over-charged and damaged.
**TL;DR: Don't do this, the batteries and cables will blow up. Always use a proper charger.** | Most 12V LiFePO4 batteries are designed as a replacement for a car/truck/boat/RV battery and in particular, EXACTLY to be charged by an ordinary car alternator that is limited at 14.2-14.6 volt. (In contrast, PV/wind/offgrid installations are usually made from single 3.2V cells with external BMS)
Charging it from the car battery (without the alternator running) is not possible directly because of insufficient voltage of the lead-acid battery in any state of charge. Well, some equalizing current will flow, but it is absolutely not a practical approach.
It is possible and practical to use dedicated dc/dc charging devices like those made by Revolectrix or iSDT - with or without alternator running, as long as you don't deplete the car battery to the point where you can't start the (last) car.
What can go wrong, then?
1. Alternator being slightly off-spec (like, 14.8 or 15.2 volt). Lead-acids tolerate this to some extent. Some alternators adjust intentionally their voltage that high in cold weather or immediately after starting the engine. This is good for lead-acid batteries, but not so good for LiFePO4. Avoid aftermarket alternators unless you know exactly how these behave. Be aware that most of their owners (offroad/RV/marine enthusiasts) don't know either.
2. Jumper cables are not to be used unattended. They are related to a significant percent of car fires even when used for their intended purpose. When used for a prolonged period (like 15 minutes or more) they can overheat, melt, lose grip, etc... you get the hint. Use adequate connections, rated for the power of the alternator.
3. The alternator maximal (self-limiting) current may be higher than what your battery is happy with. Most modern passenger cars are equipped with 100-180 ampere alternators. At idle, they may produce as low as 1/3 of their rated power, making your calculations about the charge transferred less accurate.
4. Some modern cars are quite unhappy about connecting something to the battery, because they use some internal accounting about the state of charge of the battery. Connecting the negative to the chassis instead of the negative battery terminal may or may not help.
---
In short, the jump cables approach is possible in emergency, with a good pair of cables and if you exactly know what you are doing, but is a good recipe for problems as well.
Other household electronics that use similar voltages (computer PSUs, etc...) are even less practical.
A good lead-acid 2- or 3-stage AC charger may or may not do the proper thing, but even if it does, for a depleted 100Ah battery, you will likely wait a day or two (most of these chargers are 3-7 ampere). |
6,666,735 | I just want everyones feedback about the following Async Controller using the Web Api HttpClient. This looks very messy is there a way to make it cleaner? Does anyone have a good wrapper around chaining multiple async tasks together?
```
public class HomeController : AsyncController
{
public void IndexAsync()
{
var uri = "http://localhost:3018/service";
var httpClient = new HttpClient(uri);
AsyncManager.OutstandingOperations.Increment(2);
httpClient.GetAsync(uri).ContinueWith(r =>
{
r.Result.Content.ReadAsAsync<List<string>>().ContinueWith(b =>
{
AsyncManager.Parameters["items"] = b.Result;
AsyncManager.OutstandingOperations.Decrement();
});
AsyncManager.OutstandingOperations.Decrement();
});
}
public ActionResult IndexCompleted(List<string> items)
{
return View(items);
}
}
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6666735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104727/"
] | You can use oTranslate to remove numbers:
```
BTEQ -- Enter your SQL request or BTEQ command:
Select the_name, oTranslate( the_name, 'a0123456789','a')
from
( SELECT 'Larry59N' the_name FROM ( SELECT 'X' DUMMY ) a
UNION ALL
SELECT 'Laura9' FROM ( SELECT 'X' DUMMY ) b
UNION ALL
SELECT 'Mickey' the_name FROM ( SELECT 'X' DUMMY ) c
) d
;
*** Query completed. 3 rows found. 2 columns returned.
*** Total elapsed time was 1 second.
the_name oTranslate(the_name,'a0123456789','a')
-------- -----------------------------------------------------
Larry59N LarryN
Laura9 Laura
Mickey Mickey
```
HTH.
Cheers. | Unfortunately, I don't believe there is a function native to Teradata that will accomplish this. I would suggest looking at the UDF's posted on the Teradata Developer Exchange ([link](http://developer.teradata.com/blog/madmac/2010/03/a-few-basic-scalar-string-udfs)). The function `eReplaceChar` in particular looks like it may help you accomplish what you are looking to do with this data. The UDF's found at the link above were published under the Apache 2.0 license so you should not have any problems using them. |
72,102,467 | I have a couple tables (see reproducible code at the bottom):
`tbl1_have`
```
id json_col
1 {"a_i":"a","a_j":1}
1 {"a_i":"b","a_j":2}
2 {"a_i":"c","a_j":3}
2 {"a_i":"d","a_j":4}
```
`tbl2_have`
```
id json_col
1 [{"a_i":"a","a_j":1},{"a_i":"b","a_j":2}]
2 [{"a_i":"c","a_j":3},{"a_i":"d","a_j":4}]
```
I wish to extract all json columns without providing explicit data type conversion for each columns since in my use case the names and amounts of nested attributes vary.
The expected output is the same for both cases:
`tbl_want`
```
id a_i a_j
1 a 1
1 b 2
2 c 3
2 d 4
```
with `a_i` and `a_j` correctly stored as a character and numeric column, which mean I'd like to map json types to SQL types (say `INT` and `VARCHAR()` here) automatically.
The following gets me half way for both tables:
```
SELECT id, a_i, a_j FROM tbl2_have CROSS APPLY OPENJSON(json_col)
WITH(a_i VARCHAR(100), a_j INT)
id a_i a_j
1 1 a 1
2 1 b 2
3 2 c 3
4 2 d 4
```
How can I work around mentioning the types explicitly in `with()` ?
---
reproducible code :
```
CREATE TABLE tbl1_have (id INT, json_col VARCHAR(100))
INSERT INTO tbl1_have VALUES
(1, '{"a_i":"a","a_j":1}'),
(1, '{"a_i":"b","a_j":2}'),
(2, '{"a_i":"c","a_j":3}'),
(2, '{"a_i":"d","a_j":4}')
CREATE TABLE tbl2_have (id INT, json_col VARCHAR(100))
INSERT INTO tbl2_have VALUES
(1, '[{"a_i":"a","a_j":1},{"a_i":"b","a_j":2}]'),
(2, '[{"a_i":"c","a_j":3},{"a_i":"d","a_j":4}]')
SELECT id, a_i, a_j FROM tbl1_have CROSS APPLY OPENJSON(json_col)
WITH(a_i VARCHAR(100), a_j INT)
SELECT id, a_i, a_j FROM tbl2_have CROSS APPLY OPENJSON(json_col)
WITH(a_i VARCHAR(100), a_j INT)
``` | 2022/05/03 | [
"https://Stackoverflow.com/questions/72102467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270475/"
] | I am assuming that you don't know the name and type of keys in advance. You need to use dynamic SQL.
You first need to use [`OPENJSON`](https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver15) without the `WITH` clause on the `{objects}` like so:
```
select string_agg(quotename(k) + case t
when 0 then ' nchar(1)' -- javascript null
when 1 then ' nvarchar(max)' -- javascript string
when 2 then ' float' -- javascript number
when 3 then ' bit' -- javascript boolean
else ' nvarchar(max) as json' -- javascript array or object
end, ', ') within group (order by k)
from (
select j2.[key], max(j2.[type])
from test
cross apply openjson(case when json_col like '{%}' then '[' + json_col + ']' else json_col end) as j1
cross apply openjson(j1.value) as j2
group by j2.[key]
) as kt(k, t)
```
The inner query gives you the name and type of all the keys across all json values in the table. The outer query builds the `WITH` clause for dynamic SQL.
The rest is relatively straight forward, use the generated clause in your dynamic SQL. Here is the complete example:
```
declare @table_name nvarchar(100) = 'test';
declare @with_clause nvarchar(100);
declare @query1 nvarchar(999) = N'select @with_clause_temp = string_agg(quotename(k) + case t
when 0 then '' nchar(1)''
when 1 then '' nvarchar(max)''
when 2 then '' float''
when 3 then '' bit''
else '' nvarchar(max) as json''
end, '', '') within group (order by k)
from (
select j2.[key], max(j2.[type])
from ' + quotename(@table_name) + '
cross apply openjson(case when json_col like ''{%}'' then ''['' + json_col + '']'' else json_col end) as j1
cross apply openjson(j1.value) as j2
group by j2.[key]
) as kt(k, t)';
exec sp_executesql @query1, N'@with_clause_temp nvarchar(100) out', @with_clause out;
declare @query2 nvarchar(999) = N'select id, j.*
from ' + quotename(@table_name) + '
cross apply openjson(json_col)
with (' + @with_clause + ') as j';
exec sp_executesql @query2;
```
[Demo on db<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=e4322a9abcf27d819ebf5f61000e6ab7) | Would using the Value returned from OPENJSON work? It probably maps to a string data type, however, you do not have to know the type upfront. The [official doc](https://learn.microsoft.com/en-us/sql/relational-databases/json/convert-json-data-to-rows-and-columns-with-openjson-sql-server?view=sql-server-ver15) of the OPENJSON rowset function indicates that it returns a Key:Value pair as well as a Type for each parse. The Type value may be useful, however, it determines the datatype while parsing. I bet that Value is always a string type, as it would have to be.
```
;WITH X AS
(
SELECT id, a_i=J.[Key], a_j=J.[Value] FROM #tbl2_have CROSS APPLY OPENJSON(json_col) J
)
SELECT
id,
a_i=MAX(CASE WHEN J.[Key]='a_i' THEN J.[Value] ELSE NULL END),
a_j=MAX(CASE WHEN J.[Key]='a_j' THEN J.[Value] ELSE NULL END)
FROM X CROSS APPLY OPENJSON(X.a_j) J
GROUP BY
id,a_i,a_j
``` |
72,102,467 | I have a couple tables (see reproducible code at the bottom):
`tbl1_have`
```
id json_col
1 {"a_i":"a","a_j":1}
1 {"a_i":"b","a_j":2}
2 {"a_i":"c","a_j":3}
2 {"a_i":"d","a_j":4}
```
`tbl2_have`
```
id json_col
1 [{"a_i":"a","a_j":1},{"a_i":"b","a_j":2}]
2 [{"a_i":"c","a_j":3},{"a_i":"d","a_j":4}]
```
I wish to extract all json columns without providing explicit data type conversion for each columns since in my use case the names and amounts of nested attributes vary.
The expected output is the same for both cases:
`tbl_want`
```
id a_i a_j
1 a 1
1 b 2
2 c 3
2 d 4
```
with `a_i` and `a_j` correctly stored as a character and numeric column, which mean I'd like to map json types to SQL types (say `INT` and `VARCHAR()` here) automatically.
The following gets me half way for both tables:
```
SELECT id, a_i, a_j FROM tbl2_have CROSS APPLY OPENJSON(json_col)
WITH(a_i VARCHAR(100), a_j INT)
id a_i a_j
1 1 a 1
2 1 b 2
3 2 c 3
4 2 d 4
```
How can I work around mentioning the types explicitly in `with()` ?
---
reproducible code :
```
CREATE TABLE tbl1_have (id INT, json_col VARCHAR(100))
INSERT INTO tbl1_have VALUES
(1, '{"a_i":"a","a_j":1}'),
(1, '{"a_i":"b","a_j":2}'),
(2, '{"a_i":"c","a_j":3}'),
(2, '{"a_i":"d","a_j":4}')
CREATE TABLE tbl2_have (id INT, json_col VARCHAR(100))
INSERT INTO tbl2_have VALUES
(1, '[{"a_i":"a","a_j":1},{"a_i":"b","a_j":2}]'),
(2, '[{"a_i":"c","a_j":3},{"a_i":"d","a_j":4}]')
SELECT id, a_i, a_j FROM tbl1_have CROSS APPLY OPENJSON(json_col)
WITH(a_i VARCHAR(100), a_j INT)
SELECT id, a_i, a_j FROM tbl2_have CROSS APPLY OPENJSON(json_col)
WITH(a_i VARCHAR(100), a_j INT)
``` | 2022/05/03 | [
"https://Stackoverflow.com/questions/72102467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270475/"
] | I am assuming that you don't know the name and type of keys in advance. You need to use dynamic SQL.
You first need to use [`OPENJSON`](https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver15) without the `WITH` clause on the `{objects}` like so:
```
select string_agg(quotename(k) + case t
when 0 then ' nchar(1)' -- javascript null
when 1 then ' nvarchar(max)' -- javascript string
when 2 then ' float' -- javascript number
when 3 then ' bit' -- javascript boolean
else ' nvarchar(max) as json' -- javascript array or object
end, ', ') within group (order by k)
from (
select j2.[key], max(j2.[type])
from test
cross apply openjson(case when json_col like '{%}' then '[' + json_col + ']' else json_col end) as j1
cross apply openjson(j1.value) as j2
group by j2.[key]
) as kt(k, t)
```
The inner query gives you the name and type of all the keys across all json values in the table. The outer query builds the `WITH` clause for dynamic SQL.
The rest is relatively straight forward, use the generated clause in your dynamic SQL. Here is the complete example:
```
declare @table_name nvarchar(100) = 'test';
declare @with_clause nvarchar(100);
declare @query1 nvarchar(999) = N'select @with_clause_temp = string_agg(quotename(k) + case t
when 0 then '' nchar(1)''
when 1 then '' nvarchar(max)''
when 2 then '' float''
when 3 then '' bit''
else '' nvarchar(max) as json''
end, '', '') within group (order by k)
from (
select j2.[key], max(j2.[type])
from ' + quotename(@table_name) + '
cross apply openjson(case when json_col like ''{%}'' then ''['' + json_col + '']'' else json_col end) as j1
cross apply openjson(j1.value) as j2
group by j2.[key]
) as kt(k, t)';
exec sp_executesql @query1, N'@with_clause_temp nvarchar(100) out', @with_clause out;
declare @query2 nvarchar(999) = N'select id, j.*
from ' + quotename(@table_name) + '
cross apply openjson(json_col)
with (' + @with_clause + ') as j';
exec sp_executesql @query2;
```
[Demo on db<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=e4322a9abcf27d819ebf5f61000e6ab7) | I have found a solution that maybe works for your use case. I am no SQL-expert by any means, and i did not manage to automatically detect the datatypes of the dynamic columns. But i found a solution for your two examples.
First i tried to get all column names dynamically from the json\_col. I found an [answer on stackoverflow](https://stackoverflow.com/a/15745076/17372290) and got this piece of code:
```
STUFF(
(
SELECT DISTINCT ', '+QUOTENAME(columnname) FROM #tmpTbl FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
```
This will output all column names as a string separated by commas, in your example: ' `[a_i], [a_j]`'. This can then be used to dynamically `SELECT` columns.
As already mentioned above, i was not able to write a datatype detection algorithm. I just hardcoded the columns to have `nvarchar(100)` as datatype.
To dynamically get the column-names with the corresponding datatype (hardcoded as `nvarchar(100)`) i used a slightly modified version of above query:
```
STUFF(
(
SELECT DISTINCT ', '+QUOTENAME(columnname)+' nvarchar(100)' FROM #tmpTbl FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
```
Then i just used them in the `WITH`-CLAUSE.
---
Full version for the table `tbl1_have`
```
DECLARE @cols NVARCHAR(MAX), @colsWithType NVARCHAR(MAX), @query NVARCHAR(MAX);
DROP TABLE IF EXISTS #tmpTbl
SELECT outerTable.[id] AS columnid, innerTable.[key] AS columnname, innerTable.[value] AS columnvalue
INTO #tmpTbl
FROM tbl1_have outerTable CROSS APPLY OPENJSON(json_col) AS innerTable
SELECT * FROM #tmpTbl
SET @cols = STUFF(
(
SELECT DISTINCT ', '+QUOTENAME(columnname) FROM #tmpTbl FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
SET @colsWithType = STUFF(
(
SELECT DISTINCT ', '+QUOTENAME(columnname)+' nvarchar(100)' FROM #tmpTbl FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
SET @query = N'SELECT id, '+@cols+' FROM tbl1_have CROSS APPLY OPENJSON(json_col)
WITH('+@colsWithType+')';
exec sp_executesql @query
```
Full Version for the table `tbl2_have`:
```
DECLARE @cols NVARCHAR(MAX), @colsWithType NVARCHAR(MAX), @query NVARCHAR(MAX);
DROP TABLE IF EXISTS #tmpTbl
DROP TABLE IF EXISTS #tmpTbl2
SELECT *
INTO #tmpTbl
FROM tbl2_have CROSS APPLY OPENJSON(json_col)
SELECT outerTable.[id] AS columnid, innerTable.[key] AS columnname, innerTable.[value] AS columnvalue
INTO #tmpTbl2
FROM #tmpTbl outerTable CROSS APPLY OPENJSON([value]) AS innerTable
SELECT * FROM #tmpTbl
SELECT * FROM #tmpTbl2
SET @cols = STUFF(
(
SELECT DISTINCT ', '+QUOTENAME(columnname) FROM #tmpTbl2 FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
SET @colsWithType = STUFF(
(
SELECT DISTINCT ', '+QUOTENAME(columnname)+' nvarchar(100)' FROM #tmpTbl2 FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
SET @query = N'SELECT id, '+@cols+' FROM tbl2_have CROSS APPLY OPENJSON(json_col)
WITH('+@colsWithType+')';
exec sp_executesql @query
``` |
34,052,391 | I am trying to save an array of optionals `Strings` to `NSUserDefaults`, but unfortunately it doesn't work:
```
var textFieldEntries: [String?]
...
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(textFieldEntries, forKey: "textFieldEntries")
// prints error: Cannot convert value of type '[String?]'
// to expected argument type 'AnyObject?'
}
``` | 2015/12/02 | [
"https://Stackoverflow.com/questions/34052391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4735187/"
] | `[String?]` is a Swift type that cannot be represented as a Foundation type. Normally, Swift Array bridges to `NSArray`, but an `NSArray` cannot contain nil. An Array of Optionals can contain nil, so it doesn't bridge automatically.
You could work around this by using a sparse array representation. (And since your content is strings — a property list type and therefore legal for use in `NSUserDefaults` — you don't even need to use `NSCoding` to encode the array.) A dictionary makes a pretty good sparse array:
```
var textFieldEntries: [String?] = ["foo", nil, "bar"]
func saveToDefaults() {
var sparseArray: [String: String] = [:] // plists need string keys
for (index, entry) in textFieldEntries.enumerate() {
if let e = entry {
sparseArray["\(index)"] = e
}
}
// sparseArray = ["0": "foo", "2": "bar"]
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(sparseArray, forKey: "textFieldEntries")
}
```
Then, when you go to read in your data from defaults, convert from the sparse-array dictionary form to the array-of-optionals form. That's a little bit more fun because you need to figure out from the sparse representation how many nils you need the array to store.
```
func readFromDefaults() {
let defaults = NSUserDefaults.standardUserDefaults()
guard let sparseArray = defaults.objectForKey("textFieldEntries") as? [String: String]
else { fatalError("unepxected defaults key format") }
// count of the sparse array = index of highest key + 1
let count = sparseArray.keys.flatMap({Int($0)}).maxElement()! + 1
// wipe the old array to put nils in all the right places
textFieldEntries = [String?](count: count, repeatedValue: nil)
// fill in the values
for (strindex, entry) in sparseArray {
guard let index = Int(strindex)
else { fatalError("non-numeric key") }
textFieldEntries[index] = entry
}
}
```
(Alternately, you might know that `count` is constant because it's, say, the number of text fields in your UI.) | Let's say this is the original array
```
let textFieldEntries: [String?]
```
First of all let's turn the array of `String?` into an array of `String`.
```
let entries = textFieldEntries.flatMap { $0 }
```
Now we can save it
```
NSUserDefaults.standardUserDefaults().setObject(entries, forKey: "entries")
```
And retrieve it
```
if let retrieved = NSUserDefaults.standardUserDefaults().objectForKey("entries") as? [String] {
// here your have your array
print(retrieved)
}
``` |
38,211,463 | I am using VBA to extract texts from PDF file to a xls spreadsheet.
The texts are always the same "*Price of X", "Price of Y", "Price of Z"*.
I need to find, copy, and paste them in a spreadsheet.
I have not found any similar topics. | 2016/07/05 | [
"https://Stackoverflow.com/questions/38211463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523952/"
] | I think the best for you is to use a JQuery method as the following codes.
Your HTML would be like the following.
```
<select>
<option value="01" textValue="America">01</option>
<option value="02" textValue="Liberia">02</option>
<option value="03" textValue="Switzerland">03</option>
</select>
```
```
$("your select").on('focus', function(){
$(this).children().each(function(){
var text = $(this).attr('textValue') + ' - ' + $(this).attr('value');
$(this).text(text);
});
});
$("your select").on('blur', function(){
$(this).children().each(function(){
$(this).text($(this).attr('value'));
});
});
``` | I think what you want here is something like this
```html
<select>
<option value="01">America - 01</option>
<option value="02">Liberia - 02</option>
<option value="03">Switzerland - 03</option>
</select>
```
You can use click event for selecting in javascript, not quite sure of how you are planning to use those select.. |
71,603,642 | I found quite some info on output redirection, creation of streambuffers and ostream classes, but I did not manage to apply this succesfully yet for my purpose. This post has become quite lengthy because I wanted to describe my step by step approach.
I have an application that uses a class MyNotifier that captures events in the application and composes log messages based on the event data. By default it sends the log messages to std::cout, but the constructor of MyNotifier accepts a variable of type std::ostream& to overide this. I am trying to construct a class of that type which should send the logs to an different output channel, e.g. via an MQTT client. I have MQTT up and running well. My question is about the creation of the custom ostream class.
Here is the code that should use the new class (see the commented lines in app\_main) and it's output when I use std::cout. For testing, the events are generated by calling MyNotifier::Notify directly.
```
class MyNotifier {
public:
//constructor
MyNotifier(std::ostream& os = std::cout) : ost(os) {}
//takes eventdata as a code for the event
//composes some output string based on the input and outputs it to the customizable output stream ost
virtual void Notify( unsigned long eventdata);
protected:
std::ostream& ost;
}; //class MyNotifier
Implementation:
void MyNotifier::Notify(unsigned long eventdata) {
//takes eventdata as dummy for an event
//composes some output string based on the input and outputs it to the customizable output stream ost
char s[200];
int wr = sprintf(s, "RECEIVED EVENT %s ", "of type 1 ");
sprintf( s + wr , "with number %lu\n", eventdata);
std::cout << "MyNotifier::Notify" << s << std::endl; //this shows up
ost << "dummy custom_ostream output: " << eventdata << std::endl;
//trial to send over MQTT, in the end ost should generate MQTT output
esp_mqtt_client_publish(mqtt_client, "/fckx_seq/GUI", "value", 0, 1, 0); //works fine
} //MyNotifier::Notify
void app_main(void) {
MyNotifier notifier; //instantiate with default output stream (std::cout)
//MyNotifier notifier(std::cout); //instantiate with default output stream explicitly, also works with the same result
//MyNotifier notifier(custom_ostream) //desired way to send logs over a Custom_ostream object
notifier.Notify(3142727); //notify some event
}
```
This gives the desired output over cout:
**RECEIVED EVENT of type 1 with number 3142727**
In my first step to customize the output I only customize the streambuf class (OutStreamBuf). It is used by a "plain" ostream class:
```
class OutStreamBuf : public std::streambuf {
protected:
/* central output function
* - print characters in uppercase mode
*/
//converts each character to uppercase
virtual int_type overflow (int_type c) {
if (c != EOF) {
// convert lowercase to uppercase
c = std::toupper(static_cast<char>(c),getloc());
//output to standard output
putchar(c);
}
return c;
}
// write multiple characters MUST USE CONST CHAR* ?
virtual std::streamsize xsputn (char* s, std::streamsize num) {
std::cout << "**size: " << num << std::endl;
std::cout << "OutStreamBuf contents: " << s << std::endl;
return 1;
}
}; //OutStreamBuf
```
```
Implementation:
```
```
OutStreamBuf outStreamBuf;
std::ostream custom_ostream(&outStreamBuf);
MyNotifier notifier(custom_ostream); //instantiate with customized output stream
notifier.Notify(314132345); //notify some event
custom_ostream << "Test << operator" << std::endl;
```
```
Output:
**MyNotifier::Notify direct: RECEIVED EVENT of type 1 with number 314132345
DUMMY CUSTOM_OSTREAM OUTPUT: 314132345 <------ THIS IS THE DESIRED OUTPUT
TEST << OPERATOR**
In my second step I want to get hold of the buffer contents to be able to forward this to my MQTT handler. So I decided that I need a customized ostream object. In the second trial I therefore created a customized ostream class (OutStream) with an *embedded* customized streambuf class:
```
```
class OutStream : public std::ostream {
private:
//private local Outbuf for OutStream
class Outbuf : public std::streambuf {
protected:
/* central output function
* - print characters in uppercase mode
*/
//converts each character to uppercase
virtual int_type overflow (int_type c) {
if (c != EOF) {
// convert lowercase to uppercase
c = std::toupper(static_cast<char>(c),getloc());
//output to standard output
putchar(c);
}
return c;
}
// write multiple characters MUST USE CONST CHAR* (?)
virtual std::streamsize xsputn (char* s, std::streamsize num) {
std::cout << "**size: " << num << std::endl;
std::cout << "OUTBUF contents: " << s << std::endl;
return 1;
}
}; //Outbuf
Outbuf outbuf;
std::streambuf * buf;
public:
//constructor
OutStream() {
//buf = this->rdbuf(); //compiles OK, but what does it do ?
buf = rdbuf(); //compiles OK, but what does it do ?
std::cout << "SOME MESSAGE FROM OutStream constructor" <<std::endl;
esp_mqtt_client_publish(mqtt_client, "/fckx_seq/GUI", "OutStream constructor",
```
, 1, 0);
};
```
// << operator
//https://www.geeksforgeeks.org/overloading-stream-insertion-operators-c/
//have a good look on what parameters the operator should take , see the above article
friend std::ostream & operator << (std::ostream &stream, const OutStream& outStream){
esp_mqtt_client_publish(mqtt_client, "/fckx_seq/GUI", "OutStream << operator", 0, 1, 0); //doesn't show
stream << "Test << operator inside " << std::endl; //doesn't show
return stream; //return the stream
};
}; //OutStream
```
```
Implementation:
``` OutStream custom_ostream; //using a composite ostream/streambuf object
MyNotifier notifier(custom_ostream); //instantiate with customized output stream
notifier.Notify(314132345); //notify some event
custom_ostream << "Test << operator" << std::endl;
```
This does not show the customised output. Therefore I added a log in the constructor (properly shown) and a modified << operator with a log (also not shown):
**SOME MESSAGE FROM OutStream constructor**
**MyNotifier::Notify direct: RECEIVED EVENT of type 1 with number 314132345**
As the << operator log also fails I think that something is wrong with the constructor of the ostream object and/or it's binding with the streambuf. This is pretty complex stuff for me. Some help would be appreciated.
[EDIT] After discussion with Stephen M. Webb I focused on finding an example of a class based on std::streambuf that contains additional buffering. I found the following code that will hopefully be a good basis for further steps:
```
//p. 837 The C++ Standard Library Second Edition, Nicolai M. Josuttis
class Outbuf_buffered : public std::streambuf {
protected:
static const int bufferSize = 10; // size of data buffer
char buffer[bufferSize]; // data buffer
public:
// constructor
// - initialize data buffer
// - one character less to let the bufferSizeth character cause a call of overflow()
Outbuf_buffered() {
setp (buffer, buffer+(bufferSize-1));
}
// destructor
// - flush data buffer
virtual ~Outbuf_buffered() {
sync();
}
protected:
// flush the characters in the buffer
int flushBuffer () {
int num = pptr()-pbase();
if (write (1, buffer, num) != num) {
return EOF;
}
pbump (-num); // reset put pointer accordingly
return num;
}
// buffer full
// - write c and all previous characters
virtual int_type overflow (int_type c) {
if (c != EOF) {
// insert character into the buffer
*pptr() = c;
pbump(1);
}
// flush the buffer
if (flushBuffer() == EOF) {
// ERROR
return EOF;
}
return c;
}
// synchronize data with file/destination
// - flush the data in the buffer
virtual int sync () {
if (flushBuffer() == EOF) {
// ERROR
return -1;
}
return 0;
}
}; //Outbuf_buffered
``` | 2022/03/24 | [
"https://Stackoverflow.com/questions/71603642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884156/"
] | You don't want to touch ostream (the formatting layer) at all. You should do everything in the streambuf (the transport layer). You can use manipulators to set or change the state of the underlying transport layers through the generic ostream interface, if required. | By using a class that is derived from std::streambuf that contains an additional buffer member I can do the trick. The main ostream output stream is just std::ostream. I found an example from The C++ Standard Library Second Edition, Nicolai M. Josuttis, p. 837 .
See the EDIT in my original post.
Thanks @Stephen M. Webb for your perseverance in guiding me to the answer! |
7,777,906 | I have studied both Rails and .Net, and find myself longing for features in one that exist in the other and vice versa. Rails has a wonderfully simple syntax while the C# IDE does have features that make development easier (unless you are a command-line purist). Is there a language/framework out there that takes the best from both and puts them into one neat package? | 2011/10/15 | [
"https://Stackoverflow.com/questions/7777906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849359/"
] | If you like the syntax simplicity echo system of rails, and if it is the IDE, there is always ruby/rails IDEs which does same as VS for C#
* NetBeans
* [RadRails](http://www.aptana.com/products/radrails)
* [Rubymine](http://www.jetbrains.com/ruby/)
and lot more | [Scala](http://www.scala-lang.org/)
might work for you |
7,777,906 | I have studied both Rails and .Net, and find myself longing for features in one that exist in the other and vice versa. Rails has a wonderfully simple syntax while the C# IDE does have features that make development easier (unless you are a command-line purist). Is there a language/framework out there that takes the best from both and puts them into one neat package? | 2011/10/15 | [
"https://Stackoverflow.com/questions/7777906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849359/"
] | If you like the syntax simplicity echo system of rails, and if it is the IDE, there is always ruby/rails IDEs which does same as VS for C#
* NetBeans
* [RadRails](http://www.aptana.com/products/radrails)
* [Rubymine](http://www.jetbrains.com/ruby/)
and lot more | Have you by any change had a look at JRuby w/ IntelliJ as the IDE?:
* <http://jruby.org/>
* <http://www.jetbrains.com/idea/features/ruby_rails.html> |
7,777,906 | I have studied both Rails and .Net, and find myself longing for features in one that exist in the other and vice versa. Rails has a wonderfully simple syntax while the C# IDE does have features that make development easier (unless you are a command-line purist). Is there a language/framework out there that takes the best from both and puts them into one neat package? | 2011/10/15 | [
"https://Stackoverflow.com/questions/7777906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849359/"
] | If you like the syntax simplicity echo system of rails, and if it is the IDE, there is always ruby/rails IDEs which does same as VS for C#
* NetBeans
* [RadRails](http://www.aptana.com/products/radrails)
* [Rubymine](http://www.jetbrains.com/ruby/)
and lot more | I don't quite see the benefit of mixing ASP.NET MVC and Ruby when you have Rails. If you are looking for a IDE that's similar to Visual Studio (with ReSharper) for RoR, I would go for RubyMine. It gives you almost the same feeling as if you are working in Visual Studio. |
3,544,526 | I'm still getting used to SQL, so before I get to using stored procedure, I would like to understand how to use BULK INSERT effectively first.
I need to combine 50+ csv files and dump them into an SQL table. The problem is, I'd like to be able to tell each record apart (as in, each record belongs to a certain csv file, which I will identify by the file name).
Here's a small example of what I want:
```
CREATE TABLE ResultsDump
(
PC FLOAT,
Amp VARCHAR(50),
RCS VARCHAR(50),
CW VARCHAR(50),
State0 VARCHAR(50),
State1 VARCHAR(50),
)
BULK INSERT ResultsDump
FROM 'c:\distance1000_7_13_2010_1_13PM_Avery DennisonAD_2300008_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
BULK INSERT ResultsDump
FROM 'c:\distance1000_7_13_2010_2_27PM_Avery DennisonAD_2300009_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
BULK INSERT ResultsDump
FROM 'C:\distance1000_7_13_2010_2_58PM_Avery DennisonAD_230000A_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
BULK INSERT ResultsDump
FROM 'c:\distance1000_7_13_2010_3_21PM_Avery DennisonAD_230000B_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
BULK INSERT ResultsDump
FROM 'c:\distance1000_7_13_2010_3_41PM_Avery DennisonAD_230000C_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
```
I know this is an inefficient way of doing things, but I definitely like to figure out how to manually dump one file in the SQL table in the format I want before I start to create a stored procedure.
In the new table, I want something like this:
```
FileName,PC,Amp,RCS,CW,State0,State1
c:\distance1000_7_13_2010_1_13PM_Avery DennisonAD_2300008_10S_Lock.csv, ...
...
...
c:\distance1000_7_13_2010_2_27PM_Avery DennisonAD_2300009_10S_Lock.csv, ...
...
...
c:\distance1000_7_13_2010_2_58PM_Avery DennisonAD_230000A_10S_Lock.csv, ...
...
...
```
Any simple suggestions or referrals to specific functions would be great! Remember, I'm getting used to SQL and it'd be great if I could take this one step at a time, that's why I'm starting with such a simple question.
Thanks in advance! | 2010/08/23 | [
"https://Stackoverflow.com/questions/3544526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426124/"
] | You can add a column `FileName varchar(max)` to the ResultsDump table, create a view of the table with the new column, bulk insert into the view, and after every insert, set the filename for columns where it still has its default value `null`:
```
CREATE TABLE dbo.ResultsDump
(
PC FLOAT,
Amp VARCHAR(50),
RCS VARCHAR(50),
CW VARCHAR(50),
State0 VARCHAR(50),
State1 VARCHAR(50),
)
GO
ALTER TABLE dbo.ResultsDump ADD [FileName] VARCHAR(300) NULL
GO
CREATE VIEW dbo.vw_ResultsDump AS
SELECT
PC,
Amp,
RCS,
CW,
State0,
State1
FROM
ResultsDump
GO
BULK INSERT vw_ResultsDump
FROM 'c:\distance1000_7_13_2010_1_13PM_Avery DennisonAD_2300008_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
UPDATE dbo.ResultsDump
SET [FileName] = 'c:\distance1000_7_13_2010_1_13PM_Avery DennisonAD_2300008_10S_Lock.csv'
WHERE [FileName] IS NULL
BULK INSERT vw_ResultsDump
FROM 'c:\distance1000_7_13_2010_2_27PM_Avery DennisonAD_2300009_10S_Lock.csv'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
UPDATE dbo.ResultsDump
SET [FileName] = 'distance1000_7_13_2010_2_27PM_Avery DennisonAD_2300009_10S_Lock.csv'
WHERE [FileName] IS NULL
``` | Try this,
```
ALTER PROCEDURE [dbo].[ReadandUpdateFileNames_SP]
(
@spRequestId NVARCHAR(50)
,@LoopCounter INT =0
,@MaxFIVId INT=0
,@spFileName NVARCHAR(100)=NULL)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRAN
-- To read filename's from the Request Id and store it in a temp table
DECLARE @cmd nvarchar(500)
SET @cmd = 'dir D:\Input\REQUEST-'+@spRequestId+' /b '
--PRINT @cmd
DECLARE @DirOutput TABLE(
ID INT IDENTITY
, files varchar(500))
INSERT INTO @DirOutput
EXEC master.dbo.xp_cmdshell @cmd
SELECT * FROM @DirOutput WHERE files IS NOT NULL ORDER BY ID
----Read files by RequestId BEGIN
SELECT @LoopCounter = min(ID) , @MaxFIVId = max(ID)
FROM @DirOutput
WHILE(@LoopCounter IS NOT NULL AND @LoopCounter<@MaxFIVId)
BEGIN
-- Create temp table to store FIVItems
CREATE TABLE Items_TEMP
(
ControlID NVARCHAR(50)
, UNRS_Code NUMERIC(18,0)
, UNRS_Code_S NUMERIC(18,0)
, Ordered_Quantity NUMERIC(18,3)
, Sent_Quantity NUMERIC(18,3)
, Accepted_Quantity NUMERIC(18,3)
, Unit_Food_Price NUMERIC(18,2)
, Total_Price NUMERIC(18,2)
)
SELECT @spFileName=files FROM @DirOutput WHERE ID=@LoopCounter
PRINT @LoopCounter
DECLARE @spControlId NVARCHAR(50)
SET @spControlId='FFO'+ Substring(@spFileName, 4, (len(@spFileName)-7))
--PRINT @spControlId
DECLARE @sqlCmd NVARCHAR(MAX)
SET @sqlCmd='BULK INSERT
Items_TEMP
FROM ''D:\Input\REQUEST-'+@spRequestId+'\'+@spFileName+'''
WITH(
FIELDTERMINATOR='',''
, ROWTERMINATOR=''\n''
)'
PRINT @sqlCmd
EXECUTE sp_executesql @sqlCmd
---Add a new column to the table which is not present in the CSV
ALTER TABLE Items_TEMP ADD OrderId NUMERIC(18,0)NULL
UPDATE Items_TEMP SET ControlID=@spControlId,OrderId=(SELECT OrderId FROM dbo.Orders WHERE ControlID=@spControlId)
SELECT * FROM Items_TEMP
--DROP FIVItems_TEMP table once CSV output generated
DROP TABLE Items_TEMP
SET @LoopCounter=@LoopCounter+1
END
----****END***
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
PRINT 'ROLLBACK'
PRINT Error_Message()
SELECT ERROR_LINE() AS ErrorLine;
END CATCH
SET NOCOUNT OFF
END
``` |
58,091,754 | I'm sending date from Date picker it's going correct date but when I check in the controller the date was getting yesterday date in spring boot backend and angualr js in frontend
I havea tried setting timezone in application properties
like :
>
> spring.jackson.time-zone=IST
>
>
> spring.jackson.locale=in\_IN
>
>
>
but didn't work
date which is gonign ==dao: `Tue Oct 01 2019 00:00:00 GMT+0530` (India Standard Time) and
the date which gets in controller== `dao=2019-09-30T18:30:00.000Z` | 2019/09/25 | [
"https://Stackoverflow.com/questions/58091754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10293590/"
] | The easiest way is to disable user interaction of super view and then run a timer with desired delay for the touch and enable the user interaction once the timer is invalidated. | Do not use timers or the dispatch. These do not correspond to your in game time. If you exit your app or get a phone call, these will fire prematurely.
Instead, use an action on your scene:
```
let wait = SKAction.wait(forDuration:2)
let run = SKAction.run{self.isUserInteractionEnabled = true}
self.run(SKAction.sequence[wait,run])
self.isUserInteractionEnabled = false
``` |
8,615,285 | I'm trying to create a simple HTML layout where there is a header, content and footer section vertically layed out.
The heights of both header and footer should be flexible, determined by the content.
The height of the content section should be the remaining height, so the entire layout uses the full height of the window. The content section would be scrollable.
So, in order:
1. Header. Height depends on content height. No scrollbars.
2. Content. Height is the remainder; window\_height - (header\_height + footer\_height). Scrollbar if needed (overflow: auto;)
3. Footer. Height depends on content height. No scrollbars.
There are many examples for static header and footer heights but I found none that can deal with content-based heights.
I've tried plain divs with position: absolute/relative/fixed. I've tried divs with display: table/table-row/table-cell in several configurations. I've even tried using an actual . But none of these seem to work. Here's one of the many failed attempts: <http://jsbin.com/uveloj/15/edit>
How can I do this without scripting (I prefer not to rely on JS whenever possible), if it is even possible at all. | 2011/12/23 | [
"https://Stackoverflow.com/questions/8615285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/951064/"
] | The first thing you should do is read the Apple documentation relating to [App States](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html) and [Responding to Low-Memory Warnings in iOS](http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/MemoryAlloc.html#//apple_ref/doc/uid/20001881-SW1)
Also see the Adopting Multitasking videos from WWDC 2010/11
Come back and ask if you have any more questions. | you're right in that the more apps that are run the more memory is used, and if the OS decides it needs to free some memory it could kill your app. there's nothing you can do about this, apart from saving your application's state when the app enters the background (you really should do this anyway). never assume you'll stay resident in the background. |
8,615,285 | I'm trying to create a simple HTML layout where there is a header, content and footer section vertically layed out.
The heights of both header and footer should be flexible, determined by the content.
The height of the content section should be the remaining height, so the entire layout uses the full height of the window. The content section would be scrollable.
So, in order:
1. Header. Height depends on content height. No scrollbars.
2. Content. Height is the remainder; window\_height - (header\_height + footer\_height). Scrollbar if needed (overflow: auto;)
3. Footer. Height depends on content height. No scrollbars.
There are many examples for static header and footer heights but I found none that can deal with content-based heights.
I've tried plain divs with position: absolute/relative/fixed. I've tried divs with display: table/table-row/table-cell in several configurations. I've even tried using an actual . But none of these seem to work. Here's one of the many failed attempts: <http://jsbin.com/uveloj/15/edit>
How can I do this without scripting (I prefer not to rely on JS whenever possible), if it is even possible at all. | 2011/12/23 | [
"https://Stackoverflow.com/questions/8615285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/951064/"
] | you're right in that the more apps that are run the more memory is used, and if the OS decides it needs to free some memory it could kill your app. there's nothing you can do about this, apart from saving your application's state when the app enters the background (you really should do this anyway). never assume you'll stay resident in the background. | You should save your app status and data when your app before your app goes into the background. |
8,615,285 | I'm trying to create a simple HTML layout where there is a header, content and footer section vertically layed out.
The heights of both header and footer should be flexible, determined by the content.
The height of the content section should be the remaining height, so the entire layout uses the full height of the window. The content section would be scrollable.
So, in order:
1. Header. Height depends on content height. No scrollbars.
2. Content. Height is the remainder; window\_height - (header\_height + footer\_height). Scrollbar if needed (overflow: auto;)
3. Footer. Height depends on content height. No scrollbars.
There are many examples for static header and footer heights but I found none that can deal with content-based heights.
I've tried plain divs with position: absolute/relative/fixed. I've tried divs with display: table/table-row/table-cell in several configurations. I've even tried using an actual . But none of these seem to work. Here's one of the many failed attempts: <http://jsbin.com/uveloj/15/edit>
How can I do this without scripting (I prefer not to rely on JS whenever possible), if it is even possible at all. | 2011/12/23 | [
"https://Stackoverflow.com/questions/8615285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/951064/"
] | you're right in that the more apps that are run the more memory is used, and if the OS decides it needs to free some memory it could kill your app. there's nothing you can do about this, apart from saving your application's state when the app enters the background (you really should do this anyway). never assume you'll stay resident in the background. | If you want your app to run for a limited time in the background, and have set the appropriate background modes plist keys, your app must minimize it's memory footprint in order for the OS not to kill it. Release **everything** except the bare minimum resources required to run in the background, preferably to only a few MB of dirty memory. Since you can't display anything in the background, that means releasing all views, UI assets and images, etc. until your app becomes active again. |
8,615,285 | I'm trying to create a simple HTML layout where there is a header, content and footer section vertically layed out.
The heights of both header and footer should be flexible, determined by the content.
The height of the content section should be the remaining height, so the entire layout uses the full height of the window. The content section would be scrollable.
So, in order:
1. Header. Height depends on content height. No scrollbars.
2. Content. Height is the remainder; window\_height - (header\_height + footer\_height). Scrollbar if needed (overflow: auto;)
3. Footer. Height depends on content height. No scrollbars.
There are many examples for static header and footer heights but I found none that can deal with content-based heights.
I've tried plain divs with position: absolute/relative/fixed. I've tried divs with display: table/table-row/table-cell in several configurations. I've even tried using an actual . But none of these seem to work. Here's one of the many failed attempts: <http://jsbin.com/uveloj/15/edit>
How can I do this without scripting (I prefer not to rely on JS whenever possible), if it is even possible at all. | 2011/12/23 | [
"https://Stackoverflow.com/questions/8615285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/951064/"
] | The first thing you should do is read the Apple documentation relating to [App States](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html) and [Responding to Low-Memory Warnings in iOS](http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/MemoryAlloc.html#//apple_ref/doc/uid/20001881-SW1)
Also see the Adopting Multitasking videos from WWDC 2010/11
Come back and ask if you have any more questions. | You should save your app status and data when your app before your app goes into the background. |
8,615,285 | I'm trying to create a simple HTML layout where there is a header, content and footer section vertically layed out.
The heights of both header and footer should be flexible, determined by the content.
The height of the content section should be the remaining height, so the entire layout uses the full height of the window. The content section would be scrollable.
So, in order:
1. Header. Height depends on content height. No scrollbars.
2. Content. Height is the remainder; window\_height - (header\_height + footer\_height). Scrollbar if needed (overflow: auto;)
3. Footer. Height depends on content height. No scrollbars.
There are many examples for static header and footer heights but I found none that can deal with content-based heights.
I've tried plain divs with position: absolute/relative/fixed. I've tried divs with display: table/table-row/table-cell in several configurations. I've even tried using an actual . But none of these seem to work. Here's one of the many failed attempts: <http://jsbin.com/uveloj/15/edit>
How can I do this without scripting (I prefer not to rely on JS whenever possible), if it is even possible at all. | 2011/12/23 | [
"https://Stackoverflow.com/questions/8615285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/951064/"
] | The first thing you should do is read the Apple documentation relating to [App States](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html) and [Responding to Low-Memory Warnings in iOS](http://developer.apple.com/library/mac/#documentation/Performance/Conceptual/ManagingMemory/Articles/MemoryAlloc.html#//apple_ref/doc/uid/20001881-SW1)
Also see the Adopting Multitasking videos from WWDC 2010/11
Come back and ask if you have any more questions. | If you want your app to run for a limited time in the background, and have set the appropriate background modes plist keys, your app must minimize it's memory footprint in order for the OS not to kill it. Release **everything** except the bare minimum resources required to run in the background, preferably to only a few MB of dirty memory. Since you can't display anything in the background, that means releasing all views, UI assets and images, etc. until your app becomes active again. |
57,080,989 | it shows the error on the emulator while playing
>
> java.lang.RuntimeException: Unable to start activity
> ComponentInfo{com.nehagupta.braintrainer/com.nehagupta.braintrainer.MainActivity}:
> java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.TextView.setText(java.lang.CharSequence)' on a null
> object reference at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
> at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
> at android.app.ActivityThread.-wrap12(ActivityThread.java) at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
> at android.os.Handler.dispatchMessage(Handler.java:102) at
> android.os.Looper.loop(Looper.java:163) at
> android.app.ActivityThread.main(ActivityThread.java:6238) at
> java.lang.reflect.Method.invoke(Native Method) at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual
> method 'void android.widget.TextView.setText(java.lang.CharSequence)'
> on a null object reference at
> com.nehagupta.braintrainer.MainActivity.generateQuestion(MainActivity.java:36)
> at
> com.nehagupta.braintrainer.MainActivity.onCreate(MainActivity.java:90)
> at android.app.Activity.performCreate(Activity.java:6857) at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
> at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
> ... 9 more
>
>
> java.lang.RuntimeException: Unable to start activity
> ComponentInfo{com.nehagupta.braintrainer/com.nehagupta.braintrainer.MainActivity}:
> java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.TextView.setText(java.lang.CharSequence)' on a null
> object reference at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
> at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
> at android.app.ActivityThread.-wrap12(ActivityThread.java) at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
> at android.os.Handler.dispatchMessage(Handler.java:102) at
> android.os.Looper.loop(Looper.java:163) at
> android.app.ActivityThread.main(ActivityThread.java:6238) at
> java.lang.reflect.Method.invoke(Native Method) at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
> Caused by: java.lang.NullPointerException: Attempt to invoke virtual
> method 'void android.widget.TextView.setText(java.lang.CharSequence)'
> on a null object reference at
> com.nehagupta.braintrainer.MainActivity.generateQuestion(MainActivity.java:36)
> at
> com.nehagupta.braintrainer.MainActivity.onCreate(MainActivity.java:90)
> at android.app.Activity.performCreate(Activity.java:6857) at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
> at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
> ... 9 more
>
>
> | 2019/07/17 | [
"https://Stackoverflow.com/questions/57080989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11798729/"
] | Turns out that I had missed setting the default value for the `CurrencyID` property. Kind of obvious now I see it.
I added the following...
```
builder.Entity<Donation>()
.Property(p => p.CurrencyID)
.HasDefaultValue(1);
```
...and the error went away.
On a side note, this gave me a different error about causing cycles or multiple cascade paths. I got around this by modifying the `Up` method in the migration, setting the `onDelete` to `Restrict` rather than the default `Default`...
```
migrationBuilder.AddForeignKey(
name: "FK_Donations_Currencies_CurrencyID",
table: "Donations",
column: "CurrencyID",
principalTable: "Currencies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
``` | There's a few different ways you could tackle it.
1)
* Generate your migration with your property being non-nullable, and including the data as you are now, but modify the migration so it adds the column as a nullable, and pre-populate the data and alter it later to become non-nullable.
2)
* Generate a migration with the property being nullable, and including the data as you are now
* Make the property non-nullable and generate a second migration, but at the top, manually do your update via SQL. |
111,408 | On [this deleted answer](https://stackoverflow.com/questions/8054165/using-put-method-in-html-form/8054177#8054177), there is a comment which I am able to click the up arrow (great comment button) on. The vote registers, as in, it changes the arrow to orange, however when I refresh the page my upvote is not reflected.
Is this desired? Should there not be a message such as "This comment in on a deleted answer; the comment cannot be voted on"? | 2011/11/08 | [
"https://meta.stackexchange.com/questions/111408",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/-1/"
] | That *used* to trigger an alert saying
>
> Comments on deleted answers cannot be upvoted
>
>
>
Recent [bug](/questions/tagged/bug "show questions tagged 'bug'"), I assume | On Meta Stack Overflow, which is using revision 2011.11.8.6 of the code (instead of the revision 2011.11.8.4 used on Stack Overflow), voting a comment on a deleted post doesn't show an error message, and the vote seems accepted.

When you refresh the page, the comment is shown as not voted.

This means the vote was not really recorded, also because (as pointed out from Anna Lear) there should be a 1 close the the black arrow, which is missing in the first screenshot I shown.
It simply happens that the error message is not shown anymore, but the vote is not recorded. |
49,047,244 | I am processing outputs from a piece of software that provides co-ordinates as an x, y, z triple in a single column. Is there any way to split the string out into its three separate parts and convert to floats in one fell swoop? For example, I know that I can do the following:
```
import pandas as pd
df = pd.DataFrame({'ID': {0: 3864, 1: 3864, 2: 3864, 3: 3864, 4: 3864},
'COORDFRONT': {0: '787.547 238.639 0.000', 1: '787.141 238.847 0.000', 2: '786.729 239.057 0.000', 3: '786.310 239.271 0.000', 4: '785.886 239.488 0.000'},
'COORDREAR': {0: '803.545 230.467 0.000', 1: '803.139 230.675 0.000', 2: '802.727 230.885 0.000', 3: '802.309 231.099 0.000', 4: '801.884 231.316 0.000'}})
df['Front_x'], df['Front_y'], df['Front_z'] = df['COORDFRONT'].str.split(' ').str
```
To separate out the three strings, but trying for example
```
df['COORDFRONT'].str.split(' ').astype(float)
```
returns a `ValueError`. | 2018/03/01 | [
"https://Stackoverflow.com/questions/49047244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309300/"
] | Use [`split`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html) with `expand=True` for `DataFrame` and assign to new columns in subset by double `[]`:
```
df[['Front_x', 'Front_y', 'Front_z']] = df['COORDFRONT'].str.split(expand=True).astype(float)
print (df)
COORDFRONT COORDREAR ID Front_x Front_y \
0 787.547 238.639 0.000 803.545 230.467 0.000 3864 787.547 238.639
1 787.141 238.847 0.000 803.139 230.675 0.000 3864 787.141 238.847
2 786.729 239.057 0.000 802.727 230.885 0.000 3864 786.729 239.057
3 786.310 239.271 0.000 802.309 231.099 0.000 3864 786.310 239.271
4 785.886 239.488 0.000 801.884 231.316 0.000 3864 785.886 239.488
Front_z
0 0.0
1 0.0
2 0.0
3 0.0
4 0.0
```
If no `NaN`s values in column is possible use `list comprehension`:
```
L = [x.split() for x in df['COORDFRONT'].values.tolist()]
df[['Front_x', 'Front_y', 'Front_z']] = pd.DataFrame(L).astype(float)
``` | This is one way:
```
df['Front_x'], df['Front_y'], df['Front_z'] = list(zip(*[list(map(float, i)) for i in \
df['COORDFRONT'].str.split(' ')]))
```
**Result**
```
df.dtypes
# COORDFRONT object
# COORDREAR object
# ID int64
# Front_x float64
# Front_y float64
# Front_z float64
# dtype: object
```
**Explanation**
* `map` each row of string values to `float` from your `split` results.
* Apply `zip(*...)` in order to output as 3 arrays required to assign to 3 series.
**Performance**
For better performance on large dataframes, use [@jezrael's solution](https://stackoverflow.com/a/49047277/9209546). Some benchmarking results below.
```
df = pd.DataFrame({'ID': {0: 3864, 1: 3864, 2: 3864, 3: 3864, 4: 3864},
'COORDFRONT': {0: '787.547 238.639 0.000', 1: '787.141 238.847 0.000', 2: '786.729 239.057 0.000', 3: '786.310 239.271 0.000', 4: '785.886 239.488 0.000'},
'COORDREAR': {0: '803.545 230.467 0.000', 1: '803.139 230.675 0.000', 2: '802.727 230.885 0.000', 3: '802.309 231.099 0.000', 4: '801.884 231.316 0.000'}})
def jp(df):
df['Front_x'], df['Front_y'], df['Front_z'] = list(zip(*[list(map(float, i)) for i in df['COORDFRONT'].str.split(' ')]))
return df
def jez(df):
df[['Front_x', 'Front_y', 'Front_z']] = df['COORDFRONT'].str.split(expand=True).astype(float)
return df
# df = pd.concat([df]*100)
%timeit jp(df) # 2.2ms
%timeit jez(df) # 2.94ms
# df = pd.concat([df]*10000
%timeit jp(df) # 154ms
%timeit jez(df) # 127ms
``` |
260,818 | [Drupal 8]
I have a List (text) field that allows multiple values, displayed as a check box list when editing. But when viewing the node, only the checked values are displayed.
**How can I display *all* values, with an indicator which ones are checked/unchecked?** Is this possible with theming?
What I found so far:
* For Boolean fields, I can select something like this under "Output format" (e.g., "✔ / ✖"), but this doesn’t seem to be possible for List (text) fields. I guess the workaround would be to use multiple Boolean fields, but this makes Views Exposed Filters harder to use.
* For Drupal 7, there is the module [Selected and unselected values formatter](https://www.drupal.org/project/selected_and_unselected_values_formatter) (via the question [*How to display all values of List (text) instead of just the selected ones?*](https://drupal.stackexchange.com/q/107666/9223))
* I could imagine (but didn’t try) it would be possible to create a View and display it instead of the field, but then quick-editing would no longer work for this field, as far as I know. | 2018/04/29 | [
"https://drupal.stackexchange.com/questions/260818",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/9223/"
] | You can easily generate a field formatter to output what you need in drupal 8 ([generate field formatter](https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter) => `drupal gpff` with drupal console) and get the result into a view.
Getting the field definition will allow you to get all possibles values (selected or not) for your list and display items as check or not considering the current node value.
```
$defs = \Drupal::service('entity_field.manager')->getFieldDefinitions('{ENTITY_TYPE}', '{BUNDLE}');
$field_definition = $defs['{FIELD_NAME}'];
```
Your custom formatter will be available in views (and everywhere it is usable, node display etc.). | ['Display Selected and Unselected'](https://www.drupal.org/project/display_selected_and_unselected) module - is one of the possible solutions for Drupal 8. |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | The `List.fold` function takes a lambda / function of type `State -> T -> State`. The `+` operator in this case has type `Person -> Person -> int` which is incompatible with the signature. This is why you're getting the error.
To fold the ages try the following
```
people |> List.fold (fun sum p -> sum + p.Age) 0
```
One way to use the `+` operator here as part of the fold is to map the `Person` into the Age property and then use fold against the `int +` operator.
```
people
|> Seq.ofList
|> Seq.map (fun p -> p.Age)
|> Seq.fold (+) 0
``` | How about this (+) overload?
```
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = { Name = x.Name + " and " + y.Name; Age = x.Age + y.Age }
let jen = { Name = "Jen"; Age = 20 }
let kevin = { Name = "Kevin"; Age = 40 }
[jen; kevin] |> List.fold (+) { Name = ""; Age = 0 };;
```
will return
```
val it : Person = {Name = "Jen and Kevin";
Age = 60;}
```
Makes sense?
But seriously, if you feel that finding summary age of a group of people is integral to your `Person` class you may consider making the correspondent static class member `GroupAge` instead of overloading `(+)`:
```
type Person =
{ Name : string; Age: int }
static member GroupAge = List.fold (fun age person -> age + person.Age) 0
```
and use it when needed as below:
```
[jen; kevin] |> Person.GroupAge
``` |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | The `List.fold` function takes a lambda / function of type `State -> T -> State`. The `+` operator in this case has type `Person -> Person -> int` which is incompatible with the signature. This is why you're getting the error.
To fold the ages try the following
```
people |> List.fold (fun sum p -> sum + p.Age) 0
```
One way to use the `+` operator here as part of the fold is to map the `Person` into the Age property and then use fold against the `int +` operator.
```
people
|> Seq.ofList
|> Seq.map (fun p -> p.Age)
|> Seq.fold (+) 0
``` | Here is a reasonable solution that may be useful for you.
```
type Person = {
Name : string
Age: int
} with
static member (+) (x: Person, y: Person) =
{ Set = Set.ofList [x; y]; SumOfAges = x.Age + y.Age }
and People = {
Set:Person Set
SumOfAges:int
} with
static member (+) (x:People, y:Person) =
{ x with Set = x.Set.Add y; SumOfAges = x.SumOfAges + y.Age }
static member Empty =
{ Set = Set.empty; SumOfAges = 0 }
let p = [ { Name = "Matt"; Age = 32; }; { Name = "Dan"; Age = 26; } ]
let r = p |> List.fold (+) People.Empty
``` |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | The `List.fold` function takes a lambda / function of type `State -> T -> State`. The `+` operator in this case has type `Person -> Person -> int` which is incompatible with the signature. This is why you're getting the error.
To fold the ages try the following
```
people |> List.fold (fun sum p -> sum + p.Age) 0
```
One way to use the `+` operator here as part of the fold is to map the `Person` into the Age property and then use fold against the `int +` operator.
```
people
|> Seq.ofList
|> Seq.map (fun p -> p.Age)
|> Seq.fold (+) 0
``` | I think your problem is conceptual. What you pass to `List.fold` is a single function. It is best to think of `+` as syntactic sugar for a whole stack of different functions - with type signatures like `int -> int -> int`, `float -> float -> float` and `person -> person -> int`.
So what happens when the compiler sees this: ?
```
List.fold (+) 0 people;;
```
So we have a `person` list as well as a default argument of `0` which is an `int`. So we look at the signature for `fold`
```
List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State
```
One way of interpreting this could be `'State = int`, based on the `0`. So as a result, we need to find an overload of `+` which looks like
```
int -> Person -> int
```
This of course doesn't exist. You can then use this to come up with a better definition for your `+` operator. Something like
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: int, y: Person) = x + y.Age
``` |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | The `List.fold` function takes a lambda / function of type `State -> T -> State`. The `+` operator in this case has type `Person -> Person -> int` which is incompatible with the signature. This is why you're getting the error.
To fold the ages try the following
```
people |> List.fold (fun sum p -> sum + p.Age) 0
```
One way to use the `+` operator here as part of the fold is to map the `Person` into the Age property and then use fold against the `int +` operator.
```
people
|> Seq.ofList
|> Seq.map (fun p -> p.Age)
|> Seq.fold (+) 0
``` | the problem is than + is defined for add integers,floats,etc and you define an + for add 2 Persons..but when you try:
```
List.fold (+) 0 people;;
```
you're trying add an int (0) with a Person (people)
that is!..
actually when you add 2 peoples this return an integer...then everytime than you iterate over people you will get the accumulate (integer) and the people (Person list).....
now..the simple way solve this without add more overloads or generics would be try:
```
[kevin;jen] |> List.fold (fun acc person -> acc + person.Age) 0
```
similar to the example from <http://msdn.microsoft.com/en-us/library/dd233224.aspx>
```
let data = [("Cats",4);
("Dogs",5);
("Mice",3);
("Elephants",2)]
let count = List.fold (fun acc (nm,x) -> acc+x) 0 data
printfn "Total number of animals: %d" count
```
... |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | How about this (+) overload?
```
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = { Name = x.Name + " and " + y.Name; Age = x.Age + y.Age }
let jen = { Name = "Jen"; Age = 20 }
let kevin = { Name = "Kevin"; Age = 40 }
[jen; kevin] |> List.fold (+) { Name = ""; Age = 0 };;
```
will return
```
val it : Person = {Name = "Jen and Kevin";
Age = 60;}
```
Makes sense?
But seriously, if you feel that finding summary age of a group of people is integral to your `Person` class you may consider making the correspondent static class member `GroupAge` instead of overloading `(+)`:
```
type Person =
{ Name : string; Age: int }
static member GroupAge = List.fold (fun age person -> age + person.Age) 0
```
and use it when needed as below:
```
[jen; kevin] |> Person.GroupAge
``` | the problem is than + is defined for add integers,floats,etc and you define an + for add 2 Persons..but when you try:
```
List.fold (+) 0 people;;
```
you're trying add an int (0) with a Person (people)
that is!..
actually when you add 2 peoples this return an integer...then everytime than you iterate over people you will get the accumulate (integer) and the people (Person list).....
now..the simple way solve this without add more overloads or generics would be try:
```
[kevin;jen] |> List.fold (fun acc person -> acc + person.Age) 0
```
similar to the example from <http://msdn.microsoft.com/en-us/library/dd233224.aspx>
```
let data = [("Cats",4);
("Dogs",5);
("Mice",3);
("Elephants",2)]
let count = List.fold (fun acc (nm,x) -> acc+x) 0 data
printfn "Total number of animals: %d" count
```
... |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | Here is a reasonable solution that may be useful for you.
```
type Person = {
Name : string
Age: int
} with
static member (+) (x: Person, y: Person) =
{ Set = Set.ofList [x; y]; SumOfAges = x.Age + y.Age }
and People = {
Set:Person Set
SumOfAges:int
} with
static member (+) (x:People, y:Person) =
{ x with Set = x.Set.Add y; SumOfAges = x.SumOfAges + y.Age }
static member Empty =
{ Set = Set.empty; SumOfAges = 0 }
let p = [ { Name = "Matt"; Age = 32; }; { Name = "Dan"; Age = 26; } ]
let r = p |> List.fold (+) People.Empty
``` | the problem is than + is defined for add integers,floats,etc and you define an + for add 2 Persons..but when you try:
```
List.fold (+) 0 people;;
```
you're trying add an int (0) with a Person (people)
that is!..
actually when you add 2 peoples this return an integer...then everytime than you iterate over people you will get the accumulate (integer) and the people (Person list).....
now..the simple way solve this without add more overloads or generics would be try:
```
[kevin;jen] |> List.fold (fun acc person -> acc + person.Age) 0
```
similar to the example from <http://msdn.microsoft.com/en-us/library/dd233224.aspx>
```
let data = [("Cats",4);
("Dogs",5);
("Mice",3);
("Elephants",2)]
let count = List.fold (fun acc (nm,x) -> acc+x) 0 data
printfn "Total number of animals: %d" count
```
... |
8,797,562 | I'm trying to use List.fold on a record type that defines an operator overload for `+`, but I'm getting a type mismatch error when trying to use the `(+)` operator as the lambda passed to fold. Here's a simplified snippet that exemplifies my problem:
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: Person, y: Person) = x.Age + y.Age
```
the `+` overload works just fine
```
> jen + kevin;;
val it : int = 87
```
but say I have a list of person:
```
> let people = [kevin;jen];;
```
I can't use List.fold to sum all the ages:
```
> List.fold (+) 0 people;;
List.fold (+) 0 people;;
----------------^^^^^^
error FS0001: Type constraint mismatch. The type
int
is not compatible with type
Person
The type 'int' is not compatible with the type 'Person'
```
I'm guessing the problem is that F# isn't able to discern the overload of `+` when passed in this fashion, since fold is implicitly typing the list to `int` because I used '0' as the accumulator. I'm not sure if it's possible to get my custom operator overload to work correctly, and if it is possible, what I'm missing to make it happen. (I'm assuming it is possible to make this work because you can use `+` on floats).
edit
----
I understand that the problem is the the type mismatch. As JaredPar writes, I get that I could write a lambda to take two person records and add the ages. That's not my point. The issue is that it seems to me there should be a way to get the `+` operator overload I already wrote to be acknowledged by fold as a valid overload.
another edit
------------
Thanks all for your input. One thing that's becoming clear is that it **isn't** possible to do what I want, but that's fine. I learned something! What I'm seeing is that the resolution of operator overloads is such that they don't work in every context--so with `fold` there is no **seamless** way to make `+` passed as a lambda work just like it would when used as an infix ala `jen + kevin`. It makes total sense why this doesn't work right. The resolutions people have suggested to resolve this problem basically are one-off's to handle the particular issue of `fold`--what I'm really after is how to get the correct operator overload to get picked for **every** situation (i.e. `foldback`, etc)--I didn't want to have to write a bunch of special case code for working over lists. It's pretty clear not what F#'s operator overload resolution has some limitations that make it work to a skin-deep level, which is fine. | 2012/01/10 | [
"https://Stackoverflow.com/questions/8797562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73482/"
] | I think your problem is conceptual. What you pass to `List.fold` is a single function. It is best to think of `+` as syntactic sugar for a whole stack of different functions - with type signatures like `int -> int -> int`, `float -> float -> float` and `person -> person -> int`.
So what happens when the compiler sees this: ?
```
List.fold (+) 0 people;;
```
So we have a `person` list as well as a default argument of `0` which is an `int`. So we look at the signature for `fold`
```
List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State
```
One way of interpreting this could be `'State = int`, based on the `0`. So as a result, we need to find an overload of `+` which looks like
```
int -> Person -> int
```
This of course doesn't exist. You can then use this to come up with a better definition for your `+` operator. Something like
```
// a record type that also includes an overload for '+'
type Person =
{ Name : string; Age: int }
static member ( + ) (x: int, y: Person) = x + y.Age
``` | the problem is than + is defined for add integers,floats,etc and you define an + for add 2 Persons..but when you try:
```
List.fold (+) 0 people;;
```
you're trying add an int (0) with a Person (people)
that is!..
actually when you add 2 peoples this return an integer...then everytime than you iterate over people you will get the accumulate (integer) and the people (Person list).....
now..the simple way solve this without add more overloads or generics would be try:
```
[kevin;jen] |> List.fold (fun acc person -> acc + person.Age) 0
```
similar to the example from <http://msdn.microsoft.com/en-us/library/dd233224.aspx>
```
let data = [("Cats",4);
("Dogs",5);
("Mice",3);
("Elephants",2)]
let count = List.fold (fun acc (nm,x) -> acc+x) 0 data
printfn "Total number of animals: %d" count
```
... |
33,806 | I sometimes see ‘you and …’ in English, for example “you and the other nine”, “You and your big mouth!”. This makes me sensitive to *you and something*.
>
> “Okay,” said Harry slowly. “But … are you saying Karkaroff put my name in the goblet? Because if he did, he’s a really good actor. He seemed furious about it. He wanted to stop me from competing.”
>
>
> “We know he’s a good actor,” said Sirius, “because he convinced the Ministry of Magic to set him free, didn’t he? Now, I’ve been keeping an eye on the *Daily Prophet*, Harry –“
>
>
> “– **you and the rest of the world**,” said Harry bitterly.
>
>
> “—and reading between the lines of that Skeeter woman’s article last month, Moody was attacked the night before he started at Hogwarts. (The rest is omitted.)
> (p333, Harry Potter 4, US edition)
>
>
>
**NB** - Harry doesn’t like anyone to be interested in the *Daily Prophet* because Skeeter, a news reporter of the paper, is always inventing stories about Harry.
Does this ‘**you and the rest of the world**’ mean just a literal meaning? If Harry says “The other people, too”, is there any big difference in what Harry means to say? | 2011/07/12 | [
"https://english.stackexchange.com/questions/33806",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | As stated by yourself, Harry doesn't like anyone to be interested in the *Daily Prophet*.
When "Harry" said 'you and the rest of the world', he is stating : "*Everyone* reads the *Daily Prophet*!"
It's the same when someone say, teases you. You could get upset and say "No one likes me anymore!"
Not really literally *no one*. It's just an expression. | Harry is using sarcasm to convey his contempt for the Daily Prophet. If the statement didn't include exaggeration as it does, it would lose meaning sounding a bit absurd.
"You and..." is a fairly common meme used in this sarcastic context. It can be used either in a happy joking fashion or the above bitter fashion amongst others. "You and your whole family," "You and everybody else in the neighborhood"
It can be used to mock an object, a practice, or the target of "you" for appearing to claim something unique about themselves which is, in fact, common. |
33,806 | I sometimes see ‘you and …’ in English, for example “you and the other nine”, “You and your big mouth!”. This makes me sensitive to *you and something*.
>
> “Okay,” said Harry slowly. “But … are you saying Karkaroff put my name in the goblet? Because if he did, he’s a really good actor. He seemed furious about it. He wanted to stop me from competing.”
>
>
> “We know he’s a good actor,” said Sirius, “because he convinced the Ministry of Magic to set him free, didn’t he? Now, I’ve been keeping an eye on the *Daily Prophet*, Harry –“
>
>
> “– **you and the rest of the world**,” said Harry bitterly.
>
>
> “—and reading between the lines of that Skeeter woman’s article last month, Moody was attacked the night before he started at Hogwarts. (The rest is omitted.)
> (p333, Harry Potter 4, US edition)
>
>
>
**NB** - Harry doesn’t like anyone to be interested in the *Daily Prophet* because Skeeter, a news reporter of the paper, is always inventing stories about Harry.
Does this ‘**you and the rest of the world**’ mean just a literal meaning? If Harry says “The other people, too”, is there any big difference in what Harry means to say? | 2011/07/12 | [
"https://english.stackexchange.com/questions/33806",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | As stated by yourself, Harry doesn't like anyone to be interested in the *Daily Prophet*.
When "Harry" said 'you and the rest of the world', he is stating : "*Everyone* reads the *Daily Prophet*!"
It's the same when someone say, teases you. You could get upset and say "No one likes me anymore!"
Not really literally *no one*. It's just an expression. | This is a common phrase that actually has a pretty nuanced meaning. It's synonymous to the phrase "Everyone and their grandmother." Everyone would already include all grandmothers, so this is just a silly way of saying "A whole lot of people."
Of course, Harry isn't actually saying "Everyone else in the world is reading the Daily Prophet." At its base, it means "A whole lot of people -- more than one would expect in a normal circumstance -- are reading the daily prophet." This phrase is an example of hyperbole. The connotation of this phrase varies between "neutral/matter-of-fact" and "negative."
This harry potter example is negative. Something like "Everyone in the world is here" is neutral, and just an observation that 'here' has more people than he expected, by a large margin. |
33,806 | I sometimes see ‘you and …’ in English, for example “you and the other nine”, “You and your big mouth!”. This makes me sensitive to *you and something*.
>
> “Okay,” said Harry slowly. “But … are you saying Karkaroff put my name in the goblet? Because if he did, he’s a really good actor. He seemed furious about it. He wanted to stop me from competing.”
>
>
> “We know he’s a good actor,” said Sirius, “because he convinced the Ministry of Magic to set him free, didn’t he? Now, I’ve been keeping an eye on the *Daily Prophet*, Harry –“
>
>
> “– **you and the rest of the world**,” said Harry bitterly.
>
>
> “—and reading between the lines of that Skeeter woman’s article last month, Moody was attacked the night before he started at Hogwarts. (The rest is omitted.)
> (p333, Harry Potter 4, US edition)
>
>
>
**NB** - Harry doesn’t like anyone to be interested in the *Daily Prophet* because Skeeter, a news reporter of the paper, is always inventing stories about Harry.
Does this ‘**you and the rest of the world**’ mean just a literal meaning? If Harry says “The other people, too”, is there any big difference in what Harry means to say? | 2011/07/12 | [
"https://english.stackexchange.com/questions/33806",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | As stated by yourself, Harry doesn't like anyone to be interested in the *Daily Prophet*.
When "Harry" said 'you and the rest of the world', he is stating : "*Everyone* reads the *Daily Prophet*!"
It's the same when someone say, teases you. You could get upset and say "No one likes me anymore!"
Not really literally *no one*. It's just an expression. | "You and..." is an idiomatic use of English, which means it is used more figuratively than literally.
In saying *"You and the rest of the world,"* Harry is pointing out that Ron is not the only person who is reading about him in the *Prophet*. We are being told that a lot of other people are doing the same thing; not literally everyone else in the world, but still an impressively large number.
Similarly, *"You and your big mouth"* doesn't literally mean that you have an unusually large mouth. Instead it means that you talk too much (*i.e.* use that mouth a lot). The unspoken continuation of the sentence would be something like *"...have just said something really stupid."*
*"The other people, too,"* is not quite equivalent to *"You and the rest of the world."* There are shadings of meaning that make it work much less well in context; in particular, it takes the focus off "you" and implies that the others are in some way important to the discussion. *"You and the rest"* only cares that the other people exist, not that they matter. |
33,806 | I sometimes see ‘you and …’ in English, for example “you and the other nine”, “You and your big mouth!”. This makes me sensitive to *you and something*.
>
> “Okay,” said Harry slowly. “But … are you saying Karkaroff put my name in the goblet? Because if he did, he’s a really good actor. He seemed furious about it. He wanted to stop me from competing.”
>
>
> “We know he’s a good actor,” said Sirius, “because he convinced the Ministry of Magic to set him free, didn’t he? Now, I’ve been keeping an eye on the *Daily Prophet*, Harry –“
>
>
> “– **you and the rest of the world**,” said Harry bitterly.
>
>
> “—and reading between the lines of that Skeeter woman’s article last month, Moody was attacked the night before he started at Hogwarts. (The rest is omitted.)
> (p333, Harry Potter 4, US edition)
>
>
>
**NB** - Harry doesn’t like anyone to be interested in the *Daily Prophet* because Skeeter, a news reporter of the paper, is always inventing stories about Harry.
Does this ‘**you and the rest of the world**’ mean just a literal meaning? If Harry says “The other people, too”, is there any big difference in what Harry means to say? | 2011/07/12 | [
"https://english.stackexchange.com/questions/33806",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | "You and..." is an idiomatic use of English, which means it is used more figuratively than literally.
In saying *"You and the rest of the world,"* Harry is pointing out that Ron is not the only person who is reading about him in the *Prophet*. We are being told that a lot of other people are doing the same thing; not literally everyone else in the world, but still an impressively large number.
Similarly, *"You and your big mouth"* doesn't literally mean that you have an unusually large mouth. Instead it means that you talk too much (*i.e.* use that mouth a lot). The unspoken continuation of the sentence would be something like *"...have just said something really stupid."*
*"The other people, too,"* is not quite equivalent to *"You and the rest of the world."* There are shadings of meaning that make it work much less well in context; in particular, it takes the focus off "you" and implies that the others are in some way important to the discussion. *"You and the rest"* only cares that the other people exist, not that they matter. | Harry is using sarcasm to convey his contempt for the Daily Prophet. If the statement didn't include exaggeration as it does, it would lose meaning sounding a bit absurd.
"You and..." is a fairly common meme used in this sarcastic context. It can be used either in a happy joking fashion or the above bitter fashion amongst others. "You and your whole family," "You and everybody else in the neighborhood"
It can be used to mock an object, a practice, or the target of "you" for appearing to claim something unique about themselves which is, in fact, common. |
33,806 | I sometimes see ‘you and …’ in English, for example “you and the other nine”, “You and your big mouth!”. This makes me sensitive to *you and something*.
>
> “Okay,” said Harry slowly. “But … are you saying Karkaroff put my name in the goblet? Because if he did, he’s a really good actor. He seemed furious about it. He wanted to stop me from competing.”
>
>
> “We know he’s a good actor,” said Sirius, “because he convinced the Ministry of Magic to set him free, didn’t he? Now, I’ve been keeping an eye on the *Daily Prophet*, Harry –“
>
>
> “– **you and the rest of the world**,” said Harry bitterly.
>
>
> “—and reading between the lines of that Skeeter woman’s article last month, Moody was attacked the night before he started at Hogwarts. (The rest is omitted.)
> (p333, Harry Potter 4, US edition)
>
>
>
**NB** - Harry doesn’t like anyone to be interested in the *Daily Prophet* because Skeeter, a news reporter of the paper, is always inventing stories about Harry.
Does this ‘**you and the rest of the world**’ mean just a literal meaning? If Harry says “The other people, too”, is there any big difference in what Harry means to say? | 2011/07/12 | [
"https://english.stackexchange.com/questions/33806",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/-1/"
] | "You and..." is an idiomatic use of English, which means it is used more figuratively than literally.
In saying *"You and the rest of the world,"* Harry is pointing out that Ron is not the only person who is reading about him in the *Prophet*. We are being told that a lot of other people are doing the same thing; not literally everyone else in the world, but still an impressively large number.
Similarly, *"You and your big mouth"* doesn't literally mean that you have an unusually large mouth. Instead it means that you talk too much (*i.e.* use that mouth a lot). The unspoken continuation of the sentence would be something like *"...have just said something really stupid."*
*"The other people, too,"* is not quite equivalent to *"You and the rest of the world."* There are shadings of meaning that make it work much less well in context; in particular, it takes the focus off "you" and implies that the others are in some way important to the discussion. *"You and the rest"* only cares that the other people exist, not that they matter. | This is a common phrase that actually has a pretty nuanced meaning. It's synonymous to the phrase "Everyone and their grandmother." Everyone would already include all grandmothers, so this is just a silly way of saying "A whole lot of people."
Of course, Harry isn't actually saying "Everyone else in the world is reading the Daily Prophet." At its base, it means "A whole lot of people -- more than one would expect in a normal circumstance -- are reading the daily prophet." This phrase is an example of hyperbole. The connotation of this phrase varies between "neutral/matter-of-fact" and "negative."
This harry potter example is negative. Something like "Everyone in the world is here" is neutral, and just an observation that 'here' has more people than he expected, by a large margin. |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | Endgame books always **contain analysis mistakes**, and newer editions always **correct these mistakes**. So I would recommend to get up-to-date by buying the last one.
As you said, 7-men Lomonosov built since last edition, and probably 7-men tablebase revealed that some analyses wrong.
From [erreta page](https://www.newinchess.com/support/?PageID=600): "On this Errata page we provide our readers with corrections in our books of analytical mistakes, or mistakes which might lead to misunderstandings ..." | More often than not, edition differences are often just edits and re-phrasings. If you have the 3rd edition, then I would not fret about getting the 4th. |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | De la Villa's "100 Endgames you must know", though apparently a good book seems to have been plagued by an abundance of typos and mistakes as [detailed in this blogpost.](http://streathambrixtonchess.blogspot.com.es/2012/08/sixty-memorable-annotations.html)
So although the culprit in this case has been the 2nd edition, maybe it does make sense to go for the latest edition. Here you can look at [the errata page](https://www.newinchess.com/support/?PageID=600) which presumably contains errors that have now been corrected, although as I mentioned some of these corrections probably already happened in the third edition. | More often than not, edition differences are often just edits and re-phrasings. If you have the 3rd edition, then I would not fret about getting the 4th. |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | I know this answer is coming late, but as someone who had the 3rd edition and upgrated to the 4th edition I can answer this definitely. The ONLY difference in the new edition is that diagrams have an indicator of who is to move, and glancing at the text below the diagram it's very easy to see who is to move if you can't already figure it out based on the particular ending you are studying, if you already have the 3rd and you want this "feature" just go through the book with a pencil and mark every diagram with W/B for who has the move, everything else in the book word for word is IDENITCAL, yes I went through each page and did not see ANY difference whatsoever. Those that said that updated versions where usually money grabs nailed this one completely. The publisher New In Chess was extremely deceptive selling this as a new version complete with a new book cover. This could have been done in a new printing, shame on New in Chess. | More often than not, edition differences are often just edits and re-phrasings. If you have the 3rd edition, then I would not fret about getting the 4th. |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | I have the book on Chessable (popular site for reading chess books like this one):
>
> <https://www.chessable.com/endgame-book/100-endgames-you-must-know/5193/>
>
>
>
[](https://i.stack.imgur.com/jTMne.png)
The difference in edition come from improved annotations and error checking. That's common for all books (chess or not). If you already have the 3rd edition, there's no point to get the newer edition.
Please note the edition is not specified in the screenshot because it's always the latest edition. I'd recommend to get an ebook version (e.g. Chessable or other publishers). New In Chess updates their ebooks for free, you will get a free update when they release the 5th, 6th edition etc. | More often than not, edition differences are often just edits and re-phrasings. If you have the 3rd edition, then I would not fret about getting the 4th. |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | De la Villa's "100 Endgames you must know", though apparently a good book seems to have been plagued by an abundance of typos and mistakes as [detailed in this blogpost.](http://streathambrixtonchess.blogspot.com.es/2012/08/sixty-memorable-annotations.html)
So although the culprit in this case has been the 2nd edition, maybe it does make sense to go for the latest edition. Here you can look at [the errata page](https://www.newinchess.com/support/?PageID=600) which presumably contains errors that have now been corrected, although as I mentioned some of these corrections probably already happened in the third edition. | Endgame books always **contain analysis mistakes**, and newer editions always **correct these mistakes**. So I would recommend to get up-to-date by buying the last one.
As you said, 7-men Lomonosov built since last edition, and probably 7-men tablebase revealed that some analyses wrong.
From [erreta page](https://www.newinchess.com/support/?PageID=600): "On this Errata page we provide our readers with corrections in our books of analytical mistakes, or mistakes which might lead to misunderstandings ..." |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | I have the book on Chessable (popular site for reading chess books like this one):
>
> <https://www.chessable.com/endgame-book/100-endgames-you-must-know/5193/>
>
>
>
[](https://i.stack.imgur.com/jTMne.png)
The difference in edition come from improved annotations and error checking. That's common for all books (chess or not). If you already have the 3rd edition, there's no point to get the newer edition.
Please note the edition is not specified in the screenshot because it's always the latest edition. I'd recommend to get an ebook version (e.g. Chessable or other publishers). New In Chess updates their ebooks for free, you will get a free update when they release the 5th, 6th edition etc. | Endgame books always **contain analysis mistakes**, and newer editions always **correct these mistakes**. So I would recommend to get up-to-date by buying the last one.
As you said, 7-men Lomonosov built since last edition, and probably 7-men tablebase revealed that some analyses wrong.
From [erreta page](https://www.newinchess.com/support/?PageID=600): "On this Errata page we provide our readers with corrections in our books of analytical mistakes, or mistakes which might lead to misunderstandings ..." |
13,232 | Does anyone know the difference between the 3rd and 4th edition of "100 Endgames You Must Know"? I just looked at the Table Of Contents and they are identical and random pages on Amazon look the same too. I would imagine there must be some new use of the new tablebases that were completed since 2012? | 2015/12/29 | [
"https://chess.stackexchange.com/questions/13232",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/9096/"
] | De la Villa's "100 Endgames you must know", though apparently a good book seems to have been plagued by an abundance of typos and mistakes as [detailed in this blogpost.](http://streathambrixtonchess.blogspot.com.es/2012/08/sixty-memorable-annotations.html)
So although the culprit in this case has been the 2nd edition, maybe it does make sense to go for the latest edition. Here you can look at [the errata page](https://www.newinchess.com/support/?PageID=600) which presumably contains errors that have now been corrected, although as I mentioned some of these corrections probably already happened in the third edition. | I know this answer is coming late, but as someone who had the 3rd edition and upgrated to the 4th edition I can answer this definitely. The ONLY difference in the new edition is that diagrams have an indicator of who is to move, and glancing at the text below the diagram it's very easy to see who is to move if you can't already figure it out based on the particular ending you are studying, if you already have the 3rd and you want this "feature" just go through the book with a pencil and mark every diagram with W/B for who has the move, everything else in the book word for word is IDENITCAL, yes I went through each page and did not see ANY difference whatsoever. Those that said that updated versions where usually money grabs nailed this one completely. The publisher New In Chess was extremely deceptive selling this as a new version complete with a new book cover. This could have been done in a new printing, shame on New in Chess. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.