qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
34,488,876 | From my eclipse project I've removed .class file for a particular class thinking eclipse will regenerate it for me if I build it again or run the project again.
But when I tried to run the program, It's showing class not found exception.
I'm wondering what's happening there? doesn't eclipse build .class files each time we run the project? when compilation will happen in eclipse? | 2015/12/28 | [
"https://Stackoverflow.com/questions/34488876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3709218/"
] | Compilation will happen either the next time the source file is modified, if you have it set to Build Automatically, or the next time you run. *Both* of these expect compiled source files to still have their .class files around. *Clean* the project from the `Project` menu to force it to recompile regardless. | Make sure that in the Project up-menu, the option "Build Automatically" is checked then just clean your project.
It should regenerate the .class file(s). |
34,488,876 | From my eclipse project I've removed .class file for a particular class thinking eclipse will regenerate it for me if I build it again or run the project again.
But when I tried to run the program, It's showing class not found exception.
I'm wondering what's happening there? doesn't eclipse build .class files each time we run the project? when compilation will happen in eclipse? | 2015/12/28 | [
"https://Stackoverflow.com/questions/34488876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3709218/"
] | Compilation will happen either the next time the source file is modified, if you have it set to Build Automatically, or the next time you run. *Both* of these expect compiled source files to still have their .class files around. *Clean* the project from the `Project` menu to force it to recompile regardless. | Check Your java file is in a source folder (right click project, properties, build path)
and you have automatic build turned on (Project menu -> Build automatically)
Also make sure your project compilation/build succeeds, otherwise Eclipse may not compile all the classes.
Check in the Problem windows if there is any error on the project compilation then fix it first. |
34,488,876 | From my eclipse project I've removed .class file for a particular class thinking eclipse will regenerate it for me if I build it again or run the project again.
But when I tried to run the program, It's showing class not found exception.
I'm wondering what's happening there? doesn't eclipse build .class files each time we run the project? when compilation will happen in eclipse? | 2015/12/28 | [
"https://Stackoverflow.com/questions/34488876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3709218/"
] | Compilation will happen either the next time the source file is modified, if you have it set to Build Automatically, or the next time you run. *Both* of these expect compiled source files to still have their .class files around. *Clean* the project from the `Project` menu to force it to recompile regardless. | * Project menu
* Click "Clean"
* Select "clean all projects" or "Clean selected projects below" and
choose your project
* Check "Start a build immediately"
* Click "ok"
* Now run your program.
Also as suggested by other answers, enable "Build Automatically" in Projects Menu.
Hope it helps |
69,708,937 | I have a password `UICollectionViewCell` with a `UITextField` to enter the password. I want to have a button where the user can change the isSecureTextEntry property.
My Code
-------
```
private lazy var button: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.addTarget(self, action: #selector(toggle), for: .touchUpInside)
return view
}()
@objc func toggle(_ sender: UIButton) {
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
}
```
Set Up Cell
-----------
```
self.toggle(button)
```
However, my button image is not changing. | 2021/10/25 | [
"https://Stackoverflow.com/questions/69708937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6738168/"
] | Here you go:
```
your_list = [['AIGSALPPMM', 'AVIVANVS'], ['DKEPBARCLA', 'DAVIDSNKC'], ['DAVKEMBDBL', 'DAVIDSNKC'], ['DAKEMJPMPB', '']]
new_list = [[val[0], val[0]] if val[-1]=='' else val for val in your_list]
new_list
```
Correct me if I misunderstood your question | Use a boolean mask to filter your rows:
```
df = pd.read_excel('check_counterparties.xlsx', sheet_name='counterparties_cdwu',
usecols=['A', 'B'], skiprows=4)
out = df[df['B'] == '']
```
Output:
```
# DataFrame format
>>> out
A B
3 DAKEMJPMPB
# List format
>>> out.to_dict(orient='split')['data']
[['DAKEMJPMPB', '']]
``` |
69,708,937 | I have a password `UICollectionViewCell` with a `UITextField` to enter the password. I want to have a button where the user can change the isSecureTextEntry property.
My Code
-------
```
private lazy var button: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.addTarget(self, action: #selector(toggle), for: .touchUpInside)
return view
}()
@objc func toggle(_ sender: UIButton) {
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
}
```
Set Up Cell
-----------
```
self.toggle(button)
```
However, my button image is not changing. | 2021/10/25 | [
"https://Stackoverflow.com/questions/69708937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6738168/"
] | ```
main_arr = [['AIGSALPPMM', 'AVIVANVS'], ['DKEPBARCLA', 'DAVIDSNKC'], ['DAVKEMBDBL', 'DAVIDSNKC'], ['DAKEMJPMPB', '']]
for arr in main_arr:
if arr[1] == '':
print (arr)
``` | Use a boolean mask to filter your rows:
```
df = pd.read_excel('check_counterparties.xlsx', sheet_name='counterparties_cdwu',
usecols=['A', 'B'], skiprows=4)
out = df[df['B'] == '']
```
Output:
```
# DataFrame format
>>> out
A B
3 DAKEMJPMPB
# List format
>>> out.to_dict(orient='split')['data']
[['DAKEMJPMPB', '']]
``` |
69,708,937 | I have a password `UICollectionViewCell` with a `UITextField` to enter the password. I want to have a button where the user can change the isSecureTextEntry property.
My Code
-------
```
private lazy var button: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.addTarget(self, action: #selector(toggle), for: .touchUpInside)
return view
}()
@objc func toggle(_ sender: UIButton) {
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
}
```
Set Up Cell
-----------
```
self.toggle(button)
```
However, my button image is not changing. | 2021/10/25 | [
"https://Stackoverflow.com/questions/69708937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6738168/"
] | Here you go:
```
your_list = [['AIGSALPPMM', 'AVIVANVS'], ['DKEPBARCLA', 'DAVIDSNKC'], ['DAVKEMBDBL', 'DAVIDSNKC'], ['DAKEMJPMPB', '']]
new_list = [[val[0], val[0]] if val[-1]=='' else val for val in your_list]
new_list
```
Correct me if I misunderstood your question | Use list comprehension:
```
lst = [['AIGSALPPMM', 'AVIVANVS'], ['DKEPBARCLA', 'DAVIDSNKC'], ['DAVKEMBDBL', 'DAVIDSNKC'], ['DAKEMJPMPB', '']]
>>> [sublist for sublist in lst if len(sublist[-1].strip())==0]
[['DAKEMJPMPB', '']]
``` |
69,708,937 | I have a password `UICollectionViewCell` with a `UITextField` to enter the password. I want to have a button where the user can change the isSecureTextEntry property.
My Code
-------
```
private lazy var button: UIButton = {
let view = UIButton()
view.translatesAutoresizingMaskIntoConstraints = false
view.addTarget(self, action: #selector(toggle), for: .touchUpInside)
return view
}()
@objc func toggle(_ sender: UIButton) {
sender.isSelected == false ? button.setImage(secureImage, for: .normal) : button.setImage(unSecureImage, for: .selected)
}
```
Set Up Cell
-----------
```
self.toggle(button)
```
However, my button image is not changing. | 2021/10/25 | [
"https://Stackoverflow.com/questions/69708937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6738168/"
] | ```
main_arr = [['AIGSALPPMM', 'AVIVANVS'], ['DKEPBARCLA', 'DAVIDSNKC'], ['DAVKEMBDBL', 'DAVIDSNKC'], ['DAKEMJPMPB', '']]
for arr in main_arr:
if arr[1] == '':
print (arr)
``` | Use list comprehension:
```
lst = [['AIGSALPPMM', 'AVIVANVS'], ['DKEPBARCLA', 'DAVIDSNKC'], ['DAVKEMBDBL', 'DAVIDSNKC'], ['DAKEMJPMPB', '']]
>>> [sublist for sublist in lst if len(sublist[-1].strip())==0]
[['DAKEMJPMPB', '']]
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You should avoid removing from a list in the middle. It will give you polynomial time complexity, and is a little tricky to get correct anyway. Removing items from a list while iterating over it will commonly cause you to skip items, as your list changes in size. However, it is possible to do it safely by iterating backwards over the sequence:
```
>>> list1 = [6, 7, 8, 9]
>>> list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
Then simply:
```
>>> for i in reversed(range(len(list2))):
... item = list2[i]
... if any(int(c) in list1 for c in item):
... del list2[i]
...
>>> list2
['0001', '0003', '0004', '0005']
```
However, it is almost always faster and more efficient and straight-forward to create a new list as an intermediate and use it to change the original list in-place:
```
>>> list2[:] = [x for x in list2 if any(int(c) in list1 for c in x)]
>>> list2
['0009', '0008', '0006', '0007']
```
Finally, if you are going to be checking membership in a list, consider using a `set` object instead. Checking if an item is in a list is a linear operation, versus constant time with a `set`. | Try a list comprehension:
```
list1_set = set(list1)
list2[:] = [x for x in list2 if int(x) not in list1_set]
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | If all `list2` items are unique, you can remove them in a reversed iteration:
```
for item in reversed(list2):
for number in list1:
if str(number) in item:
list2.remove(item)
break
print(list2)
#['0001', '0003', '0004', '0005']
``` | You can always use set intersection:
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
list1 = set(map(str, list1))
# {'6', '8', '9', '7'}
list2[:] = [x for x in list2 if not list1.intersection(x)]
print(list2)
```
Which Outputs:
```
['0001', '0003', '0004', '0005']
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | Try a list comprehension:
```
list1_set = set(list1)
list2[:] = [x for x in list2 if int(x) not in list1_set]
``` | You can try something like this
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for i in list2:
if int(list(i)[-1:][0]) not in list1:
print(i)
```
output:
```
0001
0003
0004
0005
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You should avoid removing from a list in the middle. It will give you polynomial time complexity, and is a little tricky to get correct anyway. Removing items from a list while iterating over it will commonly cause you to skip items, as your list changes in size. However, it is possible to do it safely by iterating backwards over the sequence:
```
>>> list1 = [6, 7, 8, 9]
>>> list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
Then simply:
```
>>> for i in reversed(range(len(list2))):
... item = list2[i]
... if any(int(c) in list1 for c in item):
... del list2[i]
...
>>> list2
['0001', '0003', '0004', '0005']
```
However, it is almost always faster and more efficient and straight-forward to create a new list as an intermediate and use it to change the original list in-place:
```
>>> list2[:] = [x for x in list2 if any(int(c) in list1 for c in x)]
>>> list2
['0009', '0008', '0006', '0007']
```
Finally, if you are going to be checking membership in a list, consider using a `set` object instead. Checking if an item is in a list is a linear operation, versus constant time with a `set`. | You can try something like this
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for i in list2:
if int(list(i)[-1:][0]) not in list1:
print(i)
```
output:
```
0001
0003
0004
0005
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You should avoid removing from a list in the middle. It will give you polynomial time complexity, and is a little tricky to get correct anyway. Removing items from a list while iterating over it will commonly cause you to skip items, as your list changes in size. However, it is possible to do it safely by iterating backwards over the sequence:
```
>>> list1 = [6, 7, 8, 9]
>>> list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
Then simply:
```
>>> for i in reversed(range(len(list2))):
... item = list2[i]
... if any(int(c) in list1 for c in item):
... del list2[i]
...
>>> list2
['0001', '0003', '0004', '0005']
```
However, it is almost always faster and more efficient and straight-forward to create a new list as an intermediate and use it to change the original list in-place:
```
>>> list2[:] = [x for x in list2 if any(int(c) in list1 for c in x)]
>>> list2
['0009', '0008', '0006', '0007']
```
Finally, if you are going to be checking membership in a list, consider using a `set` object instead. Checking if an item is in a list is a linear operation, versus constant time with a `set`. | You can always use set intersection:
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
list1 = set(map(str, list1))
# {'6', '8', '9', '7'}
list2[:] = [x for x in list2 if not list1.intersection(x)]
print(list2)
```
Which Outputs:
```
['0001', '0003', '0004', '0005']
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You can use `re.findall`:
```
import re
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
new_list2 = filter(lambda x:int(re.findall('\d+(?=$)', x)[0]) not in list1, list2)
```
Output:
```
['0001', '0003', '0004', '0005']
``` | You can always use set intersection:
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
list1 = set(map(str, list1))
# {'6', '8', '9', '7'}
list2[:] = [x for x in list2 if not list1.intersection(x)]
print(list2)
```
Which Outputs:
```
['0001', '0003', '0004', '0005']
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | Try a list comprehension:
```
list1_set = set(list1)
list2[:] = [x for x in list2 if int(x) not in list1_set]
``` | You can always use set intersection:
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
list1 = set(map(str, list1))
# {'6', '8', '9', '7'}
list2[:] = [x for x in list2 if not list1.intersection(x)]
print(list2)
```
Which Outputs:
```
['0001', '0003', '0004', '0005']
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You should avoid removing from a list in the middle. It will give you polynomial time complexity, and is a little tricky to get correct anyway. Removing items from a list while iterating over it will commonly cause you to skip items, as your list changes in size. However, it is possible to do it safely by iterating backwards over the sequence:
```
>>> list1 = [6, 7, 8, 9]
>>> list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
Then simply:
```
>>> for i in reversed(range(len(list2))):
... item = list2[i]
... if any(int(c) in list1 for c in item):
... del list2[i]
...
>>> list2
['0001', '0003', '0004', '0005']
```
However, it is almost always faster and more efficient and straight-forward to create a new list as an intermediate and use it to change the original list in-place:
```
>>> list2[:] = [x for x in list2 if any(int(c) in list1 for c in x)]
>>> list2
['0009', '0008', '0006', '0007']
```
Finally, if you are going to be checking membership in a list, consider using a `set` object instead. Checking if an item is in a list is a linear operation, versus constant time with a `set`. | If all `list2` items are unique, you can remove them in a reversed iteration:
```
for item in reversed(list2):
for number in list1:
if str(number) in item:
list2.remove(item)
break
print(list2)
#['0001', '0003', '0004', '0005']
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You can use `re.findall`:
```
import re
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
new_list2 = filter(lambda x:int(re.findall('\d+(?=$)', x)[0]) not in list1, list2)
```
Output:
```
['0001', '0003', '0004', '0005']
``` | You can try something like this
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for i in list2:
if int(list(i)[-1:][0]) not in list1:
print(i)
```
output:
```
0001
0003
0004
0005
``` |
48,432,737 | I wonder how can i iterate over a list2 and remove all ittems that contains one of the list1 ittems ?
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
and result will be :
```
list2=[ '0001', '0003', '0004', '0005']
```
i try somthing like :
```
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2.remove(ittem)
print(list2)
```
for ittem in list2:
for digit in ittem:
if digit in ittem:
list2
>
> result :ValueError: list.remove(x): x not in list
>
>
>
ps : i dont want to creat a new list , i want to remove ittems .. Any ideas ? | 2018/01/24 | [
"https://Stackoverflow.com/questions/48432737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8700815/"
] | You should avoid removing from a list in the middle. It will give you polynomial time complexity, and is a little tricky to get correct anyway. Removing items from a list while iterating over it will commonly cause you to skip items, as your list changes in size. However, it is possible to do it safely by iterating backwards over the sequence:
```
>>> list1 = [6, 7, 8, 9]
>>> list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
```
Then simply:
```
>>> for i in reversed(range(len(list2))):
... item = list2[i]
... if any(int(c) in list1 for c in item):
... del list2[i]
...
>>> list2
['0001', '0003', '0004', '0005']
```
However, it is almost always faster and more efficient and straight-forward to create a new list as an intermediate and use it to change the original list in-place:
```
>>> list2[:] = [x for x in list2 if any(int(c) in list1 for c in x)]
>>> list2
['0009', '0008', '0006', '0007']
```
Finally, if you are going to be checking membership in a list, consider using a `set` object instead. Checking if an item is in a list is a linear operation, versus constant time with a `set`. | You can use `re.findall`:
```
import re
list1 = [6, 7, 8, 9]
list2=['0009', '0001', '0008', '0003', '0004', '0005', '0006', '0007']
new_list2 = filter(lambda x:int(re.findall('\d+(?=$)', x)[0]) not in list1, list2)
```
Output:
```
['0001', '0003', '0004', '0005']
``` |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the case where you are ignoring the first character, you only want to compare `word.length() - 1` characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter. | Try using:
```
if (str.length() > 0 && str.substring(1).startsWith(word.substring(1))) {
```
for the conditional as it is much clearer. Also, tvanfosson and Darth Eru are correct that the first conditional with the exact match on the first character is extraneous. |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your problem is in your second comparison (the general case). You are taking a substring of str to the end of str, and comparing it with a substring of word to the end of word. However, if str="hippo" and word="xip", "ippo" != "ip".
As an additional note, once you fix the second case, you won't really need the first case, as it's covered by the second case. | In the case where you are ignoring the first character, you only want to compare `word.length() - 1` characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter. |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the case where you are ignoring the first character, you only want to compare `word.length() - 1` characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter. | Try Regex!
```
java.lang.String
boolean matches(String regex)
``` |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the case where you are ignoring the first character, you only want to compare `word.length() - 1` characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter. | Here's a starting point for you
```
import junit.framework.TestCase;
public class HippoTest extends TestCase {
public void testActualStart() throws Exception {
assertEquals("hi", startWord("hippo", "hi"));
}
public void testSimilarStart() throws Exception {
assertEquals("xip", startWord("hippo", "hip"));
assertEquals("h", startWord("i", "hip"));
}
public void testWrongStart() throws Exception {
assertEquals("", startWord("hippo", "hx"));
}
private String startWord(String string, String string2) {
// TODO Auto-generated method stub
return null;
}
}
```
If you make these test cases pass, one at a time, perhaps it will be easier than trying to solve the whole problem at once. |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your problem in your second IF statement is that you are comparing the word to the entire substring. What you should compare it to (after checking their length of course) is:
```
str.substring(1,word.length()).equals(word.substring(1,word.length()))
``` | Try using:
```
if (str.length() > 0 && str.substring(1).startsWith(word.substring(1))) {
```
for the conditional as it is much clearer. Also, tvanfosson and Darth Eru are correct that the first conditional with the exact match on the first character is extraneous. |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your problem in your second IF statement is that you are comparing the word to the entire substring. What you should compare it to (after checking their length of course) is:
```
str.substring(1,word.length()).equals(word.substring(1,word.length()))
``` | Try Regex!
```
java.lang.String
boolean matches(String regex)
``` |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you've got the right idea there... simply compare a substring of **str** from character 1 to **word.length** to a substring of **word** from character 1 to the end of word.
if they match return the substring of **str** to **word.length**. | Try Regex!
```
java.lang.String
boolean matches(String regex)
``` |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your problem is in your second comparison (the general case). You are taking a substring of str to the end of str, and comparing it with a substring of word to the end of word. However, if str="hippo" and word="xip", "ippo" != "ip".
As an additional note, once you fix the second case, you won't really need the first case, as it's covered by the second case. | Try Regex!
```
java.lang.String
boolean matches(String regex)
``` |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the case where you are ignoring the first character, you only want to compare `word.length() - 1` characters -- and the same length for both the string and the word.
Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter. | You could try using regular expressions, starting at the 2nd character, to see if there is a match. You could also do some sort of substring, as I see you have done.
For the boundary case of a 1 letter long string, just hard code it to return properly. |
1,034,726 | i posted the other day with practice questions i was getting stuck with and i am stuck again
Please firstly can i ask you dont post full solutions.
The question is from here
<http://www.javabat.com/prob/p141494>
and reads
Given a string and a second "word" string, we'll say that the word matches the string if it appears at the front of the string, except its first char does not need to match exactly. On a match, return the front of the string, or otherwise return the empty string. So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". The word will be at least length 1.
startWord("hippo", "hi") → "hi"
startWord("hippo", "xip") → "hip"
startWord("hippo", "i") → "h"
I am getting very stuck, the wording of the question isn't helping me! This is the code i have so far
```
public String startWord(String str, String word)
{
if (str.startsWith(word)){
return str.substring(0, word.length());
}
if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
return str.substring(0, word.length());
}
return "";
}
```
hopefully someone will be able to help me out here with a pointer or 2, thank you for the help | 2009/06/23 | [
"https://Stackoverflow.com/questions/1034726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your problem is in your second comparison (the general case). You are taking a substring of str to the end of str, and comparing it with a substring of word to the end of word. However, if str="hippo" and word="xip", "ippo" != "ip".
As an additional note, once you fix the second case, you won't really need the first case, as it's covered by the second case. | Here's a starting point for you
```
import junit.framework.TestCase;
public class HippoTest extends TestCase {
public void testActualStart() throws Exception {
assertEquals("hi", startWord("hippo", "hi"));
}
public void testSimilarStart() throws Exception {
assertEquals("xip", startWord("hippo", "hip"));
assertEquals("h", startWord("i", "hip"));
}
public void testWrongStart() throws Exception {
assertEquals("", startWord("hippo", "hx"));
}
private String startWord(String string, String string2) {
// TODO Auto-generated method stub
return null;
}
}
```
If you make these test cases pass, one at a time, perhaps it will be easier than trying to solve the whole problem at once. |
12,684,960 | I'm trying to get a switch to return true or false, but I seem to be failing somewhere. I keep getting false. I'm totally lost. This should have worked actually. How do I get this right?
```
if (validNum(1))
{echo 'Ok';}else{echo 'Fail';}
function validNum($x)
{
switch ($x)
{
case 1:
echo "Number 1";
break;
return true;
case 2:
echo "Number 2";
break;
return true;
case 3:
echo "Number 3";
break;
return true;
default:
echo "No number between 1 and 3";
return false;
}
}
``` | 2012/10/02 | [
"https://Stackoverflow.com/questions/12684960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407503/"
] | The whole point of `break` is that it jumps out of the `case`. You're never reaching your `return` statements. You never need to both `return` *and* `break` from within a case. | You're putting a `break` in front of your `return`. It will never hit the `return`. |
12,684,960 | I'm trying to get a switch to return true or false, but I seem to be failing somewhere. I keep getting false. I'm totally lost. This should have worked actually. How do I get this right?
```
if (validNum(1))
{echo 'Ok';}else{echo 'Fail';}
function validNum($x)
{
switch ($x)
{
case 1:
echo "Number 1";
break;
return true;
case 2:
echo "Number 2";
break;
return true;
case 3:
echo "Number 3";
break;
return true;
default:
echo "No number between 1 and 3";
return false;
}
}
``` | 2012/10/02 | [
"https://Stackoverflow.com/questions/12684960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407503/"
] | I would rewrite it to below. It merges three cases together and avoids using a `break` statement that would otherwise go past your `switch`. Basically, with `return` you don't need `break`.
```
switch ($x)
{
case 1:
case 2:
case 3:
echo "Number $x";
return true;
default:
echo "No number between 1 and 3";
return false;
}
``` | The whole point of `break` is that it jumps out of the `case`. You're never reaching your `return` statements. You never need to both `return` *and* `break` from within a case. |
12,684,960 | I'm trying to get a switch to return true or false, but I seem to be failing somewhere. I keep getting false. I'm totally lost. This should have worked actually. How do I get this right?
```
if (validNum(1))
{echo 'Ok';}else{echo 'Fail';}
function validNum($x)
{
switch ($x)
{
case 1:
echo "Number 1";
break;
return true;
case 2:
echo "Number 2";
break;
return true;
case 3:
echo "Number 3";
break;
return true;
default:
echo "No number between 1 and 3";
return false;
}
}
``` | 2012/10/02 | [
"https://Stackoverflow.com/questions/12684960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407503/"
] | I would rewrite it to below. It merges three cases together and avoids using a `break` statement that would otherwise go past your `switch`. Basically, with `return` you don't need `break`.
```
switch ($x)
{
case 1:
case 2:
case 3:
echo "Number $x";
return true;
default:
echo "No number between 1 and 3";
return false;
}
``` | You're putting a `break` in front of your `return`. It will never hit the `return`. |
2,596,177 | >
> What is the simplest accurate approximation of $\sin^{-1}x$ using a (polynomial) function of $x$ and $\sqrt{1-x^2}$?
>
>
>
The most well-known definition in this subject is Euler's formula:
$$\sin^{-1}x=-i\ln\left(\sqrt{1-x^2}+ix\right) \tag{1}$$
I'm looking for a bivariate polynomial approximation
$$\sin^{-1}x\approx p\_N(x,\sqrt{1-x^2}) \tag{2}$$
where $N$ is the degree of the polynomial. For example, for $N=3$, I discovered a formula
$$\sin^{-1}x\approx x+(1-\sqrt{1-x^2})^2(1-0.43x) \tag{3}$$
which gives a uniformly good approximation over $x\in[0,1]$. More discussions of the problem can be found [here](https://i.stack.imgur.com/6KfMU.jpg).
Are there general ways to achieve such a polynomial approximation? | 2018/01/07 | [
"https://math.stackexchange.com/questions/2596177",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | To express $\theta\in[0,\frac{\pi}{2}]$ as a polynomial of $\sin\theta$ and $\cos\theta$, consider
$$\theta\approx a\_0+\sum\_{n=1}^N(a\_n\cos n\theta+b\_n\sin n\theta),\quad\theta\in[0,\frac{\pi}{2}].$$
The fitting problem becomes linear this way. However, there is no requirement on the value of the right-hand side for $\theta\in(\frac{\pi}{2},2\pi)$. So the coefficients $a\_n,b\_n$ are not determined straightforwardly by a Fourier integral, but needs to be found numerically using perhaps a least-square fitting technique. After the coefficients are found, use trignometric identities to convert $\cos n\theta$ and $\sin n\theta$ into polynomials of $\sin\theta$ and $\cos\theta$. The degree of the polynomial will be truncated by $N$. At the end of the calculation use $\sin\theta=x$ and $\cos\theta=\sqrt{1-x^2}$. A good approximation
$$\sin^{-1}x\approx\frac{\pi}{4}+0.9776\;(x-\sqrt{1-x^2})+0.1931\;(1-2x^2),\quad x\in[0,1]$$
can be found using this method by setting $N=2$. The root-mean-square error (RMSE) is under $5\times 10^{-4}$. If $N=3$, the RMSE can be made lower than $5\times 10^{-5}$. If $\theta=\sin^{-1}x\in[-\frac{\pi}{2},\frac{\pi}{2}]$ is required on the full domain, symmetry would cancel all $a\_n$ terms. Then for $N=3$ one obtains
$$\sin^{-1}x\approx 1.6434\;x-0.8719\;x\sqrt{1-x^2}+0.0804\;(3x-4x^3),\quad x\in[-1,1].$$
This formula has the right symmetry of being an odd function, but is much less accurate (RMSE = $3\times 10^{-3}$). Since $(\sqrt{1-x^2})^2=1-x^2$ is a polynomial, the general approximant takes the form $\sin^{-1}x\approx P(x)+Q(x)\sqrt{1-x^2}$, with $P(x)$ and $Q(x)$ being polynomials of desired degree. | From the classic
"Approximations for Digital Computers"
by Hastings,
published in 1955:
$\arcsin(x)
=\dfrac{\pi}{2}-\sqrt{1-x}f\_n(x)
$
where
$f\_n(x)
=\sum\_{k=0}^n a\_{n, k}x^k
$
are polynomials of degree $n$
for $n=3$ to $7$.
The simplest is
$f\_{3}(x)$
for which
$a\_{3, 0..3}
=1.5707288,
-.2121144,
.0742610,
-0.187293
$
with a maximum error of
about $0.00007$.
Using
$f\_7(x)$,
the maximum error is about
$0.00000002$.
Note:
I find it fascinating
to read the first section,
which describes how
the approximations were gotten.
In 1955,
the computer power
we are so accustomed to
was not available. |
39,140 | I play acoustic guitar in a band with drums, electric bass, and electric guitar. I'm often told that I need to switch to electric because nobody can hear my guitar However, I like the sound of acoustic on pretty much all of our songs.
My current setup is an acoustic/electric into a Fishman Loudbox Mini, with a line out to the PA. It seems like this works in some situations, but not others, but the most specific comment I've gotten is "during the quiet times, when it's just the acoustic, you're fine, but when it gets loud, you get lost."
Is this just a characteristic of acoustic guitar in an otherwise electric band? Is it a problem with the mixing? Do I need a bigger amp? Could I be setting my EQ incorrectly? Should I switch to an electric guitar amp, for the more "cutting" sound (even if it does mean losing a lot of the characteristics of my lovely Taylor)?
**How can I get my acoustic guitar to consistently be heard in live performance?** | 2015/11/05 | [
"https://music.stackexchange.com/questions/39140",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/12245/"
] | In a lot of mixes, it's normal and even intentional for the acoustic guitar(s) to get hidden behind the electric guitars and other instruments during the loud parts. If you listen to the Led Zeppelin songs that have both acoustic and electric guitars, it can sound like the acoustic track is muted during the "loud" parts, but it's usually actually sitting there in the background for the whole song.
The people saying they can't hear your guitar are probably people who specifically like your playing, like acoustic guitars, and/or like you, since they are not merely listening to the whole band as one unit.
Here are some thoughts:
* You might want or need a [sound hole cover](http://www.planetwaves.com/pwProductDetail.Page?ActiveID=4115&productid=497&productname=Screeching_Halt) to reduce possible feedback from bringing up the levels on your acoustic.
* With my sound engineer hat on, I prefer an active DI feed straight from the acoustic output over the DI out of an acoustic amp. Both as an engineer and as an acoustic player, I would bring my own DI to make sure I have one that I know how to use. The [Radial J48](http://www.radialeng.com/j48.php) and [Countryman Type 85](http://www.countryman.com/type-85-direct-box) are good examples of active DIs for acoustic.
* If you don't want the acoustic to be behind the other instruments during loud sections (check with your bandmates regarding the overall sound you all want), make sure you are clear about that with any sound engineers you are working with.
* The mix starts with the arrangement and the performance. Almost no engineering or equipment can make the acoustic heard during a loud chorus with a distorted electric guitar part, open hi-hat eighth notes, pounding bass line, and passionate vocals. If the whole band agrees on how the acoustic part should sit in the mix, then everyone will need to make sure they are leaving the necessary space (this applies to all the instruments, of course).
* It's really common for some instruments, including acoustic guitar, to get lost in the mix, and many times it's ok and even desireable. Take all audience comments with a grain of salt - even the positive ones. Actually, even negative comments are positive since it means the person listened to you and thought about your playing and had a strong enough feeling about it they had to come talk to you. Assuming the you and the band are ok with the acoustic getting lost sometimes, come up with a few ready responses to this kind of audience feedback that is validating so you are acknowledging the person giving advice even if you don't plan to follow it.
* If you use an electric guitar amp, it will make your acoustic sound like a weird sounding electric guitar. I worked with a band that made this their signature sound - outside of that I wouldn't normally consider it a good sound. | Agreed - a well played acoustic guitar often sounds better for rhythm in a band situation. If it's being DI'd from your little amp into the P.A., then it should come through the mix properly. If your mixer guy is doing it right, he should be able to remix for the louder numbers. It may just be that it's the Freddie Green syndrome. He played rhythm guitar, and was thought of as one of the best. He could hardly be heard, but when he stopped playing, it was noticed. Subtlety, I think it's called. Don't rely on others for comments - get a recording to hear for yourself. One from where the audience is, not off the P.A. It may be that the mix engineer has his own ideas of how you should sound. I lost count of the number of times I've moved the mic from in front of my amp, as he wasn't mixing what I wanted. His job is to produce the mix YOU all want, NOT what he thinks is good. I did it for a couple of years, and got into trouble for just that initially. You may also need to address the foldback, as if you're hearing a different mix there, it may fool you into thinking, for example, you're too loud, so play quieter. |
39,140 | I play acoustic guitar in a band with drums, electric bass, and electric guitar. I'm often told that I need to switch to electric because nobody can hear my guitar However, I like the sound of acoustic on pretty much all of our songs.
My current setup is an acoustic/electric into a Fishman Loudbox Mini, with a line out to the PA. It seems like this works in some situations, but not others, but the most specific comment I've gotten is "during the quiet times, when it's just the acoustic, you're fine, but when it gets loud, you get lost."
Is this just a characteristic of acoustic guitar in an otherwise electric band? Is it a problem with the mixing? Do I need a bigger amp? Could I be setting my EQ incorrectly? Should I switch to an electric guitar amp, for the more "cutting" sound (even if it does mean losing a lot of the characteristics of my lovely Taylor)?
**How can I get my acoustic guitar to consistently be heard in live performance?** | 2015/11/05 | [
"https://music.stackexchange.com/questions/39140",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/12245/"
] | I also play a Taylor Acoustic (614CE) in a band with electric guitar and electric bass and drums. I also play in an acoustic duo and play at open mics with other musicians with all sorts of instrumentation in the impromptu bands we form, and I play solo acoustic. So I would like to share what I have learned from personal experience. The most important part is at the end.
First I want to address those who have suggested switching to an electric guitar.
I don't think you want to do that at all. The acoustic guitar is really a totally different instrument than an electric guitar. Sure they have similarities, but the sound and playing style are as different as a banjo is to a guitar. If the acoustic guitar is an integral part of your band's sound, stick with the acoustic by all means. And don't go with an electric amp for your acoustic. That will rob your guitar of some of the rich, resonant sound that endears us to the acoustic guitar.
In my band, we play mostly songs that an acoustic guitar complements well. There are a few songs we play that are more authentically rendered with two electrics and no acoustic. For those songs I would use an electric. But I would never substitute an electric for an acoustic, if the acoustic sound was what I am looking for.
**Now let's talk about how your acoustic can be heard in your live performance.**
First of all, it is a very common problem getting an acoustic guitar to cut through the mix in a live setting with electric bass and electric guitar and drums. Turning it up louder does not help much. Part of the problem is the sound envelope of the electric instruments and the drums is such that the sound will be perceived as louder. The sound of an acoustic guitar blooms and swells as the strings cause the soundboard to vibrate which then causes a sympathetic vibration in the strings which goes back to the guitar and creates a certain resonance and overtones. The pickup in your acoustic is detecting these vibrations in the top. In the electric guitars, the pickup is responding to an electrical response between the string and the magnetic pickup - **so it's reacting directly to the strings**. The resulting sharper peak in amplitude will travel more rapidly to the ears of the audience and be perceived as louder - even though the volume may be set the same as measured independently.
**But there are several things you can do to overcome this common and natural phenomenon.**
**Start with EQ: You can EQ your guitar alone but then it is vital that you EQ the entire band as a whole. The guitar might sound great by itself, but be completely lost in the mix once the full band is playing. So you must EQ the band - not just the acoustic guitar.**
Let's start with the acoustic guitar. **If you have a Taylor with the Expression System, you can use a TRS to XLR cable to plug directly into the mixer. This will actually give you a higher output signal and more volume with a given setting on the mixer than using a standard guitar cable.** [Taylor ES System from Taylor Guitar](https://www.taylorguitars.com/sites/default/files/10_UnderstandingES.pdf) I am not sure why you need the Fishman Loudbox when you are using a PA. Another note on the Expression System. If you have a 2008 or newer Taylor with the ES, there is a switch inside the guitar that will turn off the body sensor(s). **Using only the neck pickup will reduce feedback with stage volumes.**
If you skip the Fishman Loudbox you would start with your volume, bass and treble controls in the neutral (on Taylor the detent) or middle position. Plug your guitar into a channel on the mixer and adjust the trim or input gain on that channel by turning it up until you can cause it to clip (red) by strumming hard, then back it down until it no longer clips. Now you have the input gain set and can adjust the channel volume and channel EQ from there.
If your mixer does not have individual channel EQ with at least 4 bands, you might want to consider a DI BOX with an equalizer such as the LR Baggs Parametric EQ DI box [LR Baggs Website PARA DI](http://www.lrbaggs.com/preamps/para-di-acoustic-preamp) or this one for less than $30. [7 Band Danelectro DJ14](http://www.guitarcenter.com/Danelectro/DJ14-Fish-and-Chips-7-Band-EQ-Pedal-1273887999666.gc)
. When you are playing with a band as you describe, you will EQ your acoustic guitar entirely differently than if you were playing acoustic solo.
**When playing with a bass guitar and a kick drum, there is no need or room for the low end of an acoustic guitar.** If you have a high pass filter (HP) on the guitar channel of your mixer you can use that to keep the lows in check - but otherwise, you want to roll off the lows with your EQ. I have found that most acoustic guitars sound better with the mids (600-800 Hz) pulled back. Try boosting the 1,000 – 3,500 Hz range slightly but not so much that the vocals can't find their place - and boosting the 3,500 – 12,000 Hz range. There is some trial and error involved. **Remember when you are EQing your acoustic for part of the overall band mix, it is not going to sound as good as you think it should by itself.**
So once you think your guitar EQ is dialed in, and the bassist, electric guitarist, and drummer have their EQ adjusted, and everyone's gain is adjusted properly, it's time to listen to the overall band as a whole. **Mixing for a full band isn’t about getting the best sound out of each instrument - but rather about getting the best overall sound from the band as a whole.**
Mixing the band will involve adjusting the relative volume of each instrument, and to the extent your equipment allows, further **tweaking the EQ of each instrument so they each occupy their intended and appropriate tonal bandwidth. The object is to achieve an ideal balance by blending and contrasting among the instruments.**
To get one instrument to stand out more in the mix, **start by cutting down the volume of the instruments (or vocals) that appear to be stepping on or drowning out the instrument that needs more prominence.** If you start compensating by turning up the instrument that needs to be heard, then some other instrument might need to be turned up and the volume wars start. During this band mixing process, it's always best to turn down than to turn up. **After the optimal mix is achieved, you can turn up the main volume without affecting the relative m**ix.
After adjusting relative volume of all the instruments in the mix, you will want to tweak the EQ settings. Obviously you want the bass and kick drum to occupy the lower end of the tonal spectrum, the cymbals and snare, the higher end, the vocals in the middle and the guitars somewhere between the cymbals and vocals. The cutting before boosting adage applies to EQ as well. Again, trial and error and a trained ear are a big part of this process.
**After getting the overall band mixed properly there are a few other things you can do to get better results on stage with your acoustic.**
**The monitor volumes need to be just loud enough for the musicians to hear what they need to hear, particularly your monitor.** If your monitor is too loud, you will get feedback and will have to dial back the volume of your guitar. Also, if you hear your guitar too loud in your monitor, you might subconsciously play softer, thereby reducing how much of your acoustic the audience hears.
Another idea is to use a simple **20db boost pedal** with your guitar for those parts of songs where the entire band is playing/singing really loud and you want your guitar to be heard. Of course you would set the volume control to give you far less than 20db. Here is a link to information about one that is geared towards use with an acoustic electric guitar. [Signal Boost Pedal for acoustic guitar](http://www.modtone.net/signal-booster.html)
If you are using phosphor bronze guitar strings, you might switch to **80/20 bronze** for playing with the band. It will give your acoustic a brighter more present tone and may help it cut through better. **Obviously old dull strings will not sound as good as fresh strings.**
Okay, now that I have covered the things you can do to get your acoustic heard **as much as possible** in the mix - **we still have the inherent problem discussed earlier that brings us back to the reality that no matter what you do - an acoustic guitar will never be heard over an electric guitar in a band situation like yours.**
**So what now?** The next part of the puzzle was mentioned in **Todd Wilcox's** excellent answer - **arrangement and performance dynamics.**
The only time an acoustic guitar is really going to shine on a stage with all the other instruments in your band, is when it is playing almost by itself. **There may be some parts of some songs where you want the acoustic guitar to be featured. In those cases, the other instruments need to either drop out completely, or play very softly at much lower volumes.**
The other thing that will help if your acoustic is the primary rhythm guitar, is to **have the electric guitar play around you instead of on top of you**. This means while you are chunking out the beefy acoustic chord progression that carries the verses or chorus, the electric guitar should just play fills and single note runs almost between chords. When it comes time for the lead solo, that's when the electric should be drowning out the acoustic.
I know that's a tall order for many electric lead guitar players. Some of them seem to want to hog the spotlight. **But if your electric guitar player is playing too much all the time, that may be the biggest part of your problem of not being heard on your acoustic.** A good guitar player knows when to play and more importantly **when not to play**. **So arrangement and performance dynamics should facilitate the acoustic and electric guitars working TOGETHER and complementing one another - not competing with one another (the electric will always win)!**
I hope some of this helps. Good luck ... and rock on brother! | Agreed - a well played acoustic guitar often sounds better for rhythm in a band situation. If it's being DI'd from your little amp into the P.A., then it should come through the mix properly. If your mixer guy is doing it right, he should be able to remix for the louder numbers. It may just be that it's the Freddie Green syndrome. He played rhythm guitar, and was thought of as one of the best. He could hardly be heard, but when he stopped playing, it was noticed. Subtlety, I think it's called. Don't rely on others for comments - get a recording to hear for yourself. One from where the audience is, not off the P.A. It may be that the mix engineer has his own ideas of how you should sound. I lost count of the number of times I've moved the mic from in front of my amp, as he wasn't mixing what I wanted. His job is to produce the mix YOU all want, NOT what he thinks is good. I did it for a couple of years, and got into trouble for just that initially. You may also need to address the foldback, as if you're hearing a different mix there, it may fool you into thinking, for example, you're too loud, so play quieter. |
39,140 | I play acoustic guitar in a band with drums, electric bass, and electric guitar. I'm often told that I need to switch to electric because nobody can hear my guitar However, I like the sound of acoustic on pretty much all of our songs.
My current setup is an acoustic/electric into a Fishman Loudbox Mini, with a line out to the PA. It seems like this works in some situations, but not others, but the most specific comment I've gotten is "during the quiet times, when it's just the acoustic, you're fine, but when it gets loud, you get lost."
Is this just a characteristic of acoustic guitar in an otherwise electric band? Is it a problem with the mixing? Do I need a bigger amp? Could I be setting my EQ incorrectly? Should I switch to an electric guitar amp, for the more "cutting" sound (even if it does mean losing a lot of the characteristics of my lovely Taylor)?
**How can I get my acoustic guitar to consistently be heard in live performance?** | 2015/11/05 | [
"https://music.stackexchange.com/questions/39140",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/12245/"
] | I also play a Taylor Acoustic (614CE) in a band with electric guitar and electric bass and drums. I also play in an acoustic duo and play at open mics with other musicians with all sorts of instrumentation in the impromptu bands we form, and I play solo acoustic. So I would like to share what I have learned from personal experience. The most important part is at the end.
First I want to address those who have suggested switching to an electric guitar.
I don't think you want to do that at all. The acoustic guitar is really a totally different instrument than an electric guitar. Sure they have similarities, but the sound and playing style are as different as a banjo is to a guitar. If the acoustic guitar is an integral part of your band's sound, stick with the acoustic by all means. And don't go with an electric amp for your acoustic. That will rob your guitar of some of the rich, resonant sound that endears us to the acoustic guitar.
In my band, we play mostly songs that an acoustic guitar complements well. There are a few songs we play that are more authentically rendered with two electrics and no acoustic. For those songs I would use an electric. But I would never substitute an electric for an acoustic, if the acoustic sound was what I am looking for.
**Now let's talk about how your acoustic can be heard in your live performance.**
First of all, it is a very common problem getting an acoustic guitar to cut through the mix in a live setting with electric bass and electric guitar and drums. Turning it up louder does not help much. Part of the problem is the sound envelope of the electric instruments and the drums is such that the sound will be perceived as louder. The sound of an acoustic guitar blooms and swells as the strings cause the soundboard to vibrate which then causes a sympathetic vibration in the strings which goes back to the guitar and creates a certain resonance and overtones. The pickup in your acoustic is detecting these vibrations in the top. In the electric guitars, the pickup is responding to an electrical response between the string and the magnetic pickup - **so it's reacting directly to the strings**. The resulting sharper peak in amplitude will travel more rapidly to the ears of the audience and be perceived as louder - even though the volume may be set the same as measured independently.
**But there are several things you can do to overcome this common and natural phenomenon.**
**Start with EQ: You can EQ your guitar alone but then it is vital that you EQ the entire band as a whole. The guitar might sound great by itself, but be completely lost in the mix once the full band is playing. So you must EQ the band - not just the acoustic guitar.**
Let's start with the acoustic guitar. **If you have a Taylor with the Expression System, you can use a TRS to XLR cable to plug directly into the mixer. This will actually give you a higher output signal and more volume with a given setting on the mixer than using a standard guitar cable.** [Taylor ES System from Taylor Guitar](https://www.taylorguitars.com/sites/default/files/10_UnderstandingES.pdf) I am not sure why you need the Fishman Loudbox when you are using a PA. Another note on the Expression System. If you have a 2008 or newer Taylor with the ES, there is a switch inside the guitar that will turn off the body sensor(s). **Using only the neck pickup will reduce feedback with stage volumes.**
If you skip the Fishman Loudbox you would start with your volume, bass and treble controls in the neutral (on Taylor the detent) or middle position. Plug your guitar into a channel on the mixer and adjust the trim or input gain on that channel by turning it up until you can cause it to clip (red) by strumming hard, then back it down until it no longer clips. Now you have the input gain set and can adjust the channel volume and channel EQ from there.
If your mixer does not have individual channel EQ with at least 4 bands, you might want to consider a DI BOX with an equalizer such as the LR Baggs Parametric EQ DI box [LR Baggs Website PARA DI](http://www.lrbaggs.com/preamps/para-di-acoustic-preamp) or this one for less than $30. [7 Band Danelectro DJ14](http://www.guitarcenter.com/Danelectro/DJ14-Fish-and-Chips-7-Band-EQ-Pedal-1273887999666.gc)
. When you are playing with a band as you describe, you will EQ your acoustic guitar entirely differently than if you were playing acoustic solo.
**When playing with a bass guitar and a kick drum, there is no need or room for the low end of an acoustic guitar.** If you have a high pass filter (HP) on the guitar channel of your mixer you can use that to keep the lows in check - but otherwise, you want to roll off the lows with your EQ. I have found that most acoustic guitars sound better with the mids (600-800 Hz) pulled back. Try boosting the 1,000 – 3,500 Hz range slightly but not so much that the vocals can't find their place - and boosting the 3,500 – 12,000 Hz range. There is some trial and error involved. **Remember when you are EQing your acoustic for part of the overall band mix, it is not going to sound as good as you think it should by itself.**
So once you think your guitar EQ is dialed in, and the bassist, electric guitarist, and drummer have their EQ adjusted, and everyone's gain is adjusted properly, it's time to listen to the overall band as a whole. **Mixing for a full band isn’t about getting the best sound out of each instrument - but rather about getting the best overall sound from the band as a whole.**
Mixing the band will involve adjusting the relative volume of each instrument, and to the extent your equipment allows, further **tweaking the EQ of each instrument so they each occupy their intended and appropriate tonal bandwidth. The object is to achieve an ideal balance by blending and contrasting among the instruments.**
To get one instrument to stand out more in the mix, **start by cutting down the volume of the instruments (or vocals) that appear to be stepping on or drowning out the instrument that needs more prominence.** If you start compensating by turning up the instrument that needs to be heard, then some other instrument might need to be turned up and the volume wars start. During this band mixing process, it's always best to turn down than to turn up. **After the optimal mix is achieved, you can turn up the main volume without affecting the relative m**ix.
After adjusting relative volume of all the instruments in the mix, you will want to tweak the EQ settings. Obviously you want the bass and kick drum to occupy the lower end of the tonal spectrum, the cymbals and snare, the higher end, the vocals in the middle and the guitars somewhere between the cymbals and vocals. The cutting before boosting adage applies to EQ as well. Again, trial and error and a trained ear are a big part of this process.
**After getting the overall band mixed properly there are a few other things you can do to get better results on stage with your acoustic.**
**The monitor volumes need to be just loud enough for the musicians to hear what they need to hear, particularly your monitor.** If your monitor is too loud, you will get feedback and will have to dial back the volume of your guitar. Also, if you hear your guitar too loud in your monitor, you might subconsciously play softer, thereby reducing how much of your acoustic the audience hears.
Another idea is to use a simple **20db boost pedal** with your guitar for those parts of songs where the entire band is playing/singing really loud and you want your guitar to be heard. Of course you would set the volume control to give you far less than 20db. Here is a link to information about one that is geared towards use with an acoustic electric guitar. [Signal Boost Pedal for acoustic guitar](http://www.modtone.net/signal-booster.html)
If you are using phosphor bronze guitar strings, you might switch to **80/20 bronze** for playing with the band. It will give your acoustic a brighter more present tone and may help it cut through better. **Obviously old dull strings will not sound as good as fresh strings.**
Okay, now that I have covered the things you can do to get your acoustic heard **as much as possible** in the mix - **we still have the inherent problem discussed earlier that brings us back to the reality that no matter what you do - an acoustic guitar will never be heard over an electric guitar in a band situation like yours.**
**So what now?** The next part of the puzzle was mentioned in **Todd Wilcox's** excellent answer - **arrangement and performance dynamics.**
The only time an acoustic guitar is really going to shine on a stage with all the other instruments in your band, is when it is playing almost by itself. **There may be some parts of some songs where you want the acoustic guitar to be featured. In those cases, the other instruments need to either drop out completely, or play very softly at much lower volumes.**
The other thing that will help if your acoustic is the primary rhythm guitar, is to **have the electric guitar play around you instead of on top of you**. This means while you are chunking out the beefy acoustic chord progression that carries the verses or chorus, the electric guitar should just play fills and single note runs almost between chords. When it comes time for the lead solo, that's when the electric should be drowning out the acoustic.
I know that's a tall order for many electric lead guitar players. Some of them seem to want to hog the spotlight. **But if your electric guitar player is playing too much all the time, that may be the biggest part of your problem of not being heard on your acoustic.** A good guitar player knows when to play and more importantly **when not to play**. **So arrangement and performance dynamics should facilitate the acoustic and electric guitars working TOGETHER and complementing one another - not competing with one another (the electric will always win)!**
I hope some of this helps. Good luck ... and rock on brother! | In a lot of mixes, it's normal and even intentional for the acoustic guitar(s) to get hidden behind the electric guitars and other instruments during the loud parts. If you listen to the Led Zeppelin songs that have both acoustic and electric guitars, it can sound like the acoustic track is muted during the "loud" parts, but it's usually actually sitting there in the background for the whole song.
The people saying they can't hear your guitar are probably people who specifically like your playing, like acoustic guitars, and/or like you, since they are not merely listening to the whole band as one unit.
Here are some thoughts:
* You might want or need a [sound hole cover](http://www.planetwaves.com/pwProductDetail.Page?ActiveID=4115&productid=497&productname=Screeching_Halt) to reduce possible feedback from bringing up the levels on your acoustic.
* With my sound engineer hat on, I prefer an active DI feed straight from the acoustic output over the DI out of an acoustic amp. Both as an engineer and as an acoustic player, I would bring my own DI to make sure I have one that I know how to use. The [Radial J48](http://www.radialeng.com/j48.php) and [Countryman Type 85](http://www.countryman.com/type-85-direct-box) are good examples of active DIs for acoustic.
* If you don't want the acoustic to be behind the other instruments during loud sections (check with your bandmates regarding the overall sound you all want), make sure you are clear about that with any sound engineers you are working with.
* The mix starts with the arrangement and the performance. Almost no engineering or equipment can make the acoustic heard during a loud chorus with a distorted electric guitar part, open hi-hat eighth notes, pounding bass line, and passionate vocals. If the whole band agrees on how the acoustic part should sit in the mix, then everyone will need to make sure they are leaving the necessary space (this applies to all the instruments, of course).
* It's really common for some instruments, including acoustic guitar, to get lost in the mix, and many times it's ok and even desireable. Take all audience comments with a grain of salt - even the positive ones. Actually, even negative comments are positive since it means the person listened to you and thought about your playing and had a strong enough feeling about it they had to come talk to you. Assuming the you and the band are ok with the acoustic getting lost sometimes, come up with a few ready responses to this kind of audience feedback that is validating so you are acknowledging the person giving advice even if you don't plan to follow it.
* If you use an electric guitar amp, it will make your acoustic sound like a weird sounding electric guitar. I worked with a band that made this their signature sound - outside of that I wouldn't normally consider it a good sound. |
46,278,853 | I have been going through a tutorial on Spring boot and there I learnt how to stop jackson from converting dates to **timestamp**. eg :
```
{"birthDate":1505736233603} //before
{"birthDate":"2017-09-18T12:04:27.345+0000"}//after
```
by writing
```
spring.jackson.serialization.write-dates-as-timestamps=false
```
in **application.properties.**
How do I do the same for SpringMVC, ofcourse there is no **application.properties** in **SpringMVC** | 2017/09/18 | [
"https://Stackoverflow.com/questions/46278853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960619/"
] | You'll have to configure the Spring Bean in charge of creating the JSON your service is returning.
First off, you need to define the Jackson Object Mapper Bean that your converter will use to create the JSON:
```
<bean class="com.fasterxml.jackson.databind.ObjectMapper" id="objectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"/>
</bean>
</property>
</bean>
```
(NOTE that you can define the dateFormat that you need).
Then, you need to inject this objectMapper bean into the JSON Message converter:
```
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
```
As you can see, I'm using the "mvc" namespace ("<http://www.springframework.org/schema/mvc>") to define the MVC beans.
If you're using Annotations rather than XML configuration, you can do exactly the same by defining the next Configuration class (or adapt it to you code :) )
```
@EnableWebMvc
@Configuration
@ComponentScan({ "com.yourorg.app" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
messageConverters.add(new createJsonHttpMessageConverter());
super.configureMessageConverters(converters);
}
private HttpMessageConverter<Object> createJsonHttpMessageConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
MappingJackson2HttpMessageConverter jsonConverter =
new MappingJackson2HttpMessageConverter();
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}
}
```
Hope this helps :) | if you have access to the ObjectMapper, you can also set it as a property programmatically
```
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new ISO8601DateFormat());
``` |
46,278,853 | I have been going through a tutorial on Spring boot and there I learnt how to stop jackson from converting dates to **timestamp**. eg :
```
{"birthDate":1505736233603} //before
{"birthDate":"2017-09-18T12:04:27.345+0000"}//after
```
by writing
```
spring.jackson.serialization.write-dates-as-timestamps=false
```
in **application.properties.**
How do I do the same for SpringMVC, ofcourse there is no **application.properties** in **SpringMVC** | 2017/09/18 | [
"https://Stackoverflow.com/questions/46278853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960619/"
] | You'll have to configure the Spring Bean in charge of creating the JSON your service is returning.
First off, you need to define the Jackson Object Mapper Bean that your converter will use to create the JSON:
```
<bean class="com.fasterxml.jackson.databind.ObjectMapper" id="objectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"/>
</bean>
</property>
</bean>
```
(NOTE that you can define the dateFormat that you need).
Then, you need to inject this objectMapper bean into the JSON Message converter:
```
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
```
As you can see, I'm using the "mvc" namespace ("<http://www.springframework.org/schema/mvc>") to define the MVC beans.
If you're using Annotations rather than XML configuration, you can do exactly the same by defining the next Configuration class (or adapt it to you code :) )
```
@EnableWebMvc
@Configuration
@ComponentScan({ "com.yourorg.app" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
messageConverters.add(new createJsonHttpMessageConverter());
super.configureMessageConverters(converters);
}
private HttpMessageConverter<Object> createJsonHttpMessageConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
MappingJackson2HttpMessageConverter jsonConverter =
new MappingJackson2HttpMessageConverter();
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}
}
```
Hope this helps :) | Another way is to configure the `MessageConverter` after they have been populated/configured by the framework:
```java
@EnableWebMvc
@Configuration
public class AppConfiguration implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof AbstractJackson2HttpMessageConverter) {
AbstractJackson2HttpMessageConverter jacksonconverter = (AbstractJackson2HttpMessageConverter) converter;
jacksonconverter.getObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
}
}
```
Moreover, this code should also apply to `SMILE` because `MappingJackson2SmileHttpMessageConverter` extends `AbstractJackson2HttpMessageConverter`. |
46,278,853 | I have been going through a tutorial on Spring boot and there I learnt how to stop jackson from converting dates to **timestamp**. eg :
```
{"birthDate":1505736233603} //before
{"birthDate":"2017-09-18T12:04:27.345+0000"}//after
```
by writing
```
spring.jackson.serialization.write-dates-as-timestamps=false
```
in **application.properties.**
How do I do the same for SpringMVC, ofcourse there is no **application.properties** in **SpringMVC** | 2017/09/18 | [
"https://Stackoverflow.com/questions/46278853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960619/"
] | Another way is to configure the `MessageConverter` after they have been populated/configured by the framework:
```java
@EnableWebMvc
@Configuration
public class AppConfiguration implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof AbstractJackson2HttpMessageConverter) {
AbstractJackson2HttpMessageConverter jacksonconverter = (AbstractJackson2HttpMessageConverter) converter;
jacksonconverter.getObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
}
}
```
Moreover, this code should also apply to `SMILE` because `MappingJackson2SmileHttpMessageConverter` extends `AbstractJackson2HttpMessageConverter`. | if you have access to the ObjectMapper, you can also set it as a property programmatically
```
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new ISO8601DateFormat());
``` |
350,100 | I have a new install of Debian 8 ("Jessie") and want to install the `firewalld` package, but APT can't find it. This may be related to the fact that I didn't specify a mirror during installation, but as far as I can tell, I've made the appropriate configurations.
`firewalld` is located on the mirror here:
`http://ftp.us.debian.org/debian/pool/main/f/firewalld/`
That mirror is in my `/etc/apt/sources.list` file:
```
deb http://ftp.us.debian.org/debian/ jessie-updates main contrib
deb-src http://ftp.us.debian.org/debian/ jessie-updates main contrib
```
I've updated the available packages:
`# apt update`
APT still can't find it:
```
# apt search firewalld
Sorting... Done
Full Text Search... Done
```
Why can't it find the package? | 2017/03/08 | [
"https://unix.stackexchange.com/questions/350100",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/219868/"
] | You need to have the full Jessie repository in your `sources.list`; you should have at least
```
deb http://ftp.us.debian.org/debian jessie main
deb http://ftp.us.debian.org/debian jessie-updates main
deb http://security.debian.org jessie/updates main
```
(you can add `contrib` if you want, and the corresponding `deb-src` lines if you want to be able to download source code for the packages too).
Check your `sources.list` contains at least those three lines, then run
```
apt update
apt install firewalld
```
The `jessie-updates` repository only contains updates to Jessie, it doesn’t contain the packages which were part of the original Jessie release and haven't been updated since. See [What is the difference between the "jessie" and "jessie-updates" distributions in /etc/apt/sources.list?](https://unix.stackexchange.com/q/210394/86440) for more information. | "Installing firewalld package on Debian 8 (Jessie) is as easy as running the following command on terminal:"
>
> sudo apt-get update
>
>
> sudo apt-get install firewalld
>
>
>
From <https://www.howtoinstall.co/en/debian/jessie/firewalld> |
65,492,839 | I am attempting to deploy a resource with Terraform using an ARM template. I will give some simple sample code below that demonstrates the issue. I realize the code below is deploying a storage account and can be done in Terraform without an ARM template, but I am just providing a piece of simple code to demonstrate the problem. My real code is deploying a SQL Managed Instance which is much more complicated and likely just confuses the question.
Here is the main.tf:
```
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "2.41.0"
}
}
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "resourcegroup" {
location = "North Central US"
name = "test"
}
resource "azurerm_resource_group_template_deployment" "deployment" {
name = "test-${formatdate("YYYYMMDDhhmmss", timestamp())}"
resource_group_name = azurerm_resource_group.resourcegroup.name
deployment_mode = "Incremental"
template_content = file("template.json")
parameters_content = templatefile("parameters.json",
{
name = "vwtuvnpplzgelqey"
supportsHttpsTrafficOnly = true
}
)
}
```
Here is the ARM template.json file:
```
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"name": {
"type": "string"
},
"supportsHttpsTrafficOnly": {
"type": "bool"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-04-01",
"name": "[parameters('name')]",
"location": "northcentralus",
"sku": {
"name": "Standard_LRS"
},
"kind": "StorageV2",
"properties": {
"supportsHttpsTrafficOnly": "[parameters('supportsHttpsTrafficOnly')]"
}
}
]
}
```
Here is the ARM parameters.json file:
```
{
"name": {
"value": "${name}"
},
"supportsHttpsTrafficOnly": {
"value": "${supportsHttpsTrafficOnly}"
}
}
```
If I run terraform apply on this with just the `name` as a parameter and hard-code `supportsHttpsTrafficOnly` to a true value (e.g. `"supportsHttpsTrafficOnly": true`), it works perfectly and the storage account is successfully deployed. As soon as I change it to use the parameter for supportsHttpsTrafficOnly, it fails with the following error:
```
: Code="InvalidTemplate" Message="Deployment template validation failed: 'Template parameter JToken type is not valid. Expected 'Boolean'. Actual 'String'. Please see https://aka.ms/resource-manager-parameter-files for usage details.'." AdditionalInfo=[{"info":{"lineNumber":1,"linePosition":213,"path":"properties.template.parameters.supportsHttpsTrafficOnly"},"type":"TemplateViolation"}]
```
This error indicates that the value for supportsHttpsTrafficOnly is a string when it should be a boolean. I don't understand this error as I am clearly defining the type as bool in the template.json file.
What am I missing so that the value is interpreted as a bool value instead of a string? | 2020/12/29 | [
"https://Stackoverflow.com/questions/65492839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636887/"
] | It turns out this is actually an easy fix, if not an obvious one.
Apparently all parameters need to be defined as string and then use the ARM template conversion functions to convert to the correct type.
In the template.json, we would have this in the parameters section:
```
“supportsHttpsTrafficOnly”: {
“type”: “string”
}
```
And then in the resources section, convert the string to a boolean using a template conversion:
```
"properties": {
"supportsHttpsTrafficOnly": "[bool(parameters('supportsHttpsTrafficOnly'))]"
}
```
Then finally in main.tf, pass the value as a string:
```
parameters_content = templatefile("parameters.json",
{
name = "vwtuvnpplzgelqey"
supportsHttpsTrafficOnly = "true"
}
``` | Per documentation: <https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-syntax#data-types>
>
> When specifying boolean and integer values in your template, don't
> surround the value with quotation marks. Start and end string values
> with double quotation marks.
>
>
>
What you have in your code is `"value": "${supportsHttpsTrafficOnly}"`. This probably interpreted as `"value": "true"` when you pass a var into it.
Switching to `"value": ${supportsHttpsTrafficOnly}` should fix your issue.
But if I were you, I would go for the heredoc way, which is also the one used in the example of in the provider docs: <https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/resource_group_template_deployment>
So use:
```
...
template_content = <<TEMPLATE
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {},
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
...
TEMPLATE
}
```
instead of using a different .json file. |
35,102,011 | Can I change the pitch of the voice in AVSpeechSynthesizer or putting any effects on the output voice from it so it could sound differently? | 2016/01/30 | [
"https://Stackoverflow.com/questions/35102011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes, you can change the **pitch** and the **rate** of the spoken sentence.
The `AVSpeechUtterance` class has two relevant properties:
* `pitchMultiplier: Float` (value between **0.5** (lowest pitch) to **2.0** (highest pitch)). The default pitch is **1.0**.
* `rate: Float` (value between two constants: `AVSpeechUtteranceMinimumSpeechRate` (the slowest rate of speech) and `AVSpeechUtteranceMaximumSpeechRate` (the highest rate of speech).
When you create your `AVSpeechUtterance`, simply set these properties appropriately before getting your `AVSpeechSynthesizer` to speak the utterance.
Note: You can also change the **voice** (accent) of `AVSpeechUtterance`.
I hope this helps. Let me know if anything I said was unclear. | The default pitch is 0.5.
AVSpeechUtteranceMinimumSpeechRate is 0.0
AVSpeechUtteranceMaximumSpeechRate is 1.0 (the highest rate of speech).
```
AVSpeechSynthesizer *synthesizer= [[AVSpeechSynthesizer alloc]init];
synthesizer.delegate=self;
AVSpeechUtterance *utterances =
[AVSpeechUtterance speechUtteranceWithString:text];utterances.voice
= [AVSpeechSynthesisVoice voiceWithLanguage:@"de-DE"];//change voice utterances.rate=0.5;//default rate
[synthesizer
speakUtterance:utterances];
``` |
41,421,670 | I am using a subtitle cell in a UITableView. I have set the following in `viewDidLoad` to make the row height automatically expand:
```
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
```
I have also set the title and subtitle of the cell to word wrap:
```
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.lineBreakMode = .byWordWrapping
```
When I type in the title, all is good. But the subtitle does not expand the row. Is there something else I need to do to get the subtitle to increase the row height?
 | 2017/01/02 | [
"https://Stackoverflow.com/questions/41421670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767270/"
] | By using this code from <https://stackoverflow.com/a/40168001/4045472> and define the cell as:
```
class MyTableViewCell: UITableViewCell {
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.layoutIfNeeded()
var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
if let textLabel = self.textLabel, let detailTextLabel = self.detailTextLabel {
let detailHeight = detailTextLabel.frame.size.height
if detailTextLabel.frame.origin.x > textLabel.frame.origin.x { // style = Value1 or Value2
let textHeight = textLabel.frame.size.height
if (detailHeight > textHeight) {
size.height += detailHeight - textHeight
}
} else { // style = Subtitle, so always add subtitle height
size.height += detailHeight
}
}
return size
}
}
```
And change the cell custom class in storyboard to MyTableViewCell will set the correct size automatically.
In the table view datasource's tableView:cellForRow: function, after set the labels' text, call `cell.setNeedsLayout()` to force it adjust layout. | You need to set constraints so that the cell can size automatically based on the size of the label. Here is a tutorial on dynamic cells. <https://www.raywenderlich.com/129059/self-sizing-table-view-cells> |
41,421,670 | I am using a subtitle cell in a UITableView. I have set the following in `viewDidLoad` to make the row height automatically expand:
```
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
```
I have also set the title and subtitle of the cell to word wrap:
```
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.lineBreakMode = .byWordWrapping
```
When I type in the title, all is good. But the subtitle does not expand the row. Is there something else I need to do to get the subtitle to increase the row height?
 | 2017/01/02 | [
"https://Stackoverflow.com/questions/41421670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767270/"
] | You should take one lable and give constrain like that,
[](https://i.stack.imgur.com/MXvbd.png)
After that, write this two delegate method of tableview.
```
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
```
So, tableview height increse as per lable text size. | You need to set constraints so that the cell can size automatically based on the size of the label. Here is a tutorial on dynamic cells. <https://www.raywenderlich.com/129059/self-sizing-table-view-cells> |
71,503,416 | It should be ok to add all the variables as global inside the function? All the other functions will receive them? I did a short test and it should work. Should I need to add Get-Variable -ValueOnly...?
```
$ReleaseVersion = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).ReleaseVersion
$Sourceversion = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).Sourceversion
$LinkForVersion = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).LinkForVersion
$VersionNumber = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).VersionNumber
$buildver = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).buildver
$PipelineID = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).PipelineID
$xmlFilePath = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).xmlFilePath
$ReleaseBuildVer = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).ReleaseBuildVer
Set-Variable -Name "ReleaseVersion" -Value $ReleaseVersion -Scope global
Set-Variable -Name "Sourceversion" -Value $Sourceversion -Scope global
Set-Variable -Name "LinkForVersion" -Value $LinkForVersion -Scope global
Set-Variable -Name "VersionNumber" -Value $VersionNumber -Scope global
Set-Variable -Name "buildver" -Value $buildver -Scope global
Set-Variable -Name "PipelineID" -Value $PipelineID -Scope global
Set-Variable -Name "xmlFilePath" -Value $xmlFilePath -Scope global
Set-Variable -Name "ReleaseBuildVer" -Value $ReleaseBuildVer -Scope global
}
```
I have a script that read from excel collect files according to a column, Before the running I need to define 4 variables, the issue is that I need to run it for several versions. That means that for each run I need to leave active 4 variables and the rest should be in comment (#) and I do it manually (need to add 12 times #
There is a smart way to choose all the 4 variables per version?
I will give an example:
[](https://i.stack.imgur.com/FGhLm.png)
Each time only one set is enabled (According to version I want to work on)
The using of those parameters are:
```
Add-VSTeamWorkItem -ProjectName "Client-Server" -Title "[Side VIP] [$VersionNumber]"
$Versionlocationforpatches = "$Sourceversion\Installer\Patches"
$Versionlocationforcabs = "$Sourceversion\Installer"
Add-VSTeamBuild -ProjectName "Client-Server" -BuildDefinitionId $PipelineID
function RenameVerFile ([string] $buildver)
{
$DefaultFile = Get-ChildItem $Sourceversion | Where-Object {$_.Name -like "BuildVer.txt"}
Clear-Content $DefaultFile.FullName -Force
$Newcontent = Add-Content $DefaultFile.FullName -Value ($buildver + "." + (Get-Random))
}
```
Some of them are using in other places
Now I have something like this and I am very happy but I want to display the user a menu like:
For version 8.5.34 choose 1, Without insert manually the number
[](https://i.stack.imgur.com/Lq0wz.png)
I hope this will do the job
```
do {$VersionToUse = $Versions.buildver | Out-Gridview -Title "Choose version" -PassThru } while ($Versions.buildver -notcontains $VersionToUse)
``` | 2022/03/16 | [
"https://Stackoverflow.com/questions/71503416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18253602/"
] | Edit: Totally Changed this answer to include latest information
User of the script will now see versions to select and then enter version number to be used. your four variables are then filled with the relevant data.
```
$SharedDriveFolderPath= "\\Test\xxx" # This is just for me to test - you have your own data somewhere
$Versions = @()
$Versions += "VersionNumber;Sourceversion;PipelineID;buildvers;"
$Versions += "8.5.34;$SharedDriveFolderPath\Versions\8.5.34.31;18710;8.5.34.31"
$Versions += "8.5.35;$SharedDriveFolderPath\Versions\8.5.34.35;18713;8.5.34.35"
$Versions = $Versions | ConvertFrom-CSV -Del ";"
do {$VersionToUse = ($Versions | Out-GridView -OutputMode Single -Title "Select version to use").VersionNumber} while (-not $VersionToUse)
$VersionNumber = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).VersionNumber
$Sourceversion = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).Sourceversion
$PipelineID = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).PipelineID
$buildvers = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).buildvers
```
Take this Code to replace your version lines (the ones you posted here as screenshot example)
Alternative as json if you prefer that:
```
$SharedDriveFolderPath= "\\Test\xxx" # This is just for me to test - you have your own data somewhere
$Versions = @"
[
{
"VersionNumber": "8.5.34",
"Sourceversion": "$($SharedDriveFolderPath -replace "\\","\\")\\Versions\\8.5.34.31",
"PipelineID": "18710",
"buildvers": "8.5.34.31"
},
{
"VersionNumber": "8.5.35",
"Sourceversion": "$($SharedDriveFolderPath -replace "\\","\\")\\Versions\\8.5.34.35",
"PipelineID": "18713",
"buildvers": "8.5.34.35"
}
]
"@ | ConvertFrom-Json
do {$VersionToUse = ($Versions | Out-GridView -OutputMode Single -Title "Select version to use").VersionNumber} while (-not $VersionToUse)
$VersionNumber = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).VersionNumber
$Sourceversion = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).Sourceversion
$PipelineID = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).PipelineID
$buildvers = ($Versions | where {$_.VersionNumber -eq $VersionToUse}).buildvers
```
Replace the line starting with "do" with the following code to get another way of selection if you don't like the gridview
```
$i = 0; foreach ($Version in $Versions.VersionNumber) {$i++; "[$i] $Version"; }; $VersionToUse = ($Versions[$(do {"Enter ID of Version to use"; $id = Read-Host} while (-not ($id -le $Versions.count -and $id -gt 0));$id - 1)]).VersionNumber
``` | You could store and choose it that way with a hashtable:
```
$myVars = @{}
$myVars.Version2000 = @{"Path"="c:\";"Title"="MySensitiveData"}
$myVars.Version2000.Path
$myVars.Version2000.Title
```
it could then look like
```
PS C:\> $myVars = @{}
PS C:\> $myVars.Version2000 = @{
>> "Path"="c:\Prog2000"
>> "Title"="MySensitiveData"
>> "Var3"="Value3"
>> "Var4"="value4"
>> }
PS C:\> $myVars.Version2013 = @{
>> "Path"="c:\Prog2013"
>> "Title"="MySensitiveData"
>> "Var3"="Value3"
>> "Var4"="value4"
>> }
PS C:\> $myVars.Version2000
Name Value
---- -----
Var4 value4
Path c:\
Var3 Value3
Title MySensitiveData
PS C:\> $myVars.Version2000.Path
c:\
```
EDIT: Added a new answer as more information came in OP |
27,512,122 | I have a TextBoxFor that is set to read only and it currently holds a person's last name. What I now need to do is add to it so that the person's suffix (II, III, Sr., Jr., etc) shows in the text box next to their last name.
This is what I have so far with just the last name. I can't figure out how to add the suffix portion to it (m.Person.Suffix). Everything I have tried has caused an error.
```
<div class="control-group">
<label>Last Name</label>
<div class="controls">
@Html.TextBoxFor(m => m.Person.LastName, new { @readonly = "readonly" })
</div>
</div>
``` | 2014/12/16 | [
"https://Stackoverflow.com/questions/27512122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3885497/"
] | One possibility to do this, if this will always be readonly, would be adding this to your model:
```
public string LastNameWithSuffix
{
get { return String.Format("{0} {1}", Person.LastName, Person.Suffix); }
}
```
Then you can just change your code in the textbox to reference m.LastNameWithSuffix directly:
```
<div class="control-group">
<label>Last Name</label>
<div class="controls">
@Html.TextBoxFor(m => m.LastNameWithSuffix, new { @readonly = "readonly" })
</div>
</div>
``` | I believe this may only be achieved through using a viewmodel. In your controller, instead of passing the original data model, you would pass the viewmodel, (used in your view) and one the entities of the viewmodel would contain the combination.
```
public class ViewModel
{
public string LastName {get; set;}
public string Suffix {get; set;}
public string Combo {get; set;
//rest of data needed for view
}
```
This would be my way of approaching this, although there are possibly other methods. |
22,001,200 | I'm starting to use IntelliJ IDEA 13 Ultimate Edition and was wonder if it had a searchable tabular view of maven dependencies for a project like Eclipse does.
For example, in Eclipse I can check my project's maven dependencies by going to its pom and then clicking on the "Dependencies Hierarchy" tab. From there, I can search for the existence of specific dependencies and have the ability to view the POMs of said dependencies.
All I've found so far in IntelliJ is the diagram view of dependencies, which can get really cluttered when you have a lot of dependencies and doesn't really allow me to view POMs or search.
Any ideas? | 2014/02/24 | [
"https://Stackoverflow.com/questions/22001200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623941/"
] | Try [Maven Helper plugin](http://plugins.jetbrains.com/plugin/7179?pr=idea_ce): once you install it, every POM file gets a tab for "Dependency Analyzer" which also includes a search bar.
If you need something more, report an issue. But it should be easy to implement it yourself and send a pull request. | Firstly, you have the maven plugin enabled, and you can build your project in IntelliJ via the `Maven Projects` pane (top right) ?
Now, you can see all your maven dependencies in a *linear* list in the `Project` pane (top left), underneath your source code. You can also type a search-string (e.g. "apache" will highlight all your `org.apache.x.y.z` dependencies.
For a **structural** view of the dependencies, you can start with one of the maven modules in the `Maven Projects` pane. Go to `My Module` -> `dependencies` and browse the tree. You can go to the pom of any of the dependencies in this tree with `f4`.
From within any pom, control-clicking on another artifactId will navigate to that pom, if available.
I hope this helps! |
7,427,564 | So far i have created a search box, which searches the primary key of my database.
How can i modify my php query to search multiple values in my database.
eg: If i search the name of the car instead of the VIN (primary key) it will show all the results matching the search value.
This
```
$query = ("SELECT * FROM cars
WHERE VIN='$VIN'");
```
This is my form :
```
<form name="search" action="http://www.deakin.edu.au/~sjrem/SIT104_3/cars.php" method="post">
<h2> Search for a car of your choice </h2>
<table border="0">
<tr>
<td><input type="text" name="VIN" /> </td>
</tr>
</table>
<p>
<input type="submit" name="action" value="search" />
</FORM>
``` | 2011/09/15 | [
"https://Stackoverflow.com/questions/7427564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/946094/"
] | Have you tried something like `$query = ("SELECT * FROM cars WHERE VIN='$VIN' OR name LIKE '%$VIN%'");`?
"LIKE" uses % as wildcard, so it will find all cars that have $VIN in their name.
But anyway make sure to `mysql_real_escape_string()` your parameter $VIN first, to prevent SQL injections! | Use the following query:
```
$query = ("SELECT * FROM cars WHERE Name LIKE '%$txtName%'");
```
**NOTE:**: Wildcard `%` is been used at the beginning and end to return all names having your search word anywhere in the field. |
7,427,564 | So far i have created a search box, which searches the primary key of my database.
How can i modify my php query to search multiple values in my database.
eg: If i search the name of the car instead of the VIN (primary key) it will show all the results matching the search value.
This
```
$query = ("SELECT * FROM cars
WHERE VIN='$VIN'");
```
This is my form :
```
<form name="search" action="http://www.deakin.edu.au/~sjrem/SIT104_3/cars.php" method="post">
<h2> Search for a car of your choice </h2>
<table border="0">
<tr>
<td><input type="text" name="VIN" /> </td>
</tr>
</table>
<p>
<input type="submit" name="action" value="search" />
</FORM>
``` | 2011/09/15 | [
"https://Stackoverflow.com/questions/7427564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/946094/"
] | Have you tried something like `$query = ("SELECT * FROM cars WHERE VIN='$VIN' OR name LIKE '%$VIN%'");`?
"LIKE" uses % as wildcard, so it will find all cars that have $VIN in their name.
But anyway make sure to `mysql_real_escape_string()` your parameter $VIN first, to prevent SQL injections! | something like this might work for you
```
$query = ("SELECT * FROM cars WHERE VIN='$VIN' OR CARS='$VIN'");
``` |
16,760,210 | I have been translating some shell code to MS-DOS Batch. In my code, I have the sample:
```
for %%i in (%*) do set "clargs=!clargs! %%i"
```
If I input the argument "-?" (without the quotation marks), it is not added to clargs. I assume it is because '?' is a wildcard character. Is there anything I can do to ensure that for does not do special things because of the question mark being located in the argument? | 2013/05/26 | [
"https://Stackoverflow.com/questions/16760210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2397924/"
] | You are correct, the wild card characters `*` and `?` are always expanded when used within a FOR IN() clause. Unfortunately, there is no way to prevent the wildcard expansion.
You cannot use a FOR loop to access all parameters if they contain wildcards. Instead, you should use a GOTO loop, along with the SHIFT command.
```
set clargs=%1
:parmLoop
if "%~1" neq "" (
set clargs=%clargs% %1
shift /1
goto :parmLoop
)
```
Although your sample is quite silly, since the resultant `clargs` variable ends up containing the same set of values that were already in `%*`. If you simply want to set a variable containing all values, simply use `set clargs=%*`
More typically, an "array" of argument variables is created.
```
set argCnt=0
:parmLoop
if "%~1" equ "" goto :parmsDone
set /a argCnt+=1
set arg%argCnt%=%1
shift /1
goto :parmLoop
:parmsDone
:: Working with the "array" of arguments is best done with delayed expansion
setlocal enableDelayedExpansion
for /l %%N in (1 1 %argCnt%) do echo arg%%N = !arg%%N!
```
See [Windows Bat file optional argument parsing](https://stackoverflow.com/a/8162578/1012053) for a robust method to process unix style arguments passed to a Windows batch script. | ```
@ECHO OFF
SETLOCAL
SET dummy=%*
FOR /f "tokens=1*delims==" %%f IN ('set dummy') DO CALL :addme %%g
ECHO %clargs%
GOTO :eof
:addme
IF "%~1"=="" GOTO :EOF
IF DEFINED clargs SET clargs=%clargs% %1
IF NOT DEFINED clargs SET clargs=%1
SHIFT
GOTO addme
```
I severly doubt you'll get a completely bullet-proof solution. The above solution will drop separators (comma, semicolon, equals) for instance. Other solutions may have problems with close-parentheses; there's the perpetual `%` and `^` problems - but it will handle `-?`
But for your purposes, from what you've shown, what's wrong with
```
set clargs=%clargs% %*
```
(No doubt you'll want to process further, but ve haff vays...) |
66,026,657 | I'm following a video to code a fully responsive website, but I can't seem to be able to make the background video full screen like in the video, maybe I'm missing a line of code? You'll see on the screenshot a big white space at the bottom. I'll leave some code below, hopefully that'll help to find the issue. Many thanks!
index.js:
```
return (
<HeroContainer>
<HeroBg>
<VideoBg autoPlay loop muted src={Video} type='video/mp4' />
</HeroBg>
<HeroContent>
<HeroH1>Estudio Contable</HeroH1>
<HeroP>
Consultá por nuestros servicios.
</HeroP>
<HeroBtnWrapper>
<Button
to='contactanos'
onMouseEnter={onHover}
onMouseLeave={onHover}
primary="true"
dark="true"
>
Contactanos {hover ? <ArrowForward /> : <ArrowRight />}
</Button>
</HeroBtnWrapper>
</HeroContent>
</HeroContainer>
)
}
```
styling:
```
export const HeroBg = styled.div`
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
`
export const VideoBg = styled.video`
width: 100%;
height: 100%;
-o-object-fit: cover;
object-fit: cover;
background: #232a34;
`
```
[](https://i.stack.imgur.com/wOshB.jpg) | 2021/02/03 | [
"https://Stackoverflow.com/questions/66026657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14781362/"
] | Set the position: fix, along with top & left properties. this will ensure the entire background area is covered.
In your case this will be in the variable `VideoBg`
```css
video {
object-fit: cover;
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
}
```
source: <https://css-tricks.com/full-page-background-video-styles/> | try setting the height of your HeroBg to 100vh instead of 100%;
```
export const HeroBg = styled.div`
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100vh;
overflow: hidden;
`
``` |
2,760,326 | Let
$$y=\cos \phi+i\sin \phi \tag{1}$$
Differentiating both sides of equation (1) with respect to $\phi$, we get,
$$\begin{align}
\frac{dy}{d\phi} &=-\sin \phi+i\cos \phi \\
&=i(\cos \phi-\frac{1}{i}\sin \phi) \\
&=i(\cos\phi+i\sin \phi) \\
&=iy \\
\implies\frac{1}{y}dy &=i\;d\phi \tag{2}
\end{align}$$
Integrating both sides of equation (2), we get,
$$\begin{align}
\int\frac{1}{y}dy&=\int i\;d\phi \\
\implies \ln(y)&=i\phi+c \tag{3}
\end{align}$$
Substituting $\phi=0$ in equation (1), we get,
$$y=\cos 0+i\sin 0 \implies y=1 \tag{4}$$
Substituting $\phi=0$ and $y=1$ in equation (3) we get,
$$\ln(1)=c \implies c=0 \tag{5}$$
Substituting $c=0$ in equation (3) we get,
$$\begin{align}
\ln(y)&=i\phi \tag{6}\\
\implies e^{i\phi}&=y \tag{7}\\
\therefore e^{i\phi}&=\cos \phi+i\sin \phi \tag{8}
\end{align}$$
I found this proof in a book. I think that there is a problem. In $(3)$ and $(6)$, shouldn't $\ln(y)$ be $\ln|y|$ instead? Or is it that, for complex numbers, we do not take the absolute value of the number within the $\ln$? | 2018/04/30 | [
"https://math.stackexchange.com/questions/2760326",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/351620/"
] | Your proof is correct, but there are some hidden assumptions which your book has conveniently failed to mention.
In particular the key assumption is the definition of symbol $e^{iy} $ for $y\in\mathbb{R} $ or equivalently the definition of $\log z$ for $z\in\mathbb{C} $.
One approach is to define $e^z, z\in\mathbb{C} $ via the limit $$e^z=\lim\_{n\to\infty} \left(1+\frac{z}{n}\right)^n\tag{1}$$ or via the series $$e^z=1+z+\frac{z^2}{2!}+\frac{z^3}{3!}+\dots\tag{2}$$ Using any of the above definitions one can easily prove that $e^{iy} =\cos y+i\sin y$. In particular the series definition can be used with the proof you have provided. Using series definition one can prove that if $f(y) =e^{iy} $ then $f'(y) =if(y) $ and then we can use the function $$g(y) =f(y) (\cos y-i\sin y) $$ to establish $g'(y) =0$ so that $g$ is constant. Thus $g(y) =g(0)=1$ and $f(y) =\cos y+i\sin y$.
The proof using limit definition $(1)$ is more interesting and you may have a [look at it](https://math.stackexchange.com/a/1668179/72031). Both the approaches avoid integrals altogether. | >
> Note that indefinite integrals defined algebraically deal with complex quantities. However, many elementary calculus textbooks write formulas such as
>
>
> $$\int \frac{dx}{x} = \ln{|x|} \:\:\:\:\:\:\:\:\:\:\:\:\:\:\: (4)$$
>
>
> (where the notation $x$ is used to indicate that $x$ is assumed to be a real number) instead of the complex variable version
>
>
> $$\int \frac{dz}{z} = \ln{z} \:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\: (5)$$
>
>
> where z is generically a complex number (but also holds for real $z$).
>
>
> * <http://mathworld.wolfram.com/IndefiniteIntegral.html>
>
>
> |
57,421 | I want to insert a 1\*12 table in Sketch 3 artboard. But I'm not able to find out how to insert it.
I've already read this [article](https://graphicdesign.stackexchange.com/questions/54819/sketch3-is-it-possible-to-create-a-text-table). But according to the answer, the plugin is used to distribute the items. I need a "real" table which has borders.
Could someone tell me how to achieve this? | 2015/08/03 | [
"https://graphicdesign.stackexchange.com/questions/57421",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/41130/"
] | As crazy as this sounds, you can use [Apple's spreadsheet app, Numbers](https://www.apple.com/mac/numbers/) to create a table that you can copy and paste into Sketch. I did this example really quick
**Basic workflow**
1. Create a table (do most of the design in here)
[](https://i.stack.imgur.com/pyKDq.png)
2. Copy the whole table
* *EDIT: January 22, 2018*
[](https://i.stack.imgur.com/Z0dQC.png)
* In the latest version of Numbers, you'll want to highlight the object you want to copy, right click it, and select `Copy as PDF`
3. Go to Sketch
4. Paste your clipboard
[](https://i.stack.imgur.com/i1RRO.png)
[](https://i.stack.imgur.com/Em9We.png)
5. Voilà
**Working in Sketch**
1. We have a table in Sketch! No self adjusting columns though — it's all a manual process from here on out
[](https://i.stack.imgur.com/lWQoA.png)
2. Here's my table with an expanded group list view
[](https://i.stack.imgur.com/fI8wd.png)
3. Some drastic (and horrible looking) changes to show editing capabilities. All the text is left aligned.
[](https://i.stack.imgur.com/Og3OS.png) | It is true Sketch lacks a table tool, but the work around is to make rectangles styles the way of your liking and duplicating it 12 times. |
28,998,792 | I'm using a trained opencv cascade classifier to detect hands in video frames, and would like to lower my false positive rate.
Reading up on the net, I saw you can do so by accessing the
`rejectLevels` and `levelWeights` information returned by the detectMultiScale method. I saw [here](http://choorucode.com/2014/10/30/how-to-get-detection-score-from-opencv-cascade-classifier/) that this is possible in C++, my question is- has anyone managed to do it in Python? A similar question was asked [here](https://stackoverflow.com/questions/7948055/classifiers-confidence-in-opencv-face-detector) but it was for an earlier version of of the detection method.
If it is possible, what is the proper syntax to call the method? If it worked for you, please mention the OpenCV version you're using. I'm on 2.4.9.
The 2.4.11 API gives the following syntax
```
Python: cv2.CascadeClassifier.detectMultiScale(image, rejectLevels, levelWeights[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize[, outputRejectLevels]]]]]])
```
So accordingly, I've tried
```
import cv2
import cv2.cv as cv
import time
hand_cascade = cv2.CascadeClassifier('cascade.xml')
img = cv2.imread('test.jpg')
rejectLevels = []
levelWeights = []
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = hand_cascade.detectMultiScale(gray,rejectLevels,levelWeights, 1.1, 5,cv.CV_HAAR_FIND_BIGGEST_OBJECT,(30, 30),(100,100),True)
```
But the output I get is
```
[[259 101 43 43]
[354 217 43 43]
[240 189 43 43]
[316 182 47 47]
[277 139 92 92]]
[]
[]
```
Thanks for the help,
Ronen | 2015/03/11 | [
"https://Stackoverflow.com/questions/28998792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2882125/"
] | For anyone coming to this question and using OpenCV 3.0 I worked out after poking around the python API.
On the cascade classifier there are three methods `detectMultiScale`, `detectMultiScale2`, and `detectMultiScale3`. Using the third one, I was able to get what looked like a confidence/weight.
```
faces = faceCascade.detectMultiScale3(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE,
outputRejectLevels = True
)
rects = faces[0]
neighbours = faces[1]
weights = faces[2]
```
`weights[i]` looks to match the confidence of the face defined by `rects[i]`. `neighbours[i]` is the number of matches in neighbourhood of the current rectangle. | Short of hacking the c++, it doesn't look like there's any way to get the actual rejectLevels and levelWeights. |
377 | The Drupal community traditionally clustered around Drupal.org. While surely there will be a community around drupal.stackexchange.com I am really curious on how can we channel these people back to drupal.org where they can contribute in the many ways drupal.org lets us: code reviews, handbook page, answering questions in the issue queues, bug reports, etc. | 2011/07/06 | [
"https://drupal.meta.stackexchange.com/questions/377",
"https://drupal.meta.stackexchange.com",
"https://drupal.meta.stackexchange.com/users/-1/"
] | Ideally *Drupal Answers* would be a part of drupal.org. The only problem is that with a community as big as Drupal it will take a long time to form the consensus needed to get something like it there.
I'm sure you know there have been some talks about this in groups.drupal.org, but to go from there to actually have an implemented solution for asking and answering questions that's useful and organized might take as long as 2-3 years.
**So how can we bring people back to drupal.org?**
I'm not sure how many people there actually is channel back to Drupal.org. This site currently have around 130 of what SE calls avid users. That is a user with more than 200 rep. This is actually not much rep, but it is high enough that you have to make an effort, either being a regular user or creating some good answers or questions. Of those avid users, I believe most of them like yourself are already contributing to drupal.org. I think it would be quite rare to find some one experienced enough to answer questions here regularly, that isn't already active on drupal.org in one way or the other.
**We do**
What we do already it to point people to the issue queue of a module if they encounter a bug instead of answering it here. But it's actually rare that this happens.
**Random people**
We do get some traffic from google, about 2k or so visits per day. The only reason we get this traffic is because right now this site fills a need that drupal.org doesn't. You can get a quick and easy answer to your question. I'm not sure that we can or should try to channel these people back. But I guess they won't be part of the community around this site anyways. If they don't come here, they might go to SO, a random blog or some other place. | I think that 'answering questions in the issue queues' is a real weakness in D.O. the redesign didn't address. There is still no email notification of answers happening. So I am guessing there is no notification of questions either, which makes it really difficult to use to get the answers; therefore, there is a migration to an easier platform, such as drupal.stackexchange.com.
D.O. is great for filing bugs, and let the maintainers know what is going on, but I really don't think it functions as a community. IRC does a good job if you happen to be in the right time zone (I'm not, so it's really quiet when I get on it). These are just my 2c. |
377 | The Drupal community traditionally clustered around Drupal.org. While surely there will be a community around drupal.stackexchange.com I am really curious on how can we channel these people back to drupal.org where they can contribute in the many ways drupal.org lets us: code reviews, handbook page, answering questions in the issue queues, bug reports, etc. | 2011/07/06 | [
"https://drupal.meta.stackexchange.com/questions/377",
"https://drupal.meta.stackexchange.com",
"https://drupal.meta.stackexchange.com/users/-1/"
] | Ideally *Drupal Answers* would be a part of drupal.org. The only problem is that with a community as big as Drupal it will take a long time to form the consensus needed to get something like it there.
I'm sure you know there have been some talks about this in groups.drupal.org, but to go from there to actually have an implemented solution for asking and answering questions that's useful and organized might take as long as 2-3 years.
**So how can we bring people back to drupal.org?**
I'm not sure how many people there actually is channel back to Drupal.org. This site currently have around 130 of what SE calls avid users. That is a user with more than 200 rep. This is actually not much rep, but it is high enough that you have to make an effort, either being a regular user or creating some good answers or questions. Of those avid users, I believe most of them like yourself are already contributing to drupal.org. I think it would be quite rare to find some one experienced enough to answer questions here regularly, that isn't already active on drupal.org in one way or the other.
**We do**
What we do already it to point people to the issue queue of a module if they encounter a bug instead of answering it here. But it's actually rare that this happens.
**Random people**
We do get some traffic from google, about 2k or so visits per day. The only reason we get this traffic is because right now this site fills a need that drupal.org doesn't. You can get a quick and easy answer to your question. I'm not sure that we can or should try to channel these people back. But I guess they won't be part of the community around this site anyways. If they don't come here, they might go to SO, a random blog or some other place. | IRC is something which we don't promote very much. While it isn't a direct link to D.org it is a hotline to the Drupal community. Perhaps we should mention it more. |
377 | The Drupal community traditionally clustered around Drupal.org. While surely there will be a community around drupal.stackexchange.com I am really curious on how can we channel these people back to drupal.org where they can contribute in the many ways drupal.org lets us: code reviews, handbook page, answering questions in the issue queues, bug reports, etc. | 2011/07/06 | [
"https://drupal.meta.stackexchange.com/questions/377",
"https://drupal.meta.stackexchange.com",
"https://drupal.meta.stackexchange.com/users/-1/"
] | Ideally *Drupal Answers* would be a part of drupal.org. The only problem is that with a community as big as Drupal it will take a long time to form the consensus needed to get something like it there.
I'm sure you know there have been some talks about this in groups.drupal.org, but to go from there to actually have an implemented solution for asking and answering questions that's useful and organized might take as long as 2-3 years.
**So how can we bring people back to drupal.org?**
I'm not sure how many people there actually is channel back to Drupal.org. This site currently have around 130 of what SE calls avid users. That is a user with more than 200 rep. This is actually not much rep, but it is high enough that you have to make an effort, either being a regular user or creating some good answers or questions. Of those avid users, I believe most of them like yourself are already contributing to drupal.org. I think it would be quite rare to find some one experienced enough to answer questions here regularly, that isn't already active on drupal.org in one way or the other.
**We do**
What we do already it to point people to the issue queue of a module if they encounter a bug instead of answering it here. But it's actually rare that this happens.
**Random people**
We do get some traffic from google, about 2k or so visits per day. The only reason we get this traffic is because right now this site fills a need that drupal.org doesn't. You can get a quick and easy answer to your question. I'm not sure that we can or should try to channel these people back. But I guess they won't be part of the community around this site anyways. If they don't come here, they might go to SO, a random blog or some other place. | Actually there is something that can be done to channel people back to Drupal.org, but this is not actually possible in a beta site.
In other SE sites (e.g., Super User with [Community Promotion Ads - 1H 2011](https://meta.superuser.com/questions/2164/community-promotion-ads-1h-2011)), I saw a question on their meta site asking to provide an image and a link that would be then shown as ad in the main site; the most up-voted ones will then be used in the main site. As far as I recall, on MSO the ads where about projects under a GPL or similar license.
If that would be done for Drupal Answers too, we could create an ad for a particular initiative that is important to Drupal.org, or we could put an ad for a project (module or theme) that needs some care, and that is maybe interesting for Drupal.org because it is going to be used on Drupal.org, and there are bugs or improvements to be done for the project.
The ad could even link to a page where a list of initiatives are reported, and that link could even take to the group that is used for such initiatives.
**Edit:** Now we have it too; see [Community Promotion Ads - 2012](https://drupal.meta.stackexchange.com/questions/592/community-promotion-ads-1h-2012). |
377 | The Drupal community traditionally clustered around Drupal.org. While surely there will be a community around drupal.stackexchange.com I am really curious on how can we channel these people back to drupal.org where they can contribute in the many ways drupal.org lets us: code reviews, handbook page, answering questions in the issue queues, bug reports, etc. | 2011/07/06 | [
"https://drupal.meta.stackexchange.com/questions/377",
"https://drupal.meta.stackexchange.com",
"https://drupal.meta.stackexchange.com/users/-1/"
] | IRC is something which we don't promote very much. While it isn't a direct link to D.org it is a hotline to the Drupal community. Perhaps we should mention it more. | I think that 'answering questions in the issue queues' is a real weakness in D.O. the redesign didn't address. There is still no email notification of answers happening. So I am guessing there is no notification of questions either, which makes it really difficult to use to get the answers; therefore, there is a migration to an easier platform, such as drupal.stackexchange.com.
D.O. is great for filing bugs, and let the maintainers know what is going on, but I really don't think it functions as a community. IRC does a good job if you happen to be in the right time zone (I'm not, so it's really quiet when I get on it). These are just my 2c. |
377 | The Drupal community traditionally clustered around Drupal.org. While surely there will be a community around drupal.stackexchange.com I am really curious on how can we channel these people back to drupal.org where they can contribute in the many ways drupal.org lets us: code reviews, handbook page, answering questions in the issue queues, bug reports, etc. | 2011/07/06 | [
"https://drupal.meta.stackexchange.com/questions/377",
"https://drupal.meta.stackexchange.com",
"https://drupal.meta.stackexchange.com/users/-1/"
] | Actually there is something that can be done to channel people back to Drupal.org, but this is not actually possible in a beta site.
In other SE sites (e.g., Super User with [Community Promotion Ads - 1H 2011](https://meta.superuser.com/questions/2164/community-promotion-ads-1h-2011)), I saw a question on their meta site asking to provide an image and a link that would be then shown as ad in the main site; the most up-voted ones will then be used in the main site. As far as I recall, on MSO the ads where about projects under a GPL or similar license.
If that would be done for Drupal Answers too, we could create an ad for a particular initiative that is important to Drupal.org, or we could put an ad for a project (module or theme) that needs some care, and that is maybe interesting for Drupal.org because it is going to be used on Drupal.org, and there are bugs or improvements to be done for the project.
The ad could even link to a page where a list of initiatives are reported, and that link could even take to the group that is used for such initiatives.
**Edit:** Now we have it too; see [Community Promotion Ads - 2012](https://drupal.meta.stackexchange.com/questions/592/community-promotion-ads-1h-2012). | I think that 'answering questions in the issue queues' is a real weakness in D.O. the redesign didn't address. There is still no email notification of answers happening. So I am guessing there is no notification of questions either, which makes it really difficult to use to get the answers; therefore, there is a migration to an easier platform, such as drupal.stackexchange.com.
D.O. is great for filing bugs, and let the maintainers know what is going on, but I really don't think it functions as a community. IRC does a good job if you happen to be in the right time zone (I'm not, so it's really quiet when I get on it). These are just my 2c. |
54,111,389 | I'm creating a wp plugin for my website and I have a form on my website who have to put some value into my db. my problem is the data don't want to be put into my db.
I try to change my coding multiple time, and I debug the fonction (the data are recive by the fonction) but actually my code looks like this:
my front page :
```
$date_start = $_POST['startDate'];
$date_end = $_POST['endDate'];
$description = $_POST['description'];
$place = $_POST['lieu'];
$value = $_POST['value'];
$user_id = $_POST['id_user'];
$current_user = wp_get_current_user();
$current_user_id = $current_user->id;
$date_current = date('Y/m/d', time());
frdp_add($user_id, $description, $place, $date_start, $date_end, $value, $date_current, $current_user_id);
```
my plugin page :
```
$table_name = $wpdb->prefix . 'frais_deplacement';
function frdp_add($user_id, $description, $place, $date_start, $date_end, $value, $date_current, $current_user_id) {
global $wpdb;
$wpdb->insert(
$table_name,
array(
'id_user' => $user_id,
'description' => $description,
'place' => $place,
'date_start' => $date_start,
'date_end' => $date_end,
'value' => $value,
'created_at' => $date_current,
'created_by' => $current_user_id
)
);
}
``` | 2019/01/09 | [
"https://Stackoverflow.com/questions/54111389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10645178/"
] | One counting problem I see is happening is in your self-join of the `writtenby` table. There, you are not checking that the matching row has a *different* `author_id`. If the `author_id` be the same, then you should not be counting it. Also, what you should be counting for the number of shared authors is the second `writtenby` table. This way, should a given author not have any coauthors, the count would show up as zero.
```
SELECT p.doi, p.year, COUNT(w2.author_id) AS cnt
FROM authors a
INNER JOIN writtenby w1
ON a.author_id = w1.author_id
INNER JOIN writtenby w2
ON w1.paper_id = w2.paper_id AND w1.author_id <> w2.author_id
INNER JOIN papers p
ON w2.paper_id = p.paper_id
WHERE
a.name = 'Beck' AND a.firstname = 'H P'
GROUP BY
p.doi, p.year
ORDER BY
cnt DESC;
``` | With the help of Tim Biegeleisen and the sample data, I found that what was missing is the clause DISTINCT in the count
```
SELECT p.doi, p.year, COUNT(DISTINCT w2.author_id) AS cnt
FROM authors a
INNER JOIN writtenby w1
ON a.author_id = w1.author_id
INNER JOIN writtenby w2
ON w1.paper_id = w2.paper_id
INNER JOIN papers p
ON w2.paper_id = p.paper_id
WHERE
a.name = 'De La Rue' AND a.firstname = 'A'
GROUP BY
p.doi, p.year
ORDER BY
cnt DESC;
```
give the total number of authors.
```
doi1 2017 4
doi2 2018 3
doi3 2018 3
```
Withe the clause `w1.author_id <> w2.author_id`, the count is reduced by one.
F. |
5,807,750 | What are the best JQuery/Javascript controls for common use?
I am looking for the basics: Grid, Calendar, Datepicker, google-suggest-like textbox, etc...
Preferably themed with jQueryUI.
The main controls I am looking for are clientside alternatives to Telerik ASP.NET AJAX RadGrid, Scheduler and Editor, treeview controls etc... | 2011/04/27 | [
"https://Stackoverflow.com/questions/5807750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614695/"
] | Entity life-cycle callback methods @PrePersist, @PreUpdate can be used here to verify the field value NAN/-INF/+INF etc & then setting the default value accordingly.
```
//--
@PrePersist
@PreUpdate
private void resetField() {
if(field == Double.POSITIVE_INFINITY)
field = somePredefinedValue;
}
//--
``` | MySQL doesn't seem to support "infinity". [This article](http://www.ryannitz.org/tech-notes/2009/01/19/mysql-and-negative-infinity/) writes that:
>
> Storing and retrieving negative infinity in a MySQL database is accomplished by inserting an arbitrarily large negative number.
>
>
>
Same goes for positive. [Other resources](http://lists.mysql.com/java/5996) also use `1e500`.
Instead of using infinity, I would suggest that you use `Float.MAX_VALUE` and `Float.MIN_VALUE` (or `Double` equivalents)
If you can't do this in your code when setting the values, do it in a `@PrePersist` as already suggested. |
5,807,750 | What are the best JQuery/Javascript controls for common use?
I am looking for the basics: Grid, Calendar, Datepicker, google-suggest-like textbox, etc...
Preferably themed with jQueryUI.
The main controls I am looking for are clientside alternatives to Telerik ASP.NET AJAX RadGrid, Scheduler and Editor, treeview controls etc... | 2011/04/27 | [
"https://Stackoverflow.com/questions/5807750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614695/"
] | Entity life-cycle callback methods @PrePersist, @PreUpdate can be used here to verify the field value NAN/-INF/+INF etc & then setting the default value accordingly.
```
//--
@PrePersist
@PreUpdate
private void resetField() {
if(field == Double.POSITIVE_INFINITY)
field = somePredefinedValue;
}
//--
``` | I managed this problem by adding a varchar column to store the text representation of `Float.NaN`, `Float.POSITIVE_INFINITY` and `Float.NEGATIVE_INFINITY` while the original column will store `NULL`.
Then I use the setter and the getter to do manage those two columns.
In my @Entity class
```
/** The value I persist. See it is a Float; */
@Column(name = "VALUE")
private Float value;
/** the 'value complement' that does the trick. */
@Column(name = "VALUE_COMPLEMENT") // You can see I've added a new column in my table (it is a varchar)
private String valueComplement;
/**
* value getter.
* If my value is null, it could mean that it is a NaN or +/- infinity.
* Then let's check the complement.
*/
public Float getValue() {
if (value == null) {
try {
return Float.parseFloat(this.valueComplement);
} catch (NumberFormatException e) {
return null;
}
} else {
return value;
}
}
/**
* value setter
* If the given value is a NaN or Inf, set this.value to null
* and this.complement to the string representation of NaN or +/- Inf.
*/
public void setValue(Float value) {
if (value != null && (value.isNaN() || value.isInfinite())) {
this.valueComplement = value.toString();
this.value = null;
} else {
this.value = value;
}
}
```
Result :
```
| ID | LABEL | VALUE | VALUE_COMPLEMENT |
| -- | --------------------- | ----- | ---------------- |
| 1 | PI | 3.14 | NULL |
| 2 | gravity acceleration | 9.81 | NULL |
| 3 | sqare root of -1 | NULL | NaN |
| 4 | log of 0 | NULL | -Infinity |
``` |
5,807,750 | What are the best JQuery/Javascript controls for common use?
I am looking for the basics: Grid, Calendar, Datepicker, google-suggest-like textbox, etc...
Preferably themed with jQueryUI.
The main controls I am looking for are clientside alternatives to Telerik ASP.NET AJAX RadGrid, Scheduler and Editor, treeview controls etc... | 2011/04/27 | [
"https://Stackoverflow.com/questions/5807750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614695/"
] | MySQL doesn't seem to support "infinity". [This article](http://www.ryannitz.org/tech-notes/2009/01/19/mysql-and-negative-infinity/) writes that:
>
> Storing and retrieving negative infinity in a MySQL database is accomplished by inserting an arbitrarily large negative number.
>
>
>
Same goes for positive. [Other resources](http://lists.mysql.com/java/5996) also use `1e500`.
Instead of using infinity, I would suggest that you use `Float.MAX_VALUE` and `Float.MIN_VALUE` (or `Double` equivalents)
If you can't do this in your code when setting the values, do it in a `@PrePersist` as already suggested. | I managed this problem by adding a varchar column to store the text representation of `Float.NaN`, `Float.POSITIVE_INFINITY` and `Float.NEGATIVE_INFINITY` while the original column will store `NULL`.
Then I use the setter and the getter to do manage those two columns.
In my @Entity class
```
/** The value I persist. See it is a Float; */
@Column(name = "VALUE")
private Float value;
/** the 'value complement' that does the trick. */
@Column(name = "VALUE_COMPLEMENT") // You can see I've added a new column in my table (it is a varchar)
private String valueComplement;
/**
* value getter.
* If my value is null, it could mean that it is a NaN or +/- infinity.
* Then let's check the complement.
*/
public Float getValue() {
if (value == null) {
try {
return Float.parseFloat(this.valueComplement);
} catch (NumberFormatException e) {
return null;
}
} else {
return value;
}
}
/**
* value setter
* If the given value is a NaN or Inf, set this.value to null
* and this.complement to the string representation of NaN or +/- Inf.
*/
public void setValue(Float value) {
if (value != null && (value.isNaN() || value.isInfinite())) {
this.valueComplement = value.toString();
this.value = null;
} else {
this.value = value;
}
}
```
Result :
```
| ID | LABEL | VALUE | VALUE_COMPLEMENT |
| -- | --------------------- | ----- | ---------------- |
| 1 | PI | 3.14 | NULL |
| 2 | gravity acceleration | 9.81 | NULL |
| 3 | sqare root of -1 | NULL | NaN |
| 4 | log of 0 | NULL | -Infinity |
``` |
69,314,655 | I am using react-router-dom and according to docs it says for url pattern `https:\\example.com\user\:id\:gender`
we can use `useParams()` hook to read the patters like
```
import {useParams, Route} from react-router;
<Route exact path="/user/:id/:gender" component={User}/>
const user=(props)=>{
const params = useParams()
}
//params = {id:'1',gender:'f'}; output for url pattern >>> https:\\example.com\user\1\f
```
But in my case, I have two requirement
1. gender field is sometime required and some time not, then what changes needed in the Router?
2. How to read url pattern `https://example.com/user?id=1&gender=f` , because in this patter If I interchange the order then no effect will be on parameter object. | 2021/09/24 | [
"https://Stackoverflow.com/questions/69314655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9489351/"
] | I assume the code that does the `malloc` and calls `callback` doesn't know anything about the type of the object, only its size.
```
#include <stdlib.h>
void *alloc_and_init(size_t nmemb, size_t size, void (*callback)(void *))
{
void *b = calloc(nmemb, size);
if (b)
{
char *p = b;
for (size_t i = 0; i < nmemb; i++)
{
callback(p);
p += size;
}
}
return b;
}
typedef struct{
int type;
}Base;
typedef struct{
Base base;
int value;
}inherited;
void init_inherited(void *p)
{
inherited *obj = p;
/* do initialization of obj->* here */
}
int main(void)
{
int objcount = 10;
inherited *objarr;
objarr = alloc_and_init(objcount, sizeof(*objarr),
init_inherited);
/* ... */
free(objarr);
}
``` | ```
for( inherited *p = b, *e = p + count; p < e; p++ ){
callback(p);
}
``` |
69,314,655 | I am using react-router-dom and according to docs it says for url pattern `https:\\example.com\user\:id\:gender`
we can use `useParams()` hook to read the patters like
```
import {useParams, Route} from react-router;
<Route exact path="/user/:id/:gender" component={User}/>
const user=(props)=>{
const params = useParams()
}
//params = {id:'1',gender:'f'}; output for url pattern >>> https:\\example.com\user\1\f
```
But in my case, I have two requirement
1. gender field is sometime required and some time not, then what changes needed in the Router?
2. How to read url pattern `https://example.com/user?id=1&gender=f` , because in this patter If I interchange the order then no effect will be on parameter object. | 2021/09/24 | [
"https://Stackoverflow.com/questions/69314655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9489351/"
] | ```
for( inherited *p = b, *e = p + count; p < e; p++ ){
callback(p);
}
``` | Polymorphism in C is always rather clunky. Basically you have to construct a "vtable" manually. The naive, simplified version below lets each object have its own function pointer. You'll end up with something rather contrived like this:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct base_t base_t;
typedef void callback_t (const base_t* arg);
struct base_t
{
int type;
callback_t* callback;
};
typedef struct
{
base_t base;
int value;
} inherited_t;
void callback_base (const base_t* arg)
{
puts(__func__);
}
void callback_inherited (const base_t* arg)
{
const inherited_t* iarg = (const inherited_t*)arg;
printf("%s value: %d\n", __func__, iarg->value);
}
int main (void)
{
// allocate memory
base_t* array [3] =
{
[0] = malloc(sizeof(inherited_t)),
[1] = malloc(sizeof(base_t)),
[2] = malloc(sizeof(inherited_t)),
};
// initialize objects
*(inherited_t*)array[0] = (inherited_t){ .base.callback=callback_inherited, .value = 123 };
*(array[1]) = (base_t){ .callback=callback_base };
*(inherited_t*)array[2] = (inherited_t){ .base.callback=callback_inherited, .value = 456 };
for (int i = 0; i < 3; i++)
{
array[i]->callback(array[i]); // now we get polymorphism here
}
}
```
A more professional version involves writing a translation unit (.h + .c) per "class" and then combine allocation with initialization in the "constructor". It would be implemented with opaque type, see [How to do private encapsulation in C?](https://software.codidact.com/posts/283888) Inside the constructor, set the vtable corresponding to the type of object allocated.
I'd also boldly claim that any OO solution using `void*` arguments has some design flaw. The interface should be using the base class pointer. Void pointers are dangerous. |
69,314,655 | I am using react-router-dom and according to docs it says for url pattern `https:\\example.com\user\:id\:gender`
we can use `useParams()` hook to read the patters like
```
import {useParams, Route} from react-router;
<Route exact path="/user/:id/:gender" component={User}/>
const user=(props)=>{
const params = useParams()
}
//params = {id:'1',gender:'f'}; output for url pattern >>> https:\\example.com\user\1\f
```
But in my case, I have two requirement
1. gender field is sometime required and some time not, then what changes needed in the Router?
2. How to read url pattern `https://example.com/user?id=1&gender=f` , because in this patter If I interchange the order then no effect will be on parameter object. | 2021/09/24 | [
"https://Stackoverflow.com/questions/69314655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9489351/"
] | I assume the code that does the `malloc` and calls `callback` doesn't know anything about the type of the object, only its size.
```
#include <stdlib.h>
void *alloc_and_init(size_t nmemb, size_t size, void (*callback)(void *))
{
void *b = calloc(nmemb, size);
if (b)
{
char *p = b;
for (size_t i = 0; i < nmemb; i++)
{
callback(p);
p += size;
}
}
return b;
}
typedef struct{
int type;
}Base;
typedef struct{
Base base;
int value;
}inherited;
void init_inherited(void *p)
{
inherited *obj = p;
/* do initialization of obj->* here */
}
int main(void)
{
int objcount = 10;
inherited *objarr;
objarr = alloc_and_init(objcount, sizeof(*objarr),
init_inherited);
/* ... */
free(objarr);
}
``` | Polymorphism in C is always rather clunky. Basically you have to construct a "vtable" manually. The naive, simplified version below lets each object have its own function pointer. You'll end up with something rather contrived like this:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct base_t base_t;
typedef void callback_t (const base_t* arg);
struct base_t
{
int type;
callback_t* callback;
};
typedef struct
{
base_t base;
int value;
} inherited_t;
void callback_base (const base_t* arg)
{
puts(__func__);
}
void callback_inherited (const base_t* arg)
{
const inherited_t* iarg = (const inherited_t*)arg;
printf("%s value: %d\n", __func__, iarg->value);
}
int main (void)
{
// allocate memory
base_t* array [3] =
{
[0] = malloc(sizeof(inherited_t)),
[1] = malloc(sizeof(base_t)),
[2] = malloc(sizeof(inherited_t)),
};
// initialize objects
*(inherited_t*)array[0] = (inherited_t){ .base.callback=callback_inherited, .value = 123 };
*(array[1]) = (base_t){ .callback=callback_base };
*(inherited_t*)array[2] = (inherited_t){ .base.callback=callback_inherited, .value = 456 };
for (int i = 0; i < 3; i++)
{
array[i]->callback(array[i]); // now we get polymorphism here
}
}
```
A more professional version involves writing a translation unit (.h + .c) per "class" and then combine allocation with initialization in the "constructor". It would be implemented with opaque type, see [How to do private encapsulation in C?](https://software.codidact.com/posts/283888) Inside the constructor, set the vtable corresponding to the type of object allocated.
I'd also boldly claim that any OO solution using `void*` arguments has some design flaw. The interface should be using the base class pointer. Void pointers are dangerous. |
69,314,655 | I am using react-router-dom and according to docs it says for url pattern `https:\\example.com\user\:id\:gender`
we can use `useParams()` hook to read the patters like
```
import {useParams, Route} from react-router;
<Route exact path="/user/:id/:gender" component={User}/>
const user=(props)=>{
const params = useParams()
}
//params = {id:'1',gender:'f'}; output for url pattern >>> https:\\example.com\user\1\f
```
But in my case, I have two requirement
1. gender field is sometime required and some time not, then what changes needed in the Router?
2. How to read url pattern `https://example.com/user?id=1&gender=f` , because in this patter If I interchange the order then no effect will be on parameter object. | 2021/09/24 | [
"https://Stackoverflow.com/questions/69314655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9489351/"
] | I assume the code that does the `malloc` and calls `callback` doesn't know anything about the type of the object, only its size.
```
#include <stdlib.h>
void *alloc_and_init(size_t nmemb, size_t size, void (*callback)(void *))
{
void *b = calloc(nmemb, size);
if (b)
{
char *p = b;
for (size_t i = 0; i < nmemb; i++)
{
callback(p);
p += size;
}
}
return b;
}
typedef struct{
int type;
}Base;
typedef struct{
Base base;
int value;
}inherited;
void init_inherited(void *p)
{
inherited *obj = p;
/* do initialization of obj->* here */
}
int main(void)
{
int objcount = 10;
inherited *objarr;
objarr = alloc_and_init(objcount, sizeof(*objarr),
init_inherited);
/* ... */
free(objarr);
}
``` | ```
char *b = malloc(size * count);
for (int i = 0; i < count; i++){
// iterate based on known size & send to callback
callback( b + i * size );
}
``` |
69,314,655 | I am using react-router-dom and according to docs it says for url pattern `https:\\example.com\user\:id\:gender`
we can use `useParams()` hook to read the patters like
```
import {useParams, Route} from react-router;
<Route exact path="/user/:id/:gender" component={User}/>
const user=(props)=>{
const params = useParams()
}
//params = {id:'1',gender:'f'}; output for url pattern >>> https:\\example.com\user\1\f
```
But in my case, I have two requirement
1. gender field is sometime required and some time not, then what changes needed in the Router?
2. How to read url pattern `https://example.com/user?id=1&gender=f` , because in this patter If I interchange the order then no effect will be on parameter object. | 2021/09/24 | [
"https://Stackoverflow.com/questions/69314655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9489351/"
] | ```
char *b = malloc(size * count);
for (int i = 0; i < count; i++){
// iterate based on known size & send to callback
callback( b + i * size );
}
``` | Polymorphism in C is always rather clunky. Basically you have to construct a "vtable" manually. The naive, simplified version below lets each object have its own function pointer. You'll end up with something rather contrived like this:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct base_t base_t;
typedef void callback_t (const base_t* arg);
struct base_t
{
int type;
callback_t* callback;
};
typedef struct
{
base_t base;
int value;
} inherited_t;
void callback_base (const base_t* arg)
{
puts(__func__);
}
void callback_inherited (const base_t* arg)
{
const inherited_t* iarg = (const inherited_t*)arg;
printf("%s value: %d\n", __func__, iarg->value);
}
int main (void)
{
// allocate memory
base_t* array [3] =
{
[0] = malloc(sizeof(inherited_t)),
[1] = malloc(sizeof(base_t)),
[2] = malloc(sizeof(inherited_t)),
};
// initialize objects
*(inherited_t*)array[0] = (inherited_t){ .base.callback=callback_inherited, .value = 123 };
*(array[1]) = (base_t){ .callback=callback_base };
*(inherited_t*)array[2] = (inherited_t){ .base.callback=callback_inherited, .value = 456 };
for (int i = 0; i < 3; i++)
{
array[i]->callback(array[i]); // now we get polymorphism here
}
}
```
A more professional version involves writing a translation unit (.h + .c) per "class" and then combine allocation with initialization in the "constructor". It would be implemented with opaque type, see [How to do private encapsulation in C?](https://software.codidact.com/posts/283888) Inside the constructor, set the vtable corresponding to the type of object allocated.
I'd also boldly claim that any OO solution using `void*` arguments has some design flaw. The interface should be using the base class pointer. Void pointers are dangerous. |
4,280,455 | Currently I am working on an embedded project. The client side is an 8bits MCU and the server side is computer.
As part of goal, I want to minimize the chance people copy our product. During the initialization phase, the server send its serial number to client and client do some simple calculation with its serial number then send result back to server. The server checks the result to a pre-calculated, hardcoded value, if match the client is authentic.
The problem is the calculated serial number that sent back to server is always fixed. Any copycat company can figure it out quite easily with a logic analyzer. I want to make the transmitting serial number seems random bits from time to time but still be able to decrypt back to its original value. [A good example using AES encryption](http://www.movable-type.co.uk/scripts/aes.html) (notice every time you press the *Encrypt It* button a seemingly random text is generated, but as you decrypt it, then it reverts to the original text.)
Due to ROM/RAM and process power limitation in 8bits MCU I can’t fit a complete AES routine in it, so AES is out of a solution. Is there an easy and efficiency algorithm just to randomize the transmission? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4280455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/520592/"
] | Use a key pair. On initialization:
* Client tells server "I am online"
* Server encrypts a verification message, which only the client will be able to decode
* Client sends back the decrypted message
There should be no need for the server's key to be hardcoded - it can be generated based on a timestamp (only an answer within an acceptable range is accepted) or the codes can be generated on an as-needed basis with a timeout to prevent them from being stored for a long term. | Have the server send either a monotonically-increasing counter or a timestamp to the client, alongside the serial number. The client then includes that in the calculation it performs.
Because the server always sends a different request, the response will always be different (of course, if the market is lucrative enough your competitors can always disassemble your MCU code and figure out how to replicate it, but there's really no stopping that). |
4,280,455 | Currently I am working on an embedded project. The client side is an 8bits MCU and the server side is computer.
As part of goal, I want to minimize the chance people copy our product. During the initialization phase, the server send its serial number to client and client do some simple calculation with its serial number then send result back to server. The server checks the result to a pre-calculated, hardcoded value, if match the client is authentic.
The problem is the calculated serial number that sent back to server is always fixed. Any copycat company can figure it out quite easily with a logic analyzer. I want to make the transmitting serial number seems random bits from time to time but still be able to decrypt back to its original value. [A good example using AES encryption](http://www.movable-type.co.uk/scripts/aes.html) (notice every time you press the *Encrypt It* button a seemingly random text is generated, but as you decrypt it, then it reverts to the original text.)
Due to ROM/RAM and process power limitation in 8bits MCU I can’t fit a complete AES routine in it, so AES is out of a solution. Is there an easy and efficiency algorithm just to randomize the transmission? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4280455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/520592/"
] | Use a key pair. On initialization:
* Client tells server "I am online"
* Server encrypts a verification message, which only the client will be able to decode
* Client sends back the decrypted message
There should be no need for the server's key to be hardcoded - it can be generated based on a timestamp (only an answer within an acceptable range is accepted) or the codes can be generated on an as-needed basis with a timeout to prevent them from being stored for a long term. | A different idea might be to require the 8 bit controller to send a CRC of the date, time and serial number to the server. The server can verify it is a unique serial and send a CRC with date, time and authorization code.
You might also look into the rolling code algorythms used for garage doors openers to see if they could be applied to your application. |
56,450,254 | When I use this code I would like to turn to every element of array of structures like this:
```
array[0]->X;
array[1]->X;
```
I tried everything I could, but in all cases I've had Segmentation fault. What am I doing wrong?
Please look at blocks between #if 0 #endif
```
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
typedef struct
{
double X;
double Y;
} ArrayOfStructures;
typedef struct
{
uint_fast64_t length;
ArrayOfStructures **array;
} Points;
typedef struct
{
Points *points;
} Config;
void add_new_array(Config *conf)
{
printf("conf=%p\n",conf);
printf("conf->points=%p\n",conf->points);
printf("conf->points->length=%zu\n",conf->points->length);
printf("conf->points->array=%p\n",conf->points->array);
#if 0
ArrayOfStructures *temp = (ArrayOfStructures*)calloc(conf->points->length,sizeof(ArrayOfStructures));
printf("temp=%p\n",temp);
// Segmentation fault
*conf->points->array = temp;
#else
conf->points->array = (ArrayOfStructures **)calloc(conf->points->length,sizeof(ArrayOfStructures *));
#endif
printf("conf->points->array=%p\n",conf->points->array);
}
void another_function(Config *conf)
{
conf->points->length = 1;
add_new_array(conf);
conf->points->array[0]->X = 0.1;
conf->points->array[0]->Y = 0.2;
printf("The result: X=%.12f, Y=%.12f, length=%zu\n",conf->points->array[0]->X,conf->points->array[0]->Y,conf->points->length);
}
void some_function(Config * conf)
{
// To pass the structure to another function
another_function(conf);
}
int main(void)
{
// Stack's allocated memory
Config conf_;
Config *conf = &conf_;
memset(conf,0x0,sizeof(Config));
// Stack's allocated memory
Points points;
memset(&points,0x0,sizeof(Points));
conf->points = &points;
some_function(conf);
return(EXIT_SUCCESS);
}
```
Compiled using:
```
gcc -D_SVID_SOURCE -g -ggdb -ggdb1 -ggdb2 -ggdb3 -O0 -DDEBUG -std=c11 -Wall --pedantic arryay.c -o array
```
I tried to find answers for handling a double pointer, but everything is very confusing. | 2019/06/04 | [
"https://Stackoverflow.com/questions/56450254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7104681/"
] | If you do not mind creating one more dataframe for `mylist`, one way may be to use `merge`:
```
mylist_df = pd.DataFrame(mylist, columns=['RPN', 'npi']) # creating other df
df = df.merge(mylist_df, how='left', on='RPN')
df['npi'].fillna(df['RPN'], inplace=True) # fill na values with RPN of same dataframe
``` | `map` with a dict + `fillna` to replace unmapped values. Depending upon the shape of `mylist` choose the correct dictionary:
```
d = dict(zip(*mylist)) # if [[1, 2, 3], ['2000', '2000a', '2000b']]
d = dict(mylist) # if [[1, '2000'], [2, '2000a'], [3,'2000b']]
df['npi'] = df.RPN.map(d).fillna(df.RPN)
# RPN Source city npi
#0 1 netflix baltimore 2000
#1 1 netflix baltimore 2000
#2 2 hulu orlando 2000a
#3 4 hulu houston 4
``` |
56,450,254 | When I use this code I would like to turn to every element of array of structures like this:
```
array[0]->X;
array[1]->X;
```
I tried everything I could, but in all cases I've had Segmentation fault. What am I doing wrong?
Please look at blocks between #if 0 #endif
```
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <inttypes.h>
typedef struct
{
double X;
double Y;
} ArrayOfStructures;
typedef struct
{
uint_fast64_t length;
ArrayOfStructures **array;
} Points;
typedef struct
{
Points *points;
} Config;
void add_new_array(Config *conf)
{
printf("conf=%p\n",conf);
printf("conf->points=%p\n",conf->points);
printf("conf->points->length=%zu\n",conf->points->length);
printf("conf->points->array=%p\n",conf->points->array);
#if 0
ArrayOfStructures *temp = (ArrayOfStructures*)calloc(conf->points->length,sizeof(ArrayOfStructures));
printf("temp=%p\n",temp);
// Segmentation fault
*conf->points->array = temp;
#else
conf->points->array = (ArrayOfStructures **)calloc(conf->points->length,sizeof(ArrayOfStructures *));
#endif
printf("conf->points->array=%p\n",conf->points->array);
}
void another_function(Config *conf)
{
conf->points->length = 1;
add_new_array(conf);
conf->points->array[0]->X = 0.1;
conf->points->array[0]->Y = 0.2;
printf("The result: X=%.12f, Y=%.12f, length=%zu\n",conf->points->array[0]->X,conf->points->array[0]->Y,conf->points->length);
}
void some_function(Config * conf)
{
// To pass the structure to another function
another_function(conf);
}
int main(void)
{
// Stack's allocated memory
Config conf_;
Config *conf = &conf_;
memset(conf,0x0,sizeof(Config));
// Stack's allocated memory
Points points;
memset(&points,0x0,sizeof(Points));
conf->points = &points;
some_function(conf);
return(EXIT_SUCCESS);
}
```
Compiled using:
```
gcc -D_SVID_SOURCE -g -ggdb -ggdb1 -ggdb2 -ggdb3 -O0 -DDEBUG -std=c11 -Wall --pedantic arryay.c -o array
```
I tried to find answers for handling a double pointer, but everything is very confusing. | 2019/06/04 | [
"https://Stackoverflow.com/questions/56450254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7104681/"
] | If you do not mind creating one more dataframe for `mylist`, one way may be to use `merge`:
```
mylist_df = pd.DataFrame(mylist, columns=['RPN', 'npi']) # creating other df
df = df.merge(mylist_df, how='left', on='RPN')
df['npi'].fillna(df['RPN'], inplace=True) # fill na values with RPN of same dataframe
``` | This can be viewed as a left join with a `fillna` operation afterwards.
```
my_series = pd.series(index=[1, 2, 3], data=['2000', '2000a', '2000b'], name='RPN')
df = pd.DataFrame({"RPN": [1, 1, 2, 4], "Source": ['netflix', 'netflix', 'hulu', 'hulu']}).set_index("RPN")
result = df.join(my_series, how="left").reset_index()
result = result.fillna(result.RPN, axis=0)
``` |
5,127,573 | In the eclipse directory, there is .classpath file. What's the purpose of this file?
I have ant build.xml available, why Eclipse still need its own? | 2011/02/26 | [
"https://Stackoverflow.com/questions/5127573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496949/"
] | Eclipse has its own mechanism for building your project. The .classpath file contains information that the IDE uses to create the classpath used at build-time, runtime etc. You can directly edit this file if you want but it is created by the IDE based on the settings that you provide via the project properties dialog.
There is Ant integration within Eclipse insofar as it provides you a specific editor for build files, but it can't use any of the information in the build file for its own builders. Ant files are custom, so there is no way Eclipse could know what info to use. | The reason for this is that it doesn't matter if you have an Ant file or not. The reason for the presence of this file is that this is a Java Project, and the corresponding Project nature always generate such a file. Create a normal Project (New->Project->General->Project) and you'll see that there is no .classpath file.
In general I would recommend to split those functionalities in separate projects, that means one Java Project for developing, one non-Java-Project for executing your Ant scripts.
HTH Tom |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | I would recommend [SharpKeys](http://sharpkeys.codeplex.com):
>
> SharpKeys is a Registry hack that is used to make certain keys on a
> keyboard act like other keys. For example, if you accidentally hit
> Caps Lock often, you could use this utility to map Caps Lock to a
> Shift key or even turn it off completely. This official release
> includes support for up to 104 mappings, an extensive list of
> available keys, and a "Type Key" option to help when managing
> mappings.
>
>
>
I have not used it personally, but know someone who has used it in the past and is quite happy with it. | Why not a hardware solution? Physically remove the key. |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | I would recommend [SharpKeys](http://sharpkeys.codeplex.com):
>
> SharpKeys is a Registry hack that is used to make certain keys on a
> keyboard act like other keys. For example, if you accidentally hit
> Caps Lock often, you could use this utility to map Caps Lock to a
> Shift key or even turn it off completely. This official release
> includes support for up to 104 mappings, an extensive list of
> available keys, and a "Type Key" option to help when managing
> mappings.
>
>
>
I have not used it personally, but know someone who has used it in the past and is quite happy with it. | If I understand you correctly, the problem is not pressing `AltGr`, but `AltGr` in combination with other keys?
You might want to get [The Microsoft Keyboard Layout Creator](http://msdn.microsoft.com/en-us/goglobal/bb964665.aspx).
There you `Load existing Keyboard...` (from File-Menu), select the language and design your user prefers, delete any bindings to keys with the `Shift states` of `AltGr`. Then you `Build DLL and Setup Package` (from Project-Menu) and afterwards install your individual keyboard design to the target machine. |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | I would recommend [SharpKeys](http://sharpkeys.codeplex.com):
>
> SharpKeys is a Registry hack that is used to make certain keys on a
> keyboard act like other keys. For example, if you accidentally hit
> Caps Lock often, you could use this utility to map Caps Lock to a
> Shift key or even turn it off completely. This official release
> includes support for up to 104 mappings, an extensive list of
> available keys, and a "Type Key" option to help when managing
> mappings.
>
>
>
I have not used it personally, but know someone who has used it in the past and is quite happy with it. | Thanks guys. MS KLC was also an idea I considered, but as I only wanted to disable that simple key, it seemed too much work to create a separate layout etc.
I finally found "keytweak" (here: <http://webpages.charter.net/krumsick/> ) and that has an easy switch "disable key" which quickly fixed the problem. :) |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | I would recommend [SharpKeys](http://sharpkeys.codeplex.com):
>
> SharpKeys is a Registry hack that is used to make certain keys on a
> keyboard act like other keys. For example, if you accidentally hit
> Caps Lock often, you could use this utility to map Caps Lock to a
> Shift key or even turn it off completely. This official release
> includes support for up to 104 mappings, an extensive list of
> available keys, and a "Type Key" option to help when managing
> mappings.
>
>
>
I have not used it personally, but know someone who has used it in the past and is quite happy with it. | I'm using the [keymapper](https://code.google.com/p/keymapper/) program to accomplish this. It lets you remap and disable keyboard keys using a virtual keyboard. |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | If I understand you correctly, the problem is not pressing `AltGr`, but `AltGr` in combination with other keys?
You might want to get [The Microsoft Keyboard Layout Creator](http://msdn.microsoft.com/en-us/goglobal/bb964665.aspx).
There you `Load existing Keyboard...` (from File-Menu), select the language and design your user prefers, delete any bindings to keys with the `Shift states` of `AltGr`. Then you `Build DLL and Setup Package` (from Project-Menu) and afterwards install your individual keyboard design to the target machine. | Why not a hardware solution? Physically remove the key. |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | If I understand you correctly, the problem is not pressing `AltGr`, but `AltGr` in combination with other keys?
You might want to get [The Microsoft Keyboard Layout Creator](http://msdn.microsoft.com/en-us/goglobal/bb964665.aspx).
There you `Load existing Keyboard...` (from File-Menu), select the language and design your user prefers, delete any bindings to keys with the `Shift states` of `AltGr`. Then you `Build DLL and Setup Package` (from Project-Menu) and afterwards install your individual keyboard design to the target machine. | Thanks guys. MS KLC was also an idea I considered, but as I only wanted to disable that simple key, it seemed too much work to create a separate layout etc.
I finally found "keytweak" (here: <http://webpages.charter.net/krumsick/> ) and that has an easy switch "disable key" which quickly fixed the problem. :) |
588,069 | I am supporting a user that can't type and consequently often hits `AltGr` (on the right side of space-key). He has enough power to decide he wants to disable that key (instead of learning to type). and he asked me to quickly get rid of that key
The only way I found was using KbdEdit and map `AltGr` to "KANA" ([How to](http://www.kbdedit.com/manual/ex13_replacing_altgr_with_kana.html)) but unfortunately that does not behave as promised. I am waiting for support from the developer, but thought that meanwhile I should see if anyone of you has better suggestion how to address this. | 2013/04/26 | [
"https://superuser.com/questions/588069",
"https://superuser.com",
"https://superuser.com/users/25225/"
] | If I understand you correctly, the problem is not pressing `AltGr`, but `AltGr` in combination with other keys?
You might want to get [The Microsoft Keyboard Layout Creator](http://msdn.microsoft.com/en-us/goglobal/bb964665.aspx).
There you `Load existing Keyboard...` (from File-Menu), select the language and design your user prefers, delete any bindings to keys with the `Shift states` of `AltGr`. Then you `Build DLL and Setup Package` (from Project-Menu) and afterwards install your individual keyboard design to the target machine. | I'm using the [keymapper](https://code.google.com/p/keymapper/) program to accomplish this. It lets you remap and disable keyboard keys using a virtual keyboard. |
14,062,904 | I'm working on a low latency system and need a solution to convert a double number to byte array but with precision for decimal numbers. I need to consider there should be less object creation within the solution. Also, I'm getting value as double.
My current implementation is somewhat like
```
int offset = 0;
double d = 1211.11;
long integerPart = (long) d;
byte[] b = new byte[16];
offset += addToByteArray(integerPart, b, offset);
//implementation to add each digit to byte array, returns new offset
int lengthDecimal = 16 - offset;
if(lengthDecimal > 0)
b[offset++] = '.';
long tmp = 1;
for(int i=0; i<lengthDecimal; i++){
tmp = tmp * 10;
int digit = (int)(((long) (d * tmp)) % 10);
b[offset++] = (byte) ('0' + digit);
}
```
Then the byte array is manipulated to trim later zeros and '.' if required.
The problem is if I check the byte array, I don't find the exact digits. Since, I'm using double, the precision of decimal point is lost while working.
I've searched and found everywhere to use BigDecimal. The use of BigDecimal seems to work fine but I'm worried about the performance and number of objects created as this part of the code is hit frequently.
I've also tried to work with String like this
```
String doubleNumber = Double.toString(d);
long fractionalPart = 0;
offset += addToByteArray(integerPart, b, offset);
if(doubleNumber.substring(doubleNumber.indexOf(".")).length() > 0) {
fractionalPart = Long.valueOf(doubleNumber.substring(doubleNumber.indexOf(".") + 1));
b[offset++] = '.';
offset += addToByteArray(fractionalPart, b, offset);
}
```
Please suggest me the best approach for the purpose. | 2012/12/27 | [
"https://Stackoverflow.com/questions/14062904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293768/"
] | ```
byte[] bytes = new byte[8];
java.nio.ByteBuffer.wrap(bytes).putDouble(yourDouble);
``` | If you really want low latency, then the important thing is to avoid heap memory allocations (which cause GC pauses at some unspecified later point).
So I'm assuming that:
* You have allocated your byte array in advance
* You want to put a double in your byte array without doing any intermediate allocations
The trick is to use `doubleToLongBits`:
```
long v = Double.doubleToLongBits(myDouble);
```
Then write the `long` into the correct position in your byte array (presumably using 8 consecutive bytes). You might as well just do this the brute force way:
```
data[pos+7] = (byte)(v);
data[pos+6] = (byte)(v>>>8);
data[pos+5] = (byte)(v>>>16);
data[pos+4] = (byte)(v>>>24);
data[pos+3] = (byte)(v>>>32);
data[pos+2] = (byte)(v>>>40);
data[pos+1] = (byte)(v>>>48);
data[pos] = (byte)(v>>>56);
```
Note we are using primitives at every point, so there are no memory allocations throughout this process. |
14,062,904 | I'm working on a low latency system and need a solution to convert a double number to byte array but with precision for decimal numbers. I need to consider there should be less object creation within the solution. Also, I'm getting value as double.
My current implementation is somewhat like
```
int offset = 0;
double d = 1211.11;
long integerPart = (long) d;
byte[] b = new byte[16];
offset += addToByteArray(integerPart, b, offset);
//implementation to add each digit to byte array, returns new offset
int lengthDecimal = 16 - offset;
if(lengthDecimal > 0)
b[offset++] = '.';
long tmp = 1;
for(int i=0; i<lengthDecimal; i++){
tmp = tmp * 10;
int digit = (int)(((long) (d * tmp)) % 10);
b[offset++] = (byte) ('0' + digit);
}
```
Then the byte array is manipulated to trim later zeros and '.' if required.
The problem is if I check the byte array, I don't find the exact digits. Since, I'm using double, the precision of decimal point is lost while working.
I've searched and found everywhere to use BigDecimal. The use of BigDecimal seems to work fine but I'm worried about the performance and number of objects created as this part of the code is hit frequently.
I've also tried to work with String like this
```
String doubleNumber = Double.toString(d);
long fractionalPart = 0;
offset += addToByteArray(integerPart, b, offset);
if(doubleNumber.substring(doubleNumber.indexOf(".")).length() > 0) {
fractionalPart = Long.valueOf(doubleNumber.substring(doubleNumber.indexOf(".") + 1));
b[offset++] = '.';
offset += addToByteArray(fractionalPart, b, offset);
}
```
Please suggest me the best approach for the purpose. | 2012/12/27 | [
"https://Stackoverflow.com/questions/14062904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293768/"
] | ```
byte[] bytes = new byte[8];
java.nio.ByteBuffer.wrap(bytes).putDouble(yourDouble);
``` | If you want a double formatted into an ASCII (character) string then String.format is probably the simplest approach that gives you control over the format:
```
String result = String.formatter("%5.3f", theDoubleValue);
``` |
14,062,904 | I'm working on a low latency system and need a solution to convert a double number to byte array but with precision for decimal numbers. I need to consider there should be less object creation within the solution. Also, I'm getting value as double.
My current implementation is somewhat like
```
int offset = 0;
double d = 1211.11;
long integerPart = (long) d;
byte[] b = new byte[16];
offset += addToByteArray(integerPart, b, offset);
//implementation to add each digit to byte array, returns new offset
int lengthDecimal = 16 - offset;
if(lengthDecimal > 0)
b[offset++] = '.';
long tmp = 1;
for(int i=0; i<lengthDecimal; i++){
tmp = tmp * 10;
int digit = (int)(((long) (d * tmp)) % 10);
b[offset++] = (byte) ('0' + digit);
}
```
Then the byte array is manipulated to trim later zeros and '.' if required.
The problem is if I check the byte array, I don't find the exact digits. Since, I'm using double, the precision of decimal point is lost while working.
I've searched and found everywhere to use BigDecimal. The use of BigDecimal seems to work fine but I'm worried about the performance and number of objects created as this part of the code is hit frequently.
I've also tried to work with String like this
```
String doubleNumber = Double.toString(d);
long fractionalPart = 0;
offset += addToByteArray(integerPart, b, offset);
if(doubleNumber.substring(doubleNumber.indexOf(".")).length() > 0) {
fractionalPart = Long.valueOf(doubleNumber.substring(doubleNumber.indexOf(".") + 1));
b[offset++] = '.';
offset += addToByteArray(fractionalPart, b, offset);
}
```
Please suggest me the best approach for the purpose. | 2012/12/27 | [
"https://Stackoverflow.com/questions/14062904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293768/"
] | If you really want low latency, then the important thing is to avoid heap memory allocations (which cause GC pauses at some unspecified later point).
So I'm assuming that:
* You have allocated your byte array in advance
* You want to put a double in your byte array without doing any intermediate allocations
The trick is to use `doubleToLongBits`:
```
long v = Double.doubleToLongBits(myDouble);
```
Then write the `long` into the correct position in your byte array (presumably using 8 consecutive bytes). You might as well just do this the brute force way:
```
data[pos+7] = (byte)(v);
data[pos+6] = (byte)(v>>>8);
data[pos+5] = (byte)(v>>>16);
data[pos+4] = (byte)(v>>>24);
data[pos+3] = (byte)(v>>>32);
data[pos+2] = (byte)(v>>>40);
data[pos+1] = (byte)(v>>>48);
data[pos] = (byte)(v>>>56);
```
Note we are using primitives at every point, so there are no memory allocations throughout this process. | If you want a double formatted into an ASCII (character) string then String.format is probably the simplest approach that gives you control over the format:
```
String result = String.formatter("%5.3f", theDoubleValue);
``` |
112,727 | I am trying to switch to a GameScreen when the LinearVelocity of a Box2D - Object is x = 0.
If it is so, I am using the setScreen() - Method by calling the main class. This works perfekt, but when the screen should change, it just flickers, which is most likely caused by the render() - method in the screen class.
So my question is now, how to dipose that render method or how to dispose the whole screen class, so that I only the new screen appears!
Thanks | 2015/12/09 | [
"https://gamedev.stackexchange.com/questions/112727",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/75877/"
] | The obvious answer to this question is to sit down and watch through the entire archive of [**Handmade Hero**](http://handmadehero.org).
It is *exactly* what you are after. It is literally a tutorial on how to make a game from scratch, without engines or libraries. Obviously it is very long. | Unless you want to spend a couple of years writing your own drivers, you'll need at least a graphics library. I'm all for making things from scratch and while that can be fun, making **EVERYTHING** from scratch is frustrating, annoying and pointless.
The logic behind using libraries like OpenGL is to avoid complicated tedium that has a general solution and it lets you focus on the game.
As for where to learn?
This is impossible for us to answer, as there isn't just one skill that has to be gained, my advice is to start with a game idea and learn as you go. |
112,727 | I am trying to switch to a GameScreen when the LinearVelocity of a Box2D - Object is x = 0.
If it is so, I am using the setScreen() - Method by calling the main class. This works perfekt, but when the screen should change, it just flickers, which is most likely caused by the render() - method in the screen class.
So my question is now, how to dipose that render method or how to dispose the whole screen class, so that I only the new screen appears!
Thanks | 2015/12/09 | [
"https://gamedev.stackexchange.com/questions/112727",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/75877/"
] | The obvious answer to this question is to sit down and watch through the entire archive of [**Handmade Hero**](http://handmadehero.org).
It is *exactly* what you are after. It is literally a tutorial on how to make a game from scratch, without engines or libraries. Obviously it is very long. | **Sure you can!** Just, probably not very well on PC. You can pretty much forget about graphics card acceleration. To quote [Patrick Hughes' answer to another question](https://gamedev.stackexchange.com/a/16156/22026):
>
> [PC is like the] wild west, barroom brawls and your OS is the sheriff keeping everyone from getting shot.
>
>
> [...]on home PCs you have to support tens of different chipsets that have to work flawlessly against millions of programs written across the past decade or more? Personally I think that it's a miracle that the house of cards keeps standing!
>
>
>
As a business venture there's just too much going on there for you to be able to confidently support much more than *your own* PC, let alone the variety of quirks that crop up on other people's systems. But, if you're just interested in learning things about low level tricks (which in today's world only come up if you're working on drivers/middleware/APIs - things studios don't really do) and thus don't care too much about compatibility check out some of the code released from demoscenes, at ie
[The Great Demoscene Sourcecode Giveaway](http://www.displayhack.org/2012/the-great-demoscene-sourcecode-giveaway/).
Or, as a technical exercise, writing a game from the ground up targeting a simple platform like Arduino is completely achievable. Since it's essentially just a flashable chip, you'll have to decide on the parameters of your game. Maybe you skip the screen and do sound only? Strange controller? It would be a good setup for getting into console development. |
33,022,749 | I'm trying to store some field of a form into database, using this code:
```
$data = $form->getData();
$em=$this->getDoctrine()->getManager();
$em=persist($data->getCompany());
$em->flush();
return $this->redirectToRoute('target_success');}
```
But I get following error:
```
Attempted to call function "persist" from namespace "site\formBundle\Controller".
```
Any help would be welcome. | 2015/10/08 | [
"https://Stackoverflow.com/questions/33022749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820116/"
] | `$em=persist ...` should be `$em->persist(...);`
Furthermore I wonder if it is going to work. Does `getCompany()` return an entity? | $em->persist() must have an instance of an entity object as its parameter. The persist operation tells Doctrine you want this entity to be written to database. You can't give an individual field to persist(), it writes the whole object. Also you appear to be trying to write a form back to the database. You need to pass the form to an entity object, then persist that object to database. Have you created an entity class yet?
I'm not sure why you need to write back fields to database one by one (this is a very odd requirement).
There's no point in me suggesting any code yet as it's not clear if you've got an entity class or not, so I can only suggest you take a good read of [Symfony's simple form guide](http://symfony.com/doc/current/book/forms.html). This shows you how to define your entity, how to create a form, how to copy the submitted form back to your entity object, then how to write your entity object to database. |
64,055,519 | I am making shopping app and I am listing user's cart in a recycler view then calculate total price inside `onBindViewHolder` but I have to scroll down to get price of all items.
can I make recycler view load all items at once or is there better solution to count total price?
by the way I tried putting the recycler view inside nester scroll view but did not work it show empty list | 2020/09/24 | [
"https://Stackoverflow.com/questions/64055519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14337006/"
] | If you simply want to specify WHICH database to query, you can fully-qualify the reference to the `INFORMATION_SCHEMA.TABLES` view as follows:
```
select t.table_schema,
t.table_name
from DATABASE_NAME_TO_SEARCH.information_schema.tables t
inner join information_schema.columns c on
c.table_schema = t.table_schema and c.table_name = t.table_name
where t.table_type = 'BASE TABLE'
and column_name ='N_NAME'
order by t.table_schema,
t.table_name;
```
If you want to scan across ALL databases within a Snowflake account, you can do it with the following PAIR of commands:
```
SHOW COLUMNS LIKE 'COLUMN_NAME_HERE' IN ACCOUNT
;
SELECT "database_name" AS TABLE_DB
,"schema_name" AS TABLE_SCHEMA
,"table_name" AS TABLE_NAME
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
WHERE "kind" = 'COLUMN'
ORDER BY 1, 2, 3
;
``` | One option is to use the database `SNOWFLAKE.ACCOUNT_USAGE`:
```sql
select table_schema, table_name, column_name
from snowflake.account_usage.columns
where deleted is null
and column_name='RIP4'
```
Most users don't have access to it, so you might need to grant the privileges first:
```sql
use role accountadmin;
grant imported privileges on database snowflake to role sysadmin;
```
>
> <https://docs.snowflake.com/en/sql-reference/account-usage.html>
>
>
> |
64,055,519 | I am making shopping app and I am listing user's cart in a recycler view then calculate total price inside `onBindViewHolder` but I have to scroll down to get price of all items.
can I make recycler view load all items at once or is there better solution to count total price?
by the way I tried putting the recycler view inside nester scroll view but did not work it show empty list | 2020/09/24 | [
"https://Stackoverflow.com/questions/64055519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14337006/"
] | One option is to use the database `SNOWFLAKE.ACCOUNT_USAGE`:
```sql
select table_schema, table_name, column_name
from snowflake.account_usage.columns
where deleted is null
and column_name='RIP4'
```
Most users don't have access to it, so you might need to grant the privileges first:
```sql
use role accountadmin;
grant imported privileges on database snowflake to role sysadmin;
```
>
> <https://docs.snowflake.com/en/sql-reference/account-usage.html>
>
>
> | An alternative way to get the tables that contain a specific column name is the following:
```
show columns like 'COLUMN_NAME' in schema "DB_NAME"."SCHEMA_NAME"
```
In the above example, we search for all tables under the database "DB\_NAME" and under the schema "SCHEMA\_NAME" that contain the column called "COLUMN\_NAME".
You can have a look at the [Show Columns](https://docs.snowflake.com/en/sql-reference/sql/show-columns.html) Snowflake Documentation. The full syntax is:
```
SHOW COLUMNS [ LIKE '<pattern>' ]
[ IN { ACCOUNT | DATABASE [ <database_name> ] | SCHEMA [ <schema_name> ] | TABLE | [ TABLE ] <table_name> | VIEW | [ VIEW ] <view_name> } ]
```
Note that if you specify the keyword ACCOUNT, then the command retrieves records for all schemas in all databases of the current account.
Source: [Predictive Hacks](https://predictivehacks.com/?all-tips=how-to-find-tables-that-contain-a-specific-column-in-snowflake) |
64,055,519 | I am making shopping app and I am listing user's cart in a recycler view then calculate total price inside `onBindViewHolder` but I have to scroll down to get price of all items.
can I make recycler view load all items at once or is there better solution to count total price?
by the way I tried putting the recycler view inside nester scroll view but did not work it show empty list | 2020/09/24 | [
"https://Stackoverflow.com/questions/64055519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14337006/"
] | If you simply want to specify WHICH database to query, you can fully-qualify the reference to the `INFORMATION_SCHEMA.TABLES` view as follows:
```
select t.table_schema,
t.table_name
from DATABASE_NAME_TO_SEARCH.information_schema.tables t
inner join information_schema.columns c on
c.table_schema = t.table_schema and c.table_name = t.table_name
where t.table_type = 'BASE TABLE'
and column_name ='N_NAME'
order by t.table_schema,
t.table_name;
```
If you want to scan across ALL databases within a Snowflake account, you can do it with the following PAIR of commands:
```
SHOW COLUMNS LIKE 'COLUMN_NAME_HERE' IN ACCOUNT
;
SELECT "database_name" AS TABLE_DB
,"schema_name" AS TABLE_SCHEMA
,"table_name" AS TABLE_NAME
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
WHERE "kind" = 'COLUMN'
ORDER BY 1, 2, 3
;
``` | An alternative way to get the tables that contain a specific column name is the following:
```
show columns like 'COLUMN_NAME' in schema "DB_NAME"."SCHEMA_NAME"
```
In the above example, we search for all tables under the database "DB\_NAME" and under the schema "SCHEMA\_NAME" that contain the column called "COLUMN\_NAME".
You can have a look at the [Show Columns](https://docs.snowflake.com/en/sql-reference/sql/show-columns.html) Snowflake Documentation. The full syntax is:
```
SHOW COLUMNS [ LIKE '<pattern>' ]
[ IN { ACCOUNT | DATABASE [ <database_name> ] | SCHEMA [ <schema_name> ] | TABLE | [ TABLE ] <table_name> | VIEW | [ VIEW ] <view_name> } ]
```
Note that if you specify the keyword ACCOUNT, then the command retrieves records for all schemas in all databases of the current account.
Source: [Predictive Hacks](https://predictivehacks.com/?all-tips=how-to-find-tables-that-contain-a-specific-column-in-snowflake) |
91,779 | I had created the dropdown list with fields Lab,Pharmacy,Food and Nurse.When I select the lab it generates the new fields and when I select the pharmacy it generates the new field with upload button.I need to send the mail with these details for lab and pharmacy.
By using below mail function I can send only for lab but when I select pharmacy I could not send any mail.Please help me
```
<?php
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if ($_POST['servicetype'] == 'Lab') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if ($_POST['servicetype'] == 'Pharmacy') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
} else if ($_POST['servicetype'] == 'Gym') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
} else if ($_POST['servicetype'] == 'Food') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
} else if ($_POST['servicetype'] == 'Nurse') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
} else if ($_POST['servicetype'] == 'Physio') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata = $readconnection->fetchAll($allrecord);
foreach ($alldata as $data) {
sendMailserviceAction($data['email'], $data['name']);
}
function sendMailserviceAction($email, $pname) {
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype = $_POST['servicetype'];
$cemail = $_POST['labemail'];
$cemail = $_POST['pemail'];
$cemail = $_POST['femail'];
if ($_POST['servicetype'] == 'Lab') {
$cemail = $_POST['labemail'];
$servicetype = $_POST['servicetype'];
$testname = $_POST['testname'];
$name = $_POST['name'];
$mobile = $_POST['labmobile'];
$city = $_POST['rcity'];
$zipcode = $_POST['labzip_code'];
$html = '
<p>Service Type: ' . $servicetype . '</p>
<p>Testname:' . $testname . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile Number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Pharmacy') {
$name = $_POST['pname'];
$medicine = $_POST['medicinename'];
$cemail = $_POST['pemail'];
$mobile = $_POST['pmobile'];
$city = $_POST['pcity'];
$zipcode = $_POST['pzip_code'];
$html = '<p>Service Type:' . $servicetype . '</p> <p> Medicine name: ' . $medicine . '</p>
<p>Name:' . $name . '</p>
<p> Email: ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Gym') {
$name = $_POST['fname'];
$mobile = $_POST['fmobile'];
$cemail = $_POST['femail'];
$city = $_POST['fcity'];
$zipcode = $_POST['fzip_code'];
$html = '
<p>Service Type:' . $servicetype . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Food') {
$name = $_POST['fname'];
$cemail = $_POST['femail'];
$mobile = $_POST['fmobile'];
$city = $_POST['fcity'];
$zipcode = $_POST['fzip_code'];
$html = '
<p>Service Type:' . $servicetype . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
}
if (!empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype'] == 'Pharmacy') {
$image_ext = end(explode('.', $_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif', 'png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'rtf', 'odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1, 100) . rand(1, 100))) . str_replace(" ", "_", $_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename;
if (in_array($image_ext, $allowed_ext)) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in', "Labwise");
$mail->addTo($email, $pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if (file_exists(Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename)) {
$attachment = file_get_contents(Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
} catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailserviceAction();
?>
``` | 2015/11/27 | [
"https://magento.stackexchange.com/questions/91779",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/29354/"
] | try that for sending the email just change the `model` and `attachment` code
```
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($cemail,$pname);
$mail->setSubject('Blood Donor');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
$mail->send();
```
**new and tested code**
leave the html before as it is
```
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($ssemail,$pname);
$mail->setSubject('Blood Donor');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
$mail->send();
```
with your code
```
<?php
function sendMailAction(){
//Mage::getModel('sales/order')->load(24999);
$servicetype=$_POST['servicetype'];
if($_POST['servicetype']=='Lab'){
$name=$_POST['name'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$email=$_POST['labemail'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Testname: '.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>
';
}
else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$email=$_POST['pemail'];
$city=$_POST['pcity'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html=
'<p>Service Type:'.$servicetype.'</p>
<p>Medicinename: '.$medicine.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Physio')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Nurse')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($email,$pname);
$mail->setSubject('Blood Donor');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
}
catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailAction();
?>
```
for service provider
```
<?php
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if($_POST['servicetype']=='Lab')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if($_POST['servicetype']=='Pharmacy')
{
$allrecord =$rea connection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
}else if($_POST['servicetype']=='Gym')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
}else if($_POST['servicetype']=='Food')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
}else if($_POST['servicetype']=='Nurse')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
}else if($_POST['servicetype']=='Physio')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata =$readconnection->fetchAll($allrecord);
foreach($alldata as $data)
{
sendMailserviceAction($data['email'],$data['name']);
}
function sendMailserviceAction($ccemail,$pname){
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype=$_POST['servicetype'];
$cemail=$_POST['labemail'];
$cemail=$_POST['pemail'];
$cemail=$_POST['femail'];
if($_POST['servicetype']=='Lab')
{
$cemail=$_POST['labemail'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$name=$_POST['name'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html ='
<p>Service Type: '.$servicetype.'</p>
<p>Testname:'.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile Number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$cemail=$_POST['pemail'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html ='<p>Service Type:'.$servicetype.'</p> <p> Medicine name: '.$medicine.'</p>
<p>Name:'.$name.'</p>
<p> Email: '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$mobile=$_POST['fmobile'];
$cemail=$_POST['femail'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$cemail=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($ccemail,$pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename ) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
}
catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailserviceAction();
?>
``` | This code is Working for me try this le me know if you have any query
```
$mailTemplate = Mage::getModel('core/email_template');
/* @var $mailTemplate Mage_Core_Model_Email_Template */
// file attached
if($post['file']){
$destination_path = Mage::getBaseDir('media'). DS .'uploads'.DS.$post['file'];
$mailTemplate->getMail()->createAttachment(
file_get_contents($destination_path),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$post['file']
);
}
// after file attached
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
``` |
91,779 | I had created the dropdown list with fields Lab,Pharmacy,Food and Nurse.When I select the lab it generates the new fields and when I select the pharmacy it generates the new field with upload button.I need to send the mail with these details for lab and pharmacy.
By using below mail function I can send only for lab but when I select pharmacy I could not send any mail.Please help me
```
<?php
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if ($_POST['servicetype'] == 'Lab') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if ($_POST['servicetype'] == 'Pharmacy') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
} else if ($_POST['servicetype'] == 'Gym') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
} else if ($_POST['servicetype'] == 'Food') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
} else if ($_POST['servicetype'] == 'Nurse') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
} else if ($_POST['servicetype'] == 'Physio') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata = $readconnection->fetchAll($allrecord);
foreach ($alldata as $data) {
sendMailserviceAction($data['email'], $data['name']);
}
function sendMailserviceAction($email, $pname) {
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype = $_POST['servicetype'];
$cemail = $_POST['labemail'];
$cemail = $_POST['pemail'];
$cemail = $_POST['femail'];
if ($_POST['servicetype'] == 'Lab') {
$cemail = $_POST['labemail'];
$servicetype = $_POST['servicetype'];
$testname = $_POST['testname'];
$name = $_POST['name'];
$mobile = $_POST['labmobile'];
$city = $_POST['rcity'];
$zipcode = $_POST['labzip_code'];
$html = '
<p>Service Type: ' . $servicetype . '</p>
<p>Testname:' . $testname . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile Number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Pharmacy') {
$name = $_POST['pname'];
$medicine = $_POST['medicinename'];
$cemail = $_POST['pemail'];
$mobile = $_POST['pmobile'];
$city = $_POST['pcity'];
$zipcode = $_POST['pzip_code'];
$html = '<p>Service Type:' . $servicetype . '</p> <p> Medicine name: ' . $medicine . '</p>
<p>Name:' . $name . '</p>
<p> Email: ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Gym') {
$name = $_POST['fname'];
$mobile = $_POST['fmobile'];
$cemail = $_POST['femail'];
$city = $_POST['fcity'];
$zipcode = $_POST['fzip_code'];
$html = '
<p>Service Type:' . $servicetype . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Food') {
$name = $_POST['fname'];
$cemail = $_POST['femail'];
$mobile = $_POST['fmobile'];
$city = $_POST['fcity'];
$zipcode = $_POST['fzip_code'];
$html = '
<p>Service Type:' . $servicetype . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
}
if (!empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype'] == 'Pharmacy') {
$image_ext = end(explode('.', $_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif', 'png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'rtf', 'odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1, 100) . rand(1, 100))) . str_replace(" ", "_", $_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename;
if (in_array($image_ext, $allowed_ext)) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in', "Labwise");
$mail->addTo($email, $pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if (file_exists(Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename)) {
$attachment = file_get_contents(Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
} catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailserviceAction();
?>
``` | 2015/11/27 | [
"https://magento.stackexchange.com/questions/91779",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/29354/"
] | this is tested code all email are working without any error.
```
<?php
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
function sendMailAction($uploadfilename){
//Mage::getModel('sales/order')->load(24999);
$servicetype=$_POST['servicetype'];
if($_POST['servicetype']=='Lab'){
$name=$_POST['name'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$email=$_POST['labemail'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Testname: '.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>
';
}
else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$email=$_POST['pemail'];
$city=$_POST['pcity'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html=
'<p>Service Type:'.$servicetype.'</p>
<p>Medicinename: '.$medicine.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Physio')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Nurse')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($email,$name);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
$mail->send();
}
//Customer mail
function sendMailcustomerAction(){
//Mage::getModel('sales/order')->load(24999);
if($_POST['servicetype']=='Lab'){
$name=$_POST['name'];
$servicetype=$_POST['servicetype'];
$email=$_POST['labemail'];
$testname=$_POST['testname'];
$html=
'Dear '.$name.',
<p>We have received your order for '.$testname.'. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Pharmacy')
{ $name=$_POST['pname'];
$email=$_POST['pemail'];
$medicine=$_POST['medicinename'];
$html=
'Dear '.$name.',
<p>We have received your order for '.$medicine.'. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Physio')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Nurse')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
$mail = Mage::getModel('core/email');
$mail->setToName($name);
$mail->setToEmail($email);
$mail->setBody($html);
$mail->setSubject('Quick Service');
$mail->setFromEmail('admin@labwise.in');
$mail->setFromName("Labwise");
//$mail->addBcc("contact@labwise.in");
$mail->setType('html');// YOu can use Html or text as Mail format
try {
$mail->send();
//Mage::getSingleton('core/session')->addSuccess('Your Order is successfully Completed');
//Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl());
return '<h2>Your Request has been submitted.Thank you for using labwise. </h2>';
//$this->_redirect('');
}
catch (Exception $e) {
//Mage::getSingleton('core/session')->addError('Unable to send.');
//Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl());
return '</h2>Unable to submit.</h2>';
//$this->_redirect('');
}
}
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if($_POST['servicetype']=='Lab')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if($_POST['servicetype']=='Pharmacy')
{
$allrecord =$reaconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
}else if($_POST['servicetype']=='Gym')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
}else if($_POST['servicetype']=='Food')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
}else if($_POST['servicetype']=='Nurse')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
}else if($_POST['servicetype']=='Physio')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata =$readconnection->fetchAll($allrecord);
foreach($alldata as $data)
{
sendMailserviceAction($data['email'],$data['name']);
}
function sendMailserviceAction($ccemail,$pname,$uploadfilename){
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype=$_POST['servicetype'];
$cemail=$_POST['labemail'];
$cemail=$_POST['pemail'];
$cemail=$_POST['femail'];
if($_POST['servicetype']=='Lab')
{
$cemail=$_POST['labemail'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$name=$_POST['name'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html ='
<p>Service Type: '.$servicetype.'</p>
<p>Testname:'.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile Number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$cemail=$_POST['pemail'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html ='<p>Service Type:'.$servicetype.'</p> <p> Medicine name: '.$medicine.'</p>
<p>Name:'.$name.'</p>
<p> Email: '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$mobile=$_POST['fmobile'];
$cemail=$_POST['femail'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$cemail=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($ccemail,$pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename ) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
}
catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
?>
``` | try that for sending the email just change the `model` and `attachment` code
```
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($cemail,$pname);
$mail->setSubject('Blood Donor');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
$mail->send();
```
**new and tested code**
leave the html before as it is
```
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($ssemail,$pname);
$mail->setSubject('Blood Donor');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
$mail->send();
```
with your code
```
<?php
function sendMailAction(){
//Mage::getModel('sales/order')->load(24999);
$servicetype=$_POST['servicetype'];
if($_POST['servicetype']=='Lab'){
$name=$_POST['name'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$email=$_POST['labemail'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Testname: '.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>
';
}
else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$email=$_POST['pemail'];
$city=$_POST['pcity'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html=
'<p>Service Type:'.$servicetype.'</p>
<p>Medicinename: '.$medicine.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Physio')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Nurse')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($email,$pname);
$mail->setSubject('Blood Donor');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
}
catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailAction();
?>
```
for service provider
```
<?php
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if($_POST['servicetype']=='Lab')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if($_POST['servicetype']=='Pharmacy')
{
$allrecord =$rea connection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
}else if($_POST['servicetype']=='Gym')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
}else if($_POST['servicetype']=='Food')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
}else if($_POST['servicetype']=='Nurse')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
}else if($_POST['servicetype']=='Physio')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata =$readconnection->fetchAll($allrecord);
foreach($alldata as $data)
{
sendMailserviceAction($data['email'],$data['name']);
}
function sendMailserviceAction($ccemail,$pname){
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype=$_POST['servicetype'];
$cemail=$_POST['labemail'];
$cemail=$_POST['pemail'];
$cemail=$_POST['femail'];
if($_POST['servicetype']=='Lab')
{
$cemail=$_POST['labemail'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$name=$_POST['name'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html ='
<p>Service Type: '.$servicetype.'</p>
<p>Testname:'.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile Number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$cemail=$_POST['pemail'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html ='<p>Service Type:'.$servicetype.'</p> <p> Medicine name: '.$medicine.'</p>
<p>Name:'.$name.'</p>
<p> Email: '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$mobile=$_POST['fmobile'];
$cemail=$_POST['femail'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$cemail=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($ccemail,$pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename ) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
}
catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailserviceAction();
?>
``` |
91,779 | I had created the dropdown list with fields Lab,Pharmacy,Food and Nurse.When I select the lab it generates the new fields and when I select the pharmacy it generates the new field with upload button.I need to send the mail with these details for lab and pharmacy.
By using below mail function I can send only for lab but when I select pharmacy I could not send any mail.Please help me
```
<?php
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if ($_POST['servicetype'] == 'Lab') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if ($_POST['servicetype'] == 'Pharmacy') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
} else if ($_POST['servicetype'] == 'Gym') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
} else if ($_POST['servicetype'] == 'Food') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
} else if ($_POST['servicetype'] == 'Nurse') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
} else if ($_POST['servicetype'] == 'Physio') {
$allrecord = $readconnection->select()->from(array('serviceprovider' => 'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata = $readconnection->fetchAll($allrecord);
foreach ($alldata as $data) {
sendMailserviceAction($data['email'], $data['name']);
}
function sendMailserviceAction($email, $pname) {
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype = $_POST['servicetype'];
$cemail = $_POST['labemail'];
$cemail = $_POST['pemail'];
$cemail = $_POST['femail'];
if ($_POST['servicetype'] == 'Lab') {
$cemail = $_POST['labemail'];
$servicetype = $_POST['servicetype'];
$testname = $_POST['testname'];
$name = $_POST['name'];
$mobile = $_POST['labmobile'];
$city = $_POST['rcity'];
$zipcode = $_POST['labzip_code'];
$html = '
<p>Service Type: ' . $servicetype . '</p>
<p>Testname:' . $testname . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile Number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Pharmacy') {
$name = $_POST['pname'];
$medicine = $_POST['medicinename'];
$cemail = $_POST['pemail'];
$mobile = $_POST['pmobile'];
$city = $_POST['pcity'];
$zipcode = $_POST['pzip_code'];
$html = '<p>Service Type:' . $servicetype . '</p> <p> Medicine name: ' . $medicine . '</p>
<p>Name:' . $name . '</p>
<p> Email: ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Gym') {
$name = $_POST['fname'];
$mobile = $_POST['fmobile'];
$cemail = $_POST['femail'];
$city = $_POST['fcity'];
$zipcode = $_POST['fzip_code'];
$html = '
<p>Service Type:' . $servicetype . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
} else if ($_POST['servicetype'] == 'Food') {
$name = $_POST['fname'];
$cemail = $_POST['femail'];
$mobile = $_POST['fmobile'];
$city = $_POST['fcity'];
$zipcode = $_POST['fzip_code'];
$html = '
<p>Service Type:' . $servicetype . '</p>
<p>Name: ' . $name . '</p>
<p>Email : ' . $cemail . '</p>
<p>Mobile number: ' . $mobile . '</p>
<p>City:' . $city . '</p>
<p>Zip Code:' . $zipcode . '</p>';
}
if (!empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype'] == 'Pharmacy') {
$image_ext = end(explode('.', $_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif', 'png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'rtf', 'odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1, 100) . rand(1, 100))) . str_replace(" ", "_", $_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename;
if (in_array($image_ext, $allowed_ext)) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in', "Labwise");
$mail->addTo($email, $pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if (file_exists(Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename)) {
$attachment = file_get_contents(Mage::getBaseDir('media') . DS . 'requestquote' . DS . $uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
} catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
echo sendMailserviceAction();
?>
``` | 2015/11/27 | [
"https://magento.stackexchange.com/questions/91779",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/29354/"
] | this is tested code all email are working without any error.
```
<?php
if( !empty($_FILES["fileToUpload"]["name"]) and $_POST['servicetype']=='Pharmacy')
{
$image_ext = end(explode('.',$_FILES["fileToUpload"]["name"]));
$allowed_ext = array('gif','png' ,'jpg','jpeg','pdf','doc','docx','rtf','odt');
$uploadfilename = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,100).rand(1,100))).str_replace(" ","_",$_FILES["fileToUpload"]["name"]);
$source_upl = $_FILES["fileToUpload"]["tmp_name"];
$target_path_upl = Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename;
if(in_array($image_ext ,$allowed_ext ) ) {
@move_uploaded_file($source_upl, $target_path_upl);
}
}
function sendMailAction($uploadfilename){
//Mage::getModel('sales/order')->load(24999);
$servicetype=$_POST['servicetype'];
if($_POST['servicetype']=='Lab'){
$name=$_POST['name'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$email=$_POST['labemail'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Testname: '.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>
';
}
else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$email=$_POST['pemail'];
$city=$_POST['pcity'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html=
'<p>Service Type:'.$servicetype.'</p>
<p>Medicinename: '.$medicine.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Physio')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Nurse')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html=
$html=
'<p>Service Type: '.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email:'.$email.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($email,$name);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
$mail->send();
}
//Customer mail
function sendMailcustomerAction(){
//Mage::getModel('sales/order')->load(24999);
if($_POST['servicetype']=='Lab'){
$name=$_POST['name'];
$servicetype=$_POST['servicetype'];
$email=$_POST['labemail'];
$testname=$_POST['testname'];
$html=
'Dear '.$name.',
<p>We have received your order for '.$testname.'. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Pharmacy')
{ $name=$_POST['pname'];
$email=$_POST['pemail'];
$medicine=$_POST['medicinename'];
$html=
'Dear '.$name.',
<p>We have received your order for '.$medicine.'. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Physio')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
else if($_POST['servicetype']=='Nurse')
{
$name=$_POST['fname'];
$email=$_POST['femail'];
$html=
'Dear '.$name.',
<p>We have received your order. You will be attended shortly.</p>
<p>Best Regards,</p>
<p>Team Labwise.</p>';
}
$mail = Mage::getModel('core/email');
$mail->setToName($name);
$mail->setToEmail($email);
$mail->setBody($html);
$mail->setSubject('Quick Service');
$mail->setFromEmail('admin@labwise.in');
$mail->setFromName("Labwise");
//$mail->addBcc("contact@labwise.in");
$mail->setType('html');// YOu can use Html or text as Mail format
try {
$mail->send();
//Mage::getSingleton('core/session')->addSuccess('Your Order is successfully Completed');
//Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl());
return '<h2>Your Request has been submitted.Thank you for using labwise. </h2>';
//$this->_redirect('');
}
catch (Exception $e) {
//Mage::getSingleton('core/session')->addError('Unable to send.');
//Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl());
return '</h2>Unable to submit.</h2>';
//$this->_redirect('');
}
}
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
if($_POST['servicetype']=='Lab')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.islab=?', '1'
);
} else if($_POST['servicetype']=='Pharmacy')
{
$allrecord =$reaconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.ishospital=?', '1'
);
}else if($_POST['servicetype']=='Gym')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isgym=?', '1'
);
}else if($_POST['servicetype']=='Food')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.isfood=?', '1'
);
}else if($_POST['servicetype']=='Nurse')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.nurse=?', '1'
);
}else if($_POST['servicetype']=='Physio')
{
$allrecord =$readconnection->select()->from(array('serviceprovider'=>'mg_serviceprovider'))->where('serviceprovider.physio=?', '1'
);
}
$alldata =$readconnection->fetchAll($allrecord);
foreach($alldata as $data)
{
sendMailserviceAction($data['email'],$data['name']);
}
function sendMailserviceAction($ccemail,$pname,$uploadfilename){
//Mage::getModel('sales/order')->load(24999);
//$location=$_POST['location'];
$servicetype=$_POST['servicetype'];
$cemail=$_POST['labemail'];
$cemail=$_POST['pemail'];
$cemail=$_POST['femail'];
if($_POST['servicetype']=='Lab')
{
$cemail=$_POST['labemail'];
$servicetype=$_POST['servicetype'];
$testname=$_POST['testname'];
$name=$_POST['name'];
$mobile=$_POST['labmobile'];
$city=$_POST['rcity'];$zipcode=$_POST['labzip_code'];
$html ='
<p>Service Type: '.$servicetype.'</p>
<p>Testname:'.$testname.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile Number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}else if($_POST['servicetype']=='Pharmacy')
{
$name=$_POST['pname'];
$medicine=$_POST['medicinename'];
$cemail=$_POST['pemail'];
$mobile=$_POST['pmobile'];
$city=$_POST['pcity'];$zipcode=$_POST['pzip_code'];
$html ='<p>Service Type:'.$servicetype.'</p> <p> Medicine name: '.$medicine.'</p>
<p>Name:'.$name.'</p>
<p> Email: '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Gym')
{
$name=$_POST['fname'];
$mobile=$_POST['fmobile'];
$cemail=$_POST['femail'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
else if($_POST['servicetype']=='Food')
{
$name=$_POST['fname'];
$cemail=$_POST['femail'];
$mobile=$_POST['fmobile'];
$city=$_POST['fcity'];$zipcode=$_POST['fzip_code'];
$html ='
<p>Service Type:'.$servicetype.'</p>
<p>Name: '.$name.'</p>
<p>Email : '.$cemail.'</p>
<p>Mobile number: '.$mobile.'</p>
<p>City:'.$city.'</p>
<p>Zip Code:'.$zipcode.'</p>';
}
$mail = new Zend_Mail();
$mail->setFrom('admin@labwise.in',"Labwise");
$mail->addTo($ccemail,$pname);
$mail->setSubject('Quick Service');
$mail->setBodyHtml($html);
if(file_exists(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename ) )
{
$attachment = file_get_contents(Mage::getBaseDir('media').DS.'requestquote'.DS.$uploadfilename);
$ext = pathinfo($uploadfilename, PATHINFO_EXTENSION);
$file = new Zend_Mime_Part($attachment);
$file->filename = $uploadfilename;
$file->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$file->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($file);
}
try {
$mail->send();
return '<h2> Email Sent. </h2>';
}
catch (Exception $e) {
return '</h2>Unable to submit.</h2>';
}
}
?>
``` | This code is Working for me try this le me know if you have any query
```
$mailTemplate = Mage::getModel('core/email_template');
/* @var $mailTemplate Mage_Core_Model_Email_Template */
// file attached
if($post['file']){
$destination_path = Mage::getBaseDir('media'). DS .'uploads'.DS.$post['file'];
$mailTemplate->getMail()->createAttachment(
file_get_contents($destination_path),
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$post['file']
);
}
// after file attached
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
``` |
10,999,855 | I am using:
```
if (UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight)
{
viewofimage.frame = CGRectMake(130, 45, 220, 115);
share.frame = CGRectMake(205, 161, 70, 70);
invite.frame = CGRectMake(8, 161, 70, 70);
contact.frame = CGRectMake(402, 161, 70, 70);
invitation.frame = CGRectMake(3, 227, 81, 21);
sharing.frame = CGRectMake(200, 227, 81, 21);
contacting.frame = CGRectMake(397, 227, 81, 21);
}
else
{
viewofimage.frame = CGRectMake(20, 64, 280, 206);
invite.frame = CGRectMake(8, 285, 70, 70);
share.frame = CGRectMake(125, 285, 70, 70);
contact.frame = CGRectMake(242, 285, 70, 70);
invitation.frame = CGRectMake(3, 358, 81, 21);
sharing.frame = CGRectMake(120, 358, 81, 21);
contacting.frame = CGRectMake(237, 358, 81, 21);
}
```
to set buttons and labels in certain places when rotated. The only issue is that when I leave that view controller and go to a different controller, with the same code in place, it does not move the buttons and labels to defined CGRECTMAKE values. It only moves them when the selected viewcontroller is rotated. How can I get the other view controllers to detect what orientation it is in, and have it resized properly when getting to them? | 2012/06/12 | [
"https://Stackoverflow.com/questions/10999855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/717452/"
] | This is due to [specificity](http://www.w3.org/TR/CSS21/cascade.html#specificity): although `a` is an element type selector which is less specific than a class selector, it's accompanied by a `:link` pseudo-class which is equally specific to your `.button` class. A type + pseudo-class will therefore be more specific than a class.
There is no inheritance going on here as there are no parent element styles that I can see being applied to your element. [Inheritance](http://www.w3.org/TR/CSS21/cascade.html#inheritance) refers to adopting styles from parent elements. When you see the link displaying blue instead of white, that's the [cascade](http://www.w3.org/TR/CSS21/cascade.html#cascade) at work, not inheritance.
Locality isn't a CSS term (at least not in its glossary), so I'm not sure what you mean by that.
If you need your call-to-action button to be white, simply give it the `a` selector as well, so your selectors are equally specific and the last declaration will take precedence:
```
a:link {font-size:0.875em;color:#005984}
a.button {color:#fff}
``` | >
> A selector's specificity is calculated as follows:
>
> - count the number of ID selectors in the selector (= a)
>
> - count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
>
> - count the number of type selectors and pseudo-elements in the selector (= c)
>
> - ignore the universal selector
>
>
> Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.
>
>
> Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
>
>
>
So:
>
> `a:link`
>
> - a=0
>
> - b=1
>
> - c=1
>
> - Result = 011
>
>
> `.button`
>
> - a=0
>
> - b=1
>
> - c=0
>
> - Result = 010
>
>
> **Result**: `a:link` is higher than `.button`.
>
>
>
Fix: `:link` won't work on anything but `a` tags anyway, so specifying `a:link` is redundant. Use `:link` instead, and that will fix the problem (provided `.button` is defined *after* `:link`) |
413 | When viewing a single contact, I can select "Actions" Vcard and export a vcard which can then be used in other applications (Outlook, OwnCloud, etc)
I would like to be able to select "Create Vcard" in the drop down list for actions for search results, and get a vcard file of many contacts that could be imported into other apps. | 2015/04/09 | [
"https://civicrm.stackexchange.com/questions/413",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/275/"
] | This option does not exist (as yet).I'm not aware of an extension to do this either. Your options include:
a. Write an extension that adds the above functionality
b. Use the api to export the data into a program that can generate multiple vcards and use that | You can use the extension vcard-export. See <https://lab.civicrm.org/extensions/vcard-export> . |
66,793,543 | I'm trying to make a starboard code with my bot, and everything else is working good. But I'm trying to make it to where the bot ignores reactions from the author of the actual message.
This is my current code:
```js
client.on('messageReactionAdd', (reaction_orig, message, user) => {
if (message.author.id === reaction_orig.users.id) return
manageBoard(reaction_orig)
})
```
It returns the following error:
```
if (message.author.id === reaction_orig.users.id) return;
^
TypeError: Cannot read property 'id' of undefined
``` | 2021/03/25 | [
"https://Stackoverflow.com/questions/66793543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14722081/"
] | The problem is that [`messageReactionAdd`](https://discord.js.org/#/docs/main/master/class/Client?scrollTo=e-messageReactionAdd) takes two parameters; the message reaction as the first one, and the user that applied the emoji as the second one. When you write `reaction_orig, message, user`, `reaction_orig` is the reaction (which is correct), but `message` is the user who reacted as it's the second parameter. The `user` variable will be `undefined`.
Another issue is that `reaction_orig.users` returns a [ReactionUserManager](https://discord.js.org/#/docs/main/master/class/ReactionUserManager) that doesn't have an `id` property. Luckily, the `user` is already passed down to your callback so you can use its ID.
Also, `reaction_orig` has a `message` property, the original message that this reaction refers to so you can get its authors' ID from it.
You can change your code to this to work:
```js
client.on('messageReactionAdd', (reaction_orig, user) => {
if (reaction_orig.message.author.id === user.id) {
// the reaction is coming from the same user who posted the message
return;
}
manageBoard(reaction_orig);
});
```
However, the code above only works on cached messages, ones posted after the bot is connected. Reacting on older messages won't fire the `messageReactionAdd` event. If you also want to listen to reactions on old messages you need to enable partial structures for `MESSAGE`, `CHANNEL` and `REACTION` when instantiating your client, like this:
```js
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
```
You can check if the message is cached by e.g. checking if its `author` property is not `null`. If it's `null`, you can [fetch the message](https://discord.js.org/#/docs/main/master/class/Message?scrollTo=fetch). Now, you have both the message author and the user who reacted, so you can compare their IDs:
```js
// make sure it's an async function
client.on('messageReactionAdd', async (reaction_orig, user) => {
// fetch the message if it's not cached
const message = !reaction_orig.message.author
? await reaction_orig.message.fetch()
: reaction_orig.message;
if (message.author.id === user.id) {
// the reaction is coming from the same user who posted the message
return;
}
// the reaction is coming from a different user
manageBoard(reaction_orig);
});
``` | Try doing this :
```js
client.on('messageReactionAdd', (reaction, user) => {
if (!reaction.message.author.id === user.id){
//Do whatever you like with it
console.log(reaction.name)
}
});
```
Note: The message must be cached. For that you'll need to do this
```js
Client.channels.cache.get("ChannelID").messages.fetch("MessageID");
```
I'm guessing you're using discord.js v12 |
28,319 | One thing about German language bothers me since ever. As far as I know you still use "Sie" even if the context is disrespectful.
For example:
>
> "Sie sind ein Arschloch!" `("You are an asshole!")`
>
>
>
Isn't it a little bit silly to use the formal person to, for example, offend someone? Why is it still done? | 2016/02/22 | [
"https://german.stackexchange.com/questions/28319",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/16024/"
] | As Burki mentioned in his comment:
>
> The *Sie* is not only used to show respect, but also to indicate distance. Apart from that it is a language convention, and as such it is a bit hard to get rid of.
>
>
>
You can use *du* or *Sie* in disrespectful context and they can have different levels of respect.
Some examples:
The fine for an insult may differ. A [German court ruled](http://www.swp.de/ulm/nachrichten/politik/Gericht-hat-entschieden-Buerschle-ist-eine-Beleidigung;art4306,2530738):
>
> Der Fall war klar: „Bürschle“ war in diesem Fall eine Beleidigung. Auch das verwendete Pronomen sprach eine deutliche Sprache: „Du Bürschle“ habe der Angeklagte gesagt, und nicht „Sie Bürschle“.
>
>
>
The usage of *du* is an indication of an insult. With *Sie* it could be a *friendly* dialect expression.
But it can also be the [opposite way](http://www.wianka.de/schwaebisch_lernen.htm) (*du Seggel* between swabians is no insult, *Sie Seggel* to a foreigner is an insult):
>
> So hat zum Beispiel »du Seggel« – einem Landsmann gegenüber gesagt – einen ganz anderen Stellenwert als »Sie Seggel« gegenüber einem Nichtschwaben.
>
>
>
Especially *Arschloch* can have different meanings:
>
> … dass das inkriminierte Wort Arschloch im Schwäbischen keine Beleidigung ist. Für ihn ist es das schwäbisches Schlüsselwort schlechthin. Synonym für Leben. Mit ihm begrüßt man beste Freunde („Ja, wo kommschd Du alds Arschloch no au her!“)
>
>
>
*Du Arschloch* is no insult in swabian, it can be used as a greeting between friends. Source: <http://www.theaterhaus.de/theaterhaus/index.php?id=1,3,8356>
(This is a quote from a cabaret artist, so don't take it too serious, there is some exaggeration involved)
One warning: Don’t try to use this greetings. It makes a big difference how and by who it is done. There are also many regional differences. | I'd go further than the accepted answer, and say that "Sie"/"Du" are nowadays almost never used to show respect, they are almost always used to only show closeness. Using "Du" with someone you barely know is usually inappropriate and thus disrespectful, but the "Du" itself is not indicating disrespect at all. I don't know of any German speaking region where Friends and Family aren't always addressed with "Du".
Additionally, using "Du" implicitly invites the other side to use "Du" as well, which is not something you intend to offer to a stranger you're calling "Arschloch".
An exception to all this is if there's a significant age difference, most often between adults and children, but sometimes also between younger adults and very old people. As an adult you address children with "Du", even if you've never met them before, while children address adults they don't know closely with "Sie". This is a leftover from ages past when there were many more situations where it was expected for one side to use "Sie" and the other side to use "Du". The court ruling cited by knut must be looked at in this context: "Bürschle" can loosely be translated as "brat". If this is used to address an adult, the intent to use this as a demeaning phrase is clarified by prefixing it with "Du".
Also the usage of "Arschloch" as greeting is pretty much the same as using any insult as greeting among very close friends in English, only slightly more common - unless you understand the nuances, only use it to respond in kind, usually with a different insult to make the exchange more amusing. |
11,559,316 | Hi all : How can i fix the problem of css in ie 7 and ie6 : my divs change possition in those two : www.justcode/housetostay: I will be very glad if i get any help | 2012/07/19 | [
"https://Stackoverflow.com/questions/11559316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use conditionals to do this.
In your add this code.
```
<!--[if lt IE 8]>
// Add your IE only stylesheet here
<![endif]-->
```
This means that if the browser is Less Than IE8 load the stylesheet in the comments.
You can be more specific if you need to.
`<!--[if IE ]>` - Targets all IE versions from 5.5 up to 9
`<!--[if gt IE6 ]>` - Targets all IE versions Greater Than IE6
`<!--[if IE7 ]>` - Targets only IE7 | Without using hacks I would suggest using this technique
```
<!--[if lt IE 7]><html class="ie6"><![endif]-->
<!--[if IE 7]><html class="ie7"><![endif]-->
<!--[if IE 8]><html class="ie8"><![endif]-->
<!--[if gt IE 8]><!--><html><!--<![endif]-->
```
Then you can add css:
```
.ie6 .my-div {
}
.ie7 .my-div {
}
```
Using separate stylesheets for each version of IE is pretty outdated/poor IMO when you can target all versions in your regular single stylesheet
you can read more here: <http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/> |
9,982,786 | Has anyone tried to get Windows 7/8 running on linux with the Microsoft Virtual PC download directly from Microsoft? It doesn't seem to be working using the default Boxes or Virtual Machine (QEMU) in CentOS / Red Hat?
```
SETTINGS:
Base Memory 1024 MB
Video Memory 128 MB
Network Adapter: Intel PRO/1000 MT Desktop (NAT)
Windows Virtual Box (from Microsoft)
```
<http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11575>
forward to <http://dev.modern.ie/>
Is there any chance Microsoft or modern.ie will just release an iso install rather then a native Virtual System File? | 2012/04/02 | [
"https://Stackoverflow.com/questions/9982786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164146/"
] | It sounds like you're trying to get Microsoft's IE Virtual PC *images* working in VirtualBox (not Virtual PC itself).
Luckily there is a tool available to automate the process of converting the images and getting them to work in VirtualBox. Take a look at [ievms](https://github.com/xdissent/ievms). | Microsoft Virtual PC downloads from <http://dev.modern.ie/> (MS) only support Virtual Box on linux and not the Virtual Machine Manager that comes with CentOS. |
9,982,786 | Has anyone tried to get Windows 7/8 running on linux with the Microsoft Virtual PC download directly from Microsoft? It doesn't seem to be working using the default Boxes or Virtual Machine (QEMU) in CentOS / Red Hat?
```
SETTINGS:
Base Memory 1024 MB
Video Memory 128 MB
Network Adapter: Intel PRO/1000 MT Desktop (NAT)
Windows Virtual Box (from Microsoft)
```
<http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11575>
forward to <http://dev.modern.ie/>
Is there any chance Microsoft or modern.ie will just release an iso install rather then a native Virtual System File? | 2012/04/02 | [
"https://Stackoverflow.com/questions/9982786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164146/"
] | Check <http://www.modern.ie/en-us/virtualization-tools#downloads>
This images are legal as `modern.ie` launched by Microsoft.
Site provide a wide range of up-today Windows images for Windows/Mac/Linux. | Microsoft Virtual PC downloads from <http://dev.modern.ie/> (MS) only support Virtual Box on linux and not the Virtual Machine Manager that comes with CentOS. |
9,982,786 | Has anyone tried to get Windows 7/8 running on linux with the Microsoft Virtual PC download directly from Microsoft? It doesn't seem to be working using the default Boxes or Virtual Machine (QEMU) in CentOS / Red Hat?
```
SETTINGS:
Base Memory 1024 MB
Video Memory 128 MB
Network Adapter: Intel PRO/1000 MT Desktop (NAT)
Windows Virtual Box (from Microsoft)
```
<http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11575>
forward to <http://dev.modern.ie/>
Is there any chance Microsoft or modern.ie will just release an iso install rather then a native Virtual System File? | 2012/04/02 | [
"https://Stackoverflow.com/questions/9982786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164146/"
] | It sounds like you're trying to get Microsoft's IE Virtual PC *images* working in VirtualBox (not Virtual PC itself).
Luckily there is a tool available to automate the process of converting the images and getting them to work in VirtualBox. Take a look at [ievms](https://github.com/xdissent/ievms). | Check <http://www.modern.ie/en-us/virtualization-tools#downloads>
This images are legal as `modern.ie` launched by Microsoft.
Site provide a wide range of up-today Windows images for Windows/Mac/Linux. |
17,487,872 | I want to add lines to /etc/my.conf as "sudo" using Shell.
Without logging as sudo, I can do:
```
{ echo "[mysqld]"
echo "default-character-set=utf8"
echo "character_set_server=utf8"
echo "[mysql]"
echo "default-character-set=utf8"
} >> /etc/my.conf
```
But when:
```
sudo { echo "[mysqld]"
echo "default-character-set=utf8"
echo "character_set_server=utf8"
echo "[mysql]"
echo "default-character-set=utf8"
} >> /etc/my.conf
```
I get an error:
```
sudo: {: command not found
character_set_server=utf8
[mysql]
default-character-set=utf8 .....
```
What am I doing wrong? | 2013/07/05 | [
"https://Stackoverflow.com/questions/17487872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185098/"
] | Firstly, use cat with a here-doc rather than a series of echoes. It's much cleaner. You can use the special form with a dash which strips leading tabs (tabs, not spaces!) to let you indent the here-doc to make it stand out.
Secondly, you can do the redirection as sudo by using `sudo sh -c` to start a root subshell, in which you then run cat doing the redirection.
Putting it together:
```
sudo sh -c "cat >>/etc/my.conf" <<-EOF
[mysqld]
default-character-set=utf8
character_set_server=utf8
[mysql]
default-character-set=utf8
EOF
```
I don't know of a more direct way to write a stream to a file as root. It's a shame if there really isn't one. | ```
$ sudo echo "foo
bar
baz" > f
```
should work |
17,487,872 | I want to add lines to /etc/my.conf as "sudo" using Shell.
Without logging as sudo, I can do:
```
{ echo "[mysqld]"
echo "default-character-set=utf8"
echo "character_set_server=utf8"
echo "[mysql]"
echo "default-character-set=utf8"
} >> /etc/my.conf
```
But when:
```
sudo { echo "[mysqld]"
echo "default-character-set=utf8"
echo "character_set_server=utf8"
echo "[mysql]"
echo "default-character-set=utf8"
} >> /etc/my.conf
```
I get an error:
```
sudo: {: command not found
character_set_server=utf8
[mysql]
default-character-set=utf8 .....
```
What am I doing wrong? | 2013/07/05 | [
"https://Stackoverflow.com/questions/17487872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2185098/"
] | An alternative to launching a new shell is to use the `tee` command:
```
{ echo "[mysqld]"
echo "default-character-set=utf8"
echo "character_set_server=utf8"
echo "[mysql]"
echo "default-character-set=utf8"
} | sudo tee -a /etc/my.conf > /dev/null
```
or
```
sudo tee -a /etc/my.conf >/dev/null <<-EOF
[mysqld]
default-character-set=utf8
character_set_server=utf8
[mysql]
default-character-set=utf8
EOF
``` | ```
$ sudo echo "foo
bar
baz" > f
```
should work |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.