qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
42,103,738 | I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions).
I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database.
When I make the button change the `view.backgroundColor` and put if else tied to the colour it works.
But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it.
```
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
@IBAction func OnOffButton(_ sender: UITapGestureRecognizer){
if button.backgroundColor == UIColor.white {
OnOff(state:"ON")
OnOffButton.backgroundColor = UIColor.blue
} else{
OnOff(state:"OFF")
OnOffButton.backgroundColor = UIColor.white
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
OnOff(state: "Off")
OnOffButton.backgroundColor = UIColor.white
}
``` | 2017/02/08 | ['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/'] | `UIButton` inherits from `UIControl` which has an `isSelected` property. Use this to track state. Typically you'll use `button.isSelected == true` to correspond to your on state, and `false` is your off state.
To toggle state you can use `button.isSelected = !button.isSelected`.
For your specific example:
```
// User pressed the button, so toggle the state:
button.isSelected = !button.isSelected
// Now do something with the new state
if button.isSelected {
// button is on, so ...
} else {
// button is off, so...
}
``` | Par's solution should work. However, I would suggest a different approach.
In general it's not good design to store state in a view object. It's fragile, and doesn't follow the MVC design pattern, where view objects display and collect state information, not store it.
Instead I would create an instance variable in your view controller, buttonIsSelected. Toggle that when the button is tapped, and have it change the state of the button's selected property, the button's color, AND log the new state to FireBase.
If you store more complex state in your view controller it would be worth separating that out into a model object. It can be as simple as a struct that holds the different state values. That way you have a clear separation between your controller (view controller) and model. |
42,103,738 | I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions).
I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database.
When I make the button change the `view.backgroundColor` and put if else tied to the colour it works.
But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it.
```
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
@IBAction func OnOffButton(_ sender: UITapGestureRecognizer){
if button.backgroundColor == UIColor.white {
OnOff(state:"ON")
OnOffButton.backgroundColor = UIColor.blue
} else{
OnOff(state:"OFF")
OnOffButton.backgroundColor = UIColor.white
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
OnOff(state: "Off")
OnOffButton.backgroundColor = UIColor.white
}
``` | 2017/02/08 | ['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/'] | `UIButton` inherits from `UIControl` which has an `isSelected` property. Use this to track state. Typically you'll use `button.isSelected == true` to correspond to your on state, and `false` is your off state.
To toggle state you can use `button.isSelected = !button.isSelected`.
For your specific example:
```
// User pressed the button, so toggle the state:
button.isSelected = !button.isSelected
// Now do something with the new state
if button.isSelected {
// button is on, so ...
} else {
// button is off, so...
}
``` | Here’s a quick and dirty implementation of Duncan C’s suggestion to use a `buttonIsSelected` variable to store the button state:
```
import UIKit
class ViewController: UIViewController {
var buttonIsSelected = false
@IBOutlet weak var onOffButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
updateOnOffButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onOffButtonTapped(_ sender: Any) {
buttonIsSelected = !buttonIsSelected
updateOnOffButton()
}
func updateOnOffButton() {
if buttonIsSelected {
onOffButton.backgroundColor = UIColor.blue
}
else {
onOffButton.backgroundColor = UIColor.white
}
}
}
``` |
42,103,738 | I am really new to Swift and working on my first project (I have a bit of experience with Javascript and web development). I have run into trouble (going on 4 hours of trying different solutions).
I have an app where when a `UIButton` is pushed it logs a value to FireBase (ON). When it is pushed a second time it logs (OFF) to the database.
When I make the button change the `view.backgroundColor` and put if else tied to the colour it works.
But I can't for the life of me figure out how to build my if else based on the state of the button. I have now ended up trying to change the colour of the button itself and tie the if else to that. Which I know is a really messy improper way to go about it.
```
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
@IBAction func OnOffButton(_ sender: UITapGestureRecognizer){
if button.backgroundColor == UIColor.white {
OnOff(state:"ON")
OnOffButton.backgroundColor = UIColor.blue
} else{
OnOff(state:"OFF")
OnOffButton.backgroundColor = UIColor.white
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
OnOff(state: "Off")
OnOffButton.backgroundColor = UIColor.white
}
``` | 2017/02/08 | ['https://Stackoverflow.com/questions/42103738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7532077/'] | Here’s a quick and dirty implementation of Duncan C’s suggestion to use a `buttonIsSelected` variable to store the button state:
```
import UIKit
class ViewController: UIViewController {
var buttonIsSelected = false
@IBOutlet weak var onOffButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
updateOnOffButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onOffButtonTapped(_ sender: Any) {
buttonIsSelected = !buttonIsSelected
updateOnOffButton()
}
func updateOnOffButton() {
if buttonIsSelected {
onOffButton.backgroundColor = UIColor.blue
}
else {
onOffButton.backgroundColor = UIColor.white
}
}
}
``` | Par's solution should work. However, I would suggest a different approach.
In general it's not good design to store state in a view object. It's fragile, and doesn't follow the MVC design pattern, where view objects display and collect state information, not store it.
Instead I would create an instance variable in your view controller, buttonIsSelected. Toggle that when the button is tapped, and have it change the state of the button's selected property, the button's color, AND log the new state to FireBase.
If you store more complex state in your view controller it would be worth separating that out into a model object. It can be as simple as a struct that holds the different state values. That way you have a clear separation between your controller (view controller) and model. |
69,550,532 | I'm learning haskell, and I'm trying to rewrite a function using composition only
Here's the function I'm trying to refactor:
```hs
ceilingDiv a b = ceiling (a / b)
```
So far I managed to make it work using curry and uncurry but it feels dirty:
```hs
ceilingDiv = curry $ ceiling . uncurry (/)
```
Is there any way to do this more cleanly? I was thinking `ceiling . div`, but it doesn't work because `(/)` returns a function and ceiling takes a Double as its argument. | 2021/10/13 | ['https://Stackoverflow.com/questions/69550532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2410957/'] | Compositions with multiple arguments are usually best just left in point-ful form. None of the alternatives is as clean and clear. Do make use of composition- and grouping operators, but don't golf away arguments just for the sake of it.
```
ceilingDiv a b = ceiling $ a/b
```
What you can certainly do is eta-reduce the `b` argument
```
ceilingDiv a = ceiling . (a/)
```
but I'd leave it at that. Even that is IMO less clean than the original 2-argument form, because the division operator needs to be sectioned.
When directly passing compositions to a higher-order function then it can make sense to aim a bit more agressively point-free, to avoid lambda bindings. The [`composition` package](https://hackage.haskell.org/package/composition-1.0.2.2/docs/Data-Composition.html#v:.:) has a whole bunch of operators for composing with more arguments. In this case, you could use the indeed quite concise
```
ceilingDiv = ceiling .: (/)
``` | There's a fun site called <https://pointfree.io> - it provides a solution to your problem like this: `ceilingDiv = (ceiling .) . (/)`. It looks ugly because point-free composition with multiple arguments is a pain. Sometimes it's achieved by using `.` [sections](https://wiki.haskell.org/Section_of_an_infix_operator) like here, sometimes by using an [Applicative](https://wiki.haskell.org/Applicative_functor) instance of functions and the `<*>` operator.
I think your solution with curry-uncurry is nice. It deals with passing multiple arguments by wrapping them into one tuple. |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | Please execute query inside the loop as given below
```
...
$conn = mysqli_connect($servername, $username, $password, $dbname);
...
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$sql = "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "')";
$conn->query($sql);// Query should execute inside loop
}
}
``` | If you want to execute the query outside the loop
Try using as following
```
if (isset($_POST['array'])) {
$sql="";
foreach ($_POST['array'] as $loop) {
$sql .= "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "');\n";
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | Better way is only one time create `insert`
```
if (isset($_POST['array'])) {
$values = [];
$sql = "insert into persons (Name, Email) values ";
foreach ($_POST['array'] as $loop) {
$values[] = "('" . $conn->real_escape_string($loop['name']) . "', '" . $conn->real_escape_string($loop['email']) . "')";
}
if (!empty($values)) {
$conn->query($sql . implode(', ', $values));
}
}
``` | Please execute query inside the loop as given below
```
...
$conn = mysqli_connect($servername, $username, $password, $dbname);
...
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$sql = "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "')";
$conn->query($sql);// Query should execute inside loop
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | The reason why it doesn't work is because you never execute your SQL query anywhere.
To execute the query you should first prepare the statement and then bind the params and execute.
```
// Your connection to DB
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['array'])) {
$stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)');
foreach ($_POST['array'] as $loop) {
$stmt->bind_param('ss', $loop['name'], $loop['email']);
$stmt->execute();
}
}
``` | Please execute query inside the loop as given below
```
...
$conn = mysqli_connect($servername, $username, $password, $dbname);
...
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$sql = "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "')";
$conn->query($sql);// Query should execute inside loop
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | Please execute query inside the loop as given below
```
...
$conn = mysqli_connect($servername, $username, $password, $dbname);
...
if (isset($_POST['array'])) {
foreach ($_POST['array'] as $loop) {
$sql = "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "')";
$conn->query($sql);// Query should execute inside loop
}
}
``` | I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach`
```
// loop through the array
foreach ($data as $row) {
echo "Data has been Uploaded successfully <br>";
// get the project details
$id = $row['id'];
$name = $row['name'];
$togglCid = $row['cid'];
// execute insert query
mysqli_stmt_execute($sql);
}
```
This means it executes the code after each loop |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | Better way is only one time create `insert`
```
if (isset($_POST['array'])) {
$values = [];
$sql = "insert into persons (Name, Email) values ";
foreach ($_POST['array'] as $loop) {
$values[] = "('" . $conn->real_escape_string($loop['name']) . "', '" . $conn->real_escape_string($loop['email']) . "')";
}
if (!empty($values)) {
$conn->query($sql . implode(', ', $values));
}
}
``` | If you want to execute the query outside the loop
Try using as following
```
if (isset($_POST['array'])) {
$sql="";
foreach ($_POST['array'] as $loop) {
$sql .= "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "');\n";
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | The reason why it doesn't work is because you never execute your SQL query anywhere.
To execute the query you should first prepare the statement and then bind the params and execute.
```
// Your connection to DB
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['array'])) {
$stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)');
foreach ($_POST['array'] as $loop) {
$stmt->bind_param('ss', $loop['name'], $loop['email']);
$stmt->execute();
}
}
``` | If you want to execute the query outside the loop
Try using as following
```
if (isset($_POST['array'])) {
$sql="";
foreach ($_POST['array'] as $loop) {
$sql .= "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "');\n";
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach`
```
// loop through the array
foreach ($data as $row) {
echo "Data has been Uploaded successfully <br>";
// get the project details
$id = $row['id'];
$name = $row['name'];
$togglCid = $row['cid'];
// execute insert query
mysqli_stmt_execute($sql);
}
```
This means it executes the code after each loop | If you want to execute the query outside the loop
Try using as following
```
if (isset($_POST['array'])) {
$sql="";
foreach ($_POST['array'] as $loop) {
$sql .= "insert into persons (Name, Email)
values ('" . $loop['name'] . "', '" . $loop['email'] . "');\n";
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | The reason why it doesn't work is because you never execute your SQL query anywhere.
To execute the query you should first prepare the statement and then bind the params and execute.
```
// Your connection to DB
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['array'])) {
$stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)');
foreach ($_POST['array'] as $loop) {
$stmt->bind_param('ss', $loop['name'], $loop['email']);
$stmt->execute();
}
}
``` | Better way is only one time create `insert`
```
if (isset($_POST['array'])) {
$values = [];
$sql = "insert into persons (Name, Email) values ";
foreach ($_POST['array'] as $loop) {
$values[] = "('" . $conn->real_escape_string($loop['name']) . "', '" . $conn->real_escape_string($loop['email']) . "')";
}
if (!empty($values)) {
$conn->query($sql . implode(', ', $values));
}
}
``` |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | Better way is only one time create `insert`
```
if (isset($_POST['array'])) {
$values = [];
$sql = "insert into persons (Name, Email) values ";
foreach ($_POST['array'] as $loop) {
$values[] = "('" . $conn->real_escape_string($loop['name']) . "', '" . $conn->real_escape_string($loop['email']) . "')";
}
if (!empty($values)) {
$conn->query($sql . implode(', ', $values));
}
}
``` | I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach`
```
// loop through the array
foreach ($data as $row) {
echo "Data has been Uploaded successfully <br>";
// get the project details
$id = $row['id'];
$name = $row['name'];
$togglCid = $row['cid'];
// execute insert query
mysqli_stmt_execute($sql);
}
```
This means it executes the code after each loop |
59,499,722 | The predicate function:
```
bool Schedule::predicateFunc(map<pair<string,int>,pair<string,Array> >::iterator it,string &a)
{
return (it->first).first == a;
}
```
Function which I have to use predicate func:
```
void Schedule::studentSchedule() {
string s,c;
cout<<"Enter the student and course name to create schedule"<<endl;
cin>>s>>c;
list<string>::iterator studentLoc;
map<pair<string,int>,pair<string,Array> >::iterator courseL;
map<pair<string,int>,pair<string,Array> >::iterator location;
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
if(studentLoc != getStudentList().end() && location != getMatchMap().end())
{
cout<<"I found it"<<endl;
}
else
cout<<"I cant found it"<<endl;
}
```
When I tried to use predicate function in here:
```
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicateFunc(courseL,c) )
```
I am getting an error like this:
```
In file included from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algobase.h:71,
from C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/algorithm:61,
from C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:4:
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]':
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:104:42: required from '_InputIterator std::__find_if(_InputIterator, _InputIterator, _Predicate, std::input_iterator_tag) [with _InputIterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = __gnu_cxx::__ops::_Iter_pred<bool>]'
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/stl_algo.h:3930:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::pair<std::__cxx11::basic_string<char>, int>, std::pair<std::__cxx11::basic_string<char>, std::array<int, 6> > > >; _Predicate = bool]'
C:\Users\Fatih\Desktop\clion\SchoolProject1\Schedule.cpp:25:93: required from here
C:/PROGRA~1/MINGW-~1/X86_64~1.0-P/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/bits/predefined_ops.h:283:11: error: expression cannot be used as a function
{ return bool(_M_pred(*__it)); }
^~~~~~~~~~~~~~~~~~~~
```
What is the true usage of the predicate funtion in here ? | 2019/12/27 | ['https://Stackoverflow.com/questions/59499722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12543764/'] | The reason why it doesn't work is because you never execute your SQL query anywhere.
To execute the query you should first prepare the statement and then bind the params and execute.
```
// Your connection to DB
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['array'])) {
$stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)');
foreach ($_POST['array'] as $loop) {
$stmt->bind_param('ss', $loop['name'], $loop['email']);
$stmt->execute();
}
}
``` | I had the same issue inserting JSON arrays into MySQL and fixed it by putting the `mysqli_stmt->execute()` function inside the `foreach`
```
// loop through the array
foreach ($data as $row) {
echo "Data has been Uploaded successfully <br>";
// get the project details
$id = $row['id'];
$name = $row['name'];
$togglCid = $row['cid'];
// execute insert query
mysqli_stmt_execute($sql);
}
```
This means it executes the code after each loop |
12,070,601 | The [NQueen problem](http://en.wikipedia.org/wiki/Eight_queens_puzzle) is a famous example of [backtracking](http://en.wikipedia.org/wiki/Backtracking). After reading from the [source](http://www.geeksforgeeks.org/archives/13387), I have tried the below code snippet.
```
int isSafe(int k,int i,int *x)
{
int j;
for(j=0;j<k;j++)
{
//old queen is placed at jth row of x[j] column
//new queen to be placed at kth row of ith column
if(i==x[j] || abs(k-j)==abs(i-x[j]))
return 0;
}
return 1;
}
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
sol[k] = 0; // backtrack
}
}
return 0; // solution not possible
}
}
```
I am getting the [output](http://ideone.com/tjo69) as:
```
1 5 8 6 3 7 2 4
```
However, when i comment the statement which backtracks, I am getting the same [output](http://ideone.com/Rkfl5) without any problem.
```
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
// sol[k] = 0; <-------------- Notice this change
}
}
return 0;
}
}
```
What exactly has made NQueen problem, a backtracking one?
Isn't it a simple recursive approach? | 2012/08/22 | ['https://Stackoverflow.com/questions/12070601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1347366/'] | The `sol[k] = 0` is not the backtracking part. The backtracking is done in the recursive call: `if( Nqueen(k+1, sol, N) )`.
The idea of backtracking is an exhaustive search - you are trying to search all possibilities, until one is found. In here, you are trying all possible assignments of queens in the board, and "keep on" if it is still safe. If you find it unsafe, you return from the recursion with a failure, and trying the next option.
I believe the commented out line only makes sure that if no solution is found, the resulting array is `[0,...,0]`, and not some nonesense array. | First, you really need to understand the algorithm (this will tell you that commenting that stuff out doesn't matter). This algorithm is recursive, as you have noticed. It is backtracking because you
* set the k-th queen to a position
* explore the possible placements for queens k+1,k+2,...
* then you go back to the k-th queen, place it somewhere else, and repeat
See, in step 3 we "go back" to the k-th queen. This is how I explain myself why it's called backtracking. |
12,070,601 | The [NQueen problem](http://en.wikipedia.org/wiki/Eight_queens_puzzle) is a famous example of [backtracking](http://en.wikipedia.org/wiki/Backtracking). After reading from the [source](http://www.geeksforgeeks.org/archives/13387), I have tried the below code snippet.
```
int isSafe(int k,int i,int *x)
{
int j;
for(j=0;j<k;j++)
{
//old queen is placed at jth row of x[j] column
//new queen to be placed at kth row of ith column
if(i==x[j] || abs(k-j)==abs(i-x[j]))
return 0;
}
return 1;
}
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
sol[k] = 0; // backtrack
}
}
return 0; // solution not possible
}
}
```
I am getting the [output](http://ideone.com/tjo69) as:
```
1 5 8 6 3 7 2 4
```
However, when i comment the statement which backtracks, I am getting the same [output](http://ideone.com/Rkfl5) without any problem.
```
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
// sol[k] = 0; <-------------- Notice this change
}
}
return 0;
}
}
```
What exactly has made NQueen problem, a backtracking one?
Isn't it a simple recursive approach? | 2012/08/22 | ['https://Stackoverflow.com/questions/12070601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1347366/'] | The `sol[k] = 0` is not the backtracking part. The backtracking is done in the recursive call: `if( Nqueen(k+1, sol, N) )`.
The idea of backtracking is an exhaustive search - you are trying to search all possibilities, until one is found. In here, you are trying all possible assignments of queens in the board, and "keep on" if it is still safe. If you find it unsafe, you return from the recursion with a failure, and trying the next option.
I believe the commented out line only makes sure that if no solution is found, the resulting array is `[0,...,0]`, and not some nonesense array. | Backtracking Problems are a programming paradigm in which you try each and every possible combination. Then for every combination you check if the combination so far is correct.
Below are few steps for N(or 8) queen problem.
1. Start from Row 0 and place 1st queen at Col 0.
2. Now place 2nd queen at Row 1 and col 0.
3. check if position is safe
4. If not safe place 2nd queen at Row 1, col 1.
5. Not Safe, now place 2nd queen at Row 1, col 2.
proceed like this by placing queen at every possible column for each and checking if it is safe.
You can omit the obvious false conditions like you won't place 2 queens in a same row.
Below is my code for 8 queen problem, printing all possible solutions.
```
#include<stdio.h>
int abs(int a){
return a>0? a : -a;
}
int isSafe(int col[],int row){
int row2,col2,i,yDiff,xDiff;
if(row == 0) return 1;
for(row2=0;row2<row;row2++){
if(col[row2] == col[row])
return 0;
xDiff = col[row2] - col[row];
xDiff = abs(xDiff);
yDiff = row - row2;
if(xDiff == yDiff)
return 0;
}
return 1;
```
}
```
int Nqueen(int col[],int n, int row){
int i;
if(row==n){
printf("\n");
for(i=0;i<n;i++)
printf("%d ",col[i]+1);
}else{
for(i=0;i<n;i++){
col[row] = i;
if(isSafe(col,row)){
queen(col,n,row+1);
}
}
}
```
}
```
int main(){
int col[8];
queen(col,8,0);
}
``` |
12,070,601 | The [NQueen problem](http://en.wikipedia.org/wiki/Eight_queens_puzzle) is a famous example of [backtracking](http://en.wikipedia.org/wiki/Backtracking). After reading from the [source](http://www.geeksforgeeks.org/archives/13387), I have tried the below code snippet.
```
int isSafe(int k,int i,int *x)
{
int j;
for(j=0;j<k;j++)
{
//old queen is placed at jth row of x[j] column
//new queen to be placed at kth row of ith column
if(i==x[j] || abs(k-j)==abs(i-x[j]))
return 0;
}
return 1;
}
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
sol[k] = 0; // backtrack
}
}
return 0; // solution not possible
}
}
```
I am getting the [output](http://ideone.com/tjo69) as:
```
1 5 8 6 3 7 2 4
```
However, when i comment the statement which backtracks, I am getting the same [output](http://ideone.com/Rkfl5) without any problem.
```
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
// sol[k] = 0; <-------------- Notice this change
}
}
return 0;
}
}
```
What exactly has made NQueen problem, a backtracking one?
Isn't it a simple recursive approach? | 2012/08/22 | ['https://Stackoverflow.com/questions/12070601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1347366/'] | Backtracking Problems are a programming paradigm in which you try each and every possible combination. Then for every combination you check if the combination so far is correct.
Below are few steps for N(or 8) queen problem.
1. Start from Row 0 and place 1st queen at Col 0.
2. Now place 2nd queen at Row 1 and col 0.
3. check if position is safe
4. If not safe place 2nd queen at Row 1, col 1.
5. Not Safe, now place 2nd queen at Row 1, col 2.
proceed like this by placing queen at every possible column for each and checking if it is safe.
You can omit the obvious false conditions like you won't place 2 queens in a same row.
Below is my code for 8 queen problem, printing all possible solutions.
```
#include<stdio.h>
int abs(int a){
return a>0? a : -a;
}
int isSafe(int col[],int row){
int row2,col2,i,yDiff,xDiff;
if(row == 0) return 1;
for(row2=0;row2<row;row2++){
if(col[row2] == col[row])
return 0;
xDiff = col[row2] - col[row];
xDiff = abs(xDiff);
yDiff = row - row2;
if(xDiff == yDiff)
return 0;
}
return 1;
```
}
```
int Nqueen(int col[],int n, int row){
int i;
if(row==n){
printf("\n");
for(i=0;i<n;i++)
printf("%d ",col[i]+1);
}else{
for(i=0;i<n;i++){
col[row] = i;
if(isSafe(col,row)){
queen(col,n,row+1);
}
}
}
```
}
```
int main(){
int col[8];
queen(col,8,0);
}
``` | First, you really need to understand the algorithm (this will tell you that commenting that stuff out doesn't matter). This algorithm is recursive, as you have noticed. It is backtracking because you
* set the k-th queen to a position
* explore the possible placements for queens k+1,k+2,...
* then you go back to the k-th queen, place it somewhere else, and repeat
See, in step 3 we "go back" to the k-th queen. This is how I explain myself why it's called backtracking. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | >
> I was really hoping for some sort of like "abort mechanism" that I
> could use. Is there any other ways of working around this? Any
> interesting work-arounds for this?
>
>
>
Yes, there is. It is called *exception handling*.
Let's rewrite your code:
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
```
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException` | You could just move `DoFurtherAnalysis();` into the the try block
And I would do this entire process somewhere other than the constructor.
Only thing I ever do in the constructor is initialize properties. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the "abort mechanism" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions. | >
> I was really hoping for some sort of like "abort mechanism" that I
> could use. Is there any other ways of working around this? Any
> interesting work-arounds for this?
>
>
>
Yes, there is. It is called *exception handling*.
Let's rewrite your code:
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
```
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException` |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | The easiest work-around is *don't catch the exception*. If that were to happen, it'd go straight past the `DoFurtherAnalysis()` function and out to the original caller. | use a try...catch in the constructor? |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the "abort mechanism" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions. | Well, you've got several issues mixed up here. First, it looks like you do possibly-very expensive processing from your constructor. If that processing can throw, you really don't want to call it from your constructor becuase you don't even have the option of returning an error code.
Second, (and you'll read in many threads here,) how you handlee errors really depends on the application and expectation of your users. Some errors could be corrected by changes to inputs. Others might happen in the middle of the night if analysis takes a long time and you might want to continue with another analysis, logging this error.
So I think we're really going to punt back to you for more information about the above. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program. | You could just move `DoFurtherAnalysis();` into the the try block
And I would do this entire process somewhere other than the constructor.
Only thing I ever do in the constructor is initialize properties. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | >
> I was really hoping for some sort of like "abort mechanism" that I
> could use. Is there any other ways of working around this? Any
> interesting work-arounds for this?
>
>
>
Yes, there is. It is called *exception handling*.
Let's rewrite your code:
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
```
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException` | You are subverting the existing "abort" mechanism by catching an exception that you are not doing anything about and swallowing it.
You should not use a `try{}catch{}` block in this case and let the exception bubble up and cause the application to abort. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program. | use a try...catch in the constructor? |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | >
> I was really hoping for some sort of like "abort mechanism" that I
> could use. Is there any other ways of working around this? Any
> interesting work-arounds for this?
>
>
>
Yes, there is. It is called *exception handling*.
Let's rewrite your code:
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
```
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a `FormatException` | Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the "abort mechanism" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions. | You could just move `DoFurtherAnalysis();` into the the try block
And I would do this entire process somewhere other than the constructor.
Only thing I ever do in the constructor is initialize properties. |
9,776,878 | I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
```
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
```
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form. | 2012/03/19 | ['https://Stackoverflow.com/questions/9776878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821484/'] | Just let the exception propagate up - you should only catch the exception if you can actually *handle* it. Exceptions *are* the "abort mechanism" in .NET. You're currently *swallowing* the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions. | Don't see anything anoying in returning and checking `bool` return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort **everything**, just do not `catch` exception it will abort your program. |
42,317,542 | Yesterday I was making an HTML element and this problem hit me up.
The Background-image of the DIV is not showing, and I was curious, the link worked fine.
Here is my code
```html
<div id="floating-image-<?php echo $id; ?>" class="fl-<?php echo $id; ?>" style="
background-image: url(https://images.pexels.com/photos/290470/pexels-photo-290470.jpeg?h=350&auto=compress&cs=tinysrgb);
margin-top: 20px;
height: 200px;
width: 200px;
background-position: center center;
background-repeat: no-repeat;
transform: translateY(0px);
background-size: contain;
position: relative;
margin-right: auto;
margin-left: auto;
max-width: 80%;
display:block;
"></div>
```
**EDIT**
ok, I edited the dynamic codes and replaced them with some static output.
Sorry for misleading
**Another EDIT**
I changed the image and now I am using a smaller image, but still it doesn't show up | 2017/02/18 | ['https://Stackoverflow.com/questions/42317542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | I have checked, background image is properly working. Your image size is very big, approx 7 MB. Reduce it upto 300KB, too big to show. | Issue is in the image,
You have used very high quality image.
if you use a low quality image than you have currently used,
it will work fine. |
42,317,542 | Yesterday I was making an HTML element and this problem hit me up.
The Background-image of the DIV is not showing, and I was curious, the link worked fine.
Here is my code
```html
<div id="floating-image-<?php echo $id; ?>" class="fl-<?php echo $id; ?>" style="
background-image: url(https://images.pexels.com/photos/290470/pexels-photo-290470.jpeg?h=350&auto=compress&cs=tinysrgb);
margin-top: 20px;
height: 200px;
width: 200px;
background-position: center center;
background-repeat: no-repeat;
transform: translateY(0px);
background-size: contain;
position: relative;
margin-right: auto;
margin-left: auto;
max-width: 80%;
display:block;
"></div>
```
**EDIT**
ok, I edited the dynamic codes and replaced them with some static output.
Sorry for misleading
**Another EDIT**
I changed the image and now I am using a smaller image, but still it doesn't show up | 2017/02/18 | ['https://Stackoverflow.com/questions/42317542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | The solution is going to be solved only by me since it is included in a project.
Thanks for your help, and if I found the real solution, I will post it here.
**EDIT**
Well, I feel bad now, about the wasted hour in my life.
Anyway, I found the solution and it was about the animations.
I made this feature in my theme, so the user could create animations easily.
The whole story summerizes in few words, " Didn't enable animations in the parent Section, So the normal css code goes as .class{**OPACITY:0;**} ".
Sorry! and Thanks for your deep concern in such a problem | Issue is in the image,
You have used very high quality image.
if you use a low quality image than you have currently used,
it will work fine. |
130,194 | Would be possible to apply genetic changes (like splicing in a radiation hardening gene) to an adult human? With near future technology, like advanced forms of CRISPR? Or can things like that only be applied t unborn infants? | 2018/11/13 | ['https://worldbuilding.stackexchange.com/questions/130194', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/47304/'] | Yes but it's much harder and the effects can be limited and much slower.
**Genetic Surgery**
Enough engineered viruses can change the DNA but can be limited on changing physical structures.
Here's an [example](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4401361/) where viral surgery was used to repair genetic deafness in mice
If you are making large physical changes, it might take a very long time to take effect if at all. | [Gene Therapy](https://en.wikipedia.org/wiki/Gene_therapy)
==========================================================
With the gene therapy, is possible to modify the DNA of a born creature using Virus, Retrovirus, Adenovirus, Non-Virus or others as a Vector. (Surprisingly, the Spanish Wikipedia has more information about different vectors).
This [vectors](https://en.wikipedia.org/wiki/Vectors_in_gene_therapy) are programmed to modify the DNA structure of alive cells from the host.
At the moment it's quite dangerous or ineffective this gene therapy, but in the future, with the boom of genetical manipulation, it will no longe be a problem. |
130,194 | Would be possible to apply genetic changes (like splicing in a radiation hardening gene) to an adult human? With near future technology, like advanced forms of CRISPR? Or can things like that only be applied t unborn infants? | 2018/11/13 | ['https://worldbuilding.stackexchange.com/questions/130194', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/47304/'] | **Genetic engineering of adult subjects is currently not possible, especially with splicing**
But it might be theoretically possible, with some huge challenges to overcome:
A retrovirus is a virus capable of modifying a host cell's genome. I think the current scientific cliff is left at this: The virus can either modify the genome to our purposes or replicate itself but not both. The goal is to get it to both modify a genome beneficially to our purposes and the cells as well as enable replication of the virus.
Otherwise it would require infeasible sums of engineered virus to modify one person.
**The virus can be attacked by the immune system.** Does no good if the virus is constantly eaten before it does its job. This can be overcome as some viruses can remain invisible to the immune system by the configuration of their protein shell. Its also problematic if the immune system kills the host in trying to kill the virus.
**The virus mutates.** Viruses are inherently genetically unstable and tend to mutate often. It becomes dangerous as hell if it mutates something dangerous with all the weapons its been granted. Its also dangerous if it becomes contagious infecting random people or creatures causing unknowable havoc.
**Getting the Virus Everywhere is Hard** Getting the virus into every cell is tricky as things reach different parts of the body at different rates. This also covers the fact that there are different types of cells which require different entry procedures for the virus to mutate. These problems come together in the most troublesome spot, the brain. Nerves are hard, both hard for viruses to enter (because they are less common) and are generally more protected (like the blood brain barrier). So getting the virus into everything uniformly can be difficult.
**Adults are adults:** Physical maturation is an important biological process regulated by hormones in the brain. This is important in where genes are inserted as well as the process for activating them. For instance if your re-engineering intended to grow a third eye you need someway to activate and more importantly shut off the growth process. You wouldn't want a thousand eyes. Currently this process isn't well understood either. It could be that you simply need to supply your patient hormonal treatments in order to progress the mutations construction.
**Some Cells don't Divide** Mutating a nerve would be tricky because they don't divide. That isn't to say nerves cant be enhanced because you can highjack something like a stem cell but how you manage modification of the brain can be enormously difficult and tricky. The slightest mistake could result in the permanent crippling or 'resetting'of the patient. Not to mention after you reset a person it might be possible to rehabilitate them either as the adult brain is no longer performing the same cognitive formatting as an infants. This challenge alone makes retroviral gene editing both dangerous and completely rules out neural modifications for at least the next 100 years if not the next millennium. It also limits the significance of mutations. Because general motor skills are hard wired during infancy, it would be impossible for an adult to grow 4 arms and then be able to learn how to use them.
**Complexity of the mutation** Since adults are fully grown trying to unleash massive rewrites would be dangerous. This might be conquerable through iterative editing but if you change too much too fast you run the risk of killing the host in an infinitesimal array of ways. | Yes but it's much harder and the effects can be limited and much slower.
**Genetic Surgery**
Enough engineered viruses can change the DNA but can be limited on changing physical structures.
Here's an [example](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4401361/) where viral surgery was used to repair genetic deafness in mice
If you are making large physical changes, it might take a very long time to take effect if at all. |
130,194 | Would be possible to apply genetic changes (like splicing in a radiation hardening gene) to an adult human? With near future technology, like advanced forms of CRISPR? Or can things like that only be applied t unborn infants? | 2018/11/13 | ['https://worldbuilding.stackexchange.com/questions/130194', 'https://worldbuilding.stackexchange.com', 'https://worldbuilding.stackexchange.com/users/47304/'] | **Genetic engineering of adult subjects is currently not possible, especially with splicing**
But it might be theoretically possible, with some huge challenges to overcome:
A retrovirus is a virus capable of modifying a host cell's genome. I think the current scientific cliff is left at this: The virus can either modify the genome to our purposes or replicate itself but not both. The goal is to get it to both modify a genome beneficially to our purposes and the cells as well as enable replication of the virus.
Otherwise it would require infeasible sums of engineered virus to modify one person.
**The virus can be attacked by the immune system.** Does no good if the virus is constantly eaten before it does its job. This can be overcome as some viruses can remain invisible to the immune system by the configuration of their protein shell. Its also problematic if the immune system kills the host in trying to kill the virus.
**The virus mutates.** Viruses are inherently genetically unstable and tend to mutate often. It becomes dangerous as hell if it mutates something dangerous with all the weapons its been granted. Its also dangerous if it becomes contagious infecting random people or creatures causing unknowable havoc.
**Getting the Virus Everywhere is Hard** Getting the virus into every cell is tricky as things reach different parts of the body at different rates. This also covers the fact that there are different types of cells which require different entry procedures for the virus to mutate. These problems come together in the most troublesome spot, the brain. Nerves are hard, both hard for viruses to enter (because they are less common) and are generally more protected (like the blood brain barrier). So getting the virus into everything uniformly can be difficult.
**Adults are adults:** Physical maturation is an important biological process regulated by hormones in the brain. This is important in where genes are inserted as well as the process for activating them. For instance if your re-engineering intended to grow a third eye you need someway to activate and more importantly shut off the growth process. You wouldn't want a thousand eyes. Currently this process isn't well understood either. It could be that you simply need to supply your patient hormonal treatments in order to progress the mutations construction.
**Some Cells don't Divide** Mutating a nerve would be tricky because they don't divide. That isn't to say nerves cant be enhanced because you can highjack something like a stem cell but how you manage modification of the brain can be enormously difficult and tricky. The slightest mistake could result in the permanent crippling or 'resetting'of the patient. Not to mention after you reset a person it might be possible to rehabilitate them either as the adult brain is no longer performing the same cognitive formatting as an infants. This challenge alone makes retroviral gene editing both dangerous and completely rules out neural modifications for at least the next 100 years if not the next millennium. It also limits the significance of mutations. Because general motor skills are hard wired during infancy, it would be impossible for an adult to grow 4 arms and then be able to learn how to use them.
**Complexity of the mutation** Since adults are fully grown trying to unleash massive rewrites would be dangerous. This might be conquerable through iterative editing but if you change too much too fast you run the risk of killing the host in an infinitesimal array of ways. | [Gene Therapy](https://en.wikipedia.org/wiki/Gene_therapy)
==========================================================
With the gene therapy, is possible to modify the DNA of a born creature using Virus, Retrovirus, Adenovirus, Non-Virus or others as a Vector. (Surprisingly, the Spanish Wikipedia has more information about different vectors).
This [vectors](https://en.wikipedia.org/wiki/Vectors_in_gene_therapy) are programmed to modify the DNA structure of alive cells from the host.
At the moment it's quite dangerous or ineffective this gene therapy, but in the future, with the boom of genetical manipulation, it will no longe be a problem. |
58,764,751 | Got some problems with setting up drone with my gitea instance and because there are so much different guides with different configs over the past years for different environment variables for drone, i cannot setup this the way it works for me.
And yes, i do know, they explicitly stated *"We strongly recommend installing Drone on a dedicated instance. We do not offer end-user support for installing Drone and Gitea on the same instance. We do not offer end-user support for troubleshooting network complications resulting from single-instance installations."* but i think there must be a way to install it on the same server?
my current setup
----------------
* [jwilder nginx automated proxy](https://github.com/jwilder/nginx-proxy)
* [lets encrypt companion](https://github.com/JrCs/docker-letsencrypt-nginx-proxy-companion)
* [gitea](https://github.com/go-gitea/gitea)
* [drone](https://github.com/drone/drone)
drone docker-compose.yaml
-------------------------
```
version: "3.7"
services:
drone_server:
image: drone/drone
container_name: drone_server
ports:
- 127.0.0.1:8091:80
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /srv/drone:/var/lib/drone/
restart: always
environment:
- DRONE_GITEA_SERVER=https://gitea.mydomain.tld
- DRONE_GITEA_CLIENT_ID=$GITEA_CLIENT_ID
- DRONE_GITEA_CLIENT_SECRET=$GITEA_CLIENT_SECRET
- DRONE_SERVER_HOST=drone.mydomain.tld
- DRONE_SERVER_PROTO=https
- DRONE_LOGS_DEBUG=true
- DRONE_RPC_SECRET=$DRONE_SECRET
- VIRTUAL_HOST=drone.mydomain.tld
- LETSENCRYPT_HOST=drone.mydomain.tld
networks:
- proxy
networks:
proxy:
external:
name: proxy_default
```
corresponding (autogenerated) nginx config for drone
----------------------------------------------------
(gitea is equal, but with different subdomian)
```
map $http_x_forwarded_proto $proxy_x_forwarded_proto {
default $http_x_forwarded_proto;
'' $scheme;
}
map $http_x_forwarded_port $proxy_x_forwarded_port {
default $http_x_forwarded_port;
'' $server_port;
}
map $http_upgrade $proxy_connection {
default upgrade;
'' close;
}
server_names_hash_bucket_size 128;
ssl_dhparam /etc/nginx/dhparam/dhparam.pem;
map $scheme $proxy_x_forwarded_ssl {
default off;
https on;
}
gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
log_format vhost '$host $remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
resolver 127.0.0.11;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $proxy_connection;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
proxy_set_header X-Forwarded-Ssl $proxy_x_forwarded_ssl;
proxy_set_header X-Forwarded-Port $proxy_x_forwarded_port;
# drone.mydomain.tld
upstream drone.mydomain.tld {
## Can be connected with "proxy_default" network
# drone_server
server 172.22.0.8:80;
# Cannot connect to network of this container
server 127.0.0.1 down;
}
server {
server_name drone.mydomain.tld;
listen 80 ;
access_log /var/log/nginx/access.log vhost;
return 301 https://$host$request_uri;
}
server {
server_name drone.mydomain.tld;
listen 443 ssl http2 ;
access_log /var/log/nginx/access.log vhost;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
ssl_certificate /etc/nginx/certs/drone.mydomain.tld.crt;
ssl_certificate_key /etc/nginx/certs/drone.mydomain.tld.key;
ssl_dhparam /etc/nginx/certs/drone.mydomain.tld.dhparam.pem;
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/nginx/certs/drone.mydomain.tld.chain.pem;
add_header Strict-Transport-Security "max-age=31536000" always;
include /etc/nginx/vhost.d/default;
location / {
proxy_pass http://drone.mydomain.tld;
}
}
```
the gitea\_client\_id and secret are created via gitea webinterface, the redirect url is set to `https://drone.mydomain.tld/login`
here is what i am seeing visiting drone.mydomain.tld
----------------------------------------------------
[![drone auth](https://i.stack.imgur.com/3zpwC.png)](https://i.stack.imgur.com/3zpwC.png)
After clicking authorize application the the url in my browser request changes to <https://drone.mydomain.tld/login?XXXXXXXX> and it just loads until nginx throws a 502. After this initial authorization, every request just results in the following logs and erorr.
### nginx logs
```
nginx.1 | 2019/11/08 10:44:16 [warn] 3762#3762: *47660 upstream server temporarily disabled while reading response header from upstream, client: 111.111.111.111, server: drone.mydomain.tld, request: "GET /login?XXXXXXXX HTTP/2.0", upstream: "http://172.22.0.8:80/login?XXXXXXXX", host: "drone.mydomain.tld", referrer: "https://drone.mydomain.tld/"
nginx.1 | 2019/11/08 10:44:16 [error] 3762#3762: *47660 upstream timed out (110: Operation timed out) while reading response header from upstream, client: 111.111.111.111, server: drone.mydomain.tld, request: "GET /login?XXXXXXXX HTTP/2.0", upstream: "http://172.22.0.8:80/login?XXXXXXXX", host: "drone.mydomain.tld", referrer: "https://drone.mydomain.tld/"
nginx.1 | 2019/11/08 10:44:16 [error] 3762#3762: *47660 no live upstreams while connecting to upstream, client: 111.111.111.111, server: drone.mydomain.tld, request: "GET /login?XXXXXXXX HTTP/2.0", upstream: "http://drone.mydomain.tld/login?XXXXXXXX", host: "drone.mydomain.tld", referrer: "https://drone.mydomain.tld/"
```
### drone logs
```
{"level":"debug","msg":"api: authentication required","request-id":"1TKR8MAfIewZpiiwn2YkUNEqBrt","time":"2019-11-08T09:50:39Z"}
{"level":"debug","msg":"api: guest access","request-id":"1TKR8MAfIewZpiiwn2YkUNEqBrt","time":"2019-11-08T09:50:39Z"}
{"fields.time":"2019-11-08T09:50:39Z","latency":109385,"level":"debug","method":"GET","msg":"","remote":"172.22.0.2:60330","request":"/api/user","request-id":"1TKR8MAfIewZpiiwn2YkUNEqBrt","time":"2019-11-08T09:50:39Z"}
{"fields.time":"2019-11-08T09:50:39Z","latency":64377,"level":"debug","method":"GET","msg":"","remote":"172.22.0.2:60332","request":"/login","request-id":"1TKR8IicJybGXkQf3ebpiGV4VXi","time":"2019-11-08T09:50:39Z"}
{"level":"debug","msg":"events: stream opened","request-id":"1TKR8Jv7zQrCQSzRyCFbeRLeC8M","time":"2019-11-08T09:50:39Z"}
{"level":"debug","msg":"events: stream cancelled","request-id":"1TKR8Jv7zQrCQSzRyCFbeRLeC8M","time":"2019-11-08T09:51:39Z"}
{"level":"debug","msg":"events: stream closed","request-id":"1TKR8Jv7zQrCQSzRyCFbeRLeC8M","time":"2019-11-08T09:51:39Z"}
{"level":"debug","msg":"api: guest access","request-id":"1TKR8Jv7zQrCQSzRyCFbeRLeC8M","time":"2019-11-08T09:51:39Z"}
{"fields.time":"2019-11-08T09:51:39Z","latency":60182954972,"level":"debug","method":"GET","msg":"","remote":"172.22.0.2:60334","request":"/api/stream","request-id":"1TKR8Jv7zQrCQSzRyCFbeRLeC8M","time":"2019-11-08T09:51:39Z"}
{"level":"error","msg":"oauth: cannot exchange code: ysvAfRKVkRz4ZtN9zX635Vd-mnB__oXW7Rmqpra1VGU=: Post https://gitea.mydomain.tld/login/oauth/access_token: dial tcp 144.76.155.172:443: connect: connection timed out","time":"2019-11-08T09:52:32Z"}
{"level":"debug","msg":"cannot authenticate user: Post https://gitea.mydomain.tld/login/oauth/access_token: dial tcp 144.76.155.172:443: connect: connection timed out","time":"2019-11-08T09:52:32Z"}
```
### gitea logs
```
[Macaron] 2019-11-08 10:50:21: Started GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=c697f48392907a0 for 134.96.216.2
[Macaron] 2019-11-08 10:50:21: Completed GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=c697f48392907a0 302 Found in 58.954698ms
[Macaron] 2019-11-08 10:50:39: Started GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=68255aaf95e94627 for 134.96.216.2
[Macaron] 2019-11-08 10:50:39: Completed GET /login/oauth/authorize?client_id=$GITEA_CLIENT_ID&redirect_uri=https%3A%2F%2Fdrone.mydomain.tld%2Flogin&response_type=code&state=68255aaf95e94627 302 Found in 78.11159ms
```
### page source
this is what my browser is showing while, obviously, javascript is activated
```html
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=utf-8>
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=viewport content="width=device-width,initial-scale=1,user-scalable=0">
<link id=favicon rel=icon href=/favicon.png type=image/png>
<title>Drone | Continuous Integration</title>
<link href=/css/app.835f40e0.css rel=preload as=style>
<link href=/js/app.2c99ed98.js rel=preload as=script>
<link href=/js/chunk-vendors.f5840117.js rel=preload as=script>
<link href=/css/app.835f40e0.css rel=stylesheet>
</head>
<body>
<noscript><strong>We're sorry but Drone does not work properly without JavaScript enabled. Please enable it to continue.</strong></noscript>
<div id=app></div>
<script src=/js/chunk-vendors.f5840117.js></script>
<script src=/js/app.2c99ed98.js></script>
</body>
</html>
```
is there any configuration i missed or any environment variable which is outdated (i followed different guides, but in the end checked everything with the [drone docs](https://docs.drone.io/installation/providers/gitea/))? is there anybody out there who is running a similar setup who can share his config with me? i tried pretty much every combination of http/https combination and different outdated env vars for drone, but never got to the actual webfrontend. | 2019/11/08 | ['https://Stackoverflow.com/questions/58764751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9239809/'] | Try:
```
import matplotlib.pyplot as plt
ax = df.plot.bar(y='Profile_ID Count')
plt.show()
``` | ```
# Importing the requisite libraries
import pandas as pd
import matplotlib.pyplot as plt
# Creating the DataFrame
df = pd.DataFrame({'Creation Date':['2016-06-01','2016-06-03','2016-06-04'],'Profile_ID Count':[150,3,20]})
# Creating the bar chart below.
fig, ax = plt.subplots()
ax.bar(df['Creation Date'],df['Profile_ID Count'], color='red', width = 0.5)
fig.autofmt_xdate() # This tilts the dates displayed along X-axis.
ax.set_title('Creation Date vs. Profile ID Count')
ax.set_xlabel('Creation Date')
ax.set_ylabel('Profile ID Count')
plt.show()
```
[![Bar-Chart](https://i.stack.imgur.com/FInW9.png)](https://i.stack.imgur.com/FInW9.png) |
11,106,110 | Does anyone know the standard size of a single listview item in android, in dpi or pixels?
Or maybe there isn't a standard? | 2012/06/19 | ['https://Stackoverflow.com/questions/11106110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1301563/'] | Android defines a "preferred size" using,
```
android:minHeight="?android:attr/listPreferredItemHeight"
```
Documented [here](http://developer.android.com/reference/android/R.attr.html#listPreferredItemHeight) as well. | there is a strongly recommended list view item size, which you should use: [48dip](http://developer.android.com/design/style/metrics-grids.html#48dp-rhythm). This is recommended by the new Android Design Guidelines. |
2,996 | I recently upgraded to CiviCRM 4.6.3 from 4.4.XX. Since then, the WYSIWYG editor is missing when creating a new scheduled reminder or editing an existing one. To reproduce the error:
1. Click Manage Events
2. Click Configure an event, and choose Schedule Reminders.
3. Edit or create a new reminder
4. See the editor missing.
However if on step 2, you instead choose Info and Settings, then click Schedule Reminders, the WYSIWYG editor does appear.
I've verified the error with IE, FF and Chrome, and I see the issue 100% of the time. Using Joomla 2.5.28.
Anybody else see this issue? | 2015/06/03 | ['https://civicrm.stackexchange.com/questions/2996', 'https://civicrm.stackexchange.com', 'https://civicrm.stackexchange.com/users/614/'] | Adding the contribution status itself is pretty easy. You can do that with Administer/System Settings/Option Groups, find the one for Contribution Status and click on 'options'. You will then get the possibility to add a value.
This is just adding a status, so I assume the settings of the status will be done manually. If you want to automate that you will have to develop a small extension that acts when a contribution is added or changed, and sets your status in relevant cases.
Am I making sense? | Normally, you can set new options in Administer > System Settings > Option Groups, but you'll notice that it says:
>
> This option group is reserved for system use. You cannot add or delete options in this list.
>
>
>
You could work around it by adding a new item in the civicrm\_option\_value table, but you'd be definitely doing something that CiviCRM is telling you not to do. You may have upgrade problems at some later point, because CiviCRM will assume nobody has gone in and messed around with those options.
Instead, you might consider that there really is no *new* data to be stored; you just want to be able to find really old pending contributions. If you just create a report based upon the donor detail report with the following changes, you ought to be able to find the right folks:
* Contribution Status set to Pending, Cancelled, or whatever else
* Receive date set to "To end of previous quarter" or an equivalent relative date (I know it's not exactly what you want, but date filters will be improving soon, I hear)
You can even set this as a dashlet so that the person in charge of pestering people about this can have it on his or her dashboard. |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | First, verify the path to your SD card. You can do this by running the following command from terminal:
`diskutil list`
The output shows a list of disks currently mounted on the system. Here's the relevant line from my output:
```
/dev/disk3
#: TYPE NAME SIZE IDENTIFIER
0: FDisk_partition_scheme *8.0 GB disk3
1: DOS_FAT_32 RPISDCARD 8.0 GB disk3s1
```
In this case I can verify `/dev/disk3` is my SD card because the TYPE, NAME and SIZE values are correct.
If you have an existing partition on the disk you may need to unmount it, otherwise you'll get a "Resource busy" error message when you try to write the image.
```
diskutil unmount /dev/disk3s1
```
Now to write the image file to the disk. Note the 'r' added to `rdisk3` which drastically improves write performance by telling `dd` to operate in raw disk mode:
```
sudo dd if=RetroPieImage_ver2.3.img of=/dev/rdisk3 bs=1m
```
Depending on the size of your SDcard this may take a while. You can press `CTRL+T` to see the current status of `dd`. As an example for my Samsung 8GB SD card the write speed was 12MB/s the command took 11mins to complete. | Try this: [ApplePi-Baker](http://www.tweaking4all.com/hardware/raspberry-pi/macosx-apple-pi-baker/)
It's free, writes IMG files to SD-Card, can prepare a NOOBS card and can make a backup to IMG of your SD-Card. |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | I made a script to burn .img or .iso files to SD card or USB.
[Github > burn.sh](https://github.com/jmcerrejon/scripts/blob/master/burn.sh) | Use `df` to find the device path, in this case `/dev/disk2`.
```
$ df -h
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% /
devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home
/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED
``` |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | There is a faq/howto available that discusses all the various OS-es. For the Mac it is (nearly) the same as under the various other types of Unix versions. The use of dd.
In short you type:
```
sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m
```
**N.B: the of=/rdev/diskn needs to be the SD card, if you do this wrong you might end up destroying your Mac system!!!! Be careful!**
Be sure to use `/dev/rdiskn` instead of just `/dev/diskn`. This way you are not writing to a buffered device and [it will complete much faster](https://raspberrypi.stackexchange.com/questions/3204/sd-card-write-speed-seems-to-be-14-times-slower-than-read-speed/4059#4059).
For a total step by step guide through this process please consult this [explanation](http://elinux.org/RPi_Easy_SD_Card_Setup). There are 3 chapters for the Mac in this document.
The most easy way is described on the first chapter on Mac ([Copying an image to the SD card in Mac OS X (Only with graphical interface)](http://elinux.org/RPi_Easy_SD_Card_Setup#Copying_an_image_to_the_SD_card_in_Mac.C2.A0OS.C2.A0X_.28Only_with_graphical_interface.29)), it involves an application that does everything for you, to be complete I copy the link to this application [here](http://alltheware.wordpress.com/2012/12/11/easiest-way-sd-card-setup/) | Try this: [ApplePi-Baker](http://www.tweaking4all.com/hardware/raspberry-pi/macosx-apple-pi-baker/)
It's free, writes IMG files to SD-Card, can prepare a NOOBS card and can make a backup to IMG of your SD-Card. |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | In 2020, this accepted answer is obsolete: For *most* cases, people should follow the new [raspberrypi.org Installation Guide](https://www.raspberrypi.org/documentation/installation/installing-images/README.md).
Alternatively, the community-provided [Etcher](https://www.balena.io/etcher/) tool also provides a graphical tool to burn Pi IMG files to SD card.
Sometimes the built-in SD card reader gives errors with Etcher. If you don't have a USB SD adapter, 'dd' sometimes still works although the user must *take care* because the wrong command may damage their mac's OS.
If you must use 'dd', the accepted answer `sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m` works (with care taken) *however* if you have installed [Homebrew](https://brew.sh/) with the 'gnubin' utilities, it provides the GNU dd utility which has different syntax. For GNU dd (including Linux hosts) use `1M` instead of `1m` (otherwise you get error: "`dd: invalid number: ‘1m’`" which is what inspired me to add a new answer). | You could also try: [dd Utility](https://www.thefanclub.co.za/how-to/dd-utility-write-and-backup-operating-system-img-files-memory-card-mac-os-x)
Features:
* Write IMG files to memory cards and hard drives.
* Backup and Restore IMG files to memory cards and hard drives.
* Install and Restore compressed disk image files on the fly. Supported
file formats: IMG, Zip, GZip and XZ.
* Backup and compress disk image files on the fly in ZIP format to
significantly reduce the file size of backups.
* Ideal for flashing IMG files to SD Cards for use with Raspberry Pi,
Arduino, BeagleBoard and other ARM boards.
* Mac Retina displays supported. |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | There is a faq/howto available that discusses all the various OS-es. For the Mac it is (nearly) the same as under the various other types of Unix versions. The use of dd.
In short you type:
```
sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m
```
**N.B: the of=/rdev/diskn needs to be the SD card, if you do this wrong you might end up destroying your Mac system!!!! Be careful!**
Be sure to use `/dev/rdiskn` instead of just `/dev/diskn`. This way you are not writing to a buffered device and [it will complete much faster](https://raspberrypi.stackexchange.com/questions/3204/sd-card-write-speed-seems-to-be-14-times-slower-than-read-speed/4059#4059).
For a total step by step guide through this process please consult this [explanation](http://elinux.org/RPi_Easy_SD_Card_Setup). There are 3 chapters for the Mac in this document.
The most easy way is described on the first chapter on Mac ([Copying an image to the SD card in Mac OS X (Only with graphical interface)](http://elinux.org/RPi_Easy_SD_Card_Setup#Copying_an_image_to_the_SD_card_in_Mac.C2.A0OS.C2.A0X_.28Only_with_graphical_interface.29)), it involves an application that does everything for you, to be complete I copy the link to this application [here](http://alltheware.wordpress.com/2012/12/11/easiest-way-sd-card-setup/) | Found a really good link: <http://www.tweaking4all.com/hardware/raspberry-pi/install-img-to-sd-card/#macosx> for installing file.img on SD card, very detailed steps! |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | First, verify the path to your SD card. You can do this by running the following command from terminal:
`diskutil list`
The output shows a list of disks currently mounted on the system. Here's the relevant line from my output:
```
/dev/disk3
#: TYPE NAME SIZE IDENTIFIER
0: FDisk_partition_scheme *8.0 GB disk3
1: DOS_FAT_32 RPISDCARD 8.0 GB disk3s1
```
In this case I can verify `/dev/disk3` is my SD card because the TYPE, NAME and SIZE values are correct.
If you have an existing partition on the disk you may need to unmount it, otherwise you'll get a "Resource busy" error message when you try to write the image.
```
diskutil unmount /dev/disk3s1
```
Now to write the image file to the disk. Note the 'r' added to `rdisk3` which drastically improves write performance by telling `dd` to operate in raw disk mode:
```
sudo dd if=RetroPieImage_ver2.3.img of=/dev/rdisk3 bs=1m
```
Depending on the size of your SDcard this may take a while. You can press `CTRL+T` to see the current status of `dd`. As an example for my Samsung 8GB SD card the write speed was 12MB/s the command took 11mins to complete. | Found a really good link: <http://www.tweaking4all.com/hardware/raspberry-pi/install-img-to-sd-card/#macosx> for installing file.img on SD card, very detailed steps! |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | Yes the simple answer is to just [dd](http://linux.die.net/man/1/dd) it, but there are some safety precautions you may want to enforce by wrapping your dd in a script;
```
#!/bin/bash
#
# copy_img_to_sd.sh
#
ME=$( id | grep root | wc -l | perl -p -e 's/[^0-9]+//g');
if [ "$ME" != "1" ] ;then
echo "must be root"
exit 1;
fi
IMG=$1
if [ ! -f $IMG ] ;then
echo "can not find $IMG";
exit 2;
fi
DISK=$(ls -l /dev/disk? | wc -l |perl -p -e 's/[^0-9]//g')
if [ $DISK -lt 3 ] ; then
echo "can not find sdcard";
ls -l /dev/disk?
exit 2;
fi
DISK=$(ls -1 /dev/disk? | tail -1);
R_DISK=$(ls -1 /dev/rdisk? | tail -1);
echo "we are about to do this:"
echo $(diskutil information $DISK | grep Total)
ls -1 /dev/disk?s* | grep "$DISK" | perl -p -e 's/^(.*)$/diskutil unmount $1;/g'
echo dd bs=1m if=$IMG of=$R_DISK
echo sync
echo diskutil eject $R_DISK
echo "Press [enter] to continue or [Ctrl]+[C] to cancel";
read YNM;
ls -1 /dev/disk?s* | grep "$DISK" | perl -p -e 's/^(.*)$/diskutil unmount $1;/g' | bash 2>/dev/null
dd bs=1m if=$IMG of=$R_DISK
sync
diskutil eject $R_DISK
```
Accidentally writing an image to your internal drive will require a fresh OS X install to correct. Backup and keep an install.log so if it ever happens to you you can laugh it off. | Use `df` to find the device path, in this case `/dev/disk2`.
```
$ df -h
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% /
devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home
/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED
``` |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | Found a really good link: <http://www.tweaking4all.com/hardware/raspberry-pi/install-img-to-sd-card/#macosx> for installing file.img on SD card, very detailed steps! | Use `df` to find the device path, in this case `/dev/disk2`.
```
$ df -h
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% /
devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home
/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED
``` |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | There is a faq/howto available that discusses all the various OS-es. For the Mac it is (nearly) the same as under the various other types of Unix versions. The use of dd.
In short you type:
```
sudo dd if=path_of_your_image.img of=/dev/rdiskn bs=1m
```
**N.B: the of=/rdev/diskn needs to be the SD card, if you do this wrong you might end up destroying your Mac system!!!! Be careful!**
Be sure to use `/dev/rdiskn` instead of just `/dev/diskn`. This way you are not writing to a buffered device and [it will complete much faster](https://raspberrypi.stackexchange.com/questions/3204/sd-card-write-speed-seems-to-be-14-times-slower-than-read-speed/4059#4059).
For a total step by step guide through this process please consult this [explanation](http://elinux.org/RPi_Easy_SD_Card_Setup). There are 3 chapters for the Mac in this document.
The most easy way is described on the first chapter on Mac ([Copying an image to the SD card in Mac OS X (Only with graphical interface)](http://elinux.org/RPi_Easy_SD_Card_Setup#Copying_an_image_to_the_SD_card_in_Mac.C2.A0OS.C2.A0X_.28Only_with_graphical_interface.29)), it involves an application that does everything for you, to be complete I copy the link to this application [here](http://alltheware.wordpress.com/2012/12/11/easiest-way-sd-card-setup/) | Use `df` to find the device path, in this case `/dev/disk2`.
```
$ df -h
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 465Gi 414Gi 51Gi 90% 108573777 13263821 89% /
devfs 214Ki 214Ki 0Bi 100% 741 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home
/dev/disk2s1 3.7Gi 2.3Mi 3.7Gi 1% 0 0 100% /Volumes/UNTITLED
``` |
4,144 | I want to burn a .img file of Wheezy OS to my 8GB SD Card from Mac OS X but can't figure out how.
Any help would be appreciated. | 2012/12/27 | ['https://raspberrypi.stackexchange.com/questions/4144', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/-1/'] | First, verify the path to your SD card. You can do this by running the following command from terminal:
`diskutil list`
The output shows a list of disks currently mounted on the system. Here's the relevant line from my output:
```
/dev/disk3
#: TYPE NAME SIZE IDENTIFIER
0: FDisk_partition_scheme *8.0 GB disk3
1: DOS_FAT_32 RPISDCARD 8.0 GB disk3s1
```
In this case I can verify `/dev/disk3` is my SD card because the TYPE, NAME and SIZE values are correct.
If you have an existing partition on the disk you may need to unmount it, otherwise you'll get a "Resource busy" error message when you try to write the image.
```
diskutil unmount /dev/disk3s1
```
Now to write the image file to the disk. Note the 'r' added to `rdisk3` which drastically improves write performance by telling `dd` to operate in raw disk mode:
```
sudo dd if=RetroPieImage_ver2.3.img of=/dev/rdisk3 bs=1m
```
Depending on the size of your SDcard this may take a while. You can press `CTRL+T` to see the current status of `dd`. As an example for my Samsung 8GB SD card the write speed was 12MB/s the command took 11mins to complete. | I made a script to burn .img or .iso files to SD card or USB.
[Github > burn.sh](https://github.com/jmcerrejon/scripts/blob/master/burn.sh) |
47,550,227 | I'm trying to mount mongo `/data` directory on to a NFS volume in my kubernetes master machine for persisting mongo data. I see the volume is mounted successfully but I can see only `configdb` and `db` dirs but not their subdirectories. And I see the data is not even persisting in the volume. when I `kubectl describe <my_pv>` it shows `NFS (an NFS mount that lasts the lifetime of a pod)`
Why is that so?
I see in kubernetes docs stating that:
>
> An nfs volume allows an existing NFS (Network File System) share to be
> mounted into your pod. Unlike emptyDir, which is erased when a Pod is
> removed, the contents of an nfs volume are preserved and the volume is
> merely unmounted. This means that an NFS volume can be pre-populated
> with data, and that data can be “handed off” between pods. NFS can be
> mounted by multiple writers simultaneously.
>
>
>
I'm using kubernetes version 1.8.3.
mongo-deployment.yml:
```
apiVersion: apps/v1beta2
kind: Deployment
metadata:
name: mongo
labels:
name: mongo
app: mongo
spec:
replicas: 3
selector:
matchLabels:
name: mongo
app: mongo
template:
metadata:
name: mongo
labels:
name: mongo
app: mongo
spec:
containers:
- name: mongo
image: mongo:3.4.9
ports:
- name: mongo
containerPort: 27017
protocol: TCP
volumeMounts:
- name: mongovol
mountPath: "/data"
volumes:
- name: mongovol
persistentVolumeClaim:
claimName: mongo-pvc
```
mongo-pv.yml:
```
apiVersion: v1
kind: PersistentVolume
metadata:
name: mongo-pv
labels:
type: NFS
spec:
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
persistentVolumeReclaimPolicy: Retain
storageClassName: slow
mountOptions:
- hard
- nfsvers=4.1
nfs:
path: "/mongodata"
server: 172.20.33.81
```
mongo-pvc.yml:
```
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongo-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 3Gi
storageClassName: slow
selector:
matchLabels:
type: NFS
```
The way I mounted my nfs share on my kubernetes master machine:
```
1) apt-get install nfs-kernel-server
2) mkdir /mongodata
3) chown nobody:nogroup -R /mongodata
4) vi /etc/exports
5) added the line "/mongodata *(rw,sync,all_squash,no_subtree_check)"
6) exportfs -ra
7) service nfs-kernel-server restart
8) showmount -e ----> shows the share
```
I logged into the bash of my pod and I see the directory is mounted correctly but data is not persisting in my nfs server (kubernetes master machine).
Please help me see what I am doing wrong here. | 2017/11/29 | ['https://Stackoverflow.com/questions/47550227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4088785/'] | It's possible that pods don't have permission to create files and directories. You can `exec` to your pod and try to `touch` a file in NFS share if you get permission error you can ease up permission on file system and `exports` file to allow write access.
It's possible to specify `GID` in PV object to avoid permission denied issues.
<https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/#access-control> | I see you did a `chown nobody:nogroup -R /mongodata`.
Make sure that the application on your pod runs as `nobody:nogroup` |
47,550,227 | I'm trying to mount mongo `/data` directory on to a NFS volume in my kubernetes master machine for persisting mongo data. I see the volume is mounted successfully but I can see only `configdb` and `db` dirs but not their subdirectories. And I see the data is not even persisting in the volume. when I `kubectl describe <my_pv>` it shows `NFS (an NFS mount that lasts the lifetime of a pod)`
Why is that so?
I see in kubernetes docs stating that:
>
> An nfs volume allows an existing NFS (Network File System) share to be
> mounted into your pod. Unlike emptyDir, which is erased when a Pod is
> removed, the contents of an nfs volume are preserved and the volume is
> merely unmounted. This means that an NFS volume can be pre-populated
> with data, and that data can be “handed off” between pods. NFS can be
> mounted by multiple writers simultaneously.
>
>
>
I'm using kubernetes version 1.8.3.
mongo-deployment.yml:
```
apiVersion: apps/v1beta2
kind: Deployment
metadata:
name: mongo
labels:
name: mongo
app: mongo
spec:
replicas: 3
selector:
matchLabels:
name: mongo
app: mongo
template:
metadata:
name: mongo
labels:
name: mongo
app: mongo
spec:
containers:
- name: mongo
image: mongo:3.4.9
ports:
- name: mongo
containerPort: 27017
protocol: TCP
volumeMounts:
- name: mongovol
mountPath: "/data"
volumes:
- name: mongovol
persistentVolumeClaim:
claimName: mongo-pvc
```
mongo-pv.yml:
```
apiVersion: v1
kind: PersistentVolume
metadata:
name: mongo-pv
labels:
type: NFS
spec:
capacity:
storage: 5Gi
accessModes:
- ReadWriteMany
persistentVolumeReclaimPolicy: Retain
storageClassName: slow
mountOptions:
- hard
- nfsvers=4.1
nfs:
path: "/mongodata"
server: 172.20.33.81
```
mongo-pvc.yml:
```
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongo-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 3Gi
storageClassName: slow
selector:
matchLabels:
type: NFS
```
The way I mounted my nfs share on my kubernetes master machine:
```
1) apt-get install nfs-kernel-server
2) mkdir /mongodata
3) chown nobody:nogroup -R /mongodata
4) vi /etc/exports
5) added the line "/mongodata *(rw,sync,all_squash,no_subtree_check)"
6) exportfs -ra
7) service nfs-kernel-server restart
8) showmount -e ----> shows the share
```
I logged into the bash of my pod and I see the directory is mounted correctly but data is not persisting in my nfs server (kubernetes master machine).
Please help me see what I am doing wrong here. | 2017/11/29 | ['https://Stackoverflow.com/questions/47550227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4088785/'] | It's possible that pods don't have permission to create files and directories. You can `exec` to your pod and try to `touch` a file in NFS share if you get permission error you can ease up permission on file system and `exports` file to allow write access.
It's possible to specify `GID` in PV object to avoid permission denied issues.
<https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/#access-control> | Add the parameter `mountOptions: "vers=4.1"` to your StorageClass config, this should fix your issue.
See this Github comment for more info:
<https://github.com/kubernetes-incubator/external-storage/issues/223#issuecomment-344972640> |
66,288 | I recently upgraded to Oneiric and noticed that the calendar is no longer persistent like it was in Natty and Maverick. I could open the calendar to January 2007, then move to another window and still refer to the calendar. Now, as soon as I lose focus the calendar goes back into hiding. Is this a setting somewhere? | 2011/10/14 | ['https://askubuntu.com/questions/66288', 'https://askubuntu.com', 'https://askubuntu.com/users/23482/'] | Temporarily downloaded files
----------------------------
All Linux browsers (including Firefox and Chrome) store "Open for viewing" downloads in the `/tmp` directory. Old `/tmp` files are deleted the following situations:
1. When you close your browser
2. When you restart Ubuntu
3. When your disk space is low
If you want to make a temporary download permanent, you can simply navigate to `/tmp`, find the file in question, and copy it into your home folder.
Streaming media
---------------
Flash, audio, and video files you play are cached in highly obfuscated directories like `$HOME/.mozilla/firefox/3lms8ke.default/C/2A` for Firefox. Woozie's answer to [this question](https://askubuntu.com/q/37267/24694) can help you find and retrieve flash files. Remove the `| grep Flash` part of his command to get a list of all cached files by their data type. | do you mean : "the browser cache
take a look at :
```
/home/$USER/.mozilla/firefox/SOMETHIN.default/Cache
``` |
66,288 | I recently upgraded to Oneiric and noticed that the calendar is no longer persistent like it was in Natty and Maverick. I could open the calendar to January 2007, then move to another window and still refer to the calendar. Now, as soon as I lose focus the calendar goes back into hiding. Is this a setting somewhere? | 2011/10/14 | ['https://askubuntu.com/questions/66288', 'https://askubuntu.com', 'https://askubuntu.com/users/23482/'] | Mozilla Firefox
---------------
`~/.mozilla/firefox/[something].default/Cache`
You can go to `about:cache` in your Browser to see information about this as well.
![About Cache Link](https://i.stack.imgur.com/sieVZ.png)
Chromium
--------
`~/.cache/chromium/[profile]/Cache/`
Google Chrome
-------------
`~/.cache/google-chrome/[profile]/Cache/`
Also, Chromium and Google Chrome store some additional cache at `~/.config/chromium/[profile]/Application Cache/Cache/` and `~/.config/google-chrome/[profile]/Application Cache/Cache/`
Safari
------
`~/.wine/drive_c/Document and Settings/$USER/Application Data/Apple Computer/Safari`
`~/.wine/drive_c/Document and Settings/$USER/Local Settings/Application Data/Apple Computer/Safari`
Other than this, browsers can store temporary files in `/tmp/` as well
Reference: [Chrome, Chromium](http://code.google.com/p/chromium/wiki/ChromiumBrowserVsGoogleChrome), [Firefox](http://kb.mozillazine.org/Browser.cache.disk.parent_directory), [Safari](https://discussions.apple.com/thread/1047105?start=0&tstart=0) | do you mean : "the browser cache
take a look at :
```
/home/$USER/.mozilla/firefox/SOMETHIN.default/Cache
``` |
66,288 | I recently upgraded to Oneiric and noticed that the calendar is no longer persistent like it was in Natty and Maverick. I could open the calendar to January 2007, then move to another window and still refer to the calendar. Now, as soon as I lose focus the calendar goes back into hiding. Is this a setting somewhere? | 2011/10/14 | ['https://askubuntu.com/questions/66288', 'https://askubuntu.com', 'https://askubuntu.com/users/23482/'] | Mozilla Firefox
---------------
`~/.mozilla/firefox/[something].default/Cache`
You can go to `about:cache` in your Browser to see information about this as well.
![About Cache Link](https://i.stack.imgur.com/sieVZ.png)
Chromium
--------
`~/.cache/chromium/[profile]/Cache/`
Google Chrome
-------------
`~/.cache/google-chrome/[profile]/Cache/`
Also, Chromium and Google Chrome store some additional cache at `~/.config/chromium/[profile]/Application Cache/Cache/` and `~/.config/google-chrome/[profile]/Application Cache/Cache/`
Safari
------
`~/.wine/drive_c/Document and Settings/$USER/Application Data/Apple Computer/Safari`
`~/.wine/drive_c/Document and Settings/$USER/Local Settings/Application Data/Apple Computer/Safari`
Other than this, browsers can store temporary files in `/tmp/` as well
Reference: [Chrome, Chromium](http://code.google.com/p/chromium/wiki/ChromiumBrowserVsGoogleChrome), [Firefox](http://kb.mozillazine.org/Browser.cache.disk.parent_directory), [Safari](https://discussions.apple.com/thread/1047105?start=0&tstart=0) | Temporarily downloaded files
----------------------------
All Linux browsers (including Firefox and Chrome) store "Open for viewing" downloads in the `/tmp` directory. Old `/tmp` files are deleted the following situations:
1. When you close your browser
2. When you restart Ubuntu
3. When your disk space is low
If you want to make a temporary download permanent, you can simply navigate to `/tmp`, find the file in question, and copy it into your home folder.
Streaming media
---------------
Flash, audio, and video files you play are cached in highly obfuscated directories like `$HOME/.mozilla/firefox/3lms8ke.default/C/2A` for Firefox. Woozie's answer to [this question](https://askubuntu.com/q/37267/24694) can help you find and retrieve flash files. Remove the `| grep Flash` part of his command to get a list of all cached files by their data type. |
263,735 | Problem:
How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it?
---
Goal:
I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection.
Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the "Font Pt Selection" drop down displays "9". If you then select the first 20 characters, the same drop down should have a empty/blank display.
---
What I have going so far:
I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out
```
CHARFORMAT cf;
cf.cbSize = sizeof(CHARFORMAT);
CRichEditCtrl ctrl;
ctrl.GetSelectionCharFormat( cf );
int nFontPtSize = cf.yHeight / 20;
```
This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection).
In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on). | 2008/11/04 | ['https://Stackoverflow.com/questions/263735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34460/'] | As the above answer notes, the easiest way I can think of to do this is to use the Text Object Model (TOM), which is accessed through the ITextDocument COM interface. To get at this from your rich edit control (note code not tested, but should work):
```
CComPtr<IRichEditOle> richOle;
richOle.Attach(edit.GetIRichEditOle());
CComQIPtr<ITextDocument> textDoc(richOle);
```
Then get a range. Here this is for the selected text, but one of the advantages of TOM is that you can operate on any range, not just what's selected.
```
CComPtr<ITextSelection> range;
textDoc->GetSelection(&range);
```
Then get the font for the range, and see what its characteristics are, e.g.
```
CComPtr<ITextFont> font;
range->GetFont(&font);
long size;
font->GetSize(&size);
```
If the range is formatted with a single font size, you'll get that back in "size". If there's multiple font sizes, you'll get the value "tomUndefined" instead. | Been juggling a couple things, but I was finally able to work.
This is how I finally was able to get everything to compile and run:
```
HWND hwnd;
ITextDocument* pDoc;
IUnknown* pUnk = NULL;
float size = 0;
hwnd = GetSafeHwnd();
::SendMessage( hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&pUnk );
if ( pUnk && pUnk->QueryInterface( __uuidof(ITextDocument), (void**)&pDoc ) == NOERROR )
{
CComPtr<ITextSelection> range;
pDoc->GetSelection( &range );
CComPtr<ITextFont> font;
range->GetFont( &font );
// If there are multiple font sizes in the selection, "size" comes back as -9999
font->GetSize(&size);
}
return size;
``` |
56,659,834 | I want to get the text of a tag and span tag at the same time.
```
<td class="desc_autoHeight">
<a rel="nofollow" href="#" target="_blank">Silicon Power</a>
<br><span class="FreeGift">48 Hours Only</span>
</td>
<td class="desc_autoHeight">
<a rel="nofollow" href="#" target="_blank">Silicon Power</a>
48 Hours Only
</td>
```
Result should be Silicon Power 48 Hours Only | 2019/06/19 | ['https://Stackoverflow.com/questions/56659834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9730468/'] | I suggest you create an array to store all your `a` elements like so:
```
var arr = [10, 15, 20];
```
Which you can then loop over using a for loop. In the array the 0th index represents the `a1` and the n-1th index represents `a*n*`:
```js
var arr = [10, 15, 20];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
Another approach would be to use an object, where `a1`, `a2`, ... `a*n*` are keys in your object:
```
var obj = {
'a1': 10,
'a2': 15,
'a3': 20
}
```
You can then use bracket notation to access your keys and values:
```js
var obj = {
'a1': 10,
'a2': 15,
'a3': 20
}
for (var i = 1; i <= 3; i++) {
console.log(obj['a' + i]);
}
```
...or use a `for...in` loop to loop over your properties instead:
```js
var obj = {
'a1': 10,
'a2': 15,
'a3': 20
}
for (var prop in obj) {
console.log(obj[prop]);
}
``` | ```
var a = [10, 15, 20];
for (var i=0; i<a.length; i++){
console.log("The value of a[i] is", a[i]);
}
``` |
20,939,193 | I am trying to wrap my head around network sockets. So far my understanding is that a server creates a new socket that is bound to the specific port. Then it listens to this socket to deal with client requests.
I've read this tutorial <http://docs.oracle.com/javase/tutorial/networking/sockets/definition.html> and it says
>
> If everything goes well, the server accepts the connection. Upon acceptance,
> the server gets a new socket bound to the same local port and also has
> its remote endpoint set to the address and port of the client. It needs
> a new socket so that it can continue to listen to the original socket for
> connection requests while tending to the needs of the connected client.
>
>
>
Here are a few things that I don't quite understand
>
> If everything goes well, the server accepts the connection.
>
>
>
1. Does it mean that a client request successfully arrived at the listening socket?
>
> Upon acceptance, the server gets a new socket bound to the same local port and
> also has its remote endpoint set to the address and port of the client
>
>
>
2. The new socket is created. It also gets bound to the same port but it doesn't listen for incoming requests. After server processed client request resonse is written to this socket and then it gets closed. Is it correct?
3. Does it mean that request is somehow passed from the first socket to the second socket?
>
> It needs a new socket so that it can continue to listen to the original
> socket for connection requests while tending to the needs of the connected client.
>
>
>
4. So, the new socket is created then that listens for incoming request. Are there different type of sockets? Some kind of "listening" sockets and other?
5. Why does the server have to create a new listening socket? Why can't it reuse the previous one? | 2014/01/05 | ['https://Stackoverflow.com/questions/20939193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1745356/'] | 1. No. It means that an incoming connection arrived at the server.
2. No. It gets closed if the server closes it. Not otherwise.
3. No. It means that the incoming connection causes a connection to be fully formed and a socket created at the server to represent the server-end endpoint of it.
4. (a) No. A new socket is created to *receive* requests and send responses. (b) Yes. There are passive and active sockets. A passive socket listens for connections. An active socket sends and receives data.
5. It doesn't have to create a new listening (passive) socket. It has to create a new active socket to be the endpoint of the new connection.
>
> Is new socket created for every request?
>
>
>
Most protocols, for example HTTP with keep-alive, allow multiple requests per connection. | 1) An incoming connection has arrived
2) Socket doesn't get closed
3) There is server socket and just socket. Server socket.accept returns a socket object when a client connects |
206,967 | This is my first Atmega project so I have following questions:
1. Do I have to connect all those gnds and vcc's?
2. In programming I used Vcc Reset Gnd Tx Rx SClk of USART0 is that okay?
3. I didn't used external clock generator (quarks) because I'm planning to use inside clock?
4. Is there any fundamental circuits or pins that must be connected to work simple code? (I connected only Vccs and Gnds)
5. Is there simple circuit that tests if the atmega 128 is working or not without programming it? | 2015/12/20 | ['https://electronics.stackexchange.com/questions/206967', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89445/'] | 1. **Yes.**
2. Only if you've programmed it with a serial bootloader already. Otherwise use ISP or HVPP as normal.
3. Okay? This is not a question.
4. AVCC must be connected. You probably also want to connect nPEN to a switch.
5. No. They come unprogrammed from the factory other than the ATmega103 compatibility fuse. Don't forget to unprogram that fuse before use. | @1: Yes, you have to connect all VCC and GND pins. This includes AVCC and AGND.
@2: Does the device run your program? Did the programmer return any error code?
@4: Connect a decoupling capacitor for every single VCC pin. Rule of thumb 100nF ceramic.
@5: Some devices may support JTAG testing or similar debug interface (debugWIRE), but I doubt that qualifies for "simple". |
206,967 | This is my first Atmega project so I have following questions:
1. Do I have to connect all those gnds and vcc's?
2. In programming I used Vcc Reset Gnd Tx Rx SClk of USART0 is that okay?
3. I didn't used external clock generator (quarks) because I'm planning to use inside clock?
4. Is there any fundamental circuits or pins that must be connected to work simple code? (I connected only Vccs and Gnds)
5. Is there simple circuit that tests if the atmega 128 is working or not without programming it? | 2015/12/20 | ['https://electronics.stackexchange.com/questions/206967', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89445/'] | 1. Yes. It is also recommended to place a 100nF capacitor as close to VCC and GND of every pair. On most modern devices you will see VCC/GND placed next to each other to make that easier.
2. Normally a microcontroller is programmed in-circuit via a specific port. On Atmega's this is usually some sort of SPI port (called ISP) along with RESET. On more modern devices it is a "TWI port". It's often pretty well described in the datasheet. Via this port you can write and erase the device memories, and set fuses. However, you also need a specific hardware tool (often made by the vendor as well; sometimes you can get third-party ones - but watch out for software support!).
Because of these limitations (unusual hardware connection, hardware tools, etc.) people write bootloaders. E.g. on the Arduino platform the ATMEGA can be partially reprogrammed via a serial port. However the ATMEGA needs to be preprogrammed with this bootloader software in order to do this. The preprogramming must be done via ISP.
3. This is fine in most cases. Just want to point out a few things:
* Do not set the AVR ISP communication speed too high. I am not sure of the exact oscillator to clock ratio, but a too fast speed will corrupt data and fuses.
* Corrupt fuses can turn off the ISP port (no more reprogramming via ISP!), tell the chip to use an external oscillator (bricking it if it's not there!), etc.
4. Pull RESET high via a pull-up resistor to make the chip run.
Connect all VCC/GND pairs, including AVCC/AGND.
Sometimes if there is a AREF pin, you need to place a 100nF capacitor to GND as well.
5. No, not automatically. But this is often called a blinky test. If you can upload a blinky test you have verified that you can:
* access the chip
* write memories
* chip boots your program
* oscillator is running
Then it's a case of figuring out if the oscillator speed is correct, and then you can start writing some real code. | @1: Yes, you have to connect all VCC and GND pins. This includes AVCC and AGND.
@2: Does the device run your program? Did the programmer return any error code?
@4: Connect a decoupling capacitor for every single VCC pin. Rule of thumb 100nF ceramic.
@5: Some devices may support JTAG testing or similar debug interface (debugWIRE), but I doubt that qualifies for "simple". |
19,112,318 | I want to be able to wrap text if there is a resizing of the window, I know this can be done as there have been other questions similar to mine in SO. (I guess this [one](https://stackoverflow.com/questions/18377376/how-to-get-textcolumns-to-auto-wrap-in-zurb-foundation-v3-2-5) would qualify )
I am using Foundation 4 (latest version) and the provided solution does not work; for example take a look at the following screenshot [here](https://imgur.com/KJSWntW) which shows the result, computed CSS rules and actual page markup. It also shows that the strings of consecutive a's are not wrapped as they should. Any ideas on how to go about an correcting this? | 2013/10/01 | ['https://Stackoverflow.com/questions/19112318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1414710/'] | Use dynamic memory allocation.
```
Items **type;
type = malloc(sizeof (Items *) * typenum);
for (int i = 0; i < typenum; i++)
type[i] = malloc(sizeof Items) * typetotal);
```
You need to manually free the allocated memory after using the array.
```
for (int i = 0; i < typenum; i++)
free(types[i]);
free(types);
```
Here is a tutorial on it: <http://www.eskimo.com/~scs/cclass/int/sx9b.html> | If `typenum` and `typetotal` increase as your program runs be sure to use `realloc`, which will reallocate more memory and keep the contents. You'll need to allocate the first dimension of the array like this:
```
myArray = realloc(myArray, sizeof(Items*) * typenum);
```
and then allocate the second dimension for each of the first:
```
for(...)
myArray[i] = realloc(myArray[i], sizeof(Items) * typetotal);
``` |
53,963,876 | I am a new user to Laravel and have came from craft cms. On my homepage I want the navigation to be transparent and have a black background on all other pages.
To do this I have added a class to the homepage header called header-home. I craft to add this class to the homepage inside the layout file I wrote this:
```
<header {% if craft.request.lastSegment == "" %}class="header-home" {% endif %}>
```
I know I could just create a different layout.blade.php file for the homepage but there will be other instances when I want to add a class or an element depending on what page or url the user is on.
Thanks in advance,
Jamie | 2018/12/28 | ['https://Stackoverflow.com/questions/53963876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3479267/'] | You can send the class from controller:
```
public function myAction
{
...
return view('home', ['layoutClass'=>'dark']);
}
<header class="{{ isset($layoutClass) ? $layoutClass:'') }} />
```
or you can match the route in the view:
```
<header class="{{ (\Request::route()->getName() == 'myRoute') ? 'dark':'') }} />
``` | I found the best way for me was to use an if statement in blade and check the route, below is how I done it:
```
@if (\Request::is('/'))
<img class="nav-logo" src="img/logo-light.svg">
@else
<img class="nav-logo" src="img/logo-dark.svg">
@endif
``` |
40,208,857 | I have a question about the following code.
```
public class test
{
public static void main (String[] args)
{
int a = 0;
int b = 0;
for (int i = 0; i < 5; i++); {
b = b + a;
a++;
}
System.out.println(b);
```
Why is the output of this 0? As you can see I'm a complete beginner but why does it not go through the loop 4 times before printing the answer?
Help is appreciated!
//Confused beginner | 2016/10/23 | ['https://Stackoverflow.com/questions/40208857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7062013/'] | For loops iterate over the statement or block immediately following the for statement. In this case you have a stray semicolon causing the next statement to be empty. Remove it and your code will work as indended
Replace:
```
for (int i = 0; i < 5; i++); {
b = b + a;
a++;
}
```
-with-
```
for (int i = 0; i < 5; i++) {
b = b + a;
a++;
}
``` | Just remove the semicolon after the for loop statement, otherwise the body surrounded by the curly braces will not be considered under the for loop.
Replace the following:
```
for (int i = 0; i < 5; i++); {
^ <--- remove it
b = b + a;
a++;
}
```
by
```
for (int i = 0; i < 5; i++); {
b = b + a;
a++;
}
``` |
40,208,857 | I have a question about the following code.
```
public class test
{
public static void main (String[] args)
{
int a = 0;
int b = 0;
for (int i = 0; i < 5; i++); {
b = b + a;
a++;
}
System.out.println(b);
```
Why is the output of this 0? As you can see I'm a complete beginner but why does it not go through the loop 4 times before printing the answer?
Help is appreciated!
//Confused beginner | 2016/10/23 | ['https://Stackoverflow.com/questions/40208857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7062013/'] | It does not return 0. In does not return anything as there are mistakes in your code.
After the for loop, there is no ;
```
public static void main(String[] args){
int a = 0;
int b = 0;
for (int i = 0; i < 5; i++) {
b = b + a;
a++;
}
System.out.println(b);
}
``` | Just remove the semicolon after the for loop statement, otherwise the body surrounded by the curly braces will not be considered under the for loop.
Replace the following:
```
for (int i = 0; i < 5; i++); {
^ <--- remove it
b = b + a;
a++;
}
```
by
```
for (int i = 0; i < 5; i++); {
b = b + a;
a++;
}
``` |
61,629,887 | **Problem :**
Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen.
My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?)
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[100];
int i=0;
int j;
int p;
printf("Give string 1: \n");
gets(str1);
printf("Give string 2: \n");
gets(str2);
if(strlen(str1)<strlen(str2))
p=strlen(str1);
else
p=strlen(str2);
j=0;
for(i=0; i<p*2; i++){
if(i%2==0)
str3[i]=str2[j];
else{
str3[i]=str1[j];
j++; }
}
printf("\n String 3 is : %d");
printf("\n String 2 is : %d");
printf("\n String 1 is : %d");
return 0;
}
``` | 2020/05/06 | ['https://Stackoverflow.com/questions/61629887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | This can be done in using the popular requests library
```
import requests
url = 'https://www.google.com'
headers=requests.head(url).headers
downloadable = 'attachment' in headers.get('Content-Disposition', '')
```
[Content Disposition Header reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) | On HTTP protocol level itself, there is no distinction between downloadable and non-downloadable URL. There is an HTTP request and there is a subsequent response. Response body can be a binary file, HTML, image etc..
You can just request the HTTP response header and look for `Content-Type:` and decide whether you want to consider that content-type as downloadable or non-downloadable. |
61,629,887 | **Problem :**
Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen.
My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?)
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[100];
int i=0;
int j;
int p;
printf("Give string 1: \n");
gets(str1);
printf("Give string 2: \n");
gets(str2);
if(strlen(str1)<strlen(str2))
p=strlen(str1);
else
p=strlen(str2);
j=0;
for(i=0; i<p*2; i++){
if(i%2==0)
str3[i]=str2[j];
else{
str3[i]=str1[j];
j++; }
}
printf("\n String 3 is : %d");
printf("\n String 2 is : %d");
printf("\n String 1 is : %d");
return 0;
}
``` | 2020/05/06 | ['https://Stackoverflow.com/questions/61629887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | So I tried searching for a better way, the site link which I was checking was a bit tricky
most stackoverflow answers mentioned about using head request to get response header, but the site I was checking returned 404 error.When I use get request the whole file is downloaded before outputing the header.My friend suggested me a solution of using the parameter `stream=True` and that really got worked.
```
import requests
r = requests.get(link, stream=True)
print(r.headers)
``` | On HTTP protocol level itself, there is no distinction between downloadable and non-downloadable URL. There is an HTTP request and there is a subsequent response. Response body can be a binary file, HTML, image etc..
You can just request the HTTP response header and look for `Content-Type:` and decide whether you want to consider that content-type as downloadable or non-downloadable. |
61,629,887 | **Problem :**
Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen.
My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?)
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[100];
int i=0;
int j;
int p;
printf("Give string 1: \n");
gets(str1);
printf("Give string 2: \n");
gets(str2);
if(strlen(str1)<strlen(str2))
p=strlen(str1);
else
p=strlen(str2);
j=0;
for(i=0; i<p*2; i++){
if(i%2==0)
str3[i]=str2[j];
else{
str3[i]=str1[j];
j++; }
}
printf("\n String 3 is : %d");
printf("\n String 2 is : %d");
printf("\n String 1 is : %d");
return 0;
}
``` | 2020/05/06 | ['https://Stackoverflow.com/questions/61629887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | On HTTP protocol level itself, there is no distinction between downloadable and non-downloadable URL. There is an HTTP request and there is a subsequent response. Response body can be a binary file, HTML, image etc..
You can just request the HTTP response header and look for `Content-Type:` and decide whether you want to consider that content-type as downloadable or non-downloadable. | Downloadable files must have Content-Length in headers :
```
import requests
r = requests.get(url, stream=True)
try:
print(r.headers['content-length'])
except:
print("Not Downloadable")
``` |
61,629,887 | **Problem :**
Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen.
My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?)
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[100];
int i=0;
int j;
int p;
printf("Give string 1: \n");
gets(str1);
printf("Give string 2: \n");
gets(str2);
if(strlen(str1)<strlen(str2))
p=strlen(str1);
else
p=strlen(str2);
j=0;
for(i=0; i<p*2; i++){
if(i%2==0)
str3[i]=str2[j];
else{
str3[i]=str1[j];
j++; }
}
printf("\n String 3 is : %d");
printf("\n String 2 is : %d");
printf("\n String 1 is : %d");
return 0;
}
``` | 2020/05/06 | ['https://Stackoverflow.com/questions/61629887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | This can be done in using the popular requests library
```
import requests
url = 'https://www.google.com'
headers=requests.head(url).headers
downloadable = 'attachment' in headers.get('Content-Disposition', '')
```
[Content Disposition Header reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) | So I tried searching for a better way, the site link which I was checking was a bit tricky
most stackoverflow answers mentioned about using head request to get response header, but the site I was checking returned 404 error.When I use get request the whole file is downloaded before outputing the header.My friend suggested me a solution of using the parameter `stream=True` and that really got worked.
```
import requests
r = requests.get(link, stream=True)
print(r.headers)
``` |
61,629,887 | **Problem :**
Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen.
My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?)
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[100];
int i=0;
int j;
int p;
printf("Give string 1: \n");
gets(str1);
printf("Give string 2: \n");
gets(str2);
if(strlen(str1)<strlen(str2))
p=strlen(str1);
else
p=strlen(str2);
j=0;
for(i=0; i<p*2; i++){
if(i%2==0)
str3[i]=str2[j];
else{
str3[i]=str1[j];
j++; }
}
printf("\n String 3 is : %d");
printf("\n String 2 is : %d");
printf("\n String 1 is : %d");
return 0;
}
``` | 2020/05/06 | ['https://Stackoverflow.com/questions/61629887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | This can be done in using the popular requests library
```
import requests
url = 'https://www.google.com'
headers=requests.head(url).headers
downloadable = 'attachment' in headers.get('Content-Disposition', '')
```
[Content Disposition Header reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) | Downloadable files must have Content-Length in headers :
```
import requests
r = requests.get(url, stream=True)
try:
print(r.headers['content-length'])
except:
print("Not Downloadable")
``` |
61,629,887 | **Problem :**
Build a program that reads two strings from the keyboard and generates a third string which consists of combining two strings in such a way that the characters of the first string are placed in odd positions while the characters of the second string in even positions. The length of the new string will be twice the length of the smaller string. Display all three strings on the screen.
My solution : (I've code something, but it gives me error. Can anyone show me where is the problem?)
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[100];
int i=0;
int j;
int p;
printf("Give string 1: \n");
gets(str1);
printf("Give string 2: \n");
gets(str2);
if(strlen(str1)<strlen(str2))
p=strlen(str1);
else
p=strlen(str2);
j=0;
for(i=0; i<p*2; i++){
if(i%2==0)
str3[i]=str2[j];
else{
str3[i]=str1[j];
j++; }
}
printf("\n String 3 is : %d");
printf("\n String 2 is : %d");
printf("\n String 1 is : %d");
return 0;
}
``` | 2020/05/06 | ['https://Stackoverflow.com/questions/61629887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | So I tried searching for a better way, the site link which I was checking was a bit tricky
most stackoverflow answers mentioned about using head request to get response header, but the site I was checking returned 404 error.When I use get request the whole file is downloaded before outputing the header.My friend suggested me a solution of using the parameter `stream=True` and that really got worked.
```
import requests
r = requests.get(link, stream=True)
print(r.headers)
``` | Downloadable files must have Content-Length in headers :
```
import requests
r = requests.get(url, stream=True)
try:
print(r.headers['content-length'])
except:
print("Not Downloadable")
``` |
85 | Neutron mass: 1.008664 u
Proton mass: 1.007276 u
Why the discrepancy?
On a related note, how does one go about measuring the mass of a neutron or proton, anyway? | 2010/11/02 | ['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/'] | Masses and coupling between quarks are free parameters in the standard model, so there is not real explanation to that fact.
About the measurment: you can have a look at this [wikipedia article about Penning traps](http://en.wikipedia.org/wiki/Penning_trap) which are devices used for precision measurements for nucleus. Through the cyclotron frequency (Larmor factor) we can obtain the mass of the particle.
Edit: "A neutron is a proton + an electron" is a common answer to this question, but it is a totally invalid reasoning.
Both protons and neutrons are made of three quarks. The mass of the quarks is not known with enough precision, and even more important (and that's a why for the masses of the quarks), the interaction between them is responsible for the mass value to a much larger extend. | A proton is made of two up quarks and a down quark, whereas a neutron is made of two down quarks and an up quark. The quark masses contribute very little of the actual mass of the proton and neutron, which mostly arises from energy associated with the strong interactions among the quarks. Still, they do contribute a small fraction, and the down quark is slightly heavier than the up quark, which approximately accounts for the difference. (The masses of the up and down quarks, because they're so small, are not extremely well-measured, and detailed calculations of what the proton and neutron masses would be for given quark masses are difficult. So it's hard to be quantitative about the answer in a precise way.)
You can read a bit about the state of the art in calculations of the proton mass here: <http://news.sciencemag.org/sciencenow/2008/11/21-02.html> |
85 | Neutron mass: 1.008664 u
Proton mass: 1.007276 u
Why the discrepancy?
On a related note, how does one go about measuring the mass of a neutron or proton, anyway? | 2010/11/02 | ['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/'] | Masses and coupling between quarks are free parameters in the standard model, so there is not real explanation to that fact.
About the measurment: you can have a look at this [wikipedia article about Penning traps](http://en.wikipedia.org/wiki/Penning_trap) which are devices used for precision measurements for nucleus. Through the cyclotron frequency (Larmor factor) we can obtain the mass of the particle.
Edit: "A neutron is a proton + an electron" is a common answer to this question, but it is a totally invalid reasoning.
Both protons and neutrons are made of three quarks. The mass of the quarks is not known with enough precision, and even more important (and that's a why for the masses of the quarks), the interaction between them is responsible for the mass value to a much larger extend. | We can write approximately assuming strong energy $E\_s$ contribution inside proton and neutron is almost the same:
$m\_n c^2 = m\_d c^2 +m\_d c^2 +m\_u c^2 +E\_s $
$m\_p c^2 = m\_u c^2 +m\_u c^2 +m\_d c^2 +E\_s +E\_c $
in terms of quark u and d masses and $E\_c$ - electrostatic energy around and inside the proton, which can be calculated classically $E\_c = \frac{3}{5} \frac{k e^2} {R} = 1 MeV $, and R=0.87 fm is charge radius from scattering experiments.
Thus we have
$m\_n c^2 -m\_p c^2 $ = $ m\_d c^2 - m\_u c^2 - E\_c $ = 4.8 MeV - 2.3 MeV - 1 MeV= 1.5 MeV
On the other hand we have $m\_n c^2 -m\_p c^2 $ = 1.3 MeV i.e very close (and quark masses are not know so precisely) |
85 | Neutron mass: 1.008664 u
Proton mass: 1.007276 u
Why the discrepancy?
On a related note, how does one go about measuring the mass of a neutron or proton, anyway? | 2010/11/02 | ['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/'] | Masses and coupling between quarks are free parameters in the standard model, so there is not real explanation to that fact.
About the measurment: you can have a look at this [wikipedia article about Penning traps](http://en.wikipedia.org/wiki/Penning_trap) which are devices used for precision measurements for nucleus. Through the cyclotron frequency (Larmor factor) we can obtain the mass of the particle.
Edit: "A neutron is a proton + an electron" is a common answer to this question, but it is a totally invalid reasoning.
Both protons and neutrons are made of three quarks. The mass of the quarks is not known with enough precision, and even more important (and that's a why for the masses of the quarks), the interaction between them is responsible for the mass value to a much larger extend. | A recent paper [1] has computed the mass difference ab initio from the theory, using a technique know as lattice, where one writes the equations on a discretised spacetime (this is conceptually similar to what engineers do with finite elements method to study how a beam of metal flexes for example). They took into account
* the contributions of electromagnetism and of the strong interaction,
* the difference of mass between up and down quarks,
* up, down, strange, and charm in the quark sea [\*],
Their result is
$$m\_n-m\_p = 1.51(16)(23) \text{MeV},$$
to be compared with the experimental value,
$$m\_n - m\_p = 1.29,$$
with an error orders of magnitude smaller. This is pretty impressive: an accuracy of 390 keV, and according to the paper a proof that $m\_n > m\_p$ at the level of 5 standard deviations. Again, ab initio, just from the Standard Model.
The authors of that paper also give the respective contributions of electromagnetism and of the strong interaction. This is very interesting as the electrostatic energy, just based on the quark charges, would naively be thought to be negative for the neutron but zero for the proton, on average [\*\*]. Their result is that
* $(m\_n-m\_p)\_\text{QCD}=2.52(17)(24)$ MeV,
* $(m\_n-m\_p)\_\text{QED}=-1.00(07)(14)$ MeV,
where QCD stands for Quantum ChromoDynamics, our best theory of the strong interaction, and QED for Quantum ElectroDynamics, our best theory of electromagnetism. So indeed, the different of electrostatic energy is in the intuitive direction I have just highlighted above. This is compensated by the contribution of the strong interaction which goes in the other direction. I don't have an intuitive reason for that to share.
[\*] Protons and neutrons are made of 3 so-called valence quarks, but also of a "soup" of other quarks-antiquark pairs which is called the sea.
[\*\*] The sum of the product of the charges are $\frac{2}{3}\frac{2}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{2}{3}\frac{-1}{3}=0$ for the proton but $\frac{2}{3}\frac{-1}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{-1}{3}\frac{-1}{3}=-\frac{1}{3}$ for the neutron.
[1] Sz. Borsanyi, S. Durr, Z. Fodor, C. Hoelbling, S. D. Katz, S. Krieg, L. Lellouch, T. Lippert, A. Portelli, K. K. Szabo, and B. C. Toth. Ab initio calculation of the neutron-proton mass difference. Science, 347(6229):1452–1455, 2015. [arxiv.org/abs/1406.4088](https://arxiv.org/abs/1406.4088) |
85 | Neutron mass: 1.008664 u
Proton mass: 1.007276 u
Why the discrepancy?
On a related note, how does one go about measuring the mass of a neutron or proton, anyway? | 2010/11/02 | ['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/'] | A proton is made of two up quarks and a down quark, whereas a neutron is made of two down quarks and an up quark. The quark masses contribute very little of the actual mass of the proton and neutron, which mostly arises from energy associated with the strong interactions among the quarks. Still, they do contribute a small fraction, and the down quark is slightly heavier than the up quark, which approximately accounts for the difference. (The masses of the up and down quarks, because they're so small, are not extremely well-measured, and detailed calculations of what the proton and neutron masses would be for given quark masses are difficult. So it's hard to be quantitative about the answer in a precise way.)
You can read a bit about the state of the art in calculations of the proton mass here: <http://news.sciencemag.org/sciencenow/2008/11/21-02.html> | We can write approximately assuming strong energy $E\_s$ contribution inside proton and neutron is almost the same:
$m\_n c^2 = m\_d c^2 +m\_d c^2 +m\_u c^2 +E\_s $
$m\_p c^2 = m\_u c^2 +m\_u c^2 +m\_d c^2 +E\_s +E\_c $
in terms of quark u and d masses and $E\_c$ - electrostatic energy around and inside the proton, which can be calculated classically $E\_c = \frac{3}{5} \frac{k e^2} {R} = 1 MeV $, and R=0.87 fm is charge radius from scattering experiments.
Thus we have
$m\_n c^2 -m\_p c^2 $ = $ m\_d c^2 - m\_u c^2 - E\_c $ = 4.8 MeV - 2.3 MeV - 1 MeV= 1.5 MeV
On the other hand we have $m\_n c^2 -m\_p c^2 $ = 1.3 MeV i.e very close (and quark masses are not know so precisely) |
85 | Neutron mass: 1.008664 u
Proton mass: 1.007276 u
Why the discrepancy?
On a related note, how does one go about measuring the mass of a neutron or proton, anyway? | 2010/11/02 | ['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/'] | A proton is made of two up quarks and a down quark, whereas a neutron is made of two down quarks and an up quark. The quark masses contribute very little of the actual mass of the proton and neutron, which mostly arises from energy associated with the strong interactions among the quarks. Still, they do contribute a small fraction, and the down quark is slightly heavier than the up quark, which approximately accounts for the difference. (The masses of the up and down quarks, because they're so small, are not extremely well-measured, and detailed calculations of what the proton and neutron masses would be for given quark masses are difficult. So it's hard to be quantitative about the answer in a precise way.)
You can read a bit about the state of the art in calculations of the proton mass here: <http://news.sciencemag.org/sciencenow/2008/11/21-02.html> | A recent paper [1] has computed the mass difference ab initio from the theory, using a technique know as lattice, where one writes the equations on a discretised spacetime (this is conceptually similar to what engineers do with finite elements method to study how a beam of metal flexes for example). They took into account
* the contributions of electromagnetism and of the strong interaction,
* the difference of mass between up and down quarks,
* up, down, strange, and charm in the quark sea [\*],
Their result is
$$m\_n-m\_p = 1.51(16)(23) \text{MeV},$$
to be compared with the experimental value,
$$m\_n - m\_p = 1.29,$$
with an error orders of magnitude smaller. This is pretty impressive: an accuracy of 390 keV, and according to the paper a proof that $m\_n > m\_p$ at the level of 5 standard deviations. Again, ab initio, just from the Standard Model.
The authors of that paper also give the respective contributions of electromagnetism and of the strong interaction. This is very interesting as the electrostatic energy, just based on the quark charges, would naively be thought to be negative for the neutron but zero for the proton, on average [\*\*]. Their result is that
* $(m\_n-m\_p)\_\text{QCD}=2.52(17)(24)$ MeV,
* $(m\_n-m\_p)\_\text{QED}=-1.00(07)(14)$ MeV,
where QCD stands for Quantum ChromoDynamics, our best theory of the strong interaction, and QED for Quantum ElectroDynamics, our best theory of electromagnetism. So indeed, the different of electrostatic energy is in the intuitive direction I have just highlighted above. This is compensated by the contribution of the strong interaction which goes in the other direction. I don't have an intuitive reason for that to share.
[\*] Protons and neutrons are made of 3 so-called valence quarks, but also of a "soup" of other quarks-antiquark pairs which is called the sea.
[\*\*] The sum of the product of the charges are $\frac{2}{3}\frac{2}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{2}{3}\frac{-1}{3}=0$ for the proton but $\frac{2}{3}\frac{-1}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{-1}{3}\frac{-1}{3}=-\frac{1}{3}$ for the neutron.
[1] Sz. Borsanyi, S. Durr, Z. Fodor, C. Hoelbling, S. D. Katz, S. Krieg, L. Lellouch, T. Lippert, A. Portelli, K. K. Szabo, and B. C. Toth. Ab initio calculation of the neutron-proton mass difference. Science, 347(6229):1452–1455, 2015. [arxiv.org/abs/1406.4088](https://arxiv.org/abs/1406.4088) |
85 | Neutron mass: 1.008664 u
Proton mass: 1.007276 u
Why the discrepancy?
On a related note, how does one go about measuring the mass of a neutron or proton, anyway? | 2010/11/02 | ['https://physics.stackexchange.com/questions/85', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104/'] | A recent paper [1] has computed the mass difference ab initio from the theory, using a technique know as lattice, where one writes the equations on a discretised spacetime (this is conceptually similar to what engineers do with finite elements method to study how a beam of metal flexes for example). They took into account
* the contributions of electromagnetism and of the strong interaction,
* the difference of mass between up and down quarks,
* up, down, strange, and charm in the quark sea [\*],
Their result is
$$m\_n-m\_p = 1.51(16)(23) \text{MeV},$$
to be compared with the experimental value,
$$m\_n - m\_p = 1.29,$$
with an error orders of magnitude smaller. This is pretty impressive: an accuracy of 390 keV, and according to the paper a proof that $m\_n > m\_p$ at the level of 5 standard deviations. Again, ab initio, just from the Standard Model.
The authors of that paper also give the respective contributions of electromagnetism and of the strong interaction. This is very interesting as the electrostatic energy, just based on the quark charges, would naively be thought to be negative for the neutron but zero for the proton, on average [\*\*]. Their result is that
* $(m\_n-m\_p)\_\text{QCD}=2.52(17)(24)$ MeV,
* $(m\_n-m\_p)\_\text{QED}=-1.00(07)(14)$ MeV,
where QCD stands for Quantum ChromoDynamics, our best theory of the strong interaction, and QED for Quantum ElectroDynamics, our best theory of electromagnetism. So indeed, the different of electrostatic energy is in the intuitive direction I have just highlighted above. This is compensated by the contribution of the strong interaction which goes in the other direction. I don't have an intuitive reason for that to share.
[\*] Protons and neutrons are made of 3 so-called valence quarks, but also of a "soup" of other quarks-antiquark pairs which is called the sea.
[\*\*] The sum of the product of the charges are $\frac{2}{3}\frac{2}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{2}{3}\frac{-1}{3}=0$ for the proton but $\frac{2}{3}\frac{-1}{3} + \frac{2}{3}\frac{-1}{3}+ \frac{-1}{3}\frac{-1}{3}=-\frac{1}{3}$ for the neutron.
[1] Sz. Borsanyi, S. Durr, Z. Fodor, C. Hoelbling, S. D. Katz, S. Krieg, L. Lellouch, T. Lippert, A. Portelli, K. K. Szabo, and B. C. Toth. Ab initio calculation of the neutron-proton mass difference. Science, 347(6229):1452–1455, 2015. [arxiv.org/abs/1406.4088](https://arxiv.org/abs/1406.4088) | We can write approximately assuming strong energy $E\_s$ contribution inside proton and neutron is almost the same:
$m\_n c^2 = m\_d c^2 +m\_d c^2 +m\_u c^2 +E\_s $
$m\_p c^2 = m\_u c^2 +m\_u c^2 +m\_d c^2 +E\_s +E\_c $
in terms of quark u and d masses and $E\_c$ - electrostatic energy around and inside the proton, which can be calculated classically $E\_c = \frac{3}{5} \frac{k e^2} {R} = 1 MeV $, and R=0.87 fm is charge radius from scattering experiments.
Thus we have
$m\_n c^2 -m\_p c^2 $ = $ m\_d c^2 - m\_u c^2 - E\_c $ = 4.8 MeV - 2.3 MeV - 1 MeV= 1.5 MeV
On the other hand we have $m\_n c^2 -m\_p c^2 $ = 1.3 MeV i.e very close (and quark masses are not know so precisely) |
37,548,915 | I try to upload some videos to youtube. Somewhere in the stack it comes down to a `http.Client`. This part somehow behaves weird.
The request and everything is created inside the youtube package.
After doing my request in the end it fails with:
```
Error uploading video: Post https://www.googleapis.com/upload/youtube/v3/videos?alt=json&part=snippet%2Cstatus&uploadType=multipart: Post : unsupported protocol scheme ""
```
I debugged the library a bit and printed the `URL.Scheme` content. As a string the result is `https` and in `[]byte` `[104 116 116 112 115]`
<https://golang.org/src/net/http/transport.go> on line 288 is the location where the error is thrown.
<https://godoc.org/google.golang.org/api/youtube/v3> the library I use
My code where I prepare/upload the video:
```
//create video struct which holds info about the video
video := &yt3.Video{
//TODO: set all required video info
}
//create the insert call
insertCall := service.Videos.Insert("snippet,status", video)
//attach media data to the call
insertCall = insertCall.Media(tmp, googleapi.ChunkSize(1*1024*1024)) //1MB chunk
video, err = insertCall.Do()
if err != nil {
log.Printf("Error uploading video: %v", err)
return
//return errgo.Notef(err, "Failed to upload to youtube")
}
```
So I have not idea why the schema check fails. | 2016/05/31 | ['https://Stackoverflow.com/questions/37548915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450598/'] | Ok, I figured it out. The problem was not the call to YouTube itself.
The library tried to refresh the token in the background but there was something wrong with the `TokenURL`.
Ensuring there is a valid URL fixed the problem.
A nicer error message would have helped a lot, but well... | This will probably apply to very, very few who arrive here: but my problem was that a [RoundTripper](https://pkg.go.dev/net/http#RoundTripper) was overriding the Host field with an empty string. |
340,403 | I have a validation Rule that I require assistance with , this validation rule should only allow fields to be updated by the two profile ids specified:
```
NOT(
OR(
$Profile.Id = "00e58000000yYlm",
$Profile.Id = "00e58000000E6lK",
AND(
ISPICKVAL((WorkOrder.Status ), 'WithTechnician'),
OR(
ISCHANGED ( ProposedWorkPerformed__c),
ISCHANGED ( ProposedOriginOfError__c ),
ISCHANGED ( ProposedErrorComment__c ),
ISCHANGED ( EstimatedDurationInMinutes__c ),
ISCHANGED ( ActualWorkPerformed__c ),
ISCHANGED ( ActualDurationInMinutes__c ),
ISCHANGED ( ActualOriginOfError__c ),
ISCHANGED ( ActualErrorComment__c ),
ISCHANGED ( Status ),
ISCHANGED ( Type__c ),
ISCHANGED ( Source__c)
)
)
)
)
``` | 2021/04/14 | ['https://salesforce.stackexchange.com/questions/340403', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/94096/'] | The big thing to keep in mind with validation rules is that their purpose isn't really to tell you what data is valid, but rather to tell you what data is *invalid*. It's a small shift in how you mentally frame the problem, but one that I find very helpful.
Instead of stating the outcome as "these profiles should be allowed to edit these fields", try working from "everyone who doesn't have one of these two profiles should be prevented from editing these fields".
Re-stating that a bit closer to a Validation Rule, "If the profile isn't one of our targets, and workorder status is `<X>`, and at least one of these fields are changing, then prevent the change"
**Note that** these comments are for clarity, and not in the appropriate format for a validation rule.
```
// segment 1
// User is not one of our target profiles
// The NOT() here should be limited to just the profile check
NOT(
OR(
Profile = profile1,
Profile = profile2
)
)
```
```
// segment 2
// workorder status check
ISPICKVAL((WorkOrder.Status ), 'WithTechnician')
```
```
// segment 3
// field change check
// a change to any of these fields should make this segment evaluate to "true", so OR()
// is appropriate
OR(
ISCHANGED(ProposedWorkPerformed__c),
ISCHANGED(ProposedOriginOfError__c),
ISCHANGED(ProposedErrorComment__c),
ISCHANGED(EstimatedDurationInMinutes__c),
ISCHANGED(ActualWorkPerformed__c),
ISCHANGED(ActualDurationInMinutes__c),
ISCHANGED(ActualOriginOfError__c),
ISCHANGED(ActualErrorComment__c),
ISCHANGED(Status),
ISCHANGED( Type__c),
ISCHANGED(Source__c)
)
```
The "plain language" description of what you're aiming to do tells you how these segments should be tied together (they should be `AND`-ed).
`<segment1> && <segment2> && <segment3>` would work, but the more typical approach is to use `AND()`.
```
AND(
<segment1>,
<segment2>,
<segment3>
)
``` | The issue is with OR operator on profile, AND operator on the status field, and NOT function. You haven't used/close them at appropriate places.
Below is the updated snippet.
```
AND(
ISPICKVAL(Status, "WithTechnician"),
NOT(OR(
$Profile.Id = "00e58000000yYlm",
$Profile.Id = "00e58000000E6lK")),
OR(
ISCHANGED(ProposedWorkPerformed__c),
ISCHANGED(ProposedOriginOfError__c),
ISCHANGED(ProposedErrorComment__c),
ISCHANGED(EstimatedDurationInMinutes__c),
ISCHANGED(ActualWorkPerformed__c),
ISCHANGED(ActualDurationInMinutes__c),
ISCHANGED(ActualOriginOfError__c),
ISCHANGED(ActualErrorComment__c),
ISCHANGED(Status),
ISCHANGED(Type__c),
ISCHANGED(Source__c)))
```
Take a look at sample validation rule examples [here](https://help.salesforce.com/articleView?id=fields_useful_field_validation_formulas.htm&type=0).
Thanks |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | You may create a new array (in this case, `filteredArray`) in which you store all the elements in `myArray` but the greatest two.
Also, it is better to save the indexes of the two biggest numbers rather than their values in order to be able to filter them out more easily.
This should work (you will find the array you want in `filteredArray`).
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
myArray[i] = sc.nextInt();
if (myArray[i] > myArray[first]) {
second = first;
first = i;
} else if(myArray[i] > myArray[second]) {
second = i;
}
}
int [] filteredArray = new int[n-2];
int skipped = 0;
for(int i = 0; i < myArray.length; i++) {
if(i != first && i != second)
filteredArray[i - skipped] = myArray[i];
else
skipped++;
}
``` | May be following code will useful for you
```
again :
for (int i = 0; i < n; i++)
{
if ((a[i] < a[i+1]) && (i+1)<n)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
continue again;
}
}
System.out.println("The largest " + a[0] + " & second largest " + a[i]);
```
IF you want to delete other then you can do that
```
for(int i=2; i<n ; i++)
test = ArrayUtils.remove(a, i);
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | If you are using Java 8 you can sort your array then you can loop throw your array and set it values to the other one avoiding the last two Integer for example :
```
//Your array
Integer[] array = {8, 99, 6, 336, 2};
//sort your array this can give your [2, 6, 8, 99, 336]
Arrays.sort(array);
//create a new array with the length = array - 2 if the length of array < 2 then 0
Integer[] array2 = new Integer[array.length > 2 ? array.length - 2 : 0];
//copy your array into the array2 avoiding the 2 last
System.arraycopy(array, 0, array2, 0, array.length > 2 ? array.length - 2 : 0);
//print your array, this will print [2, 6, 8]
System.out.println(Arrays.toString(array2));
``` | You may create a new array (in this case, `filteredArray`) in which you store all the elements in `myArray` but the greatest two.
Also, it is better to save the indexes of the two biggest numbers rather than their values in order to be able to filter them out more easily.
This should work (you will find the array you want in `filteredArray`).
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
myArray[i] = sc.nextInt();
if (myArray[i] > myArray[first]) {
second = first;
first = i;
} else if(myArray[i] > myArray[second]) {
second = i;
}
}
int [] filteredArray = new int[n-2];
int skipped = 0;
for(int i = 0; i < myArray.length; i++) {
if(i != first && i != second)
filteredArray[i - skipped] = myArray[i];
else
skipped++;
}
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | Sort your arrays (default sort is ascending, i.e. from smallest to largest) then make a new copy of the array without the last two elements.
```
if(myArray.length > 2) {
Arrays.sort(myArray);
myArray = Arrays.copyOf(myArray, myArray.length-2);
} else {
throw new IllegalArgumentException("Need moar elements in array!");
}
```
Then perform any calculations on the resulting array. If you want to keep the original array, don't overwrite `myArray` when doing `copyOf()`. | You may create a new array (in this case, `filteredArray`) in which you store all the elements in `myArray` but the greatest two.
Also, it is better to save the indexes of the two biggest numbers rather than their values in order to be able to filter them out more easily.
This should work (you will find the array you want in `filteredArray`).
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
myArray[i] = sc.nextInt();
if (myArray[i] > myArray[first]) {
second = first;
first = i;
} else if(myArray[i] > myArray[second]) {
second = i;
}
}
int [] filteredArray = new int[n-2];
int skipped = 0;
for(int i = 0; i < myArray.length; i++) {
if(i != first && i != second)
filteredArray[i - skipped] = myArray[i];
else
skipped++;
}
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | If you are using Java 8 you can sort your array then you can loop throw your array and set it values to the other one avoiding the last two Integer for example :
```
//Your array
Integer[] array = {8, 99, 6, 336, 2};
//sort your array this can give your [2, 6, 8, 99, 336]
Arrays.sort(array);
//create a new array with the length = array - 2 if the length of array < 2 then 0
Integer[] array2 = new Integer[array.length > 2 ? array.length - 2 : 0];
//copy your array into the array2 avoiding the 2 last
System.arraycopy(array, 0, array2, 0, array.length > 2 ? array.length - 2 : 0);
//print your array, this will print [2, 6, 8]
System.out.println(Arrays.toString(array2));
``` | May be following code will useful for you
```
again :
for (int i = 0; i < n; i++)
{
if ((a[i] < a[i+1]) && (i+1)<n)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
continue again;
}
}
System.out.println("The largest " + a[0] + " & second largest " + a[i]);
```
IF you want to delete other then you can do that
```
for(int i=2; i<n ; i++)
test = ArrayUtils.remove(a, i);
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | Sort your arrays (default sort is ascending, i.e. from smallest to largest) then make a new copy of the array without the last two elements.
```
if(myArray.length > 2) {
Arrays.sort(myArray);
myArray = Arrays.copyOf(myArray, myArray.length-2);
} else {
throw new IllegalArgumentException("Need moar elements in array!");
}
```
Then perform any calculations on the resulting array. If you want to keep the original array, don't overwrite `myArray` when doing `copyOf()`. | May be following code will useful for you
```
again :
for (int i = 0; i < n; i++)
{
if ((a[i] < a[i+1]) && (i+1)<n)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
continue again;
}
}
System.out.println("The largest " + a[0] + " & second largest " + a[i]);
```
IF you want to delete other then you can do that
```
for(int i=2; i<n ; i++)
test = ArrayUtils.remove(a, i);
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | You can simply sort the array and find or remove the two biggest elements.
```
int [] myArray = new int[]{14,5,2,16,18,20};
System.out.println("The original array is "+ " " +Arrays.toString(myArray));
Arrays.sort(myArray);
System.out.println("The sorted array is "+ " " +Arrays.toString(myArray));;
int fisrtmax = myArray[myArray.length-1];
int secondmax = myArray[myArray.length-2];
System.out.println("The first biggest number is " + fisrtmax+ " The second biggest number is " + secondmax);
int [] arrafterremove= Arrays.copyOf(myArray, myArray.length-2);
System.out.println("The array after removing the two biggest numbers is " + Arrays.toString(arrafterremove));
```
**RUN**
```
The original array is [14, 5, 2, 16, 18, 20]
The sorted array is [2, 5, 14, 16, 18, 20]
The first biggest number is 20 The second biggest number is 18
Array after removing the two biggest numbers is [2, 5, 14, 16]
``` | May be following code will useful for you
```
again :
for (int i = 0; i < n; i++)
{
if ((a[i] < a[i+1]) && (i+1)<n)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
continue again;
}
}
System.out.println("The largest " + a[0] + " & second largest " + a[i]);
```
IF you want to delete other then you can do that
```
for(int i=2; i<n ; i++)
test = ArrayUtils.remove(a, i);
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | If you are using Java 8 you can sort your array then you can loop throw your array and set it values to the other one avoiding the last two Integer for example :
```
//Your array
Integer[] array = {8, 99, 6, 336, 2};
//sort your array this can give your [2, 6, 8, 99, 336]
Arrays.sort(array);
//create a new array with the length = array - 2 if the length of array < 2 then 0
Integer[] array2 = new Integer[array.length > 2 ? array.length - 2 : 0];
//copy your array into the array2 avoiding the 2 last
System.arraycopy(array, 0, array2, 0, array.length > 2 ? array.length - 2 : 0);
//print your array, this will print [2, 6, 8]
System.out.println(Arrays.toString(array2));
``` | You can simply sort the array and find or remove the two biggest elements.
```
int [] myArray = new int[]{14,5,2,16,18,20};
System.out.println("The original array is "+ " " +Arrays.toString(myArray));
Arrays.sort(myArray);
System.out.println("The sorted array is "+ " " +Arrays.toString(myArray));;
int fisrtmax = myArray[myArray.length-1];
int secondmax = myArray[myArray.length-2];
System.out.println("The first biggest number is " + fisrtmax+ " The second biggest number is " + secondmax);
int [] arrafterremove= Arrays.copyOf(myArray, myArray.length-2);
System.out.println("The array after removing the two biggest numbers is " + Arrays.toString(arrafterremove));
```
**RUN**
```
The original array is [14, 5, 2, 16, 18, 20]
The sorted array is [2, 5, 14, 16, 18, 20]
The first biggest number is 20 The second biggest number is 18
Array after removing the two biggest numbers is [2, 5, 14, 16]
``` |
42,713,907 | I can fill my array,and found the two of biggest numbers.But,i can not delete it.May u guys could help me?
```
int n = sc.nextInt();
int [] myArray = new int[n];
int first = 0;
int second = 0;
for(int i = 0; i < myArray.length; i++) {
int num = sc.nextInt();`
if (num > first) {
second = first;
first = num;
} else if(num > second)
{
second = num;
}
}
System.out.println("The largest " + first+ "The second largest " + second);
``` | 2017/03/10 | ['https://Stackoverflow.com/questions/42713907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7513001/'] | Sort your arrays (default sort is ascending, i.e. from smallest to largest) then make a new copy of the array without the last two elements.
```
if(myArray.length > 2) {
Arrays.sort(myArray);
myArray = Arrays.copyOf(myArray, myArray.length-2);
} else {
throw new IllegalArgumentException("Need moar elements in array!");
}
```
Then perform any calculations on the resulting array. If you want to keep the original array, don't overwrite `myArray` when doing `copyOf()`. | You can simply sort the array and find or remove the two biggest elements.
```
int [] myArray = new int[]{14,5,2,16,18,20};
System.out.println("The original array is "+ " " +Arrays.toString(myArray));
Arrays.sort(myArray);
System.out.println("The sorted array is "+ " " +Arrays.toString(myArray));;
int fisrtmax = myArray[myArray.length-1];
int secondmax = myArray[myArray.length-2];
System.out.println("The first biggest number is " + fisrtmax+ " The second biggest number is " + secondmax);
int [] arrafterremove= Arrays.copyOf(myArray, myArray.length-2);
System.out.println("The array after removing the two biggest numbers is " + Arrays.toString(arrafterremove));
```
**RUN**
```
The original array is [14, 5, 2, 16, 18, 20]
The sorted array is [2, 5, 14, 16, 18, 20]
The first biggest number is 20 The second biggest number is 18
Array after removing the two biggest numbers is [2, 5, 14, 16]
``` |
30,941,209 | I have a set of defined JS functions. I want users to pick a subset of these using a comma separated string. Then I want to randomly pick from their subset, and evaluate the function selected. I have this 99% working, except it is not evaluating for some reason. Why does console keep telling me 'undefined is not a function'?
Take a peek at line 37: <http://jsfiddle.net/ftaq8q4m/>
```
// 1 User picks a subset of function names as a comma seperated string.
var effectSubset = 'func4, func5, func6';
// 2 Available functions
function func1() {
$('html').append('func1');
}
function func2() {
$('html').append('func2');
}
function func3() {
$('html').append('func3');
}
function func4() {
$('html').append('func4');
}
function func5() {
$('html').append('func3');
}
function func6() {
$('html').append('func4');
}
var autoPlay = function () {
// 3 Get the user's subset of functions, turn into array
effectArray = effectSubset.split(',');
// 4 Pick random function from array
var effect = effectArray[Math.floor(Math.random() * effectArray.length)];
// 5 run the randomly picked function
window[effect]();
}
// 6 Re-run every second
var playInterval = setInterval(autoPlay, 1000);
``` | 2015/06/19 | ['https://Stackoverflow.com/questions/30941209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422203/'] | I could see two things wrong:
1. Your functions were not assigned to the `window`
2. Your `"effect"` variable contained leading whitespace
I have corrected the above points here: <http://jsfiddle.net/ftaq8q4m/1/>
This appears to have resolved the issue you described.
**Example:**
```
window.func1 = function() {
$('html').append('func1');
}
```
**And:**
```
window[effect.trim()]();
```
---
**Update**
As a bonus I fixed your misleading append messages =D
<http://jsfiddle.net/ftaq8q4m/5/> | You approach is not working because you have a space between the function names
`var effectSubset = 'func4, func5, func6';` After split the variable effect has a space before the name of the functions.
So the functions being called are `func4`, `<space>func5`, `<space>func6` with a space which do not exist.
Firstly, its better to have a namespace.
```
var effectSubset = 'func4,func5,func6'; // <--- remove spaces here or trim like in other answers
window.myNamespace = {};
window.myNamespace.func1 = function() {
$('html').append('func1');
}
// ..... define other functions like above
window["myNamespace"][effect](); // <-- this should work
```
Here is a demo **<http://jsbin.com/lixeto/edit?html,js,output>** |
30,941,209 | I have a set of defined JS functions. I want users to pick a subset of these using a comma separated string. Then I want to randomly pick from their subset, and evaluate the function selected. I have this 99% working, except it is not evaluating for some reason. Why does console keep telling me 'undefined is not a function'?
Take a peek at line 37: <http://jsfiddle.net/ftaq8q4m/>
```
// 1 User picks a subset of function names as a comma seperated string.
var effectSubset = 'func4, func5, func6';
// 2 Available functions
function func1() {
$('html').append('func1');
}
function func2() {
$('html').append('func2');
}
function func3() {
$('html').append('func3');
}
function func4() {
$('html').append('func4');
}
function func5() {
$('html').append('func3');
}
function func6() {
$('html').append('func4');
}
var autoPlay = function () {
// 3 Get the user's subset of functions, turn into array
effectArray = effectSubset.split(',');
// 4 Pick random function from array
var effect = effectArray[Math.floor(Math.random() * effectArray.length)];
// 5 run the randomly picked function
window[effect]();
}
// 6 Re-run every second
var playInterval = setInterval(autoPlay, 1000);
``` | 2015/06/19 | ['https://Stackoverflow.com/questions/30941209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422203/'] | I could see two things wrong:
1. Your functions were not assigned to the `window`
2. Your `"effect"` variable contained leading whitespace
I have corrected the above points here: <http://jsfiddle.net/ftaq8q4m/1/>
This appears to have resolved the issue you described.
**Example:**
```
window.func1 = function() {
$('html').append('func1');
}
```
**And:**
```
window[effect.trim()]();
```
---
**Update**
As a bonus I fixed your misleading append messages =D
<http://jsfiddle.net/ftaq8q4m/5/> | There are two issues: first there are leading whitespaces after you split the input and second, JSFiddle is wrapping your script in an IIFE. The first issue can be solved by either splitting with ' ,' or mapping the resulting array with a trim function. The second issue can be solved by creating an object to assign the functions to. See this [fiddle](http://jsfiddle.net/ftaq8q4m/3/) for a working example.
```
// 1 User picks a subset of function names as a comma seperated string.
var effectSubset = 'func4, func5, func6';
// 2 Available functions
var funcObj = {
func1: function func1() {
$('html').append('func1');
},
func2: function func2() {
$('html').append('func2');
},
func3: function func3() {
$('html').append('func3');
},
func4: function func4() {
$('html').append('func4');
},
func5: function func5() {
$('html').append('func3');
},
func6: function func6() {
$('html').append('func4');
}
};
var autoPlay = function () {
// 3 Get the user's subset of functions, turn into array
effectArray = effectSubset.split(',').map(function(func) { return func.trim() });
// 4 Pick random function from array
var effect = effectArray[Math.floor(Math.random() * effectArray.length)];
// 5 run the randomly picked function
funcObj[effect]();
}
// 6 Re-run every second
var playInterval = setInterval(autoPlay, 1000);
``` |
30,941,209 | I have a set of defined JS functions. I want users to pick a subset of these using a comma separated string. Then I want to randomly pick from their subset, and evaluate the function selected. I have this 99% working, except it is not evaluating for some reason. Why does console keep telling me 'undefined is not a function'?
Take a peek at line 37: <http://jsfiddle.net/ftaq8q4m/>
```
// 1 User picks a subset of function names as a comma seperated string.
var effectSubset = 'func4, func5, func6';
// 2 Available functions
function func1() {
$('html').append('func1');
}
function func2() {
$('html').append('func2');
}
function func3() {
$('html').append('func3');
}
function func4() {
$('html').append('func4');
}
function func5() {
$('html').append('func3');
}
function func6() {
$('html').append('func4');
}
var autoPlay = function () {
// 3 Get the user's subset of functions, turn into array
effectArray = effectSubset.split(',');
// 4 Pick random function from array
var effect = effectArray[Math.floor(Math.random() * effectArray.length)];
// 5 run the randomly picked function
window[effect]();
}
// 6 Re-run every second
var playInterval = setInterval(autoPlay, 1000);
``` | 2015/06/19 | ['https://Stackoverflow.com/questions/30941209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422203/'] | You approach is not working because you have a space between the function names
`var effectSubset = 'func4, func5, func6';` After split the variable effect has a space before the name of the functions.
So the functions being called are `func4`, `<space>func5`, `<space>func6` with a space which do not exist.
Firstly, its better to have a namespace.
```
var effectSubset = 'func4,func5,func6'; // <--- remove spaces here or trim like in other answers
window.myNamespace = {};
window.myNamespace.func1 = function() {
$('html').append('func1');
}
// ..... define other functions like above
window["myNamespace"][effect](); // <-- this should work
```
Here is a demo **<http://jsbin.com/lixeto/edit?html,js,output>** | There are two issues: first there are leading whitespaces after you split the input and second, JSFiddle is wrapping your script in an IIFE. The first issue can be solved by either splitting with ' ,' or mapping the resulting array with a trim function. The second issue can be solved by creating an object to assign the functions to. See this [fiddle](http://jsfiddle.net/ftaq8q4m/3/) for a working example.
```
// 1 User picks a subset of function names as a comma seperated string.
var effectSubset = 'func4, func5, func6';
// 2 Available functions
var funcObj = {
func1: function func1() {
$('html').append('func1');
},
func2: function func2() {
$('html').append('func2');
},
func3: function func3() {
$('html').append('func3');
},
func4: function func4() {
$('html').append('func4');
},
func5: function func5() {
$('html').append('func3');
},
func6: function func6() {
$('html').append('func4');
}
};
var autoPlay = function () {
// 3 Get the user's subset of functions, turn into array
effectArray = effectSubset.split(',').map(function(func) { return func.trim() });
// 4 Pick random function from array
var effect = effectArray[Math.floor(Math.random() * effectArray.length)];
// 5 run the randomly picked function
funcObj[effect]();
}
// 6 Re-run every second
var playInterval = setInterval(autoPlay, 1000);
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | It seems that the path node\_exporter is not correct.
```
ExecStart=/usr/bin/node_exporter
```
I have another path to it on Ubuntu 16.04
```
~# cat /etc/issue
Ubuntu 16.04.3 LTS \n \l
~# which node_exporter
/usr/sbin/node_exporter
```
If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to:
```
Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart.
Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
``` | Try to launch the command you're passing to `ExecStart` manually to verify whether it runs.
I got the 203 error as well and apparently it was due to downloading/using the binary for the wrong platform. I was using "Darwin" instead of "Linux".
```
Process: 20340 ExecStart=/usr/local/bin/node_exporter (code=exited, status=203/EXEC)
$ ls -lah /usr/local/bin/node_exporter
-rwxr-xr-x 1 node_exporter node_exporter 12M Jan 16 16:36 /usr/local/bin/node_exporter
$ /usr/local/bin/node_exporter
-bash: /usr/local/bin/node_exporter: cannot execute binary file: Exec format error
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | It seems that the path node\_exporter is not correct.
```
ExecStart=/usr/bin/node_exporter
```
I have another path to it on Ubuntu 16.04
```
~# cat /etc/issue
Ubuntu 16.04.3 LTS \n \l
~# which node_exporter
/usr/sbin/node_exporter
```
If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to:
```
Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart.
Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
``` | Here is the `/etc/systemd/system/node_exporter.service`
```
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target
[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter --collector.nfs --collector.nfsd
[Install]
WantedBy=multi-user.target
```
and make sure the `node_exporter` binary in placed in an expected path. |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | It seems that the path node\_exporter is not correct.
```
ExecStart=/usr/bin/node_exporter
```
I have another path to it on Ubuntu 16.04
```
~# cat /etc/issue
Ubuntu 16.04.3 LTS \n \l
~# which node_exporter
/usr/sbin/node_exporter
```
If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to:
```
Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart.
Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
``` | I got this error. Solved as @Saex.
Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz`
```
node_exporter.service - Node Exporter
Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago
Main PID: 3830 (code=exited, status=203/EXEC)
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter.
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec>
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'.
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | I solved the problem like this...
**Node exporter:**
```none
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
```
**Mysql\_exporter:**
```none
=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
```
**Here is the complete command:**
```
sudo vim /etc/systemd/system/mysql_exporter.service
```
**Content for `mysql_exporter.service`:**
```none
[Unit]
Description=Prometheus MySQL Exporter
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
[Install]
WantedBy=multi-user.target
```
**Node exporter:**
```
sudo vim /etc/systemd/system/node_exporter.service
```
**Content for `node_exporter`:**
```none
[Unit]
Description=Prometheus Node Exporter
After=network.target
User=prometheus
Group=prometheus
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
[Install]
WantedBy=multi-user.target
``` | It seems that the path node\_exporter is not correct.
```
ExecStart=/usr/bin/node_exporter
```
I have another path to it on Ubuntu 16.04
```
~# cat /etc/issue
Ubuntu 16.04.3 LTS \n \l
~# which node_exporter
/usr/sbin/node_exporter
```
If it's not the root of the issue, check your `/var/log/syslog`. It must show the reason of the failure, something similar to:
```
Oct 20 12:30:30 prom systemd[8848]: node_exporter.service: Failed at step EXEC spawning /usr/bin/node_exporter: No such file or directory
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Unit entered failed state.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Failed with result 'exit-code'.
Oct 20 12:30:30 prom systemd[1]: node_exporter.service: Service hold-off time over, scheduling restart.
Oct 20 12:30:30 prom systemd[1]: Stopped Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
Oct 20 12:30:30 prom systemd[1]: Started Prometheus exporter for machine metrics, written in Go with pluggable metric collectors..
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | Try to launch the command you're passing to `ExecStart` manually to verify whether it runs.
I got the 203 error as well and apparently it was due to downloading/using the binary for the wrong platform. I was using "Darwin" instead of "Linux".
```
Process: 20340 ExecStart=/usr/local/bin/node_exporter (code=exited, status=203/EXEC)
$ ls -lah /usr/local/bin/node_exporter
-rwxr-xr-x 1 node_exporter node_exporter 12M Jan 16 16:36 /usr/local/bin/node_exporter
$ /usr/local/bin/node_exporter
-bash: /usr/local/bin/node_exporter: cannot execute binary file: Exec format error
``` | I got this error. Solved as @Saex.
Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz`
```
node_exporter.service - Node Exporter
Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago
Main PID: 3830 (code=exited, status=203/EXEC)
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter.
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec>
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'.
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | I solved the problem like this...
**Node exporter:**
```none
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
```
**Mysql\_exporter:**
```none
=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
```
**Here is the complete command:**
```
sudo vim /etc/systemd/system/mysql_exporter.service
```
**Content for `mysql_exporter.service`:**
```none
[Unit]
Description=Prometheus MySQL Exporter
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
[Install]
WantedBy=multi-user.target
```
**Node exporter:**
```
sudo vim /etc/systemd/system/node_exporter.service
```
**Content for `node_exporter`:**
```none
[Unit]
Description=Prometheus Node Exporter
After=network.target
User=prometheus
Group=prometheus
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
[Install]
WantedBy=multi-user.target
``` | Try to launch the command you're passing to `ExecStart` manually to verify whether it runs.
I got the 203 error as well and apparently it was due to downloading/using the binary for the wrong platform. I was using "Darwin" instead of "Linux".
```
Process: 20340 ExecStart=/usr/local/bin/node_exporter (code=exited, status=203/EXEC)
$ ls -lah /usr/local/bin/node_exporter
-rwxr-xr-x 1 node_exporter node_exporter 12M Jan 16 16:36 /usr/local/bin/node_exporter
$ /usr/local/bin/node_exporter
-bash: /usr/local/bin/node_exporter: cannot execute binary file: Exec format error
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | Here is the `/etc/systemd/system/node_exporter.service`
```
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target
[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter --collector.nfs --collector.nfsd
[Install]
WantedBy=multi-user.target
```
and make sure the `node_exporter` binary in placed in an expected path. | I got this error. Solved as @Saex.
Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz`
```
node_exporter.service - Node Exporter
Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago
Main PID: 3830 (code=exited, status=203/EXEC)
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter.
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec>
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'.
``` |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | I solved the problem like this...
**Node exporter:**
```none
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
```
**Mysql\_exporter:**
```none
=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
```
**Here is the complete command:**
```
sudo vim /etc/systemd/system/mysql_exporter.service
```
**Content for `mysql_exporter.service`:**
```none
[Unit]
Description=Prometheus MySQL Exporter
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
[Install]
WantedBy=multi-user.target
```
**Node exporter:**
```
sudo vim /etc/systemd/system/node_exporter.service
```
**Content for `node_exporter`:**
```none
[Unit]
Description=Prometheus Node Exporter
After=network.target
User=prometheus
Group=prometheus
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
[Install]
WantedBy=multi-user.target
``` | Here is the `/etc/systemd/system/node_exporter.service`
```
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target
[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter --collector.nfs --collector.nfsd
[Install]
WantedBy=multi-user.target
```
and make sure the `node_exporter` binary in placed in an expected path. |
341,338 | I have the following Perl scripts (though this applies to Python and other scripting languages): `script1.pl`, `script2.pl`, `script3.pl`
The way these scripts where written, users execute them with input flags, and the output is a file saved.
```
perl script1.pl --i input1.tsv ## this outputs the file `outputs1`
perl script2.pl --i outputs1 ## this outputs the file `outputs2`
perl script3.pl --i outputs2 ## this outputs the file `final_output`
```
Now, I would like to create an executable bash script that allows users to simply work with `input1` and get the output in return `final_output`.
Here's how I would do this with only one perl script, `execute.sh`:
```
#!/bin/sh
source ~/.bash_profile
FLAG1="--i=$1"
perl script1.pl $FLAG1
```
which could be run on the command line `execute.sh input1.tsv`
For my example with three scripts, how would I pipe the intermediate outputs into the intermediate scripts to created one `execute.sh` script, e.g. `outputs1` into `script2.pl`, then `outputs2` into `scripts3.pl`, etc.?
Isn't there a way for me to do this without rewriting the perl/python scripts? | 2017/01/30 | ['https://unix.stackexchange.com/questions/341338', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/115891/'] | I solved the problem like this...
**Node exporter:**
```none
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
```
**Mysql\_exporter:**
```none
=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
```
**Here is the complete command:**
```
sudo vim /etc/systemd/system/mysql_exporter.service
```
**Content for `mysql_exporter.service`:**
```none
[Unit]
Description=Prometheus MySQL Exporter
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/mysqld_exporter \
--config.my-cnf /etc/.mysqld_exporter.cnf \
--collect.global_status \
--collect.info_schema.innodb_metrics \
--collect.auto_increment.columns \
--collect.info_schema.processlist \
--collect.binlog_size \
--collect.info_schema.tablestats \
--collect.global_variables \
--collect.info_schema.query_response_time \
--collect.info_schema.userstats \
--collect.info_schema.tables \
--collect.perf_schema.tablelocks \
--collect.perf_schema.file_events \
--collect.perf_schema.eventswaits \
--collect.perf_schema.indexiowaits \
--collect.perf_schema.tableiowaits \
--collect.slave_status \
--web.listen-address=0.0.0.0:9104'
[Install]
WantedBy=multi-user.target
```
**Node exporter:**
```
sudo vim /etc/systemd/system/node_exporter.service
```
**Content for `node_exporter`:**
```none
[Unit]
Description=Prometheus Node Exporter
After=network.target
User=prometheus
Group=prometheus
[Service]
Type=simple
Restart=always
ExecStart=/bin/sh -c '/usr/local/bin/node_exporter'
[Install]
WantedBy=multi-user.target
``` | I got this error. Solved as @Saex.
Reason for getting this error is that I have downloaded the wrong package `node_exporter-1.2.2.darwin-amd64.tar.gz` instead of `node_exporter-1.2.2.linux-amd64.tar.gz`
```
node_exporter.service - Node Exporter
Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Wed 2021-08-18 11:22:44 UTC; 17s ago
Main PID: 3830 (code=exited, status=203/EXEC)
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: Started Node Exporter.
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed to execute command: Exec format error
Aug 18 11:22:44 ip-10-0-101-80 systemd[3830]: node_exporter.service: Failed at step EXEC spawning /opt/node_exporter/node_exporter: Exec>
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Main process exited, code=exited, status=203/EXEC
Aug 18 11:22:44 ip-10-0-101-80 systemd[1]: node_exporter.service: Failed with result 'exit-code'.
``` |
1,589,095 | In Algebra (2) I was told that if a polynomial had an even multiplicity for some $x=a$, then the graph touches $y=0$ at $x=a$ but doesn't cross $y=0$. Odd multiplicities go through the $x$-intercept. For example:$$y=x^2\to y=(x-0)(x-0)\to x=0,0$$And you can clearly see the graph "touches without intersecting" at $x=0$.
However, I am confused on how this is proven. | 2015/12/26 | ['https://math.stackexchange.com/questions/1589095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/272831/'] | Let $P(x) = Q(x)(x-a)^{2n}$ such that $(x-a)\nmid Q(x)$. In a small enough neighbourhood of $a$ (for instance one that contains no roots of $Q(x)$), then $Q(x)$ preserves sign. And $(x-a)^{2n}\geq 0$, therefore, in said neighbourhood, $P(x)$ preserves sign, i.e., the function does not cross the line $y=0$.
You can find a similar argument of why it happens the other way around for $P(x) = Q(x)(x-a)^{2n+1}$. | Suppose you have $f(x) = (x+6)(x-4)(x-7)^2$. If $x$ is near $7$ then $(x+6)(x-4)$ is near $(7+6)(7-4) =39$, so $f(x)$ is approximately $39(x-7)^2$. Notice that if $x$ is either a little bit more than $7$ or a little bit less, then $(x-7)^2$ is positive, but if $x$ is exactly $7$, then $(x-7)^2$ is $0$. Being positive on either side of that point but exactly $0$ at that point means it touches the axis without crossing over from positive to negative or vice-versa. |
27,767,713 | As a part of an internal project, I have to parse through a dns zone file records. The file looks roughly like this.
```
$ORIGIN 0001.test.domain.com.
test-qa CNAME test-qa.0001.test.domain.com.
$ORIGIN test-qa.domain.com.
unit-test01 A 192.168.0.2
$TTL 60 ; 1 minute
integration-test A 192.168.0.102
$ORIGIN dev.domain.com.
web A 192.168.10.10
$TTL 300; 5 minutes
api A 192.168.10.13
```
Default ttl is 3600, that is, for the above data,
```
test-qa CNAME test-qa.0001.test.domain.com.
```
has a ttl of 3600 because it doesn't have a $TTL mentioned anywhere. However,
```
unit-test01 A 192.168.0.2
```
has a ttl of 3600 and
```
integration-test A 192.168.0.102
```
has a ttl of 60 secs.
I am trying to create a datastructure out of this data above, and I guess a dictionary would be the best possible way to traverse through this data.
What I did:
```
origin = re.compile("^\$ORIGIN.*")
ttl = re.compile("^$TTL.*")
default_ttl = "$TTL 3600"
data_dict = {}
primary_key = None
value = None
for line in data_zones:
if origin.search(line):
line = line.replace("$ORIGIN ", "")
primary_key = line
elif ttl.search(line):
default_ttl = line
else:
value = line
data_dict[primary_key] = [default_ttl]
data_dict[primary_key][default_ttl] = value
```
I want to convert it into a dictionary, but I get the error
```
TypeError: list indices must be integers, not str
```
My sample data structure need to look something like
```
0001.test.domain.com.: #This would be the first level Key
ttl:3600: #This would be the second level key
test-qa CNAME test-qa.0001.test.domain.com. #Value
test-qa.domain.com.: #This would be the first level Key
ttl:3600: #This would be the second level key
unit-test01 A 192.168.0.2 #value
ttl:60: #This would be the second level key
integration-test A 192.168.0.102 #value
```
What am I doing wrong here? | 2015/01/04 | ['https://Stackoverflow.com/questions/27767713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3354434/'] | Before we look at the detail of the problem, there's a few things that could be cleaned up in this code that would make the error easier to find. Following code quality guidelines make code easier to maintain and understand, in particular - variable names should always be descriptive and tell the reader what the variable is going to represent. A bad variable name doesn't tell the reader anything about what it contains, and a terrible variable name will tell the reader that the variable contains something it doesn't.
Here we have a variable here called default\_ttl. A casual reader might well make an assumption that this variable is always going to contain the default ttl, but in the code sample above, the variable is overwritten as soon as a ttl is specified in the source data.
```
default_ttl = line
```
It might be a lot clearer to specify a default TTL at the top of the code, and then use assign this value to a variable called, say : current\_ttl, whenever a new origin is encountered.
So at the top of the file we would have :
```
DEFAULT_TTL = '$TTL 3600'
```
And every time a new origin is encountered, the current ttl would be reset to the default.
```
if origin.search(line):
line = line.replace("$ORIGIN ", "")
current_ttl = DEFAULT_TTL
```
When a specific TTL is encountered in the source data, the appropriate value can then be assigned to current TTL:
```
elif ttl.search(line):
current_ttl = line
```
Once this change is made, the bottom two lines of code would become:
```
data_dict[primary_key] = [current_ttl]
data_dict[primary_key][current_ttl] = value
```
The cause of the error is that you are creating a list containing exactly one entry - the current\_ttl, and creating an entry in the data\_dict dictionary containing that list.
On the next line, you get the list back out of the dictionary, and try and access it using the index current\_ttl. current\_ttl contains a string, and a list can only be accessed using an integer. The interpreter gives you an error message that sums this up succinctly!
Without major modifications to your code, the quickest clean up is to use a defaultdict for the top level data\_dict:
```
from collections import defaultdict
data_dict = defaultdict(dict)
```
So now, whenever we try to refer to a key in data\_dict that does not already exist, a new empty dictionary will be created for us by the defaultdict object and inserted to data\_dict at that key we tried to access.
The line
```
data_dict[primary_key] = [default_ttl]
```
Is now redundant and unnecessary, it can be removed from the code altogether, leaving :
```
from collections import defaultdict
origin = re.compile("^\$ORIGIN.*")
ttl = re.compile("^$TTL.*")
DEFAULT_TTL = "$TTL 3600"
data_dict = defaultdict(dict)
primary_key = None
value = None
for line in data_zones.split('\n'): #Split by line not character
if origin.search(line):
line = line.replace("$ORIGIN ", "")
current_ttl = DEFAULT_TTL
primary_key = line
elif ttl.search(line):
current_ttl = line
else:
value = line
data_dict[primary_key][current_ttl] = value
``` | The line of error is
```
data_dict[primary_key][default_ttl] = value
```
Because `data_dict[primary_key]` is a list and not a dictionary object. You can fix this by doing
```
data_dict[primary_key] = {default_ttl: value}
``` |
15,369 | I'm putting together a gaming rig with an i5 11600k (liquid cooled) and GIGABYTE Z590 mobo... average RAM, GIGABYTE AORUS NVMe Gen4 SSD, beefy PSU... everything is coming along nicely... with the end goal being to be playing on 1440p with in-game settings pretty high.
But now i need to choose my GPU. I have access to a 3060 Ti or a 3070 Ti for the same price (friendly scalper). I've read that the 3070 will likely cause a CPU bottleneck while the 3060 will be the opposite. I'm pretty new go all this, so I'm not sure I fully understand the issues involved with bottlenecking... or maybe I'm making it more complicated than it needs to be. Is the main problem that the component being bottlenecked will not be able to use 100% of its "power"... meaning that you're maybe not getting your money's worth out of of that component?
If that's the case, then I'm thinking I should definitely go with the 3070 Ti since it is costing me the same as the 3060 and will provide some future-proofing or perhaps get me a better resale price (if i ever choose to go that way). Does that sound about right or am I missing something that would actually make the 3060 Ti the better choice (with better performance) in my situation? | 2021/10/04 | ['https://hardwarerecs.stackexchange.com/questions/15369', 'https://hardwarerecs.stackexchange.com', 'https://hardwarerecs.stackexchange.com/users/20243/'] | >
> If I opt for Additional 2.5" 2 TB 5400RPM SATA Hard Drive, the battery 4 cells 64Whr battery should be selected.
>
>
>
This is probably because the larger battery takes up the space where a 2.5" HDD can be installed.
>
> Does Using both SSD & SATA Hard drive impacts Laptop Performance?
>
>
>
There is no surprise here, things that run on the SSD run at the SSD speed. Things that run on the HDD run at HDD speed. But since there's more stuff using power in the laptop the battery will be drained quicker. HDDs can conserve power by going to sleep if you make sure they're not being used in the background. If the HDD motor is running often, it will consume a little extra power and shorten the battery life.
>
> Can someone shed some light on choosing up the hard drives & battery?
>
>
>
It depends which matters more to you:
1. Is battery life the most important thing? -- Then get the 6 cell battery.
You can always plug in a USB hard drive and get extra storage space that way.
2. Is tons of storage space without having to carry an external HDD important? -- Get the SATA HDD and "normal" battery. (4 cell batteries are typical) | It doesnt affect performance, as long as nothing is on the hard drive. If you actively use the hard drive, the app that uses the hard drive slows down to hard drive speed. For some tasks (like rendering a video), you can write to the hard drive without performance issues because the bottleneck is somewhere else (cpu) |
7,518,255 | I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters.
Say you type in 6 different letters (a,b,c,d,e,f) you want to search.
You'd like to find words matching at least 3 letters.
Each letter can only appear once in a word.
And the letter 'a' always has to be containing.
How should the code look like for this specific kind of search? | 2011/09/22 | ['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/'] | Here is what I would do if I had to write this:
I'd have a function that, given a word, would check whether it satisfies the criteria and would return a boolean flag.
Then I'd have some code that would iterate over all words in the file, present each of them to the function, and print out those for which the function has returned `True`. | ```
words = 'fubar cadre obsequious xray'
def find_words(src, required=[], letters=[], min_match=3):
required = set(required)
letters = set(letters)
words = ((word, set(word)) for word in src.split())
words = (word for word in words if word[1].issuperset(required))
words = (word for word in words if len(word[1].intersection(letters)) >= min_match)
words = (word[0] for word in words)
return words
w = find_words(words, required=['a'], letters=['a', 'b', 'c', 'd', 'e', 'f'])
print list(w)
```
**EDIT 1:** I too didn't read the requirements closely enough. To ensure a word contains only 1 instance of a valid letter.
```
from collections import Counter
def valid(word, letters, min_match):
"""At least min_match, no more than one of any letter"""
c = 0
count = Counter(word)
for letter in letters:
char_count = count.get(letter, 0)
if char_count > 1:
return False
elif char_count == 1:
c += 1
if c == min_match:
return True
return True
def find_words(srcfile, required=[], letters=[], min_match=3):
required = set(required)
words = (word for word in srcfile.split())
words = (word for word in words if set(word).issuperset(required))
words = (word for word in words if valid(word, letters, min_match))
return words
``` |
7,518,255 | I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters.
Say you type in 6 different letters (a,b,c,d,e,f) you want to search.
You'd like to find words matching at least 3 letters.
Each letter can only appear once in a word.
And the letter 'a' always has to be containing.
How should the code look like for this specific kind of search? | 2011/09/22 | ['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/'] | Here is what I would do if I had to write this:
I'd have a function that, given a word, would check whether it satisfies the criteria and would return a boolean flag.
Then I'd have some code that would iterate over all words in the file, present each of them to the function, and print out those for which the function has returned `True`. | I agree with aix's general plan, but it's perhaps even more general than a 'design pattern,' and I'm not sure how far it gets you, since it boils down to, "figure out a way to check for what you want to find and then check everything you need to check."
Advice about how to find what you want to find: You've entered into one of the most fundamental areas of algorithm research. Though LCS (longest common substring) is better covered, you'll have no problems finding good examples for containment either. The most rigorous discussion of this topic I've seen is on a Google cs wonk's website: <http://neil.fraser.name>. He has something called diff-match-patch which is released and optimized in many different languages, including python, which can be downloaded here:
<http://code.google.com/p/google-diff-match-patch/>
If you'd like to understand more about python and algorithms, magnus hetland has written a great book about python algorithms and his website features some examples within string matching and fuzzy string matching and so on, including the levenshtein distance in a very simple to grasp format. (google for magnus hetland, I don't remember address).
WIthin the standard library you can look at difflib, which offers many ways to assess similarity of strings. You are looking for containment which is not the same but it is quite related and you could potentially make a set of candidate words that you could compare, depending on your needs.
Alternatively you could use the new addition to python, Counter, and reconstruct the words you're testing as lists of strings, then make a function that requires counts of 1 or more for each of your tested letters.
Finally, on to the second part of the aix's approach, 'then apply it to everything you want to test,' I'd suggest you look at itertools. If you have any kind of efficiency constraint, you will want to use generators and a test like the one aix proposes can be most efficiently carried out in python with itertools.ifilter. You have your function that returns True for the values you want to keep, and the **builtin** function bool. So you can just do itertools.ifilter(bool,test\_iterable), which will return all the values that succeed.
Good luck |
7,518,255 | I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters.
Say you type in 6 different letters (a,b,c,d,e,f) you want to search.
You'd like to find words matching at least 3 letters.
Each letter can only appear once in a word.
And the letter 'a' always has to be containing.
How should the code look like for this specific kind of search? | 2011/09/22 | ['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/'] | Let's see...
```
return [x for x in document.split()
if 'a' in x and sum((1 if y in 'abcdef' else 0 for y in x)) >= 3]
```
`split` with no parameters acts as a "words" function, splitting on any whitespace and removing words that contain no characters. Then you check if the letter 'a' is in the word. If 'a' is in the word, you use a generator expression that goes over every letter in the word. If the letter is inside of the string of available letters, then it returns a 1 which contributes to the sum. Otherwise, it returns 0. Then if the sum is 3 or greater, it keeps it. A generator is used instead of a list comprehension because sum will accept anything iterable and it stops a temporary list from having to be created (less memory overhead).
It doesn't have the best access times because of the use of `in` (which on a string should have an O(n) time), but that generally isn't a very big problem unless the data sets are huge. You can optimize that a bit to pack the string into a set and the constant 'abcdef' can easily be a set. I just didn't want to ruin the nice one liner.
EDIT: Oh, and to improve time on the `if` portion (which is where the inefficiencies are), you could separate it out into a function that iterates over the string once and returns True if the conditions are met. I would have done this, but it ruined my one liner.
EDIT 2: I didn't see the "must have 3 different characters" part. You can't do that in a one liner. You can just take the if portion out into a function.
```
def is_valid(word, chars):
count = 0
for x in word:
if x in chars:
count += 1
chars.remove(x)
return count >= 3 and 'a' not in chars
def parse_document(document):
return [x for x in document.split() if is_valid(x, set('abcdef'))]
```
This one shouldn't have any performance problems on real world data sets. | ```
words = 'fubar cadre obsequious xray'
def find_words(src, required=[], letters=[], min_match=3):
required = set(required)
letters = set(letters)
words = ((word, set(word)) for word in src.split())
words = (word for word in words if word[1].issuperset(required))
words = (word for word in words if len(word[1].intersection(letters)) >= min_match)
words = (word[0] for word in words)
return words
w = find_words(words, required=['a'], letters=['a', 'b', 'c', 'd', 'e', 'f'])
print list(w)
```
**EDIT 1:** I too didn't read the requirements closely enough. To ensure a word contains only 1 instance of a valid letter.
```
from collections import Counter
def valid(word, letters, min_match):
"""At least min_match, no more than one of any letter"""
c = 0
count = Counter(word)
for letter in letters:
char_count = count.get(letter, 0)
if char_count > 1:
return False
elif char_count == 1:
c += 1
if c == min_match:
return True
return True
def find_words(srcfile, required=[], letters=[], min_match=3):
required = set(required)
words = (word for word in srcfile.split())
words = (word for word in words if set(word).issuperset(required))
words = (word for word in words if valid(word, letters, min_match))
return words
``` |
7,518,255 | I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters.
Say you type in 6 different letters (a,b,c,d,e,f) you want to search.
You'd like to find words matching at least 3 letters.
Each letter can only appear once in a word.
And the letter 'a' always has to be containing.
How should the code look like for this specific kind of search? | 2011/09/22 | ['https://Stackoverflow.com/questions/7518255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959397/'] | Let's see...
```
return [x for x in document.split()
if 'a' in x and sum((1 if y in 'abcdef' else 0 for y in x)) >= 3]
```
`split` with no parameters acts as a "words" function, splitting on any whitespace and removing words that contain no characters. Then you check if the letter 'a' is in the word. If 'a' is in the word, you use a generator expression that goes over every letter in the word. If the letter is inside of the string of available letters, then it returns a 1 which contributes to the sum. Otherwise, it returns 0. Then if the sum is 3 or greater, it keeps it. A generator is used instead of a list comprehension because sum will accept anything iterable and it stops a temporary list from having to be created (less memory overhead).
It doesn't have the best access times because of the use of `in` (which on a string should have an O(n) time), but that generally isn't a very big problem unless the data sets are huge. You can optimize that a bit to pack the string into a set and the constant 'abcdef' can easily be a set. I just didn't want to ruin the nice one liner.
EDIT: Oh, and to improve time on the `if` portion (which is where the inefficiencies are), you could separate it out into a function that iterates over the string once and returns True if the conditions are met. I would have done this, but it ruined my one liner.
EDIT 2: I didn't see the "must have 3 different characters" part. You can't do that in a one liner. You can just take the if portion out into a function.
```
def is_valid(word, chars):
count = 0
for x in word:
if x in chars:
count += 1
chars.remove(x)
return count >= 3 and 'a' not in chars
def parse_document(document):
return [x for x in document.split() if is_valid(x, set('abcdef'))]
```
This one shouldn't have any performance problems on real world data sets. | I agree with aix's general plan, but it's perhaps even more general than a 'design pattern,' and I'm not sure how far it gets you, since it boils down to, "figure out a way to check for what you want to find and then check everything you need to check."
Advice about how to find what you want to find: You've entered into one of the most fundamental areas of algorithm research. Though LCS (longest common substring) is better covered, you'll have no problems finding good examples for containment either. The most rigorous discussion of this topic I've seen is on a Google cs wonk's website: <http://neil.fraser.name>. He has something called diff-match-patch which is released and optimized in many different languages, including python, which can be downloaded here:
<http://code.google.com/p/google-diff-match-patch/>
If you'd like to understand more about python and algorithms, magnus hetland has written a great book about python algorithms and his website features some examples within string matching and fuzzy string matching and so on, including the levenshtein distance in a very simple to grasp format. (google for magnus hetland, I don't remember address).
WIthin the standard library you can look at difflib, which offers many ways to assess similarity of strings. You are looking for containment which is not the same but it is quite related and you could potentially make a set of candidate words that you could compare, depending on your needs.
Alternatively you could use the new addition to python, Counter, and reconstruct the words you're testing as lists of strings, then make a function that requires counts of 1 or more for each of your tested letters.
Finally, on to the second part of the aix's approach, 'then apply it to everything you want to test,' I'd suggest you look at itertools. If you have any kind of efficiency constraint, you will want to use generators and a test like the one aix proposes can be most efficiently carried out in python with itertools.ifilter. You have your function that returns True for the values you want to keep, and the **builtin** function bool. So you can just do itertools.ifilter(bool,test\_iterable), which will return all the values that succeed.
Good luck |