qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
42,742,519 | I am new to programming and was trying to create a program in python that creates a staircase with size based on the user input. The program should appear as shown below:

This is the code I have so far;
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps):
n = steps+i
print(' '*(n-2) + '|_')
print('_'*n + '|')
```
This is what my output is;

Note - The horizontal lines are underscores '\_' and the vertical lines are the pipe character '|'. | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7696748/"
] | To get the correct amount of steps, you have to change the for loop to:
```
for i in range(steps-1):
```
This is because you want to print the `|_`'s one less time than there are steps; your "top" step `__` already counts as one step.
The whole thing (changed some other things to make the formatting better):
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps-1):
print(' '*(2+2*i) + '|_')
print('_'*2*steps + '|')
```
Output:
[](https://i.imgur.com/vvCcI0h.png) | It is simpler to consider that `n` is the current step and given the step size (2) then you just need `2n` for your placement:
```
steps = 5
print('__')
for n in range(1, steps):
print(' '*n*2 + '|_')
print('_'*steps*2 + '|')
```
Output:
```
__
|_
|_
|_
|_
__________|
```
You can abstract this to take any step size, e.g.:
```
steps = 5
size = 4
print('_'*size)
for n in range(1, steps):
print(' '*n*size + '|' + '_'*(size-1))
print('_'*steps*size + '|')
```
Output:
```
____
|___
|___
|___
|___
____________________|
``` |
42,742,519 | I am new to programming and was trying to create a program in python that creates a staircase with size based on the user input. The program should appear as shown below:

This is the code I have so far;
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps):
n = steps+i
print(' '*(n-2) + '|_')
print('_'*n + '|')
```
This is what my output is;

Note - The horizontal lines are underscores '\_' and the vertical lines are the pipe character '|'. | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7696748/"
] | To get the correct amount of steps, you have to change the for loop to:
```
for i in range(steps-1):
```
This is because you want to print the `|_`'s one less time than there are steps; your "top" step `__` already counts as one step.
The whole thing (changed some other things to make the formatting better):
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps-1):
print(' '*(2+2*i) + '|_')
print('_'*2*steps + '|')
```
Output:
[](https://i.imgur.com/vvCcI0h.png) | ```
def stairs(steps):
print("__")
length = 1
for i in range(steps):
length += 1
print("%s|_" % (" "*(length+i)),)
print("%s|" % ("_"*(length+steps+1)),)
stairs(4)
```
Output:
```
__
|_
|_
|_
|_
__________|
``` |
42,742,519 | I am new to programming and was trying to create a program in python that creates a staircase with size based on the user input. The program should appear as shown below:

This is the code I have so far;
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps):
n = steps+i
print(' '*(n-2) + '|_')
print('_'*n + '|')
```
This is what my output is;

Note - The horizontal lines are underscores '\_' and the vertical lines are the pipe character '|'. | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7696748/"
] | To get the correct amount of steps, you have to change the for loop to:
```
for i in range(steps-1):
```
This is because you want to print the `|_`'s one less time than there are steps; your "top" step `__` already counts as one step.
The whole thing (changed some other things to make the formatting better):
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps-1):
print(' '*(2+2*i) + '|_')
print('_'*2*steps + '|')
```
Output:
[](https://i.imgur.com/vvCcI0h.png) | You can do it via `while`.
`counter = 0
while counter < steps:
Create_stairs()
increase counter` |
42,742,519 | I am new to programming and was trying to create a program in python that creates a staircase with size based on the user input. The program should appear as shown below:

This is the code I have so far;
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps):
n = steps+i
print(' '*(n-2) + '|_')
print('_'*n + '|')
```
This is what my output is;

Note - The horizontal lines are underscores '\_' and the vertical lines are the pipe character '|'. | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7696748/"
] | To get the correct amount of steps, you have to change the for loop to:
```
for i in range(steps-1):
```
This is because you want to print the `|_`'s one less time than there are steps; your "top" step `__` already counts as one step.
The whole thing (changed some other things to make the formatting better):
```
steps = int(input('How many steps? '))
print('__')
for i in range(steps-1):
print(' '*(2+2*i) + '|_')
print('_'*2*steps + '|')
```
Output:
[](https://i.imgur.com/vvCcI0h.png) | Not sure what your exact question is. The patter of steps is:
* Step 1 -> 4 blanks
* Step 2 -> 6 blanks
* Step 3 -> 8 blanks
* Step n -> 2 + (2 \* n) blanks
steps = int(input('How many steps? ')) |
22,814,973 | im working on python application that requiring database connections..I had developed my application with sqlite3 but it start showing the error(the database is locked).. so I decided to use MySQL database instead.. and it is pretty good with no error..
the only one problem is that I need to ask every user using my application to install MySQL server on his pc (appserv for example) ..
so can I make mysql to be like sqlite3 apart of python lib. so I can produce a python script can be converted into exe file by the tool pyInstaller.exe and no need to install mysql server by users???
**update:**
after reviewing the code I found opened connection not closed correctly and work fine with sqllite3 ..thank you every body | 2014/04/02 | [
"https://Stackoverflow.com/questions/22814973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2980054/"
] | It depends (more "depends" in the answer).
If you need to share the data between the users of your application - you need a mysql database server somewhere setup, your application would need to have an access to it. And, the performance can really depend on the network - depends on how heavily would the application use the database. The application itself would only need to know how to "speak" with the database server - python mysql driver, like `MySQLdb` or `pymysql`.
If you don't need to share the data between users - then `sqlite` may be an option. Or may be not - depends on what do you want to store there, what for and what do you need to do with the data.
So, more questions than answers, probably it was more suitable for a comment. At least, think about what I've said.
Also see:
* <https://stackoverflow.com/questions/1009438/which-database-should-i-use-for-my-desktop-application>
* [Python Desktop Application Database](https://stackoverflow.com/questions/15271764/python-desktop-application-database)
* [Python Framework for Desktop Database Application](https://stackoverflow.com/questions/3255665/python-framework-for-desktop-database-application)
Hope that helps. | If your application is a stand-alone system such that each user maintains their own private database then you have no alternative to install MySQL on each system that is running the application. ~~You cannot bundle MySQL into your application such that it does not require a separate installation.~~
There is an embedded version of MySQL that you can build into your application (**thanks, Carsten, in the comments, for pointing this out**). More information is here: <http://mysql-python.blogspot.com/>. It may take some effort to get this working (on Windows you apparently need to build it from source code) and will take some more work to get it packaged up when you generate your executable, but this might be a MySQL solution for you.
I've just finished updating a web application using SQLite which had begun reporting Database is locked errors as the usage scaled up. By rewriting the database code with care I was able to produce a system that can handle moderate to heavy usage (in the context of a 15 person company) reliably still using SQLite -- you have to be careful to keep your connections around for the minimum time necessary and always call .close() on them. If your application is really single-user you should have no problem supporting it using SQLite -- and that's doubly true if it's single-threaded. |
51,583,196 | I am learning python django i am developing one website but i am struggling with URL pattern
I am Sharing my code for URL pattern i don't understand where i am getting wrong
url.py
```
urlpatterns = [
url(r'^$',views.IndexView.as_view(),name='index'),
# /music/id/
url(r'^picture/(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'),
#for PictureDetail view
url(r'^detail/(?P<pk>[0-9]+)/(?P<alb_title>[\w%20+A-Za-z]+)/(?P<song_title>[\w%20+A-Za-z]+)$', views.PicturedetailView.as_view(), name='picturedetail'),
]
```
My Detail.html:-
```
<ul>
{% for picture in album.picture_set.all %}
<div class="col-sm-4 col-lg-2">
<div class="thumbnail">
<a href="{% url 'music:picturedetail' pk=picture.pk alb_title=picture.album.album_title song_title=picture.song_title %}">
<img src="{{ picture.file_type.url }}" class="img-responsive">
</a>
<div class="caption">
<h6>{{picture.song_title}}</h6>
</div>
</div>
</div>
{% endfor %}
</ul>
{% endblock %}
```
I am passing three Parameters one with id and other two are strings ,i also updated my html href pattern but i am getting below error:-
```
Reverse for 'picturedetail' with keyword arguments '{'pk': 3, 'alb_title': 'Beautiful River', 'song_title': 'River'}' not found. 1 pattern(s) tried: ['music/detail/(?P<pk>[0-9]+)/(?P<alb_title>[\\w%20+A-Za-z]+)/(?P<song_title>[\\w%20+A-Za-z]+)$']
```
Thank you in Advance | 2018/07/29 | [
"https://Stackoverflow.com/questions/51583196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6246189/"
] | [](https://i.stack.imgur.com/xtW0A.png)
You can try this way:
```
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.red,
elevation: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(
Radius.circular(100),
),
boxShadow: [
BoxShadow(
color: Colors.purple.withOpacity(0.3),
spreadRadius: 7,
blurRadius: 7,
offset: Offset(3, 5),
),
],
),
),
),
``` | floatingActionButton: FloatingActionButton(
onPressed: (){},
backgroundColor: Color(0xf0004451),
elevation: 10,
```
child: Container(
padding: const EdgeInsets.all(14.0),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(
Radius.circular(60),
),
boxShadow: [
BoxShadow(
color: Color(0xffE1E8EB).withOpacity(0.35),
spreadRadius: 8,
blurRadius: 8,
offset: const Offset(1, 1),
),
],
),
child: const Icon(Icons.add,
color: Color(0xffE1E8EB),
size: 18,
shadows: [Shadow(
color: Color(0xffE1E8EB),
offset: Offset(0.2, 0.5),
blurRadius: 5.0,
)],
),
),
),
``` |
51,583,196 | I am learning python django i am developing one website but i am struggling with URL pattern
I am Sharing my code for URL pattern i don't understand where i am getting wrong
url.py
```
urlpatterns = [
url(r'^$',views.IndexView.as_view(),name='index'),
# /music/id/
url(r'^picture/(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'),
#for PictureDetail view
url(r'^detail/(?P<pk>[0-9]+)/(?P<alb_title>[\w%20+A-Za-z]+)/(?P<song_title>[\w%20+A-Za-z]+)$', views.PicturedetailView.as_view(), name='picturedetail'),
]
```
My Detail.html:-
```
<ul>
{% for picture in album.picture_set.all %}
<div class="col-sm-4 col-lg-2">
<div class="thumbnail">
<a href="{% url 'music:picturedetail' pk=picture.pk alb_title=picture.album.album_title song_title=picture.song_title %}">
<img src="{{ picture.file_type.url }}" class="img-responsive">
</a>
<div class="caption">
<h6>{{picture.song_title}}</h6>
</div>
</div>
</div>
{% endfor %}
</ul>
{% endblock %}
```
I am passing three Parameters one with id and other two are strings ,i also updated my html href pattern but i am getting below error:-
```
Reverse for 'picturedetail' with keyword arguments '{'pk': 3, 'alb_title': 'Beautiful River', 'song_title': 'River'}' not found. 1 pattern(s) tried: ['music/detail/(?P<pk>[0-9]+)/(?P<alb_title>[\\w%20+A-Za-z]+)/(?P<song_title>[\\w%20+A-Za-z]+)$']
```
Thank you in Advance | 2018/07/29 | [
"https://Stackoverflow.com/questions/51583196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6246189/"
] | [](https://i.stack.imgur.com/xtW0A.png)
You can try this way:
```
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.red,
elevation: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(
Radius.circular(100),
),
boxShadow: [
BoxShadow(
color: Colors.purple.withOpacity(0.3),
spreadRadius: 7,
blurRadius: 7,
offset: Offset(3, 5),
),
],
),
),
),
``` | ```
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Container(
height: 70,
width: 70,
margin: const EdgeInsets.only(bottom: 10.0),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: const BorderRadius.all(
Radius.circular(100),
),
boxShadow: [
BoxShadow(
color: MyColors.myWhite.withOpacity(0.3),
spreadRadius: 6,
blurRadius: 6,
offset: const Offset(0.5, 0.5),
),
],
),
child: FittedBox(
child: FloatingActionButton(
onPressed: (){},
backgroundColor: MyColors.myGreen,
elevation: 10,
child: const Icon(Icons.add,
color: MyColors.myWhite,
size: 18,
shadows: [Shadow(
color: MyColors.myWhite,
offset: Offset(0.2, 0.5),
blurRadius: 5.0,
)],
),
),
),
),
``` |
15,832,700 | I am newbie in python and I am trying to launch python script with a module writen on C. I am getting Segmentation fault (core dumped) error when I am trying to launch python script.
Here is a C code:
```
// input_device.c
#include "Python.h"
#include "input.h"
static PyObject* input_device_open(PyObject* self, PyObject* id)
{
int fd, nr;
PyObject* pyfd;
if (!PyInt_Check(id))
return NULL;
nr = (int)PyInt_AsLong(id);
fd = device_open(nr, 0);
if (fd == -1)
return NULL;
pyfd = PyInt_FromLong(fd);
Py_INCREF(pyfd);
return pyfd;
}
static PyMethodDef module_methods[] =
{
{ "device_open", (PyCFunction)input_device_open, METH_VARARGS, "..." },
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC initinput_device(void)
{
Py_InitModule4("input_device", module_methods, "wrapper methods", 0, PYTHON_API_VERSION);
}
```
and the python script:
```
from input_device import device_open
device_open(1)
```
Could someone take a look and point me in the right direction, what I am doing wrong. Thanks in advance. | 2013/04/05 | [
"https://Stackoverflow.com/questions/15832700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904234/"
] | Is it legitimate to return `NULL` without setting an exception, or making sure that one has been set by a function you have called? I thought that `NULL` was a signal that Python could go look for an exception to raise for the user.
I am not sure that the `Py_INCREF(pyfd);` is necessary; doesn't the object already have a refcount of 1 upon creation? | Your function receives a tuple of arguments. You need to extract the integer from the tuple:
```
static PyObject* input_device_open(PyObject* self, PyObject* args)
{
int fd, nr;
PyObject* pyfd;
if (!PyArg_ParseTuple(args, "i", &nr))
return NULL;
``` |
54,366,675 | i have a list like below:
```
[3,2,4,5]
```
and i want a list like below:
```
[['1','2','3'],['1','2'],['1','2','3','4'],['1','2','3','4','5']]
```
i mean i want to have a list that is created by the count of another list.
I want to iterate each with string.
how can i write it in python
i tried this code:
```
for i,val in enumerate(list_mf_input):
self.eachMembership.append([])
for value in range(1, val+1):
self.eachMembership.append([value])
``` | 2019/01/25 | [
"https://Stackoverflow.com/questions/54366675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6655937/"
] | You can use `range` with `list`, and list comprehension:
```
>>> a = [3, 2, 4, 5]
>>> [list(range(1, x+1)) for x in a]
[[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5]
```
And to make all strings, add `map` with `str`:
```
>>>[list(map(str, range(1, x+1))) for x in a]
[['1', '2', '3'], ['1', '2'], ['1', '2', '3', '4'], ['1', '2', '3', '4', '5']]
``` | try this code. I tried to make as easy as possible
```
lol=[3,2,4,5]
ans=[]
temp=[]
for i in lol:
for j in range(1,i+1):
temp.append(j)
ans.append(temp)
temp=[]
print(ans)
```
Hope it helps |
42,183,476 | Can someone please help me with the python equivalent of the curl command:
python equivalent of `curl -X POST -F "name=blahblah" -F "file=@blahblah.jpg"`
I would like to you python requests module, but I am not clear on the options to use. | 2017/02/12 | [
"https://Stackoverflow.com/questions/42183476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7552038/"
] | It depends on how you are going to use this reference.
1) There is no straight way to get component DOM reference within template:
```
import {Directive, Input, ElementRef, EventEmitter, Output, OnInit} from '@angular/core';
@Directive({selector: '[element]', exportAs: 'element'})
export class NgElementRef implements OnInit
{
@Output()
public elementChange:EventEmitter<any> = new EventEmitter<any>();
public elementRef:ElementRef;
constructor(elementRef:ElementRef)
{
this.elementRef = elementRef;
this.elementChange.next(undefined);
}
@Input()
public get element():any
{
return this.elementRef.nativeElement;
}
public set element(value:any)
{
}
ngOnInit():void
{
this.elementChange.next(this.elementRef.nativeElement);
}
}
```
Usage:
```
<my-comp [(element)]="var2"></my-comp>
<p>{{var2}}</p>
<!--or-->
<my-comp element #var2="element"></my-comp>
<p>{{var2.element}}</p>
```
2) You can get this reference in component that owns template with `@ViewChild('var2', {read: ElementRef})`. | As of Angular 8, the following provides access to the ElementRef and native element.
```
/**
* Export the ElementRef of the selected element for use with template references.
*
* @example
* <button mat-button #button="appElementRef" appElementRef></button>
*/
@Directive({
selector: '[appElementRef]',
exportAs: 'appElementRef'
})
export class ElementRefDirective<T> extends ElementRef<T> {
constructor(elementRef: ElementRef<T>) {
super(elementRef.nativeElement);
}
}
``` |
43,192,626 | I'm new to pandas & numpy. I'm running a simple program
```
labels = ['a','b','c','d','e']
s = Series(randn(5),index=labels)
print(s)
```
getting the following error
```
s = Series(randn(5),index=labels) File "C:\Python27\lib\site-packages\pandas\core\series.py", line 243, in
__init__
raise_cast_failure=True) File "C:\Python27\lib\site-packages\pandas\core\series.py", line 2950, in
_sanitize_array
raise Exception('Data must be 1-dimensional') Exception: Data must be 1-dimensional
```
Any idea what can be the issue? I'm trying this using eclipse, not using ipython notebook. | 2017/04/03 | [
"https://Stackoverflow.com/questions/43192626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385691/"
] | I suspect you have your imports wrong.
If you add this to your code:
```
from pandas import Series
from numpy.random import randn
labels = ['a','b','c','d','e']
s = Series(randn(5),index=labels)
print(s)
a 0.895322
b 0.949709
c -0.502680
d -0.511937
e -1.550810
dtype: float64
```
It runs fine.
That said, and as pointed out by @jezrael, it's better practice to import the modules rather than pollute the namespace.
Your code should look like this instead.
***solution***
```
import pandas as pd
import numpy as np
labels = ['a','b','c','d','e']
s = pd.Series(np.random.randn(5),index=labels)
print(s)
``` | It seems you need [`numpy.random.rand`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html) for random `floats` or [`numpy.random.randint`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html) for random `integers`:
```
import pandas as pd
import numpy as np
np.random.seed(100)
labels = ['a','b','c','d','e']
s = pd.Series(np.random.randn(5),index=labels)
print(s)
a -1.749765
b 0.342680
c 1.153036
d -0.252436
e 0.981321
dtype: float64
```
---
```
np.random.seed(100)
labels = ['a','b','c','d','e']
s = pd.Series(np.random.randint(10, size=5),index=labels)
print(s)
a 8
b 8
c 3
d 7
e 7
dtype: int32
``` |
21,729,196 | I've got the following dictionary:
```py
d = {
'A': {
'param': {
'1': {
'req': True,
},
'2': {
'req': True,
},
},
},
'B': {
'param': {
'3': {
'req': True,
},
'4': {
'req': False,
},
},
},
}
```
I want to have a generator which will give me for each first level keys, the required parameters.
```py
req = {}
for key in d:
req[key] = (p for p in d[key]['param'] if d[key]['param'][p].get('req', False))
```
So here, for each key in `d`, I get parameter `p` only if `req` is `True`.
However, when I try to use my generator, it raises a `KeyError` exception:
```py
>>> req
{'A': <generator object <genexpr> at 0x27b8960>,
'B': <generator object <genexpr> at 0x27b8910>}
>>> for elem in req['A']:
... print elem
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-a96226f95cce> in <module>()
----> 1 for elem in req['A']:
2 print elem
3
<ipython-input-4-1732088ccbdb> in <genexpr>((p,))
1 for key in d:
----> 2 req[key] = (p for p in d[key]['param'] if d[key]['param'][p].get('req', False))
3
KeyError: '1'
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21729196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2047097/"
] | The generator expressions you assign to `req[key]` binds on the `key` variable. But `key` changes from 'A' to 'B' in the loop. When you iterate over the first generator expression, it will evaluate `key` to 'B' in its `if` condition, even though `key` was 'A' when you created it.
The conventional way to bind to a variable's value and not its reference, is to wrap the expression in a lambda with a default value, and then call it immediately.
```
for key in d:
req[key] = (lambda key=key: (p for p in d[key]['param'] if d[key]['param'][p].get('req', False)))()
```
Result:
```
1
2
``` | This is because upon execution of the generator, the *latest* value of `key` is used.
Suppose the `for key in d:` iterates over the keys in the order `'A', 'B'`, the 1st generator is supposed to work with `key = 'A'`, but due to closure issues, it uses the item with `'B'` as key. And this has no `'1'` sub-entry.
Even worse, the `key` variable in the generator has two different values: the `for p in d[key]['param']` part uses the "correct" value, while the `if d[key]['param'][p].get('req', False)` uses the "closure value", which is the last one. |
30,871,488 | The familiar pythonic slicing conventions of `myList[-1:][0]` and `myList[-1]` are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?
Error verbiage for posterity:
>
> `IndexError: Cursor instances do not support negative indices`
>
>
> | 2015/06/16 | [
"https://Stackoverflow.com/questions/30871488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2355364/"
] | You need to use [$location.path()](https://docs.angularjs.org/api/ng/service/$location)
```
// given url http://blo.c/news
var path = $location.path();
// => "/news"
```
If you are using HTML5 mode you must ensure [$locationProvider.html5Mode(true)](https://docs.angularjs.org/guide/$location#html5-mode) is set so `$location` works properly.
If you are not using HTML5 mode (which is the case here); then you'll need to drop to [traditional javascript](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) to get the URL, since you are not using Angular routing in the first place:
```
// given url http://blo.c/news
var path = window.location.pathname;
// => "/news"
```
You might choose to inject [$window](https://docs.angularjs.org/api/ng/service/$window) instead of using `window` directly, this is only a thin wrapper over the native `window` object but facilitates testing. | Use the `$location.path` function to get the url. To get what's after the url, use `split`
```
$location.path.split(/\{1}/)[1]
``` |
30,871,488 | The familiar pythonic slicing conventions of `myList[-1:][0]` and `myList[-1]` are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?
Error verbiage for posterity:
>
> `IndexError: Cursor instances do not support negative indices`
>
>
> | 2015/06/16 | [
"https://Stackoverflow.com/questions/30871488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2355364/"
] | You need to use [$location.path()](https://docs.angularjs.org/api/ng/service/$location)
```
// given url http://blo.c/news
var path = $location.path();
// => "/news"
```
If you are using HTML5 mode you must ensure [$locationProvider.html5Mode(true)](https://docs.angularjs.org/guide/$location#html5-mode) is set so `$location` works properly.
If you are not using HTML5 mode (which is the case here); then you'll need to drop to [traditional javascript](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) to get the URL, since you are not using Angular routing in the first place:
```
// given url http://blo.c/news
var path = window.location.pathname;
// => "/news"
```
You might choose to inject [$window](https://docs.angularjs.org/api/ng/service/$window) instead of using `window` directly, this is only a thin wrapper over the native `window` object but facilitates testing. | ```
const URL = '/seg1/?key=value';
$location.path();// will return URI segment (in above URL it returns /seg1 ).
$location.search(); // getter will fetch URL segment after ? symbol.
//(in above URL it returns {key:value} object ).
```
Official Doc: <https://docs.angularjs.org/guide/$location> |
30,871,488 | The familiar pythonic slicing conventions of `myList[-1:][0]` and `myList[-1]` are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?
Error verbiage for posterity:
>
> `IndexError: Cursor instances do not support negative indices`
>
>
> | 2015/06/16 | [
"https://Stackoverflow.com/questions/30871488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2355364/"
] | Use the `$location.path` function to get the url. To get what's after the url, use `split`
```
$location.path.split(/\{1}/)[1]
``` | ```
const URL = '/seg1/?key=value';
$location.path();// will return URI segment (in above URL it returns /seg1 ).
$location.search(); // getter will fetch URL segment after ? symbol.
//(in above URL it returns {key:value} object ).
```
Official Doc: <https://docs.angularjs.org/guide/$location> |
54,701,639 | I have a python operator in my DAG. The python callable function is returning a bool value. But, when I run the DAG, I get the below error.
>
> TypeError: 'bool' object is not callable
>
>
>
I modified the function to return nothing but then again I keep getting the below error
>
> ERROR - 'NoneType' object is not callable
>
>
>
Below is my dag
```
def check_poke(threshold,sleep_interval):
flag=snowflake_poke(1000,10).poke()
#print(flag)
return flag
dependency = PythonOperator(
task_id='poke_check',
#python_callable=check_poke(129600,600),
provide_context=True,
python_callable=check_poke(129600,600),
dag=dag)
end = BatchEndOperator(
queue=QUEUE,
dag=dag)
start.set_downstream(dependency)
dependency.set_downstream(end)
```
Not able to figure out what it is that I am missing. Can someone help me out on this...Fairly new to airflow.
I edited the python operator in the dag as below
```
dependency = PythonOperator(
task_id='poke_check',
provide_context=True,
python_callable=check_poke(129600,600),
dag=dag)
```
But now, I get a different error.
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1245, in run
result = task_copy.execute(context=context)
File "/usr/local/lib/python2.7/dist-packages/airflow/operators/python_operator.py", line 66, in execute
return_value = self.python_callable(*self.op_args, **self.op_kwargs)
TypeError: () takes no arguments (25 given)
[2019-02-15 05:30:25,375] {models.py:1298} INFO - Marking task as UP_FOR_RETRY
[2019-02-15 05:30:25,393] {models.py:1327} ERROR - () takes no arguments (25 given)
``` | 2019/02/15 | [
"https://Stackoverflow.com/questions/54701639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4017926/"
] | The argument name gives it away. You are passing the result of a call rather than a callable.
```
python_callable=check_poke(129600,600)
```
The second error states that the callable is called with 25 arguments. So a `lambda:` won't work. The following would work but ignoring 25 arguments is really questionable.
```
python_callable=lambda *args, **kwargs: check_poke(129600,600)
``` | Agree with **@Dan D.** for the issue; but it's perplexing why his solution didn't work (it certainly works in `python` *shell*)
See if this finds you any luck (its just verbose variant of **@Dan D.**'s solution)
```
from typing import Callable
# your original check_poke function
def check_poke(arg_1: int, arg_2: int) -> bool:
# do something
# somehow returns a bool
return arg_1 < arg_2
# a function that returns a callable, that in turn invokes check_poke
# with the supplied params
def check_poke_wrapper_creator(arg_1: int, arg_2: int) -> Callable[[], bool]:
def check_poke_wrapper() -> bool:
return check_poke(arg_1=arg_1, arg_2=arg_2)
return check_poke_wrapper
..
# usage
python_callable=check_poke_wrapper_creator(129600, 600)
``` |
54,701,639 | I have a python operator in my DAG. The python callable function is returning a bool value. But, when I run the DAG, I get the below error.
>
> TypeError: 'bool' object is not callable
>
>
>
I modified the function to return nothing but then again I keep getting the below error
>
> ERROR - 'NoneType' object is not callable
>
>
>
Below is my dag
```
def check_poke(threshold,sleep_interval):
flag=snowflake_poke(1000,10).poke()
#print(flag)
return flag
dependency = PythonOperator(
task_id='poke_check',
#python_callable=check_poke(129600,600),
provide_context=True,
python_callable=check_poke(129600,600),
dag=dag)
end = BatchEndOperator(
queue=QUEUE,
dag=dag)
start.set_downstream(dependency)
dependency.set_downstream(end)
```
Not able to figure out what it is that I am missing. Can someone help me out on this...Fairly new to airflow.
I edited the python operator in the dag as below
```
dependency = PythonOperator(
task_id='poke_check',
provide_context=True,
python_callable=check_poke(129600,600),
dag=dag)
```
But now, I get a different error.
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/airflow/models.py", line 1245, in run
result = task_copy.execute(context=context)
File "/usr/local/lib/python2.7/dist-packages/airflow/operators/python_operator.py", line 66, in execute
return_value = self.python_callable(*self.op_args, **self.op_kwargs)
TypeError: () takes no arguments (25 given)
[2019-02-15 05:30:25,375] {models.py:1298} INFO - Marking task as UP_FOR_RETRY
[2019-02-15 05:30:25,393] {models.py:1327} ERROR - () takes no arguments (25 given)
``` | 2019/02/15 | [
"https://Stackoverflow.com/questions/54701639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4017926/"
] | The argument name gives it away. You are passing the result of a call rather than a callable.
```
python_callable=check_poke(129600,600)
```
The second error states that the callable is called with 25 arguments. So a `lambda:` won't work. The following would work but ignoring 25 arguments is really questionable.
```
python_callable=lambda *args, **kwargs: check_poke(129600,600)
``` | The code expects a callable, not the result (as already pointed out).
You could use [functools.Partial](https://docs.python.org/3/library/functools.html) to fill out the arguments:
```
from functools import partial
def check_poke(threshold,sleep_interval):
flag=snowflake_poke(1000,10).poke()
return flag
func = partial(check_poke, 129600, 600)
dependency = PythonOperator(
task_id='poke_check',
provide_context=True,
python_callable=func,
dag=dag)
``` |
29,829,470 | I'm trying to get range-rings on my map, with the position of the image above the user's location, but the map doesn't appear when I test it and the user's location doesn't seem to show up on the map. I don't know what went wrong, I followed a tutorial on a website.
This is the code:
```html
<!DOCTYPE html>
<html>
<head>
<title>Radar</title>
<meta http-equiv="refresh" content="300">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<style>
#map-canvas {
height: 700px;
}
#logo {
position: fixed;
z-index: 99;
top: 8%;
left: 3%;
opacity: 0.9;
}
#legenda {
position: absolute;
z-index: 98;
top: 87%;
left: 82%;
opacity: 1.0;
height: 50px;
}
</style>
</head>
<body style="overflow: hidden;">
<div id="map-canvas"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
// [START region_initialization]
// This example creates a custom overlay called USGSOverlay, containing
// a U.S. Geological Survey (USGS) image of the relevant area on the map.
// Set the custom overlay object's prototype to a new instance
// of OverlayView. In effect, this will subclass the overlay class.
// Note that we set the prototype to an instance, rather than the
// parent class itself, because we do not wish to modify the parent class.
var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();
// Initialize the map and the custom overlay.
function initialize() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
}
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var styles =
[ { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [ { "lightness": -88 }, { "saturation": -100 }, { "visibility": "on" } ] },{ "featureType": "administrative.country", "stylers": [ { "visibility": "on" }, { "weight": 1.3 }, { "lightness": 100 } ] },{ "featureType": "landscape", "stylers": [ { "saturation": -100 }, { "lightness": -81 } ] },{ "featureType": "poi", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.local", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.arterial", "elementType": "geometry", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.highway.controlled_access", "stylers": [ { "visibility": "simplified" } ] },{ "featureType": "road.highway.controlled_access", "elementType": "geometry.fill", "stylers": [ { "visibility": "simplified" }, { "saturation": -100 }, { "lightness": 100 }, { "weight": 1.3 } ] },{ "featureType": "road.highway", "stylers": [ { "visibility": "simplified" } ] },{ "featureType": "administrative.locality", "elementType": "labels", "stylers": [ { "lightness": 100 }, { "visibility": "simplified" } ] },{ "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "visibility": "simplified" }, { "lightness": 100 } ] },{ "featureType": "administrative.province", "elementType": "geometry.stroke", "stylers": [ { "lightness": 100 }, { "saturation": -100 } ] },{ "featureType": "administrative.locality", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road", "elementType": "geometry", "stylers": [ { "lightness": -65 }, { "saturation": 1 }, { "hue": "#0000ff" } ] },{ "featureType": "water", "stylers": [ { "saturation": -53 }, { "lightness": -36 }, { "hue": "#00f6ff" } ] },{ "featureType": "landscape", "stylers": [ { "lightness": -39 } ] },{ } ]
// Create a new StyledMapType object, passing it the array of styles,
// as well as the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var mapOptions = {
zoom: 7,
center: coords,
panControl: false,
zoomControl: false,
mapTypeControl: false,
streetViewControl: false,
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
var icon = {
url: 'met.nl.eu.org/klanten/python/marker.png'
};
var marker = new google.maps.Marker({
position: coords,
map: map,
icon: icon
});
// Query and plot the data once the map is ready
google.maps.event.addListenerOnce(map, 'idle', function() {
$.ajax({
dataType: "json",
url: "http://met.nl.eu.org/klanten/python/get_lightnings.php"
}).done(function(data) {
data.d.forEach(function(lightning) {
var image = 'http://met.nl.eu.org/klanten/python/strike.png'
new google.maps.Marker({
position: new google.maps.LatLng(lightning.lat, lightning.lon),
map: map,
icon: image });
});
});
});
var swBound = new google.maps.LatLng(48.895311, 0.000000);
var neBound = new google.maps.LatLng(55.973607, 10.856428);
var bounds = new google.maps.LatLngBounds(swBound, neBound);
// The photograph is courtesy of MetNL.
var srcImage = 'v2.0/historie/28-06-11/00.png';
// The custom USGSOverlay object contains the USGS image,
// the bounds of the image, and a reference to the map.
overlay = new USGSOverlay(bounds, srcImage, map);
}
// [END region_initialization]
// [START region_constructor]
/** @constructor */
function USGSOverlay(bounds, image, map) {
// Initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
// Define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
// Explicitly call setMap on this overlay.
this.setMap(map);
}
// [END region_constructor]
// [START region_attachment]
/**
* onAdd is called when the map's panes are ready and the overlay has been
* added to the map.
*/
USGSOverlay.prototype.onAdd = function() {
var div = document.createElement('div');
div.style.borderStyle = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';
// Create the img element and attach it to the div.
var img = document.createElement('img');
img.src = this.image_;
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
div.appendChild(img);
this.div_ = div;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
// [END region_attachment]
// [START region_drawing]
USGSOverlay.prototype.draw = function() {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this, we need to retrieve the projection from the overlay.
var overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's div to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
};
// [END region_drawing]
// [START region_removal]
// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
USGSOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
// [END region_removal]
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<img src="http://met.nl.eu.org/NL_nl/iframe/logo.png" id="logo"/>
<img src="http://met.nl.eu.org/klanten/python/legenda.png" id="legenda"/>
</body>
</html>
```
Wat went wrong with my code?
\*\*Edit: Ik now know the fault occurs in this portion of the code: var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
It gives a reference error saying "position is not defined" while earlier in the code i've written this: function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
} | 2015/04/23 | [
"https://Stackoverflow.com/questions/29829470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3832981/"
] | geolocation runs asynchronously.
You may either create the map/marker when it returns a result or define a default-coordinate and update map/marker when it returns a result.
The 2nd approach is preferable, because you wouldn't get a map at all when geolocation fails.
A simple implementation using a MVCObject, which makes it easy to 1. access the value and 2. observe changes(I've removed the irrelevant parts):
```
function initialize() {
//define a default-position
var coords = new google.maps.MVCObject();
coords.set('latlng', new google.maps.LatLng(52.370215, 4.895167));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
}
//set new value for coords
function success(position) {
coords.set('latlng',
new google.maps.LatLng(position.coords.latitude,
position.coords.longitude));
}
var mapOptions = {
zoom: 7,
center: coords.get('latlng')
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: coords.get('latlng'),
map: map
});
//observe the latlng-property of coords,
//and update marker and map-center when it changes
google.maps.event.addListenerOnce(coords, 'latlng_changed', function () {
var latlng = this.get('latlng');
map.setCenter(latlng);
marker.setPosition(latlng)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
```
Demo: [**http://jsfiddle.net/doktormolle/rttvLsLs/**](http://jsfiddle.net/doktormolle/rttvLsLs/) | I think you should include your Google Api key.
Try to add the script below :
```
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
type="text/javascript"></script>
``` |
53,405,006 | I am trying to set up a Dockerfile for my project and am unsure how to set a JAVA\_HOME within the container.
```
FROM python:3.6
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
# Define environment variable
ENV NAME Netflow
# Run netflow.py
CMD ["python", "netflow.py"]
```
In the requirements.txt I have...
```
numpy
pandas
kafka
pyspark
log
```
My netflow.py file is...
```
import pandas, math, re, log
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
conf = SparkConf().setAppName("building a warehouse")
sc = SparkContext(conf=conf)
df=pandas.read_csv(r'TestDataSet.csv')
```
The output in the terminal after trying to run it is....
```
JAVA_HOME is not set
Traceback (most recent call last):
File "netflow.py", line 7, in <module>
sc = SparkContext(conf=conf)
File "/usr/local/lib/python3.6/site-packages/pyspark/context.py", line 115, in __init__
SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
File "/usr/local/lib/python3.6/site-packages/pyspark/context.py", line 298, in _ensure_initialized
SparkContext._gateway = gateway or launch_gateway(conf)
File "/usr/local/lib/python3.6/site-packages/pyspark/java_gateway.py", line 94, in launch_gateway
raise Exception("Java gateway process exited before sending its port number")
```
I have been looking for a solution but none have worked so far.
I have tried
```
ENV JAVA_HOME /Library/Java/JavaVirtualMachines/openjdk-11.jdk/Contents/Home
```
and I have tried using a separate command
```
docker run -e "JAVA_HOME=/Library/Java/JavaVirtualMachines/openjdk-11.jdk/Contents/Home" project env
```
I am still getting the same error | 2018/11/21 | [
"https://Stackoverflow.com/questions/53405006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6465715/"
] | You need to actually install Java inside your container, but I would suggest rather finding a Pyspark docker image, or adding Python to the Openjdk images so that you don't need to mess with too many environment variables
More specifically, `JAVA_HOME=/Library/Java/JavaVirtualMachines` is a only available as a path to your Mac, and shouldn't be expected to work inside a Linux container
However, it's not clear why you need Pyspark when numpy is the only thing actually reading your data | To set environment variables, you can declare them in your dockerfile like so:
```
ENV JAVA_HOME="foo"
```
or
```
ENV JAVA_HOME foo
```
In fact, you already set an environment variable in the example you posted.
See [documentation](https://docs.docker.com/engine/reference/builder/#env) for more details. |
49,564,238 | I have below piece of code in python which I am using to get the component name of the JIRA issue some of them are single value in component field and some of them are multiple values in component field. My issue is that component field could have values with different name e.g R ABC 1.1 , R Aiapara 2.3A1(Active) etc.I don't want to do the way I am trying to do in below code.Is there any way I can find only the integer value from the component. from this component(R ABC 1.1) I need 1.1 and for 2nd component (R Aiapara 2.3A1(Active) I need 2.3 as well so this I would not need to depend on the name of the component
```
for version in issue["fields"]["components"]:
cacheData = json.dumps(version)
jsonToPython = json.loads(cacheData)
if jsonToPython['name'][:10] == "R Aiapara ":
allModules.append(jsonToPython["name"][10:])
print allModules
```
Below is the output I am getting
```
Retrieving list of issues
Processing SPTN-2
[u'1.6']
Processing SPTN-1
[u'1.5']
[u'1.5', u'1.6']
``` | 2018/03/29 | [
"https://Stackoverflow.com/questions/49564238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513848/"
] | Using regex:
```
import re
s1 = "R ABC 4.4"
s2 = "R Ciapara 4.4A1(Active)"
print(re.findall(r"\d+\.\d+", s1))
print(re.findall(r"\d+\.\d+", s2))
```
**Output:**
```
['4.4']
['4.4']
``` | I feel like I am not quite understanding your question, so I will try to answer as best I can, but feel free to correct me if I get anything wrong.
This function will get all the numbers from the string in a list:
```
def getNumber(string):
numbers = ".0123456789"
result = []
isNumber = False
for i in string:
if (i in numbers and isNumber):
result[-1] += i
elif i in result:
result+= [i]
isNumber = True
else:
isNumber = False
return result
```
However, if you want all the characters after the first number, then you will want this function. It will return everything after the first number, and False if there isn't a number there.
```
def getNumber(string):
numbers = ".0123456789"
result = []
isNumber = False
for i,char in enumerate(string):
if char in numbers:
return string[i:]
return False
```
Now, if you want everything between the first and last numbers, then try this one instead:
```
def getNumber(string):
numbers = ".0123456789"
result = string
isNumber = False
for i,char in enumerate(string):
if char in numbers:
result = result[i:]
break
for i in range(len(result)-1, 0, -1):
if result[i] in numbers:
result = result[:i+1]
break
return result
```
Hope this helps :) |
28,570,268 | My file contains this format [{"a":1, "c":4},{"b":2, "d":5}] and I want to read this file into a list in python. The list items should be {"a":1, "c":4} and {"b":2, "d":5}. I tried to read into a string and then typecasting into a list but that is not helping. It is reading character by character. | 2015/02/17 | [
"https://Stackoverflow.com/questions/28570268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4394027/"
] | You can "convert" a string that contains a list to an actual list like this
```
>>> import ast
>>> ast.literal_eval('[{"a":1, "c":4},{"b":2, "d":5}]')
[{'a': 1, 'c': 4}, {'b': 2, 'd': 5}]
```
You can of course sub out the literal string for the data you read from file | Another, more dirty option is this (it will produce list of strings):
```
a = str('[{"a":1, "c":4},{"b":2, "d":5}]')
b = list()
for i in a.replace('[','').replace(']','').split(sep='},'):
b.append(i+'}')
b[len(b)-1] = b[len(b)-1].replace('}}','}')
for i in b:
i
'{"a":1, "c":4}'
'{"b":2, "d":5}'
```
Since ast proposed by Tim earlier will go deaper than first level, it will actually convert underlying string into dictionary. So instead of list of strings you will get list of dictionaries. I am not sure if that's what you want to get. |
28,570,268 | My file contains this format [{"a":1, "c":4},{"b":2, "d":5}] and I want to read this file into a list in python. The list items should be {"a":1, "c":4} and {"b":2, "d":5}. I tried to read into a string and then typecasting into a list but that is not helping. It is reading character by character. | 2015/02/17 | [
"https://Stackoverflow.com/questions/28570268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4394027/"
] | You can "convert" a string that contains a list to an actual list like this
```
>>> import ast
>>> ast.literal_eval('[{"a":1, "c":4},{"b":2, "d":5}]')
[{'a': 1, 'c': 4}, {'b': 2, 'd': 5}]
```
You can of course sub out the literal string for the data you read from file | Use the json module to load json data. Since the json data is a list, it will be converted to a list in python when you call `json.load`:
```
import json
with open(path_to_jsonfile, 'r') as jsonfile:
jsonlist = json.load(jsonfile)
for listitem in jsonlist:
print listitem
```
The result should be:
```
{u'a': 1, u'c': 4}
{u'b': 2, u'd': 5}
```
If you're not trying to read the entire file in, and you are just extracting a string from it, and trying to turn that into a list, use the `json.loads` method instead. `json.load` reads a file, `json.loads` reads a string. |
3,172,236 | I am writing a piece of code which will extract words from running text. This text can contain delimiters like \r,\n etc. which might be there in text.
I want to discard all these delimiters and only extract full words. How can I do this with Python? any library available for crunching text in python? | 2010/07/03 | [
"https://Stackoverflow.com/questions/3172236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348663/"
] | Assuming your definition of "word" agrees with that of the regular expression module (`re`), that is, letters, digits and underscores, it's easy:
```
import re
fullwords = re.findall(r'\w+', thetext)
```
where `thetext` is the string in question (e.g., coming from an `f.read()` of a file object `f` open for reading, if that's where you get your text from).
If you define words differently (e.g. you want to include apostrophes so for example "it's" will be considered "one word"), it isn't much harder -- just use as the first argument of `findall` the appropriate pattern, e.g. `r"[\w']+"` for the apostrophe case.
If you need to be very, *very* sophisticated (e.g., deal with languages that use no breaks between words), then the problem suddenly becomes much harder and you'll need some third-party package like [nltk](http://www.nltk.org/). | Assuming your delimiters are whitespace characters (like space, `\r` and `\n`), then basic [`str.split()`](http://docs.python.org/library/stdtypes.html#str.split) does what you want:
```
>>> "asdf\nfoo\r\nbar too\tbaz".split()
['asdf', 'foo', 'bar', 'too', 'baz']
``` |
74,200,925 | I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value.
Example of what I'm trying to do:
```
list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0]
'area1': [83740], 'area2': [18150]
total value = 101890
```
Main.py:
```
def cubicMeterCalculator():
floorAreaList = {}
print("Example of how this would look like 'area1 395 212' 'area2 165 110'")
n = int(input("\nHow many walls? "))
for i in range(n):
print("\nEnter name of the wall first and 'Space' to separate the name and numbers before hitting enter.")
name, *lengths = input().split(" ")
l_lengths = list(map(float,lengths))
floorAreaList[name] = l_lengths
print(floorAreaList)
total = sum(float, floorAreaList)
print(total)
``` | 2022/10/25 | [
"https://Stackoverflow.com/questions/74200925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248393/"
] | You can use a generator expression to multiply the pairs of values in your dictionary, then `sum` the output of that:
```py
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
total = sum(v[0]*v[1] for v in lst.values())
# 101890.0
``` | You can find the area using list comprehension.
Iterate through `lst.values()` -> `dict_values([[395.0, 212.0], [165.0, 110.0]])` and multiply the elements. Finally, use `sum` to find out the total.
```
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
area = sum([i[0]*i[1] for i in lst.values()])
# 101890.0
```
As solution with `map` + `sum`,
```
sum(map(lambda x: x[0]*x[1], lst.values()))
``` |
74,200,925 | I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value.
Example of what I'm trying to do:
```
list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0]
'area1': [83740], 'area2': [18150]
total value = 101890
```
Main.py:
```
def cubicMeterCalculator():
floorAreaList = {}
print("Example of how this would look like 'area1 395 212' 'area2 165 110'")
n = int(input("\nHow many walls? "))
for i in range(n):
print("\nEnter name of the wall first and 'Space' to separate the name and numbers before hitting enter.")
name, *lengths = input().split(" ")
l_lengths = list(map(float,lengths))
floorAreaList[name] = l_lengths
print(floorAreaList)
total = sum(float, floorAreaList)
print(total)
``` | 2022/10/25 | [
"https://Stackoverflow.com/questions/74200925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248393/"
] | You can use a generator expression to multiply the pairs of values in your dictionary, then `sum` the output of that:
```py
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
total = sum(v[0]*v[1] for v in lst.values())
# 101890.0
``` | The answer with sum, map, and a lambda is probally the best for just areas.
Give this a try if there are more dimensions:
this approach scales with dimensions collected (areas and volumes). We can use the reduce function with a lambda expression to handle multidimensional situations (i.e. you collect LxWxH and want the sum of the volumes)
```
from functools import reduce
inputs = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
vals = [reduce(lambda x, y: x*y,p) for p in inputs.values()]
total = sum(vals)
print(total)
```
with more dimensions
```
inputs = {'vol1': [395.0, 212.0, 10.0], 'vol2': [165.0, 110.0, 10.0]}
vals = [reduce(lambda x, y: x*y,p) for p in inputs.values()]
total = sum(vals)
print(total)
``` |
74,200,925 | I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value.
Example of what I'm trying to do:
```
list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0]
'area1': [83740], 'area2': [18150]
total value = 101890
```
Main.py:
```
def cubicMeterCalculator():
floorAreaList = {}
print("Example of how this would look like 'area1 395 212' 'area2 165 110'")
n = int(input("\nHow many walls? "))
for i in range(n):
print("\nEnter name of the wall first and 'Space' to separate the name and numbers before hitting enter.")
name, *lengths = input().split(" ")
l_lengths = list(map(float,lengths))
floorAreaList[name] = l_lengths
print(floorAreaList)
total = sum(float, floorAreaList)
print(total)
``` | 2022/10/25 | [
"https://Stackoverflow.com/questions/74200925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248393/"
] | You can use a generator expression to multiply the pairs of values in your dictionary, then `sum` the output of that:
```py
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
total = sum(v[0]*v[1] for v in lst.values())
# 101890.0
``` | I think something like this will do the trick
```
from functools import reduce
total = sum([reduce(lambda x, y: x*y, area) for area in floorAreaList.values()])
```
with `values()` you get the values of the dictionary and then with the `lambda` you multiply every element and in the end `sum` them. |
74,200,925 | I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value.
Example of what I'm trying to do:
```
list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0]
'area1': [83740], 'area2': [18150]
total value = 101890
```
Main.py:
```
def cubicMeterCalculator():
floorAreaList = {}
print("Example of how this would look like 'area1 395 212' 'area2 165 110'")
n = int(input("\nHow many walls? "))
for i in range(n):
print("\nEnter name of the wall first and 'Space' to separate the name and numbers before hitting enter.")
name, *lengths = input().split(" ")
l_lengths = list(map(float,lengths))
floorAreaList[name] = l_lengths
print(floorAreaList)
total = sum(float, floorAreaList)
print(total)
``` | 2022/10/25 | [
"https://Stackoverflow.com/questions/74200925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248393/"
] | The answer with sum, map, and a lambda is probally the best for just areas.
Give this a try if there are more dimensions:
this approach scales with dimensions collected (areas and volumes). We can use the reduce function with a lambda expression to handle multidimensional situations (i.e. you collect LxWxH and want the sum of the volumes)
```
from functools import reduce
inputs = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
vals = [reduce(lambda x, y: x*y,p) for p in inputs.values()]
total = sum(vals)
print(total)
```
with more dimensions
```
inputs = {'vol1': [395.0, 212.0, 10.0], 'vol2': [165.0, 110.0, 10.0]}
vals = [reduce(lambda x, y: x*y,p) for p in inputs.values()]
total = sum(vals)
print(total)
``` | You can find the area using list comprehension.
Iterate through `lst.values()` -> `dict_values([[395.0, 212.0], [165.0, 110.0]])` and multiply the elements. Finally, use `sum` to find out the total.
```
lst = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
area = sum([i[0]*i[1] for i in lst.values()])
# 101890.0
```
As solution with `map` + `sum`,
```
sum(map(lambda x: x[0]*x[1], lst.values()))
``` |
74,200,925 | I'm new to python and having problems with summing up the numbers inside an element and then adding them together to get a total value.
Example of what I'm trying to do:
```
list = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
'area1': [395.0 * 212.0], 'area2': [165.0 * 110.0]
'area1': [83740], 'area2': [18150]
total value = 101890
```
Main.py:
```
def cubicMeterCalculator():
floorAreaList = {}
print("Example of how this would look like 'area1 395 212' 'area2 165 110'")
n = int(input("\nHow many walls? "))
for i in range(n):
print("\nEnter name of the wall first and 'Space' to separate the name and numbers before hitting enter.")
name, *lengths = input().split(" ")
l_lengths = list(map(float,lengths))
floorAreaList[name] = l_lengths
print(floorAreaList)
total = sum(float, floorAreaList)
print(total)
``` | 2022/10/25 | [
"https://Stackoverflow.com/questions/74200925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248393/"
] | The answer with sum, map, and a lambda is probally the best for just areas.
Give this a try if there are more dimensions:
this approach scales with dimensions collected (areas and volumes). We can use the reduce function with a lambda expression to handle multidimensional situations (i.e. you collect LxWxH and want the sum of the volumes)
```
from functools import reduce
inputs = {'area1': [395.0, 212.0], 'area2': [165.0, 110.0]}
vals = [reduce(lambda x, y: x*y,p) for p in inputs.values()]
total = sum(vals)
print(total)
```
with more dimensions
```
inputs = {'vol1': [395.0, 212.0, 10.0], 'vol2': [165.0, 110.0, 10.0]}
vals = [reduce(lambda x, y: x*y,p) for p in inputs.values()]
total = sum(vals)
print(total)
``` | I think something like this will do the trick
```
from functools import reduce
total = sum([reduce(lambda x, y: x*y, area) for area in floorAreaList.values()])
```
with `values()` you get the values of the dictionary and then with the `lambda` you multiply every element and in the end `sum` them. |
15,497,896 | I am very new to programming and am converting a fortran90 code into python 2.7. I have done fairly well with it so far but have hit a difficult spot. I need to write this subroutine in Python but I don't understand the fortran notation and can't find any information on what the python equivalent of the Read(1,\*) lines would be.
Any help at all would be greatly appreciated.
```
SUBROUTINE ReadBCoutput(filenameBC,count,timeArray,MbolArray,uArray,gArray,rArray,iArray,zArray)
! read Bruzual & Charlot (2003) stellar population synthesis models into arrays
CHARACTER*500,INTENT(IN):: filenameBC
INTEGER,INTENT(OUT):: count
REAL,DIMENSION(:),ALLOCATABLE,INTENT(OUT):: timeArray,MbolArray,uArray,gArray,rArray,iArray,zArray
REAL:: logTime,Mbol,g,uMg,gMr,gMi,gMz
REAL,DIMENSION(:),ALLOCATABLE:: timeArrayLocal,MbolArrayLocal,uArrayLocal,gArrayLocal,rArrayLocal,iArrayLocal,zArrayLocal
! open file and read off unnecessary 29 lines of comments
OPEN(1,FILE=TRIM(filenameBC),RECL=2000)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
! now read arrays
count=0
ALLOCATE(timeArray(count))
ALLOCATE(MbolArray(count))
ALLOCATE(uArray(count))
ALLOCATE(gArray(count))
ALLOCATE(rArray(count))
ALLOCATE(iArray(count))
ALLOCATE(zArray(count))
IOEnd=0
DO WHILE(IOEnd>-1)
READ(1,*,IOSTAT=IOEnd) logTime,Mbol,g,uMg,gMr,gMi,gMz
!print*,'filename is',filenameBC
IF (IOEnd>-1) THEN ! not at end of file yet
! add new element to list
count=count+1
ALLOCATE(timeArrayLocal(count-1))
ALLOCATE(MbolArrayLocal(count-1))
ALLOCATE(uArrayLocal(count-1))
ALLOCATE(gArrayLocal(count-1))
ALLOCATE(rArrayLocal(count-1))
ALLOCATE(iArrayLocal(count-1))
ALLOCATE(zArrayLocal(count-1))
DO countInside=1,count-1
timeArrayLocal(countInside)=timeArray(countInside)
MbolArrayLocal(countInside)=MbolArray(countInside)
uArrayLocal(countInside)=uArray(countInside)
gArrayLocal(countInside)=gArray(countInside)
rArrayLocal(countInside)=rArray(countInside)
iArrayLocal(countInside)=iArray(countInside)
zArrayLocal(countInside)=zArray(countInside)
END DO
DEALLOCATE(timeArray)
DEALLOCATE(MbolArray)
DEALLOCATE(uArray)
DEALLOCATE(gArray)
DEALLOCATE(rArray)
DEALLOCATE(iArray)
DEALLOCATE(zArray)
ALLOCATE(timeArray(count))
ALLOCATE(MbolArray(count))
ALLOCATE(uArray(count))
ALLOCATE(gArray(count))
ALLOCATE(rArray(count))
ALLOCATE(iArray(count))
ALLOCATE(zArray(count))
DO countInside=1,count-1
timeArray(countInside)=timeArrayLocal(countInside)
MbolArray(countInside)=MbolArrayLocal(countInside)
uArray(countInside)=uArrayLocal(countInside)
gArray(countInside)=gArrayLocal(countInside)
rArray(countInside)=rArrayLocal(countInside)
iArray(countInside)=iArrayLocal(countInside)
zArray(countInside)=zArrayLocal(countInside)
END DO
timeArray(count)=10**logTime
MbolArray(count)=Mbol
gArray(count)=g
uArray(count)=uMg+g
rArray(count)=g-gMr
iArray(count)=g-gMi
zArray(count)=g-gMz
DEALLOCATE(uArrayLocal)
DEALLOCATE(gArrayLocal)
DEALLOCATE(rArrayLocal)
DEALLOCATE(iArrayLocal)
DEALLOCATE(zArrayLocal)
DEALLOCATE(MbolArrayLocal)
DEALLOCATE(timeArrayLocal)
END IF
END DO
CLOSE(1)
END SUBROUTINE ReadBCoutput
```
I don't expect anyone to convert the whole thing for me - I would just like to be clear on what this is actually doing and what is/isn't necessary to do in Python. I'm capable of searching on my own but I'm kind of blown away by what to look for here.
Thanks so much! | 2013/03/19 | [
"https://Stackoverflow.com/questions/15497896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In fortran, `open(1,FILE=TRIM(filenameBC),RECL=2000)` opens the file with name `filenameBC`. The `TRIM` part is unnecessary as the fortran runtime library will do that for you (it's python equivalent is `filenameBC.rstrip()`). The `RECL=2000` part here is also a little fishy. I don't think that it does anything here -- Actually, I think that using it is undefined behavior since you're file should be connected for `"sequential"` access. According to the [fortran77 standard](http://www.fortran.com/F77_std/rjcnf0001-sh-12.html#sh-12.8.1) section 12.10.1,
>
> RECL = rl
>
>
> rl is an integer expression whose value must be positive. It specifies the length of each record in a file being connected for direct access. If the file is being connected for formatted input/output, the length is the number of characters. If the file is being connected for unformatted input/output, the length is measured in processor-dependent units. For an existing file, the value of rl must be included in the set of allowed record lengths for the file ( 12.2.2). For a new file, the processor creates the file with a set of allowed record lengths that includes the specified value. **This specifier must be given when a file is being connected for direct access; otherwise, it must be omitted.**
>
>
>
This may have changed in a newer revision of the standard -- If so, I believe that it specifies the *maximum* line length.
Fortran filehandles are simply integers. So, whereas in python you would say:
```
filehandle = open('file')
line = filehandle.readline() #or better, `next(filehandle)` :)
```
In fortran this is roughly the same as:
```
integer filehandle
filehandle = 1 ! pick an integer any positive one
! will do that we haven't used already,
! but it's best to avoid 0,5,6 as those
! usually mean `stderr`,`stdin` and `stdout`.
open(filehandle,file='file')
read(filehandle,*) line
```
the `*` basically gets you to read a single line from the file.
---
Note that this fortran code is a little buggy and HUGELY inefficient. For example the check `IF (IOEnd>-1) THEN` succeeds under any condition that isn't an end of file (e.g. strange errors will be masked similar to a bare `except` in python). In python, you can just pack this information into a list and grow the list dynamically -- python will handle all of the re-allocation that you need to do. At the end, you may choose to convert the list to a numpy `ndarray`.
In pseudo-python code, this translates roughly to:
```
data_list = []
with open(filenameBC.rstrip()) as fin:
for _ in range(29): #throw away first 29 lines (I think I counted right ...)
next(fin)
for line in fin:
data_list.append([float(x) for x in line.strip()])
timeArray,MbolArray,uArray,gArray,rArray,iArray,zArray = zip(*data_list)
``` | `READ(1,*)` is reading .... something out of your file and not storing it, i.e. just throwing it away. All those `READ(1,*)` statements are just a way of scrolling through the file until you get to the data you actually need. (Not the most compact way to code this, by the way. Whoever wrote this FORTRAN code may have been very smart in many respects but was not a terribly good programmer. Or maybe they were in a big hurry.) A python equivalent would just be
```
>>> infile.readline()
```
Note that FORTRAN can read data in *as* integers, floats, what have you, but python is just going to read everything as text, and then you are going to have to cast it to whatever numerical form you need.
However, if you want to look at [NumPy](http://docs.scipy.org/doc/numpy/reference/routines.io.html), it has a couple a routines that can read data as numbers: `loadtxt` and `genfromtxt`. Maybe a few others too, but those are the ones I have found most helpful. |
23,566,970 | I have been using argparse in a program I am writing however it doesnt seem to create the stated output file.
My code is:
```
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
output_file.write("%s\n" % item)
```
I have also tried:
```
parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
output_file.write("%s\n" % item)
```
The error that occurs is :
```
output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined
```
Can someone please explain why I am having this error occuring and how I could solve it?
All my code:
```
from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import izip
#print = print_function
parser = argparse.ArgumentParser() #simplifys the wording of using argparse as stated in the python tutorial
parser.add_argument("-r1", type=str, action='store', dest='input1', help="input the forward read file") # allows input of the forward read
parser.add_argument("-r2", type=str, action='store', dest='input2', help="input the reverse read file") # allows input of the reverse read
parser.add_argument("-v", "--verbose", action="store_true", help=" Increases the output, only needs to be used to provide feedback to Tom for debugging")
parser.add_argument("-n", action="count", default=0, help="Allows for up to 5 mismatches, however this will reduce accuracy of matching and cause mismatches. Default is 0")
#parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
parser.add_argument("-fastq", action="store_true", help=" States your input as fastq format")
parser.add_argument("-fasta", action="store_true", help=" States your input as fasta format")
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
args = parser.parse_args()
def class_chars(chrs):
if 'N' in chrs:
return 'unknown'
elif chrs[0] == chrs[1]:
return 'match'
else:
return 'not_match'
with open(output, 'w') as output_file:
s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)
for k, group in groupby(zip(s1, s2), class_chars):
elems = len(list(group))
chars[k] += elems
if k == 'match':
consec_matches.append((n, n+elems-1))
n += elems
print (chars)
print (consec_matches)
print ([x for x in consec_matches if x[1]-x[0] >= 9])
list = [x for x in consec_matches if x[1]-x[0] >= 9]
flatten_list= [x for y in list for x in y]
print (flatten_list)
matching=[y[1] for y in list for x in y if x ==0 ]
print (matching)
magic = lambda matching: int(''.join(str(i) for i in matching)) # Generator exp.
print (magic(matching))
s2_l = s2[magic(matching):]
line3=s1+s2_l
print (line3)
if line3:
output_file.write("%s\n" % item)
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23566970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3616869/"
] | You are missing the bit where the arguments are actually parsed:
```
parser.add_argument("-o", "--output", help="Directs the output to a name of your choice")
args = parser.parse_args()
with open(args.output, 'w') as output_file:
output_file.write("%s\n" % item)
```
parser.parse\_args() will give you an object from which you can access the arguments by name using the long option name bar the dashes. | When I run your script I get:
```
Traceback (most recent call last):
File "stack23566970.py", line 31, in <module>
with open(output, 'w') as output_file:
NameError: name 'output' is not defined
```
There's no place in your script that does `output = ...`.
We can correct that with:
```
with open(args.output, 'w') as output_file:
```
`argparse` returns values as attributes of the `args` object.
Now I get:
```
Traceback (most recent call last):
File "stack23566970.py", line 62, in <module>
output_file.write("%s\n" % item)
NameError: name 'item' is not defined
```
Again, there's no `item = ...` line.
What is `item` supposed to be? |
23,566,970 | I have been using argparse in a program I am writing however it doesnt seem to create the stated output file.
My code is:
```
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
output_file.write("%s\n" % item)
```
I have also tried:
```
parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
output_file.write("%s\n" % item)
```
The error that occurs is :
```
output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined
```
Can someone please explain why I am having this error occuring and how I could solve it?
All my code:
```
from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import izip
#print = print_function
parser = argparse.ArgumentParser() #simplifys the wording of using argparse as stated in the python tutorial
parser.add_argument("-r1", type=str, action='store', dest='input1', help="input the forward read file") # allows input of the forward read
parser.add_argument("-r2", type=str, action='store', dest='input2', help="input the reverse read file") # allows input of the reverse read
parser.add_argument("-v", "--verbose", action="store_true", help=" Increases the output, only needs to be used to provide feedback to Tom for debugging")
parser.add_argument("-n", action="count", default=0, help="Allows for up to 5 mismatches, however this will reduce accuracy of matching and cause mismatches. Default is 0")
#parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
parser.add_argument("-fastq", action="store_true", help=" States your input as fastq format")
parser.add_argument("-fasta", action="store_true", help=" States your input as fasta format")
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
args = parser.parse_args()
def class_chars(chrs):
if 'N' in chrs:
return 'unknown'
elif chrs[0] == chrs[1]:
return 'match'
else:
return 'not_match'
with open(output, 'w') as output_file:
s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)
for k, group in groupby(zip(s1, s2), class_chars):
elems = len(list(group))
chars[k] += elems
if k == 'match':
consec_matches.append((n, n+elems-1))
n += elems
print (chars)
print (consec_matches)
print ([x for x in consec_matches if x[1]-x[0] >= 9])
list = [x for x in consec_matches if x[1]-x[0] >= 9]
flatten_list= [x for y in list for x in y]
print (flatten_list)
matching=[y[1] for y in list for x in y if x ==0 ]
print (matching)
magic = lambda matching: int(''.join(str(i) for i in matching)) # Generator exp.
print (magic(matching))
s2_l = s2[magic(matching):]
line3=s1+s2_l
print (line3)
if line3:
output_file.write("%s\n" % item)
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23566970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3616869/"
] | You are missing the bit where the arguments are actually parsed:
```
parser.add_argument("-o", "--output", help="Directs the output to a name of your choice")
args = parser.parse_args()
with open(args.output, 'w') as output_file:
output_file.write("%s\n" % item)
```
parser.parse\_args() will give you an object from which you can access the arguments by name using the long option name bar the dashes. | I think you almost had the most correct answer. The only problem is `output_file` was not read from the args:
```
parser.add_argument("-o", "--output", action='store',
type=argparse.FileType('w'), dest='output',
help="Directs the output to a name of your choice")
#output_file is not defined, you want to read args.output to get the output_file
output_file = args.output
#now you can write to it
output_file.write("%s\n" % item)
``` |
23,566,970 | I have been using argparse in a program I am writing however it doesnt seem to create the stated output file.
My code is:
```
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
output_file.write("%s\n" % item)
```
I have also tried:
```
parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
output_file.write("%s\n" % item)
```
The error that occurs is :
```
output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined
```
Can someone please explain why I am having this error occuring and how I could solve it?
All my code:
```
from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import izip
#print = print_function
parser = argparse.ArgumentParser() #simplifys the wording of using argparse as stated in the python tutorial
parser.add_argument("-r1", type=str, action='store', dest='input1', help="input the forward read file") # allows input of the forward read
parser.add_argument("-r2", type=str, action='store', dest='input2', help="input the reverse read file") # allows input of the reverse read
parser.add_argument("-v", "--verbose", action="store_true", help=" Increases the output, only needs to be used to provide feedback to Tom for debugging")
parser.add_argument("-n", action="count", default=0, help="Allows for up to 5 mismatches, however this will reduce accuracy of matching and cause mismatches. Default is 0")
#parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
parser.add_argument("-fastq", action="store_true", help=" States your input as fastq format")
parser.add_argument("-fasta", action="store_true", help=" States your input as fasta format")
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
args = parser.parse_args()
def class_chars(chrs):
if 'N' in chrs:
return 'unknown'
elif chrs[0] == chrs[1]:
return 'match'
else:
return 'not_match'
with open(output, 'w') as output_file:
s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)
for k, group in groupby(zip(s1, s2), class_chars):
elems = len(list(group))
chars[k] += elems
if k == 'match':
consec_matches.append((n, n+elems-1))
n += elems
print (chars)
print (consec_matches)
print ([x for x in consec_matches if x[1]-x[0] >= 9])
list = [x for x in consec_matches if x[1]-x[0] >= 9]
flatten_list= [x for y in list for x in y]
print (flatten_list)
matching=[y[1] for y in list for x in y if x ==0 ]
print (matching)
magic = lambda matching: int(''.join(str(i) for i in matching)) # Generator exp.
print (magic(matching))
s2_l = s2[magic(matching):]
line3=s1+s2_l
print (line3)
if line3:
output_file.write("%s\n" % item)
``` | 2014/05/09 | [
"https://Stackoverflow.com/questions/23566970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3616869/"
] | I think you almost had the most correct answer. The only problem is `output_file` was not read from the args:
```
parser.add_argument("-o", "--output", action='store',
type=argparse.FileType('w'), dest='output',
help="Directs the output to a name of your choice")
#output_file is not defined, you want to read args.output to get the output_file
output_file = args.output
#now you can write to it
output_file.write("%s\n" % item)
``` | When I run your script I get:
```
Traceback (most recent call last):
File "stack23566970.py", line 31, in <module>
with open(output, 'w') as output_file:
NameError: name 'output' is not defined
```
There's no place in your script that does `output = ...`.
We can correct that with:
```
with open(args.output, 'w') as output_file:
```
`argparse` returns values as attributes of the `args` object.
Now I get:
```
Traceback (most recent call last):
File "stack23566970.py", line 62, in <module>
output_file.write("%s\n" % item)
NameError: name 'item' is not defined
```
Again, there's no `item = ...` line.
What is `item` supposed to be? |
50,447,751 | I'm trying to retrieve last month's media posts from an Instagram Business profile I manage, by using `'since'` and `'until'`, but it doesn't seem to work properly as the API returns posts which are out of the time range I selected.
I'm using the following string to call the API:
```
business_profile_id/media?fields=timestamp&since=2018-04-01&until=2018-04-30
```
while the Python snippet would be this (using the same [**init**](https://github.com/mobolic/facebook-sdk/blob/master/facebook/__init__.py) script from the facebook-python-sdk)
```
import facebook
graph = facebook.GraphAPI(access_token)
profile = graph.get_object(user)
posts = graph.get_connections(profile['id'], 'media?fields=caption,permalink,timestamp&since=2018-04-01&until=2018-04-30')
```
where get.connections is
```
def get_connections(self, id, connection_name, **args):
"""Fetches the connections for given object."""
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args)
```
and request is
```
def request(
self, path, args=None, post_args=None, files=None, method=None):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if 'json' in headers['content-type']:
result = response.json()
elif 'image/' in headers['content-type']:
mimetype = headers['content-type']
result = {"data": response.content,
"mime-type": mimetype,
"url": response.url}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError('Maintype was not text, image, or querystring')
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result
```
Basically I'd like to get posts for a certain period and then get insights for each one.
Has anyone encountered this problem before? | 2018/05/21 | [
"https://Stackoverflow.com/questions/50447751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8542692/"
] | Unfortunately the `since` and `until` parameters are not supported on this endpoint and this endpoint has only support cursor based pagination. The only way to do what I wish to do is to load each page of results individually using the `before` and `after` cursors provided in the API response. | For your task, I would recommend you to not use InstagramAPI library. I will show you a simple solution for this using [instabot](https://github.com/instagrambot/instabot) library. For pip installation of this library, use this command:
`pip install instabot`
Use the following python code to get the media within the specified date range.
```
import datetime
from instabot import Bot
bot = Bot()
bot.login(username="YOUR USERNAME", password="YOUR PASSWORD")
def get_media_posts(start_date, end_date):
all_posts = bot.get_your_medias()
filtered_posts = []
for post in all_posts:
post_info = bot.get_media_info(post) #the media info for the post
post_timestamp = post_info[0].get('taken_at') #get the timestamp of the post
post_date = datetime.datetime.fromtimestamp(post_timestamp).date() #convert timestamp to date
if post_date >= start_date and post_date <= end_date:
filtered_posts.append(post) #or you can also use: filtered_posts.append(post_info)
return filtered_posts
```
This will return you a list of all the posts within the specified date and you can use the `bot.get_media_info(post)` to see what is inside every post.
NOTE: start\_date and end\_date should be in date() (and not in datetime) format according to this code but you can compare with whatever datetime function you want :) |
72,470,453 | ```
import os
import sys, getopt
import signal
import time
from edge_impulse_linux.audio import AudioImpulseRunner
DEFAULT_THRESHOLD = 0.60
my_threshold = DEFAULT_THRESHOLD
runner = None
def signal_handler(sig, frame):
print('Interrupted')
if (runner):
runner.stop()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def help():
print('python classify.py <path_to_model.eim> <audio_device_ID, optional>' )
def my_function(label, score):
print('' )
def main(argv):
try:
opts, args = getopt.getopt(argv, "h", ["--help"])
except getopt.GetoptError:
help()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
help()
sys.exit()
if len(args) == 0:
help()
sys.exit(2)
model = args[0]
dir_path = os.path.dirname(os.path.realpath(__file__))
modelfile = os.path.join(dir_path, model)
with AudioImpulseRunner(modelfile) as runner:
try:
model_info = runner.init()
labels = model_info['model_parameters']['labels']
print('Loaded runner for "' + model_info['project']['owner'] + ' / ' +
model_info['project']['name'] + '"')
#Let the library choose an audio interface suitable for this model, or pass device ID
parameter to manually select a specific audio interface
selected_device_id = None
if len(args) >= 2:
selected_device_id=int(args[1])
print("Device ID "+ str(selected_device_id) + " has been provided as an
argument.")
for res, audio in runner.classifier(device_id=selected_device_id):
print('Result (%d ms.) ' % (res['timing']['dsp'] + res['timing']
['classification']), end='')
for label in labels:
score = res['result']['classification'][label]
print('%s: %.2f\t' % (label, score), end='')
print('', flush=True)
print('', flush=True)
if score > my_threshold:
my_function(label,score)
print('Yes', flush=True)
if label == "Hey Bmo":
my_function(label,score)
finally:
if (runner):
runner.stop()
if __name__ == '__main__':
main(sys.argv[1:])
main(sys.argv[1:])
```
I'm trying to make the Threshold check a specific label as it has multiple and
```
print('Yes', flush=True)
if label == "Hey Bmo":
my_function(label,score)
```
This doesn't work, this is my first time messing around with python so please excuse my lacklustre code attempt
terminal readout:
result (11 ms.) Hey Bmo: 0.02 Noise: 0.94 Unknown: 0.04
result (17 ms.) Hey Bmo: 0.90 Noise: 0.10 Unknown: 0.15
result (07 ms.) Hey Bmo: 0.05 Noise: 0.80 Unknown: 0.20
result (19 ms.) Hey Bmo: 0.10 Noise: 0.40 Unknown: 0.01
result (14 ms.) Hey Bmo: 0.01 Noise: 0.50 Unknown: 0.5
In conclusion when Hey Bmo reaches 0.60 trigger my threshold right now it checks Unknowns threshold | 2022/06/02 | [
"https://Stackoverflow.com/questions/72470453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19253158/"
] | [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) short-circuits after finding the first match so it doesn't necessarily have to iterate over the whole array of objects. And it also returns a boolean which satisfies your use-case.
```js
const query1 = ['empid','Name'];
const arr1 = [{'keyName':'empid' ,'keyValue':'2'}];
const query2 = ['empid','Name'];
const arr2 = [{'keyName':'empid2' ,'keyValue':'five'}];
const query3 = ['empid','Name', 'test'];
const arr3 = [{'keyName':'test2' ,'keyValue':'five'},{'keyName':'test' ,'keyValue':'five'}];
function found(arr, query) {
return arr.some(obj => {
return query.includes(obj.keyName);
});
}
console.log(found(arr1, query1));
console.log(found(arr2, query2));
console.log(found(arr3, query3));
``` | Use `_.isEqual(object, other);`
It may help you. |
37,277,206 | Currently while using `babel-plugin-react-intl`, separate json for every component is created with 'id', 'description' and 'defaultMessage'. What I need is that only a single json to be created which contains a single object with all the 'id' as the 'key' and 'defaultMessage' as the 'value'
Present situation:
`ComponentA.json`
```
[
{
"id": "addEmoticonA",
"description": "Add emoticon",
"defaultMessage": "Insert Emoticon"
},
{
"id": "addPhotoA",
"description": "Add photo",
"defaultMessage": "Insert photo"
}
]
```
`ComponentB.json`
```
[
{
"id": "addEmoticonB",
"description": "Add emoji",
"defaultMessage": "Insert Emoji"
},
{
"id": "addPhotoB",
"description": "Add picture",
"defaultMessage": "Insert picture"
}
]
```
What I need for translation.
`final.json`
```
{
"addEmoticonA": "Insert Emoticon",
"addPhotoA": "Insert photo",
"addEmoticonB": "Insert Emoji",
"addPhotoB": "Insert picture"
}
```
Is there any way to accomplish this task? May it be by using python script or anything. i.e to make a single json file from different json files. Or to directly make a single json file using babel-plugin-react-intl | 2016/05/17 | [
"https://Stackoverflow.com/questions/37277206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5380918/"
] | There is a [translations manager](https://github.com/GertjanReynaert/react-intl-translations-manager) that will do this.
Or for a custom option see below
---
The script below which is based on this [script](https://github.com/emmenko/redux-react-router-async-example/blob/master/scripts/i18nToXliff.js) goes through the translation messages created by
`babel-plugin-react-intl` and creates js files that contain all messages from all components in the json format.
```js
import fs from 'fs'
import {
sync as globSync
}
from 'glob'
import {
sync as mkdirpSync
}
from 'mkdirp'
import * as i18n from '../lib/i18n'
const MESSAGES_PATTERN = './_translations/**/*.json'
const LANG_DIR = './_translations/lang/'
// Ensure output folder exists
mkdirpSync(LANG_DIR)
// Aggregates the default messages that were extracted from the example app's
// React components via the React Intl Babel plugin. An error will be thrown if
// there are messages in different components that use the same `id`. The result
// is a flat collection of `id: message` pairs for the app's default locale.
let defaultMessages = globSync(MESSAGES_PATTERN)
.map(filename => fs.readFileSync(filename, 'utf8'))
.map(file => JSON.parse(file))
.reduce((collection, descriptors) => {
descriptors.forEach(({
id, defaultMessage, description
}) => {
if (collection.hasOwnProperty(id))
throw new Error(`Duplicate message id: ${id}`)
collection[id] = {
defaultMessage, description
}
})
return collection
}, {})
// Sort keys by name
const messageKeys = Object.keys(defaultMessages)
messageKeys.sort()
defaultMessages = messageKeys.reduce((acc, key) => {
acc[key] = defaultMessages[key]
return acc
}, {})
// Build the JSON document for the available languages
i18n.en = messageKeys.reduce((acc, key) => {
acc[key] = defaultMessages[key].defaultMessage
return acc
}, {})
Object.keys(i18n).forEach(lang => {
const langDoc = i18n[lang]
const units = Object.keys(defaultMessages).map((id) => [id, defaultMessages[id]]).reduce((collection, [id]) => {
collection[id] = langDoc[id] || '';
return collection;
}, {});
fs.writeFileSync(`${LANG_DIR}${lang}.json`, JSON.stringify(units, null, 2))
})
``` | You can use [babel-plugin-react-intl-extractor](https://github.com/Bolid1/babel-plugin-react-intl-extractor) for aggregate your translations in single file. Also it provides autorecompile translation files on each change of your messages. |
33,111,338 | I am trying to find out the sum of multiples of two numbers using python.I have done it already. I just want to solve it using lambda functions.
Without lambda code
```
def sumMultiples(num, limit):
sum = 0
for i in xrange(num, limit, num):
sum += i
return sum
def sum(limit):
return (sumMultiples(3, limit) +
sumMultiples(5, limit) -
sumMultiples(15, limit))
print sum(1000)
``` | 2015/10/13 | [
"https://Stackoverflow.com/questions/33111338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5442186/"
] | Try this code:
```
a = input("enter first number\n")
b= input("enter second number\n")
limit=[]
limit.append(a)
limit.append(b)
natNo=range(1,1000)
xyz = []
for i in limit:
xyz +=filter(lambda x: x == i or x % i==0, natNo)
set = {}
map(set.__setitem__, xyz, [])
nums=set.keys()
print "the multiples of the given numbers are: "+str(nums)
c=reduce(lambda x, y:x+y, nums)
print "the sum of the multiples of the given numbers is "+str(c)
``` | ```
limit = 1000
a=lambda num, limit: sum([i for i in xrange(num, limit, num)])
print a(3,limit)+a(5,limit)-a(15,limit)
``` |
42,562,876 | I'm trying to read the frames of an .mov file using OpenCV 3.2 (from the [menpo conda channel](https://anaconda.org/menpo/opencv3)). I'm using Python 3.5.3 through Anaconda on an Ubuntu 16.04 64-bit setup.
Problem is, I get the following error message from OpenCV when it hits the `cap.read()` call, and the loop immediately breaks and catches the `if num == 0` conditional.
Here's the entirety of the code I'm running:
```
import cv2
import numpy as np
import sys
f = sys.argv[1]
cap = cv2.VideoCapture(f)
frames = []
num = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret: break
gframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frames.append(gframe)
num += 1
if num % 100 == 0:
frames.append(gframe)
if num % 1000 == 0:
print(num)
if num == 0:
print("Something went wrong: no frames found.")
exit(0)
cap.release()
```
````
user@ubuntu:/data$ python read.py movie.mov
Unable to stop the stream: Inappropriate ioctl for device
Something went wrong: no frames found.
user@ubuntu:/data$
````
I've found a couple of other StackOverflow questions on this topic, but they don't quite translate to my exact circumstance:
* [This question](https://stackoverflow.com/questions/41200201/opencv-unable-to-stop-the-stream-inappropriate-ioctl-for-device) proposes rebuilding OpenCV (also uses Python 2). That's not an option for me, as I'm trying to do this with Anaconda.
* These two questions ([here](http://answers.opencv.org/question/99659/videocapture-problem-inappropriate-ioctl-for-device/) and [here](http://answers.opencv.org/question/117110/netcat-stream-on-devstdin-not-working-with-opencv-310-dev-on-ubuntu-1604/)) on the OpenCV forums were left without any satisfactory answers.
* [This one](https://stackoverflow.com/questions/1605195/inappropriate-ioctl-for-device) has a lively discussion and a thorough answer, but it's specific to perl.
To that third point--there are quite a few other questions here that have the quote `inappropriate ioctl for device` but it's hard to see if any of them is directly relevant to this problem.
As a partial aside: I've installed this exact same opencv3 conda package on my macOS machine, and the code I've pasted here works just fine and on exactly the same .mov file I've tried on the Ubuntu machine.
Any ideas? | 2017/03/02 | [
"https://Stackoverflow.com/questions/42562876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13604/"
] | Solved the problem by getting around it entirely.
Used the [opencv-feedstock](https://github.com/conda-forge/opencv-feedstock) recipe of OpenCV for conda-forge. In the `recipe` folder is the build information for conda. I modified the `build.sh` file, changing the following options:
```
-DBUILD_PNG=1
-DBUILD_JPEG=1
-DWITH_CUDA=1
-DWITH_FFMPEG=1
```
ran `conda build --numpy 1.12 recipe` from the parent directory (had to specify the NumPy version, as the build script requirement lists `numpy x.x` which means you have to provide the version at runtime), and waited.
Took **forever** (seriously, a couple hours on a very powerful machine--the time sink is CUDA), but the build eventually completed successfully.
Then it was just a matter of installing the locally-built bz2 archive (`conda install --use-local opencv`). No more weird ioctl error messages, and the above script worked just fine. | I faced the same problem with Anaconda private env & Python 3.5 on Ubuntu 16.04 .
Initially installed Opencv3 using
```
conda install -c menpo opencv3
```
Solution:
1. Remove Opencv3 `conda remove opencv3`
2. Install Opencv3 using `pip install opencv-contrib-python`
If the problem still persists:
1. Uninstall OpenCV
2. Install dependencies
`sudo apt-get install ffmpeg`
`sudo apt-get install libavcodec-dev libavformat-dev libavdevice-dev`
3. Reinstall Opencv using step 2. |
19,609,456 | Is there any way of creating a simple java(or c,c ++, python) program that prints 3 (outputs the 3) when given input=6 and it gives output=6 when given input=3 without using "if conditions" ? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19609456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2829141/"
] | Assuming you're happy for it to produce other outputs on inputs that aren't 6 or 3, then you can just compute 9-x. | You can always just use a switch-case statement. Also, if you only want those two answers, you could also take the input as an int and do 9-[your int] and print that answer. |
19,609,456 | Is there any way of creating a simple java(or c,c ++, python) program that prints 3 (outputs the 3) when given input=6 and it gives output=6 when given input=3 without using "if conditions" ? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19609456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2829141/"
] | Assuming you're happy for it to produce other outputs on inputs that aren't 6 or 3, then you can just compute 9-x. | without if or without control flow statement/condition statement ?
you could use switch statement
```
private void tes(int i) {
switch (i) {
///give output 6 where input is 3
case 3:
System.out.println(6);
break;
///give output 3 where input is 6
case 6:
System.out.println(3);
break;
}
}
``` |
19,609,456 | Is there any way of creating a simple java(or c,c ++, python) program that prints 3 (outputs the 3) when given input=6 and it gives output=6 when given input=3 without using "if conditions" ? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19609456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2829141/"
] | Assuming you're happy for it to produce other outputs on inputs that aren't 6 or 3, then you can just compute 9-x. | You can use the XOR bit operation. It compares pairs of bits and returns 0 if bits are equals and 1 if bits are different.
We have `3 = 011b` and `6 = 110b`. This numbers differ by 1 and 3 digit (bit), so XOR mask will be `101b = 5`.
Code example:
```
public static int testMethod(int value){
return System.out.println(value ^ 5);
}
``` |
19,609,456 | Is there any way of creating a simple java(or c,c ++, python) program that prints 3 (outputs the 3) when given input=6 and it gives output=6 when given input=3 without using "if conditions" ? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19609456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2829141/"
] | You can always just use a switch-case statement. Also, if you only want those two answers, you could also take the input as an int and do 9-[your int] and print that answer. | without if or without control flow statement/condition statement ?
you could use switch statement
```
private void tes(int i) {
switch (i) {
///give output 6 where input is 3
case 3:
System.out.println(6);
break;
///give output 3 where input is 6
case 6:
System.out.println(3);
break;
}
}
``` |
19,609,456 | Is there any way of creating a simple java(or c,c ++, python) program that prints 3 (outputs the 3) when given input=6 and it gives output=6 when given input=3 without using "if conditions" ? | 2013/10/26 | [
"https://Stackoverflow.com/questions/19609456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2829141/"
] | You can use the XOR bit operation. It compares pairs of bits and returns 0 if bits are equals and 1 if bits are different.
We have `3 = 011b` and `6 = 110b`. This numbers differ by 1 and 3 digit (bit), so XOR mask will be `101b = 5`.
Code example:
```
public static int testMethod(int value){
return System.out.println(value ^ 5);
}
``` | without if or without control flow statement/condition statement ?
you could use switch statement
```
private void tes(int i) {
switch (i) {
///give output 6 where input is 3
case 3:
System.out.println(6);
break;
///give output 3 where input is 6
case 6:
System.out.println(3);
break;
}
}
``` |
63,067,003 | I'm a beginner in python but I need to fix this small mistake. I tried different ways to fix it by changing the indentation. Maybe I'm overlooking something? The error is attached. Any help is much appreciated! Thank you
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
```
---
```
return model
^
IndentationError: unexpected indent
``` | 2020/07/24 | [
"https://Stackoverflow.com/questions/63067003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13986513/"
] | Here you go.
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
``` | My solution:
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
``` |
63,067,003 | I'm a beginner in python but I need to fix this small mistake. I tried different ways to fix it by changing the indentation. Maybe I'm overlooking something? The error is attached. Any help is much appreciated! Thank you
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
```
---
```
return model
^
IndentationError: unexpected indent
``` | 2020/07/24 | [
"https://Stackoverflow.com/questions/63067003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13986513/"
] | I don't know if you are a beginner or not but hope this helps:
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
``` | My solution:
```
if(pretrained_weights):
model.load_weights(pretrained_weights)
print('*************Using pretrained weights****************')
return model
``` |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | Somehow, my computer was one year behind the actual time.
I adjusted to the correct time and the time zone.
I closed and open Google Chrome. Problem was fixed. | The problem is basically on older version of OS e.g. Windows-XP with SP-II. SHA-2 algorithm has been used to generate SSL certificates which is not in range of older version of OS.
There are two solutions for the problem as:
1. Upgrade the OS. Use another OS or upgrade existing one (with SP-III). or
2. Generate new SSL certificates with SHA-1 algorithm. |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | I found a [related thread](https://productforums.google.com/forum/#!topic/chrome/5-Bf0o6YxgM) in a Google Chrome forum.
I think that the technology responsible for catching this is [HTTP Strict Transport Security](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security);
It looks like one of your extensions is intercepting SSL traffic and, in your case, that looks like BitDefender.
I would stop using BitDefender, but if you want to continue using it you could either look for a setting that stops it from intercepting SSL traffic or contact their support. | the solution consists in activating a flag for ignoring errors caused by certificates,
does not ignore the certificate itself but only the consequent error,
that is obtained by launching the binary with a specific parameter,
for your own reference: <http://www.technonsense.com/2014/04/chrome-ssl-error-solution/>
the fix forces the override of the default behaviour about certificates error |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | I found a [related thread](https://productforums.google.com/forum/#!topic/chrome/5-Bf0o6YxgM) in a Google Chrome forum.
I think that the technology responsible for catching this is [HTTP Strict Transport Security](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security);
It looks like one of your extensions is intercepting SSL traffic and, in your case, that looks like BitDefender.
I would stop using BitDefender, but if you want to continue using it you could either look for a setting that stops it from intercepting SSL traffic or contact their support. | The problem is basically on older version of OS e.g. Windows-XP with SP-II. SHA-2 algorithm has been used to generate SSL certificates which is not in range of older version of OS.
There are two solutions for the problem as:
1. Upgrade the OS. Use another OS or upgrade existing one (with SP-III). or
2. Generate new SSL certificates with SHA-1 algorithm. |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | Somehow, my computer was one year behind the actual time.
I adjusted to the correct time and the time zone.
I closed and open Google Chrome. Problem was fixed. | the solution consists in activating a flag for ignoring errors caused by certificates,
does not ignore the certificate itself but only the consequent error,
that is obtained by launching the binary with a specific parameter,
for your own reference: <http://www.technonsense.com/2014/04/chrome-ssl-error-solution/>
the fix forces the override of the default behaviour about certificates error |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | Somehow, my computer was one year behind the actual time.
I adjusted to the correct time and the time zone.
I closed and open Google Chrome. Problem was fixed. | This problem happens because your system datetime is wrong. Update your window datetime correctly. |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | I am running WIn XP WITHOUT SP3 update and this solution worked for me when using Chrome.
<http://www.technonsense.com/2014/04/chrome-ssl-error-solution/>
In short, modify your Chrome shortcut used to access the browser by appending "-ignore-certificate-errors" (without quotes) in the target field (and after "...exe").
I hope this speeds you on your way! | Double-check the actual time setting of the clock, using one of the Internet time providers. (You mentioned that you checked the time zone, but not the actual time). To do this, double-click clock, Change Date & Time, select Internet Time tab, then Change Settings, and synchronize with one of the providers listed there. If one doesn't work, try another.
Failing that, also try disabling any extensions that you have installed. Type the following into Chrome's address bar, and select the Extensions tab on the left:
```
chrome://extensions/
``` |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | I found a [related thread](https://productforums.google.com/forum/#!topic/chrome/5-Bf0o6YxgM) in a Google Chrome forum.
I think that the technology responsible for catching this is [HTTP Strict Transport Security](http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security);
It looks like one of your extensions is intercepting SSL traffic and, in your case, that looks like BitDefender.
I would stop using BitDefender, but if you want to continue using it you could either look for a setting that stops it from intercepting SSL traffic or contact their support. | This problem happens because your system datetime is wrong. Update your window datetime correctly. |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | This problem happens because your system datetime is wrong. Update your window datetime correctly. | Double-check the actual time setting of the clock, using one of the Internet time providers. (You mentioned that you checked the time zone, but not the actual time). To do this, double-click clock, Change Date & Time, select Internet Time tab, then Change Settings, and synchronize with one of the providers listed there. If one doesn't work, try another.
Failing that, also try disabling any extensions that you have installed. Type the following into Chrome's address bar, and select the Extensions tab on the left:
```
chrome://extensions/
``` |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | If you want to get past that just type in 'danger' in your browser. (just click on the window anywhere and type 'danger', you won't actually see the letters appear anywhere) it used to be proceed but that no longer works. | Double-check the actual time setting of the clock, using one of the Internet time providers. (You mentioned that you checked the time zone, but not the actual time). To do this, double-click clock, Change Date & Time, select Internet Time tab, then Change Settings, and synchronize with one of the providers listed there. If one doesn't work, try another.
Failing that, also try disabling any extensions that you have installed. Type the following into Chrome's address bar, and select the Extensions tab on the left:
```
chrome://extensions/
``` |
21,721,558 | I am working on setting up the pyramid framework on python3.3 virtual env.
For the database connection I use MySQL Connector/Python (SQLAlchemy).
I came across with the problem:
When I try to select records form the database I get the following:
`[Wed Feb 12 09:20:34.373204 2014] [:error] [pid 29351] [remote 127.0.0.1:55376] File "/home/xxx/wsgi/env/lib/python3.3/site-packages/mysql_connector_python-1.1.5-py3.3.egg/mysql/connector/pooling.py", line 29, in <module>
[Wed Feb 12 09:20:34.373237 2014] [:error] [pid 29351] [remote 127.0.0.1:55376]`
`ImportError: No module named queue`
It can't find the module queue, but this works just fine:
```
~/wsgi/env$ bin/python3.3
Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import queue
>>>
```
Where is the problem? There are no symlink in `wsgi/env/lib/python3.3/` for `queue.py`, but if I add it manually, the error still appears
**EDIT 1:**
When I use the pserve command to launch a web server, everything is ok, but with apache2, the one above happens.
Apache config:
```
# Use only 1 Python sub-interpreter. Multiple sub-interpreters
# play badly with C extensions. See
# http://stackoverflow.com/a/10558360/209039
WSGIApplicationGroup %{GLOBAL}
WSGIPassAuthorization On
WSGIDaemonProcess pyramid user=user group=staff threads=4 \
python-path=/home/user/wsgi/env/lib/python3.3/site-packages
WSGIScriptAlias /app /home/user/wsgi/env/pyramid.wsgi
<Directory /home/user/wsgi/env>
WSGIProcessGroup pyramid
# Order allow,deny
Require all granted
</Directory>
``` | 2014/02/12 | [
"https://Stackoverflow.com/questions/21721558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2304257/"
] | If you want to get past that just type in 'danger' in your browser. (just click on the window anywhere and type 'danger', you won't actually see the letters appear anywhere) it used to be proceed but that no longer works. | I am running WIn XP WITHOUT SP3 update and this solution worked for me when using Chrome.
<http://www.technonsense.com/2014/04/chrome-ssl-error-solution/>
In short, modify your Chrome shortcut used to access the browser by appending "-ignore-certificate-errors" (without quotes) in the target field (and after "...exe").
I hope this speeds you on your way! |
71,875,058 | I have a sample spark df as below:
```
df = ([[1, 'a', 'b' , 'c'],
[1, 'b', 'c' , 'b'],
[1, 'b', 'a' , 'b'],
[2, 'c', 'a' , 'a'],
[3, 'b', 'b' , 'a']]).toDF(['id', 'field1', 'field2', 'field3'])
```
What I need next is to provide a multiple aggregations to show summary of the a, b, c values for each field. I have a working but tedious process as below:
```
agg_table = (
df
.groupBy('id')
.agg(
# field1
sum(when(col('field1') == 'a',1).otherwise(0)).alias('field1_a_count')
,sum(when(col('field1') == 'b',1).otherwise(0)).alias('field1_b_count')
,sum(when(col('field1') == 'c',1).otherwise(0)).alias('field1_c_count')
# field2
,sum(when(col('field2') == 'a',1).otherwise(0)).alias('field2_a_count')
,sum(when(col('field2') == 'b',1).otherwise(0)).alias('field2_b_count')
,sum(when(col('field2') == 'c',1).otherwise(0)).alias('field2_c_count')
# field3
,sum(when(col('field3') == 'a',1).otherwise(0)).alias('field3_a_count')
,sum(when(col('field3') == 'b',1).otherwise(0)).alias('field3_b_count')
,sum(when(col('field3') == 'c',1).otherwise(0)).alias('field3_c_count')
))
```
What I am expecting to get is this:
```
agg_table = (['id':'1','2','3'],
['field1_a_count':1,0,0],
['field1_b_count':2,0,1],
['field1_c_count':0, 1, 0],
['field2_a_count':1,1,0],
['field2_b_count':1,0,1],
['field2_c_count':1,0,0],
['field3_a_count':0,1,1],
['field3_b_count':2,0,0],
['field3_c_count':1,0,0])
```
It is just fine if I only really have 3 fields, but I have 30 fields with varying/custom names. Maybe somebody can help me with the repetitive task of coding the aggregated sum per field. I tried playing around with a suggestion from :
<https://danvatterott.com/blog/2018/09/06/python-aggregate-udfs-in-pyspark/>
I can make it work if I will only pull one column and one value, but I get varying errors, one of them is:
```
AnalysisException: cannot resolve '`value`' given input columns: ['field1','field2','field3']
```
One last line I tried is using:
```
validated_cols = ['field1','field2','field3']
df.select(validated_cols).groupBy('id').agg(collect_list($'field1_a_count',$'field1_b_count',$'field1_c_count', ...
$'field30_c_count')).show()
Output: SyntaxError: invalid syntax
```
I tried with pivot too, but from searches so far, it says it is only good for one column. I tried this multiple columns:
```
df.withColumn("p", concat($"p1", $"p2"))
.groupBy("a", "b")
.pivot("p")
.agg(...)
```
I still get a syntax error.
Another link I tried: <https://danvatterott.com/blog/2019/02/05/complex-aggregations-in-pyspark/>
I also tried the exprs approach: `exprs1 = {x: "sum" for x in df.columns if x != 'id'}`
Any suggested will be appreciated. Thanks | 2022/04/14 | [
"https://Stackoverflow.com/questions/71875058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16762881/"
] | Let me answer your question in two steps. First, you are wondering if it is possible to avoid hard coding all your aggregations in your attempt to compute all your aggregations. It is. I would do it like this:
```py
from pyspark.sql import functions as f
# let's assume that this is known, but we could compute it as well
values = ['a', 'b', 'c']
# All the columns except the id
cols = [ c for c in df.columns if c != 'id' ]
def count_values(column, value):
return f.sum(f.when(f.col(column) == value, 1).otherwise(0))\
.alias(f"{column}_{value}_count")
# And this gives you the result of your hard coded aggregations:
df\
.groupBy('id')\
.agg(*[count_values(c, value) for c in cols for value in values])\
.show()
```
But that is not what you expect right? You are trying to compute some kind of pivot on the `id` column. To do this, I would not use the previous result, but just work the data differently. I would start by replacing all the columns of the dataframe but `id` (that is renamed into `x`) by an array of values of the form `{column_name}_{value}_count`, and I would explode that array. From there, we just need to compute a simple pivot on the former `id` column renamed `x`, grouped by the values contained in the exploded array.
```py
df\
.select(f.col('id').alias('x'), f.explode(
f.array(
[f.concat_ws('_', f.lit(c), f.col(c), f.lit('count')).alias(c)
for c in cols]
)
).alias('id'))\
.groupBy('id')\
.pivot('x')\
.count()\
.na.fill(0)\
.orderBy('id')\
.show()
```
which yields:
```none
+--------------+---+---+---+
| id| 1| 2| 3|
+--------------+---+---+---+
|field1_a_count| 1| 0| 0|
|field1_b_count| 2| 0| 1|
|field1_c_count| 0| 1| 0|
|field2_a_count| 1| 1| 0|
|field2_b_count| 1| 0| 1|
|field2_c_count| 1| 0| 0|
|field3_a_count| 0| 1| 1|
|field3_b_count| 2| 0| 0|
|field3_c_count| 1| 0| 0|
+--------------+---+---+---+
``` | ### update
based on discussion in the comments, I think this question is a case of an [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The task at hand is something that is seen very frequently in the world of Data Engineering and ETL development: how to partition and then quantify good and bad records.
In the case where the data is being prepared to load to a data warehouse / hadoop ecosystem, the usual pattern is to take the raw input and load it to a dataframe, then apply transformations & validations that partition the data into "The Good, The Bad, and The Ugly":
* The first— and hopefully largest— partition contains records that are successfully transformed and which pass validation. These will go on to be persisted in durable storage and certified to be used for anayltics.
* The second partition contains records that were successfully transformed but which failed during QA. The QA rules should include checks for illegal nulls, string pattern matching (like phone number format), etc...
* The third partition is for records that are rejected early in the process because they failed on a transformation step. Examples include fields that contain non-number values that are cast to numeric types, text fields that exceed the maximum length, or strings that contain control characters that are not supported by the database.
The goal **should not** be to generate counts for each of these 3 classifications across every column and for every row. Trying to do that is counterproductive. Why? Because when a transformation step or QA check fails for a given record, that entire record should be rejected immediately and sent to a separate output stream to be analyzed later. Each row in the data set should be treated as just that: a single record. It isn't possible for a single field to fail and still have the complete record pass, which makes metrics at this granularity unnecessary. What action will you take knowing that 100 rows passed on the "address" field? For valid records, all that matters is the total number that passed for every column. Otherwise, it wouldn't be a valid record.
With that said, remember that the goal is to build a usable and cleansed data set; analyzing the rejected records is a secondary task and can be done offline.
It is common practice to add a field to the rejected data to indicated which column caused the failure. That makes it easy to troubleshoot any malformed data, so there is really no need to generate counts across all columns, even for bad records. Instead, just review the rejected data after the main job finishes, and address the problems. Continue doing that iteratively until the number of rejected records is below whatever threshold you think is reasonable, and then continue to monitor it going forward.
---
#### Old answer
This is a sign of a design flaw in the data. Whatever the "field1", "field2", etc... columns actually represent, it appears they are all related, in the sense that the values quantify some attribute (maybe each one is a count for a specific merchandise ID, or the number of people with a certain property...). The problem is that these fields are being added as individual columns on a fact table1, which then needs to be aggregated, resulting in the situation that you're facing.
A better design would be to collapse those "field1", "field2", etc... columns into a single code field that can be used as the `GROUP BY` field when doing the aggregation. You might want to consider creating a separate table to do this if the existing one has many other columns and making this change would alter the grain in a way that might cause other problems.
---
1: it's usually a big red flag to have a table with a bunch of enumerated columns with the same name and purpose. I've even seen cases where someone has created tables with "spare" columns for when they want to add more attributes later. Not good. |
49,007,215 | I want get the occurrence of characters in a string, I got this code:
```
string = "Foo Fighters"
def conteo(string):
copia = ''
for i in string:
if i not in copia:
copia = copia + i
conteo = [0]*len(copia)
for i in string:
if i in copia:
conteo[copia.index(i)] = conteo[copia.index(i)] + 1
out = ['0']*2*len(copia)
for i in range(len(copia)):
out[2*i] = copia[i]
out[2*i + 1] = conteo[i]
return (out)
```
And I want return something like: `['f', 2, 'o', 2, '', 1, 'i', 1, 'g', 1, 'h', 1, 't', 1, 'e', 1, 'r', 1, 's', 1]`
How can I do it? Without use a python library
Thank you | 2018/02/27 | [
"https://Stackoverflow.com/questions/49007215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7590594/"
] | Depending on why you want this information, one method could be to use a `Counter`:
```
from collections import Counter
print(Counter("Foo Fighters"))
```
Of course, to create exactly the same output as requested, use itertools as well:
```
from collections import Counter
from itertools import chain
c = Counter("Foo Fighters")
output = list(chain.from_iterable(c.items()))
>> ['F', 2, 'o', 2, ' ', 1, 'i', 1, 'g', 1, 'h', 1, 't', 1, 'e', 1, 'r', 1, 's', 1]
``` | It's not clear whether you want a critique of your current attempt or a pythonic solution. Below is one way where output is a dictionary.
```
from collections import Counter
mystr = "Foo Fighters"
c = Counter(mystr)
```
**Result**
```
Counter({' ': 1,
'F': 2,
'e': 1,
'g': 1,
'h': 1,
'i': 1,
'o': 2,
'r': 1,
's': 1,
't': 1})
```
**Output as list**
I purposely do not combine the tuples in this list, as it's a good idea to maintain structure until absolutely necessary. It's a trivial task to combine these into one list of strings.
```
list(c.items())
# [('F', 2),
# ('o', 2),
# (' ', 1),
# ('i', 1),
# ('g', 1),
# ('h', 1),
# ('t', 1),
# ('e', 1),
# ('r', 1),
# ('s', 1)]
``` |
49,007,215 | I want get the occurrence of characters in a string, I got this code:
```
string = "Foo Fighters"
def conteo(string):
copia = ''
for i in string:
if i not in copia:
copia = copia + i
conteo = [0]*len(copia)
for i in string:
if i in copia:
conteo[copia.index(i)] = conteo[copia.index(i)] + 1
out = ['0']*2*len(copia)
for i in range(len(copia)):
out[2*i] = copia[i]
out[2*i + 1] = conteo[i]
return (out)
```
And I want return something like: `['f', 2, 'o', 2, '', 1, 'i', 1, 'g', 1, 'h', 1, 't', 1, 'e', 1, 'r', 1, 's', 1]`
How can I do it? Without use a python library
Thank you | 2018/02/27 | [
"https://Stackoverflow.com/questions/49007215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7590594/"
] | Use Python Counter (part of standard library):
```
>>> str = 'foo fighters'
>>> from collections import Counter
>>> counter = Counter(str)
Counter({'f': 2, 'o': 2, ' ': 1, 'e': 1, 'g': 1, 'i': 1, 'h': 1, 's': 1, 'r': 1, 't': 1})
>>> counter['f']
2
>>>
``` | It's not clear whether you want a critique of your current attempt or a pythonic solution. Below is one way where output is a dictionary.
```
from collections import Counter
mystr = "Foo Fighters"
c = Counter(mystr)
```
**Result**
```
Counter({' ': 1,
'F': 2,
'e': 1,
'g': 1,
'h': 1,
'i': 1,
'o': 2,
'r': 1,
's': 1,
't': 1})
```
**Output as list**
I purposely do not combine the tuples in this list, as it's a good idea to maintain structure until absolutely necessary. It's a trivial task to combine these into one list of strings.
```
list(c.items())
# [('F', 2),
# ('o', 2),
# (' ', 1),
# ('i', 1),
# ('g', 1),
# ('h', 1),
# ('t', 1),
# ('e', 1),
# ('r', 1),
# ('s', 1)]
``` |
35,782,575 | I am using a python package called kRPC that requires a basic boilerplate of setup code to use in any given instance, so here's my question:
Once I create a generic *'kRPCboilerplate.py'*, where can I place it inside my Python27 directory so that I can simply type,
```
import kRPCboilerplate
```
at the beginning of all my files?
---
I want to install my custom Python file to my Python directory so that I don't have to copy and paste the file into every new project folder I make.
I understand that,
```
import boilerplate
```
will import *'boilerplate.py'*, but only if *'boilerplate.py'* is set in the root directory **relative** to the Python file that imports it.
The program I am creating will not be distributed, so there is no need to make a module installer, which is above the scope of my abilities. I simply want to copy and paste *'kRPCboilerplate.py'* to the proper directory so that I can use **Import** without ever having to specify a path or copy and paste the imported file into the relative directory. | 2016/03/03 | [
"https://Stackoverflow.com/questions/35782575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5910286/"
] | Your module root directory is 'Python27\Lib' where Python27 is your main python folder which includes the python executable file. You can drag and drop the .py files into there and import it without any complications! | Bit late to reply, but the safest is to set a special environmental variable called PYTHONPATH which will add search location for Python to search for libraries:
eg in Linux terminal:
`export PYTHONPATH=$PYTHONPATH:/path/to/file`
note it is only the path to the file, not the filename.
If you want a more permanent solution you can add
`export PYTHONPATH=$PYTHONPATH:/path/to/file`
to your ~/.bashrc or ~/.profile file
In windows the environmental variables are set in the config panel.
Not sure about OSx |
50,070,398 | I am new to tensorflow. When I am using `import tensorflow.contrib.learn.python.learn` for using the DNNClassifier it is giving me an error: `module object has no attribute python`
Python version 3.4
Tensorflow 1.7.0 | 2018/04/27 | [
"https://Stackoverflow.com/questions/50070398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5878765/"
] | You can use `transition-delay` combined with sass loops and completely avoid javascript:
```
@for $i from 0 through 3
.mobile-container.active li:nth-child(#{$i})
transition-delay: 330ms + (100ms * $i) !important
```
Check this [fork](https://codepen.io/anon/pen/aGBPXL) of your codepen. | You can use jquery plugin <https://github.com/morr/jquery.appear/> to track elements when they appear and provide data animations based on it.
E.g. You can give your element and attribute data-animated="fadeIn" and the plugin will do the rest. |
50,070,398 | I am new to tensorflow. When I am using `import tensorflow.contrib.learn.python.learn` for using the DNNClassifier it is giving me an error: `module object has no attribute python`
Python version 3.4
Tensorflow 1.7.0 | 2018/04/27 | [
"https://Stackoverflow.com/questions/50070398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5878765/"
] | You can use `transition-delay` combined with sass loops and completely avoid javascript:
```
@for $i from 0 through 3
.mobile-container.active li:nth-child(#{$i})
transition-delay: 330ms + (100ms * $i) !important
```
Check this [fork](https://codepen.io/anon/pen/aGBPXL) of your codepen. | The fastest way is probably just to loop through each list item and create a setTimeout for a fade-in. My jquery is a little rusty but something like this:
```
$('.mobile-navigation li').each(function(index,item) {
setTimeout( function(){$(item).fadeIn();}, index*100);
});
``` |
17,903,144 | I am new in python and I am supposed to create a game where the input can only be in range of 1 and 3. (player 1, 2 , 3) and the output should be error if user input more than 3 or error if it is in string.
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if ChoosePlayer > 4:
print "Sorry! Error! Please Try Again!"
ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))
if ChoosePlayer.isdigit()== False:
print "Sorry! Integers Only"
ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
else:
print "player 0 has chosen player " + ChoosePlayer + "!"
ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")
```
I was doing it like this but the problem is that it seems like there is a problem with my code. if the input is 1, it still says "error please try again" im so confused! | 2013/07/27 | [
"https://Stackoverflow.com/questions/17903144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626540/"
] | `raw_input` returns a string. Thus, you're trying to do `"1" > 4`. You need to convert it to an integer by using [`int`](http://docs.python.org/2/library/functions.html#int)
If you want to catch whether the input is a number, do:
```
while True:
try:
ChoosePlayer = int(raw_input(...))
break
except ValueError:
print ("Numbers only please!")
```
Just note that now it's an integer, your concatenation below will fail. Here, you should use [`.format()`](http://docs.python.org/2/library/stdtypes.html#str.format)
```
print "player 0 has chosen player {}!".format(ChoosePlayer)
``` | You have to cast your value to int using method [`int()`](http://docs.python.org/2/library/functions.html#int):
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if int(ChoosePlayer) not in [1,2,3]:
print "Sorry! Error! Please Try Again!"
ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))
if ChoosePlayer.isdigit()== False:
print "Sorry! Integers Only"
ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
else:
print "player 0 has chosen player " + ChoosePlayer + "!"
ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")
``` |
17,903,144 | I am new in python and I am supposed to create a game where the input can only be in range of 1 and 3. (player 1, 2 , 3) and the output should be error if user input more than 3 or error if it is in string.
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if ChoosePlayer > 4:
print "Sorry! Error! Please Try Again!"
ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))
if ChoosePlayer.isdigit()== False:
print "Sorry! Integers Only"
ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
else:
print "player 0 has chosen player " + ChoosePlayer + "!"
ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")
```
I was doing it like this but the problem is that it seems like there is a problem with my code. if the input is 1, it still says "error please try again" im so confused! | 2013/07/27 | [
"https://Stackoverflow.com/questions/17903144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626540/"
] | `raw_input` returns a string. Thus, you're trying to do `"1" > 4`. You need to convert it to an integer by using [`int`](http://docs.python.org/2/library/functions.html#int)
If you want to catch whether the input is a number, do:
```
while True:
try:
ChoosePlayer = int(raw_input(...))
break
except ValueError:
print ("Numbers only please!")
```
Just note that now it's an integer, your concatenation below will fail. Here, you should use [`.format()`](http://docs.python.org/2/library/stdtypes.html#str.format)
```
print "player 0 has chosen player {}!".format(ChoosePlayer)
``` | You probably need to convert ChoosePlayer to an int, like:
```
ChoosePlayerInt = int(ChoosePlayer)
```
Otherwise, at least with pypy 1.9, ChoosePlayer comes back as a unicode object. |
17,903,144 | I am new in python and I am supposed to create a game where the input can only be in range of 1 and 3. (player 1, 2 , 3) and the output should be error if user input more than 3 or error if it is in string.
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if ChoosePlayer > 4:
print "Sorry! Error! Please Try Again!"
ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))
if ChoosePlayer.isdigit()== False:
print "Sorry! Integers Only"
ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
else:
print "player 0 has chosen player " + ChoosePlayer + "!"
ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")
```
I was doing it like this but the problem is that it seems like there is a problem with my code. if the input is 1, it still says "error please try again" im so confused! | 2013/07/27 | [
"https://Stackoverflow.com/questions/17903144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626540/"
] | You probably need to convert ChoosePlayer to an int, like:
```
ChoosePlayerInt = int(ChoosePlayer)
```
Otherwise, at least with pypy 1.9, ChoosePlayer comes back as a unicode object. | You have to cast your value to int using method [`int()`](http://docs.python.org/2/library/functions.html#int):
```
def makeTurn(player0):
ChoosePlayer= (raw_input ("Who do you want to ask? (1-3)"))
if int(ChoosePlayer) not in [1,2,3]:
print "Sorry! Error! Please Try Again!"
ChoosePlayer= (raw_input("Who do you want to ask? (1-3)"))
if ChoosePlayer.isdigit()== False:
print "Sorry! Integers Only"
ChoosePlayer = (raw_input("Who do you want to ask? (1-3)"))
else:
print "player 0 has chosen player " + ChoosePlayer + "!"
ChooseCard= raw_input("What rank are you seeking from player " + ChoosePlayer +"?")
``` |
54,530,138 | I am stuck on why my code doesn't count the number of vowels, including case-insensitive, and print a sentence reporting the number of vowels found in the word 'and'.
```
import sys
vowels = sys.argv[1]
count = 0
for vowel in vowels:
if(vowel =='a' or vowel == 'e' or vowel =='i' or vowel =='o' or vowel =='u' or vowel
=='A' or vowel =='E' or vowel =='I' or vowel =='O' or vowel =='U'):
count += 1
if count == 0:
print('There are 0 vowels in '.format(count))
elif count < 2:
print('There is 1 vowel in '.format(count))
else:
print('There are {} vowels'.format(count, vowels))
```
In my terminal:
**user$ python** vowel\_counter.py and
There are 0 vowels in
There are 0 vowels in | 2019/02/05 | [
"https://Stackoverflow.com/questions/54530138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | sys.argv is a list of the running arguments, where the first element is always your running file. therefore, you do not iterate over the text but rather over the arguments ['vowel\_counter.py', 'and'].
You should do something like this:
```
vowels=sys.argv[1]
``` | The following will take care of single or multiple arguments passed in the command line. Like `python vowel_count.py foo` and `python vowel_count.py foo bar`
```
$ cat vowel_count.py
import sys
args = sys.argv[1:]
print(args)
count = 0
for arg in args: # handling multiple commandline args
for char in arg:
if char.lower() in ['a','e','i','o','u']:
count += 1
print("The {} contains {} vowels".format(' ',join(args), count))
``` |
54,530,138 | I am stuck on why my code doesn't count the number of vowels, including case-insensitive, and print a sentence reporting the number of vowels found in the word 'and'.
```
import sys
vowels = sys.argv[1]
count = 0
for vowel in vowels:
if(vowel =='a' or vowel == 'e' or vowel =='i' or vowel =='o' or vowel =='u' or vowel
=='A' or vowel =='E' or vowel =='I' or vowel =='O' or vowel =='U'):
count += 1
if count == 0:
print('There are 0 vowels in '.format(count))
elif count < 2:
print('There is 1 vowel in '.format(count))
else:
print('There are {} vowels'.format(count, vowels))
```
In my terminal:
**user$ python** vowel\_counter.py and
There are 0 vowels in
There are 0 vowels in | 2019/02/05 | [
"https://Stackoverflow.com/questions/54530138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | sys.argv is a list of the running arguments, where the first element is always your running file. therefore, you do not iterate over the text but rather over the arguments ['vowel\_counter.py', 'and'].
You should do something like this:
```
vowels=sys.argv[1]
``` | One of the major problems with your code is indentation, According to the way you've presented the code, the block that checks `count` is run on every iteration of your loop.
Secondly, you've not output the word you're checking which would have probably indicated the bug that you're reading the wrong argument. Here is some working code - although kept like your original there are much better ways to do this logic
```
import sys
vowels = sys.argv[1]
count = 0
for vowel in vowels:
if(vowel =='a' or vowel =='i' or vowel =='o' or vowel =='u' or vowel
=='A' or vowel =='E' or vowel =='I' or vowel =='O' or vowel =='U'):
count += 1
if count == 0:
print('There are 0 vowels in {}'.format(vowels))
elif count < 2:
print('There is 1 vowel in {}'.format(vowels))
else:
print('There are {} vowels in {}'.format(count,vowels))
```
Note: you're missing `vowel =='e'` from your check. |
54,530,138 | I am stuck on why my code doesn't count the number of vowels, including case-insensitive, and print a sentence reporting the number of vowels found in the word 'and'.
```
import sys
vowels = sys.argv[1]
count = 0
for vowel in vowels:
if(vowel =='a' or vowel == 'e' or vowel =='i' or vowel =='o' or vowel =='u' or vowel
=='A' or vowel =='E' or vowel =='I' or vowel =='O' or vowel =='U'):
count += 1
if count == 0:
print('There are 0 vowels in '.format(count))
elif count < 2:
print('There is 1 vowel in '.format(count))
else:
print('There are {} vowels'.format(count, vowels))
```
In my terminal:
**user$ python** vowel\_counter.py and
There are 0 vowels in
There are 0 vowels in | 2019/02/05 | [
"https://Stackoverflow.com/questions/54530138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | One of the major problems with your code is indentation, According to the way you've presented the code, the block that checks `count` is run on every iteration of your loop.
Secondly, you've not output the word you're checking which would have probably indicated the bug that you're reading the wrong argument. Here is some working code - although kept like your original there are much better ways to do this logic
```
import sys
vowels = sys.argv[1]
count = 0
for vowel in vowels:
if(vowel =='a' or vowel =='i' or vowel =='o' or vowel =='u' or vowel
=='A' or vowel =='E' or vowel =='I' or vowel =='O' or vowel =='U'):
count += 1
if count == 0:
print('There are 0 vowels in {}'.format(vowels))
elif count < 2:
print('There is 1 vowel in {}'.format(vowels))
else:
print('There are {} vowels in {}'.format(count,vowels))
```
Note: you're missing `vowel =='e'` from your check. | The following will take care of single or multiple arguments passed in the command line. Like `python vowel_count.py foo` and `python vowel_count.py foo bar`
```
$ cat vowel_count.py
import sys
args = sys.argv[1:]
print(args)
count = 0
for arg in args: # handling multiple commandline args
for char in arg:
if char.lower() in ['a','e','i','o','u']:
count += 1
print("The {} contains {} vowels".format(' ',join(args), count))
``` |
59,134,194 | This is a part of HTML code from following page [following page](https://orange.e-sim.org/battle.html?id=5377):
```
<div>
<div class="sidebar-labeled-information">
<span>
Economic skill:
</span>
<span>
10.646
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Strength:
</span>
<span>
2336
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Location:
</span>
<div>
<a href="region.html?id=454">
Little Karoo
<div class="xflagsSmall xflagsSmall-Argentina">
</div>
</a>
</div>
</div>
<div class="sidebar-labeled-information">
<span>
Citizenship:
</span>
<div>
<div class="xflagsSmall xflagsSmall-Poland">
</div>
<small>
<a href="pendingCitizenshipApplications.html">
change
</a>
</small>
</div>
</div>
</div>
```
I want to extract `region.html?id=454` from it. I don't know how to narrow the search down to `<a href="region.html?id=454">`, since there are a lot of `<a href=>` tags.
Here is the python code:
```
session=session()
r = session.get('https://orange.e-sim.org/battle.html?id=5377',headers=headers,verify=False)
soup = BeautifulSoup(r.text, 'html.parser')
div = soup.find_all('div',attrs={'class':'sidebar-labeled-information'})
```
And the output of this code is:
```
[<div class="sidebar-labeled-information" id="levelMission">
<span>Level:</span> <span>15</span>
</div>, <div class="sidebar-labeled-information" id="currRankText">
<span>Rank:</span>
<span>Colonel</span>
</div>, <div class="sidebar-labeled-information">
<span>Economic skill:</span>
<span>10.646</span>
</div>, <div class="sidebar-labeled-information">
<span>Strength:</span>
<span>2336</span>
</div>, <div class="sidebar-labeled-information">
<span>Location:</span>
<div>
<a href="region.html?id=454">Little Karoo<div class="xflagsSmall xflagsSmall-Argentina"></div>
</a>
</div>
</div>, <div class="sidebar-labeled-information">
<span>Citizenship:</span>
<div>
<div class="xflagsSmall xflagsSmall-Poland"></div>
<small><a href="pendingCitizenshipApplications.html">change</a>
</small>
</div>
</div>]
```
But my desired output is `region.html?id=454`.
The page which I'm trying to search in is located [here](https://orange.e-sim.org/battle.html?id=5377), but you need to have an account to view the page. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59134194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12460618/"
] | You need to change the format string a little and pass `width` as a keyword argument to the `format()` method:
```
width = 6
with open(out_file, 'a') as file:
file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))
```
Contents of file afterwards:
```none
a b
``` | It's a bit ugly but you can do this. Using `{{}}` you can type a literal curly brace, and by that, you can format your format string with a variable width.
```
width = 6
format_str = "{{:{}}}{{:{}}}\n".format(width, width) #This makes the string "{:width}{:width}" with a variable width.
with open(out_file, a) as file:
file.write(format_str.format('a','b'))
```
EDIT: If you want to apply this type of variable width pattern to any of your patterns used in a code, you could use this function:
```
import re
def variable_width_pattern(source_pattern, width):
regex = r"\{(.*?)\}"
matches = re.findall(regex, source_pattern)
args = ["{{:{}}}".format(width) for x in range(len(matches))]
return source_pattern.format(*args)
``` |
59,134,194 | This is a part of HTML code from following page [following page](https://orange.e-sim.org/battle.html?id=5377):
```
<div>
<div class="sidebar-labeled-information">
<span>
Economic skill:
</span>
<span>
10.646
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Strength:
</span>
<span>
2336
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Location:
</span>
<div>
<a href="region.html?id=454">
Little Karoo
<div class="xflagsSmall xflagsSmall-Argentina">
</div>
</a>
</div>
</div>
<div class="sidebar-labeled-information">
<span>
Citizenship:
</span>
<div>
<div class="xflagsSmall xflagsSmall-Poland">
</div>
<small>
<a href="pendingCitizenshipApplications.html">
change
</a>
</small>
</div>
</div>
</div>
```
I want to extract `region.html?id=454` from it. I don't know how to narrow the search down to `<a href="region.html?id=454">`, since there are a lot of `<a href=>` tags.
Here is the python code:
```
session=session()
r = session.get('https://orange.e-sim.org/battle.html?id=5377',headers=headers,verify=False)
soup = BeautifulSoup(r.text, 'html.parser')
div = soup.find_all('div',attrs={'class':'sidebar-labeled-information'})
```
And the output of this code is:
```
[<div class="sidebar-labeled-information" id="levelMission">
<span>Level:</span> <span>15</span>
</div>, <div class="sidebar-labeled-information" id="currRankText">
<span>Rank:</span>
<span>Colonel</span>
</div>, <div class="sidebar-labeled-information">
<span>Economic skill:</span>
<span>10.646</span>
</div>, <div class="sidebar-labeled-information">
<span>Strength:</span>
<span>2336</span>
</div>, <div class="sidebar-labeled-information">
<span>Location:</span>
<div>
<a href="region.html?id=454">Little Karoo<div class="xflagsSmall xflagsSmall-Argentina"></div>
</a>
</div>
</div>, <div class="sidebar-labeled-information">
<span>Citizenship:</span>
<div>
<div class="xflagsSmall xflagsSmall-Poland"></div>
<small><a href="pendingCitizenshipApplications.html">change</a>
</small>
</div>
</div>]
```
But my desired output is `region.html?id=454`.
The page which I'm trying to search in is located [here](https://orange.e-sim.org/battle.html?id=5377), but you need to have an account to view the page. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59134194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12460618/"
] | You need to change the format string a little and pass `width` as a keyword argument to the `format()` method:
```
width = 6
with open(out_file, 'a') as file:
file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))
```
Contents of file afterwards:
```none
a b
``` | I googled a little and found [this](https://stackoverflow.com/questions/36138895/how-to-set-the-spaces-in-a-string-format-in-python-3?answertab=active#tab-top). With some changes, I wrote this code which I tried and got your desired output:
```
width = 6
with open(out_file, 'a') as file:
f.write("{1:<{0}}{2}\n".format(width, 'a', 'b'))
``` |
59,134,194 | This is a part of HTML code from following page [following page](https://orange.e-sim.org/battle.html?id=5377):
```
<div>
<div class="sidebar-labeled-information">
<span>
Economic skill:
</span>
<span>
10.646
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Strength:
</span>
<span>
2336
</span>
</div>
<div class="sidebar-labeled-information">
<span>
Location:
</span>
<div>
<a href="region.html?id=454">
Little Karoo
<div class="xflagsSmall xflagsSmall-Argentina">
</div>
</a>
</div>
</div>
<div class="sidebar-labeled-information">
<span>
Citizenship:
</span>
<div>
<div class="xflagsSmall xflagsSmall-Poland">
</div>
<small>
<a href="pendingCitizenshipApplications.html">
change
</a>
</small>
</div>
</div>
</div>
```
I want to extract `region.html?id=454` from it. I don't know how to narrow the search down to `<a href="region.html?id=454">`, since there are a lot of `<a href=>` tags.
Here is the python code:
```
session=session()
r = session.get('https://orange.e-sim.org/battle.html?id=5377',headers=headers,verify=False)
soup = BeautifulSoup(r.text, 'html.parser')
div = soup.find_all('div',attrs={'class':'sidebar-labeled-information'})
```
And the output of this code is:
```
[<div class="sidebar-labeled-information" id="levelMission">
<span>Level:</span> <span>15</span>
</div>, <div class="sidebar-labeled-information" id="currRankText">
<span>Rank:</span>
<span>Colonel</span>
</div>, <div class="sidebar-labeled-information">
<span>Economic skill:</span>
<span>10.646</span>
</div>, <div class="sidebar-labeled-information">
<span>Strength:</span>
<span>2336</span>
</div>, <div class="sidebar-labeled-information">
<span>Location:</span>
<div>
<a href="region.html?id=454">Little Karoo<div class="xflagsSmall xflagsSmall-Argentina"></div>
</a>
</div>
</div>, <div class="sidebar-labeled-information">
<span>Citizenship:</span>
<div>
<div class="xflagsSmall xflagsSmall-Poland"></div>
<small><a href="pendingCitizenshipApplications.html">change</a>
</small>
</div>
</div>]
```
But my desired output is `region.html?id=454`.
The page which I'm trying to search in is located [here](https://orange.e-sim.org/battle.html?id=5377), but you need to have an account to view the page. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59134194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12460618/"
] | You need to change the format string a little and pass `width` as a keyword argument to the `format()` method:
```
width = 6
with open(out_file, 'a') as file:
file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))
```
Contents of file afterwards:
```none
a b
``` | A simple multiplication will work here
(multiplication operator is overloaded here)
```
width = 6
charector = ' '
with open(out_file, 'a') as file:
file.write('a' + charector * width + 'b')
``` |
54,722,251 | I am trying to connect to a mysql database (hosted on media temple) with my python script (ran locally) but I am receiving an error when I run it.
The error is:
```
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 179, in _open_connection
self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: Bad handshake
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/Charlie/Documents/python/myscript/mysql_insert.py", line 8, in <module>
port="3306"
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/__init__.py", line 172, in connect
return CMySQLConnection(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 78, in __init__
self.connect(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/abstracts.py", line 735, in connect
self._open_connection()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 182, in _open_connection
sqlstate=exc.sqlstate)
mysql.connector.errors.OperationalError: 1043 (08S01): Bad handshake
```
Here is the code from the script
```
import mysql.connector
mydb = mysql.connector.connect(
host="external-db.s157688.gridserver.com",
user="myusername",
passwd="mypassword",
database="mydatabase",
port="3306"
)
mycursor = mydb.cursor()
sql = "INSERT INTO test (post_id, title) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
```
I tried to google it but did not find any solutions, could anybody help out? | 2019/02/16 | [
"https://Stackoverflow.com/questions/54722251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320977/"
] | make sure you've installed mysql-connector and not mysql-connector-python, to make this sure just run the following commands: `pip3 uninstall mysql-connector-python pip3 install mysql-connector` | Make sure you have given correct port number |
15,912,804 | Standard python [distutils provides a '--user' option](http://docs.python.org/2/install/index.html#alternate-installation-the-user-scheme) which lets me install a package as a limited user, like this:
```
python setup.py install --user
```
Is there an equivalent for **easy\_install** and **pip**? | 2013/04/09 | [
"https://Stackoverflow.com/questions/15912804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376587/"
] | For `pip`, see [User Installs](http://www.pip-installer.org/en/latest/cookbook.html#user-installs) for details, but basically, it's just what you'd expect:
```
pip install --user Foo
```
It's a bit trickier for `easy_install`. As Ned Deily points out, if you can rely on `distribute` rather than `setuptools`, and 0.6.11 or later, you can just use `--user` the same as `pip`. But if you need to work with `setuptools`, or older `distribute`… see [Custom Installation Locations](http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations) for details (and note that it explains how to create and set up user site packages, not just how to install there, because it needs to be able to work with Python 2.5 and earlier, which didn't do this by default). But hopefully, you're only using `easy_install` for the handful of packages that aren't `pip`-able, so that isn't a big deal.
However, it's at least worth considering whether [`virtualenv`](http://www.virtualenv.org) is a better fit for whatever you're trying to accomplish than a user site directory. `pip` and `virtualenv` work together very nicely, as [the docs](http://www.pip-installer.org/en/latest/installing.html#using-virtualenv) explain. | From the easy\_install docs
<http://peak.telecommunity.com/DevCenter/EasyInstall#downloading-and-installing-a-package>
>
> --install-dir=DIR, -d DIR Set the installation directory. It is up to you to ensure that this directory is on sys.path at runtime, and to
> use pkg\_resources.require() to enable the installed package(s) that
> you need.
>
>
> (New in 0.4a2) If this option is not directly specified on the command
> line or in a distutils configuration file, the distutils default
> installation location is used. Normally, this would be the
> site-packages directory, but if you are using distutils configuration
> files, setting things like prefix or install\_lib, then those settings
> are taken into account when computing the default installation
> directory, as is the --prefix option.
>
>
> --prefix=DIR (New in 0.6a10) Use the specified directory as a base for computing the default installation and script directories. On Windows,
> the resulting default directories will be prefix\Lib\site-packages
> and prefix\Scripts, while on other platforms the defaults will be
> prefix/lib/python2.X/site-packages (with the appropriate version
> substituted) for libraries and prefix/bin for scripts.
>
>
> Note that the --prefix option only sets the default installation and
> script directories, and does not override the ones set on the command
> line or in a configuration file.
>
>
>
You can also specify them on using a ~/.pydistutils.cfg file
<http://peak.telecommunity.com/DevCenter/EasyInstall#mac-os-x-user-installation>
Before installing EasyInstall/setuptools, just create a ~/.pydistutils.cfg file with the following contents (or add this to the existing contents):
>
> [install] install\_lib =
> ~/Library/Python/$py\_version\_short/site-packages install\_scripts =
> ~/bin This will tell the distutils and EasyInstall to always install
> packages in your personal site-packages directory, and scripts to
> ~/bin. (Note: do not replace $py\_version\_short with an actual Python
> version in the configuration file! The distutils will substitute the
> correct value at runtime, so that the above configuration file should
> work correctly no matter what Python version you use, now or in the
> future.)
>
>
> Once you have done this, you can follow the normal installation
> instructions and use easy\_install without any other special options or
> steps.
>
>
> (Note, however, that ~/bin is not in the default PATH, so you may have
> to refer to scripts by their full location. You may want to modify
> your shell startup script (likely .bashrc or .profile) or your
> ~/.MacOSX/environment.plist to include ~/bin in your PATH.
>
>
> |
15,912,804 | Standard python [distutils provides a '--user' option](http://docs.python.org/2/install/index.html#alternate-installation-the-user-scheme) which lets me install a package as a limited user, like this:
```
python setup.py install --user
```
Is there an equivalent for **easy\_install** and **pip**? | 2013/04/09 | [
"https://Stackoverflow.com/questions/15912804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376587/"
] | For `pip`, see [User Installs](http://www.pip-installer.org/en/latest/cookbook.html#user-installs) for details, but basically, it's just what you'd expect:
```
pip install --user Foo
```
It's a bit trickier for `easy_install`. As Ned Deily points out, if you can rely on `distribute` rather than `setuptools`, and 0.6.11 or later, you can just use `--user` the same as `pip`. But if you need to work with `setuptools`, or older `distribute`… see [Custom Installation Locations](http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations) for details (and note that it explains how to create and set up user site packages, not just how to install there, because it needs to be able to work with Python 2.5 and earlier, which didn't do this by default). But hopefully, you're only using `easy_install` for the handful of packages that aren't `pip`-able, so that isn't a big deal.
However, it's at least worth considering whether [`virtualenv`](http://www.virtualenv.org) is a better fit for whatever you're trying to accomplish than a user site directory. `pip` and `virtualenv` work together very nicely, as [the docs](http://www.pip-installer.org/en/latest/installing.html#using-virtualenv) explain. | I needed to do the same with my docker and deploy to AWS Elastic Beanstalk.
The issue is that **pip** and **easy\_install** (called by python setup.py) interpret the `--user` parameter in different way.
* `pip install --user PackageName` will install the PackageName to `$PYTHONUSERBASE` environment variable.
* `python setup.py develop --user` will ignore `$PYTHONUSERBASE` variable and always install to `~/.local/lib/python<python version>/site-packages` folder
The only way I found for both these folders works together, is to delete `~/.local/lib/python<python version>/site-packages` and to make link to your `$PYTHONUSERBASE`
PS: Be careful with bellow, you may need to reinstall all your local python dependencies. I recommend use it only in docker or any other virtual environment
```
# !!! Be sure you have configured $PYTHONUSERBASE environment variable
rm -r ~/.local/lib/python2.7/site-packages
ln -s $PYTHONUSERBASE/lib/python2.7/site-packages ~/.local/lib/python2.7/site-packages
```
Now both pip and python setup.py devel --user will install to the same folder |
48,791,900 | I'm using the python api to upload apks, mapping files and release note texts.
See <https://developers.google.com/resources/api-libraries/documentation/androidpublisher/v2/python/latest/androidpublisher_v2.edits.html>
I'm using the `apks().upload()`, `deobfuscationfiles().upload()` and `apklistings().update()` APIs to upload the new apks, mapping files and changelogs, respectively.
Then I call `tracks().update()` to assign the uploaded apks to the *production* track.
Finally I call `commit()` to finalize the edit.
This, however, **immediately** publishes the new apks.
What I want is for the release manager to have the final confirmation on the new release. So there should be a manual review/publish step like in a manual release.
Is this possible using the API. Do I use the wrong API calls?
One way of course would be to upload on the beta/alpha track and then have the release manager move it to production. But is there another way? | 2018/02/14 | [
"https://Stackoverflow.com/questions/48791900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261009/"
] | You need to use the new version of Google Play Developer API v3, where you can now set "status" (completed, draft, stopped, inProgress) for Edits.tracks.
<https://developers.google.com/resources/api-libraries/documentation/androidpublisher/v3/python/latest/androidpublisher_v3.edits.tracks.html> | It isn't possible to have a manual review step at the moment. |
23,768,865 | I am trying to list some of software installed on a PC by using:
```
Get-WmiObject -Class Win32_Product |
Select-Object -Property name,version |
Where-Object {$_.name -like '*Java*'}
```
It works, but when I added more names in `Where-Object` it gave me no results neither an error.
```
Get-WmiObject -Class Win32_Product |
Select-Object -Property name,version |
Where-Object {$_.name -like '*Java*','*python*','*adobe*','*access*'}
```
Why does it only work with one name? | 2014/05/20 | [
"https://Stackoverflow.com/questions/23768865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3303155/"
] | I don't think `-like` will take an array on the right hand side. Try a regex instead:
```
Where-Object {$_.name -match 'Java|python|adobe|access'}
``` | The -Like operator takes a string argument (not a string array), so whatever you give it will get cast as [string]. If you cast the arguments you've give it to string:
```
[string]('*Java*','*python*','*adobe*','*access*')
```
you get:
```
*Java* *python* *adobe* *access*
```
and that's what you're trying to match against (and you don't have any file names that look like that).
The easiest way to do this is switch to the -match operator, and an alternating regex:
```
Where-Object { $_.name -match 'Java|python|adobe|access' }
``` |
60,250,462 | I have a large list that contains usernames (about 60,000 strings). Each username represents a submission. Some users have made only one submission i.e. they are **"one-time users"**, so their username appears only once in this list. Others have made multiple submission (**returning users**) so their username can appear many times in this list. I want to count how many of these one-time users there are and get some stats based on that. Here are the variables I'm currently grabbing:
```py
import time
start_time = time.time()
users = ["UserA", "UserB", "UserC", "UserA", "UserA", "UserA", "UserB", "UserB", "UserD"] # ...just a sample, this goes up to ~60,000 elements
print(f"1: got users list. Time elapsed: {time.time() - start_time}")
one_time_users = [user for user in users if users.count(user) == 1]
print(f"2: got one-time users list. Time elapsed: {time.time() - start_time}")
returning_users = [user for user in users if users.count(user) != 1]
print(f"3: got returning users list. Time elapsed: {time.time() - start_time}")
frequencies = [users.count(user) for user in set(users)]
print(f"4: calculated frequencies list. Time elapsed: {time.time() - start_time}")
sorted_frequencies = sorted(frequencies, reverse=True) # Descending order, largest first
print(f"5: got sorted frequencies list. Time elapsed: {time.time() - start_time}")
top_ten_frequencies_sum = sum(sorted_frequencies[:10])
print(f"6: got top 10 frequencies sum. Time elapsed: {time.time() - start_time}")
top_ten_frequencies_percentage = round(((top_ten_frequencies_sum / len(users)) * 100), 2)
print(f"7: got top 10 frequencies percentage. Time elapsed: {time.time() - start_time}")
average_submissions_per_user = round(len(users) / len(set(users)), 2)
print(f"8: got average submissions per user. Time elapsed: {time.time() - start_time}")
```
This operation is **very slow.** Here is my output:
```
1: got users list. Time elapsed: 0.41695237159729004
2: got one-time users list. Time elapsed: 48.26731848716736
3: got returning users list. Time elapsed: 101.88410639762878
4: calculated frequencies list. Time elapsed: 104.39784860610962
5: got sorted frequencies list. Time elapsed: 104.39850783348083
6: got top 10 frequencies sum. Time elapsed: 104.39853930473328
7: got top 10 frequencies percentage. Time elapsed: 104.39856457710266
8: got average submissions per user. Time elapsed: 104.4005241394043
```
As you can see the list comprehensions are taking the most time. Can someone explain to me:
1. Why it's so slow in terms of time complexity.
2. Whether [collections.Counter()](https://docs.python.org/3/library/collections.html#collections.Counter) will be a better choice and how best to apply it here.
Thank you! | 2020/02/16 | [
"https://Stackoverflow.com/questions/60250462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5900486/"
] | You can improve by using a [Counter](https://docs.python.org/2/library/collections.html#collections.Counter), in `2.` for each element you are iterating the whole list, and you are doing this multiple times for the same user if an user occurs more than once.
Note that when you use `users.count(user)` you iterate all the list of users to count how many times the user occurs. This means quadratic complexity with respect to the length of the list.
Using a counter, you can solve it in linear complexity.
Also, in `4.` you are iterating and counting again, while you could just remove the ones you just computed from the whole users.
Example.
```
>>> one_time_users = {user for user,cnt in Counter(users).items() if cnt == 1}
{'UserC', 'UserD'}
>>> returning_users = set(users) - one_time_users
>>> returning_users
{'UserB', 'UserA'}
```
or more directly
```
one_time_users, returning_users = [], []
for user,cnt in Counter(users).items():
if cnt==1:
one_time_users.append(user)
else:
returning_users.append(user)
```
Here a comparison of `l.count(el)` vs a `Counter(l)`.
```
>>> l = random.choices(range(500), k=60000)
>>> timeit.timeit('[el for el in l if l.count(el) == 1]',setup='from __main__ import l',number=1)
71.70409394335002
>>> timeit.timeit('[el for el,cnt in Counter(l).items() if cnt == 1]',setup='from __main__ import l, Counter',number=1)
0.005492186639457941
``` | As mentioned in your own comment, Counter is significantly faster here. You can see from your own timing that creating a set of the results takes around 10ms to complete (#8->#9), which is roughly the time Counter will take as well.
With counter you look at at each of the N elements once, and then at each unique element (at most N) once.
When you use `.count()` you iterate through the entire list (a fast implementation, but still the entire list). You do this for every element, so you look at each of N elements N times.
Every time your list gets 1000x bigger you require 1000x the time for the Counter method, but 1000000x for .count versions. |
56,206,422 | Try to pass the dictionary into the function to print them out, but it throws error: most\_courses() takes 0 positional arguments but 1 was given
```
def most_courses(**diction):
for key, value in diction.items():
print("{} {}".format(key,value))
most_courses({'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})
```
I have used \*\*kwargs but why cant python unpack the dictionary? | 2019/05/19 | [
"https://Stackoverflow.com/questions/56206422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11523169/"
] | When you pass your dict as a param, you can either do it as you wrote:
```
most_courses({'Andrew Chalkley': ...
```
in this case `most_cources` should accept a "positional" param. That's why it raises: `most_courses() takes 0 positional arguments but 1 was given`.
You gave it 1 positional param, while `most_cources` (which looks like: `most_courses(**d)`) isn't expecting any..
You should either do:
```
most_courses(**{'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})
```
OR change the signiture of your method:
```
def most_courses(diction):
for key, value in diction.items():
print("{} {}".format(key,value))
``` | There is no reason to use `**` here. You want to pass a dict and have it processed as a dict. Just use a standard argument.
```
def most_courses(diction):
``` |
56,206,422 | Try to pass the dictionary into the function to print them out, but it throws error: most\_courses() takes 0 positional arguments but 1 was given
```
def most_courses(**diction):
for key, value in diction.items():
print("{} {}".format(key,value))
most_courses({'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})
```
I have used \*\*kwargs but why cant python unpack the dictionary? | 2019/05/19 | [
"https://Stackoverflow.com/questions/56206422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11523169/"
] | When you pass your dict as a param, you can either do it as you wrote:
```
most_courses({'Andrew Chalkley': ...
```
in this case `most_cources` should accept a "positional" param. That's why it raises: `most_courses() takes 0 positional arguments but 1 was given`.
You gave it 1 positional param, while `most_cources` (which looks like: `most_courses(**d)`) isn't expecting any..
You should either do:
```
most_courses(**{'Andrew Chalkley': ['jQuery Basics', 'Node.js Basics'],'Kenneth Love': ['Python Basics', 'Python Collections']})
```
OR change the signiture of your method:
```
def most_courses(diction):
for key, value in diction.items():
print("{} {}".format(key,value))
``` | arguments denoted with a \*\* in the definition of a function need to be passed with a keyword:
### example:
```
def test(**diction):
print(diction)
```
Argument passed without keyword:
```
test(8)
```
>
>
> ```
> ---------------------------------------------------------------------------
> TypeError Traceback (most recent call last)
> <ipython-input-9-5092d794a50d> in <module>
> 2 print(diction)
> 3
> ----> 4 test(8)
> 5 test(test_arg=9)
>
> TypeError: test() takes 0 positional arguments but 1 was given
>
> ```
>
>
With arbitrary keyword:
```
test(test_arg=8)
```
output:
```
{'test_arg': 8}
```
edit:
-----
helpful links:
[Use of \*args and \*\*kwargs](https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs)
[What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters?noredirect=1&lq=1) |
61,853,196 | I have a python file that contains these elements:
```
startaddress = 768
length = 64
subChId = 6
protection = 1
bitrate = 64
```
and I want to convert them to a single dictionary string like this:
```
{"startaddress":"768","length":"64","subChId":"6","protection":"1","bitrate":"64"}
```
so I can read the values individually using json.loads().
How can I do that? | 2020/05/17 | [
"https://Stackoverflow.com/questions/61853196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3150586/"
] | Let a package manager like [brew](https://brew.sh/) do the work for you:
```sh
brew install deno
```
Easy to install, easy to upgrade.
Check the [official repo](https://github.com/denoland/deno_install) for all the installation options. | To find the instillation options use official documentation <https://deno.land/#installation>.
For MacOS following installation options are available.
**01.Using Shell**
```
curl -fsSL https://deno.land/x/install/install.sh | sh
```
**02.Using [Homebrew](https://brew.sh/)**
```
brew install deno
```
**03.Using Cargo (macOS)**
```
cargo install deno
``` |
61,889,217 | I have this list of dictionaries.
```
[{'value': '299021.000000', 'abbrev': 'AAA'},
{'value': '299021.000000', 'abbrev': 'BBB'},
{'value': '8.597310', 'abbrev': 'CCC'}]
```
I want to transform this list to look like this;
```
[{'AAA': '299021.000000'},
{'BBB': '299021.000000'},
{'CCC': '8.597310'}]
```
Any hints on how to get started?
I am using python 3.7 | 2020/05/19 | [
"https://Stackoverflow.com/questions/61889217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7518091/"
] | With [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) you can do the following:
```
data = [
{'value': '299021.000000', 'abbrev': 'AAA'},
{'value': '299021.000000', 'abbrev': 'BBB'},
{'value': '8.597310', 'abbrev': 'CCC'}
]
data_2 = [{elem["abbrev"]: elem["value"]} for elem in data]
print(data_2)
# Output:
# [{'AAA': '299021.000000'}, {'BBB': '299021.000000'}, {'CCC': '8.597310'}]
``` | Using for loop;
```
original_list = [
{'value': '299021.000000', 'abbrev': 'AAA'},
{'value': '299021.000000', 'abbrev': 'BBB'},
{'value': '8.597310', 'abbrev': 'CCC'}
]
transformed_list = [ ]
for i in original_list:
key = i['abbrev']
value = i['value']
single_dict = {}
single_dict[key] = value
transformed_list.append(single_dict)
```
I prefer the answer from Xukrao using list comprehension. Elegant, easy to read in one line. |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | I got my Answer, it was quit simple.
Open Terminal,
Type command:
```
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
```
Press Enter: You will get the following info, and SHA1 can be seen there.
.....
Certificate fingerprints:
```
MD5: 79:F5:59:................FE:09:D1:EC
SHA1: 33:57:0A:C9:..................:91:47:14:CD
SHA256: 39:AA:23:88:D6:...................33:DF:61:24:CB:17:47:EA:39:94:99
```
....... | **Very easy and simply finding the SHA1 key for certificate in only android studio.**
You can use below steps:
```
A.Open Android Studio
B.Open Your Project
C.Click on Gradle (From Right Side Panel, you will see Gradle Bar)
D.Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of your Project)
E.Click on Your Project (Your Project Name form List (root))
F.Click on Tasks
G.Click on android
H.Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)
```
**OR**
```
1.Click on your package and choose New -> Google -> Google Maps Activity
2.Android Studio redirect you to google_maps_api.xml
```
[](https://i.stack.imgur.com/Na0EY.png) |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | Type this is the Terminal
keytool -list -v -keystore ~/.android/debug.keystore
It will ask you to enter the password
enter 'android'
Then you would get the details like the SHA1. | [](https://i.stack.imgur.com/QvqG8.png)
After clicking signingReport You will get SHA-1 finger certificate for your application
I am here if you need any other help |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | There is no way in `Android Studio` like `Eclipse` **Windows -> Preferences -> Android -> Build**.
`Android Studio` signs your app in debug mode automatically when you run or debug your project from the IDE.
You may get using the following Command!!
```
keytool -list -v -keystore ~/.android/debug.keystore
``` | Type this is the Terminal
keytool -list -v -keystore ~/.android/debug.keystore
It will ask you to enter the password
enter 'android'
Then you would get the details like the SHA1. |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | All above answers are correct.
**But,Easiest and Faster way is below:**
1. Open Android Studio
2. Open Your Project
3. Click on Gradle (From Right Side Panel, you will see Gradle Bar)
4. Click on Refresh (Click on Refresh from Gradle Bar, you will see
List Gradle scripts of your Project)
5. Click on Your Project Name like MyProject(root)
6. Click on Tasks
7. Click on android
8. Double Click on signingReport
9. Wait for few seconds and you will get SHA1 and MD5 in Console Bar
[](https://i.stack.imgur.com/pLIfX.png)
If you are adding a **MapActivity** in your project than see this answer for SHA1.
[How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?](https://stackoverflow.com/questions/12214467/how-to-obtain-signing-certificate-fingerprint-sha1-for-oauth-2-0-on-android/32558627#32558627) | [](https://i.stack.imgur.com/QvqG8.png)
After clicking signingReport You will get SHA-1 finger certificate for your application
I am here if you need any other help |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | I got my Answer, it was quit simple.
Open Terminal,
Type command:
```
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
```
Press Enter: You will get the following info, and SHA1 can be seen there.
.....
Certificate fingerprints:
```
MD5: 79:F5:59:................FE:09:D1:EC
SHA1: 33:57:0A:C9:..................:91:47:14:CD
SHA256: 39:AA:23:88:D6:...................33:DF:61:24:CB:17:47:EA:39:94:99
```
....... | The other way to get the SHA1 fingerprint instead of inputting a `keytool` command is to create dummy project and select the `Google Map Activity` in the `Add an activity module` and after the project is created you then open the `values->google_maps_api.xml` in that xml you'll see the SHA1 fingerprint of your android studio. |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | All above answers are correct.
**But,Easiest and Faster way is below:**
1. Open Android Studio
2. Open Your Project
3. Click on Gradle (From Right Side Panel, you will see Gradle Bar)
4. Click on Refresh (Click on Refresh from Gradle Bar, you will see
List Gradle scripts of your Project)
5. Click on Your Project Name like MyProject(root)
6. Click on Tasks
7. Click on android
8. Double Click on signingReport
9. Wait for few seconds and you will get SHA1 and MD5 in Console Bar
[](https://i.stack.imgur.com/pLIfX.png)
If you are adding a **MapActivity** in your project than see this answer for SHA1.
[How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?](https://stackoverflow.com/questions/12214467/how-to-obtain-signing-certificate-fingerprint-sha1-for-oauth-2-0-on-android/32558627#32558627) | Type this is the Terminal
keytool -list -v -keystore ~/.android/debug.keystore
It will ask you to enter the password
enter 'android'
Then you would get the details like the SHA1. |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | **Very easy and simply finding the SHA1 key for certificate in only android studio.**
You can use below steps:
```
A.Open Android Studio
B.Open Your Project
C.Click on Gradle (From Right Side Panel, you will see Gradle Bar)
D.Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of your Project)
E.Click on Your Project (Your Project Name form List (root))
F.Click on Tasks
G.Click on android
H.Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)
```
**OR**
```
1.Click on your package and choose New -> Google -> Google Maps Activity
2.Android Studio redirect you to google_maps_api.xml
```
[](https://i.stack.imgur.com/Na0EY.png) | Type this is the Terminal
keytool -list -v -keystore ~/.android/debug.keystore
It will ask you to enter the password
enter 'android'
Then you would get the details like the SHA1. |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | I got my Answer, it was quit simple.
Open Terminal,
Type command:
```
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
```
Press Enter: You will get the following info, and SHA1 can be seen there.
.....
Certificate fingerprints:
```
MD5: 79:F5:59:................FE:09:D1:EC
SHA1: 33:57:0A:C9:..................:91:47:14:CD
SHA256: 39:AA:23:88:D6:...................33:DF:61:24:CB:17:47:EA:39:94:99
```
....... | [](https://i.stack.imgur.com/QvqG8.png)
After clicking signingReport You will get SHA-1 finger certificate for your application
I am here if you need any other help |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | 1. Go to your key directory / Folder.
2. Use following command in the terminal: `keytool -list -v -keystore <yourKeyFileName.withExtension> -alias <yourKeyAlias>`.
3. Enter Key Password entered at time of key creations.
**yourKeyAlias had given at time of creation of your key.** | Type this is the Terminal
keytool -list -v -keystore ~/.android/debug.keystore
It will ask you to enter the password
enter 'android'
Then you would get the details like the SHA1. |
30,070,300 | **I want to bind two event to one ListCtrl weight in wxpython.**
**Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting...
How should I do?
I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_CLICK`. It works!
**But, when I use `wx.EVT_LIST_ITEM_RIGHT_CLICK`, it will also trigger the `wx.EVT_LIST_ITEM_SELECTED`**
So, How to do this without confliction? Thank you!
Here is my code!
```
import wx
class ListCtrlLeft(wx.ListCtrl):
def __init__(self, parent, i):
wx.ListCtrl.__init__(self, parent, i, style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_NO_HEADER | wx.LC_SINGLE_SEL)
self.parent = parent
self.Bind(wx.EVT_SIZE, self.on_size)
self.InsertColumn(0, '')
self.InsertStringItem(0, 'library-one')
self.InsertStringItem(0, 'library-two')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_lib_select)
self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_lib_right_click)
def on_size(self, event):
size = self.parent.GetSize()
self.SetColumnWidth(0, size.x - 5)
def on_lib_select(self, evt):
print "Item selected"
def on_lib_right_click(self, evt):
print "Item right-clicked"
class Memo(wx.Frame):
def __init__(self, parent, i, title, size):
wx.Frame.__init__(self, parent, i, title=title, size=size)
self._create_splitter_windows()
self.Centre()
self.Show(True)
def _create_splitter_windows(self):
horizontal_box = wx.BoxSizer(wx.HORIZONTAL)
splitter = wx.SplitterWindow(self, -1, style=wx.SP_LIVE_UPDATE | wx.SP_NOBORDER)
splitter.SetMinimumPaneSize(250)
vertical_box_left = wx.BoxSizer(wx.VERTICAL)
panel_left = wx.Panel(splitter, -1)
panel_left_top = wx.Panel(panel_left, -1, size=(-1, 30))
panel_left_top.SetBackgroundColour('#53728c')
panel_left_str = wx.StaticText(panel_left_top, -1, 'Libraries', (5, 5))
panel_left_str.SetForegroundColour('white')
panel_left_bottom = wx.Panel(panel_left, -1, style=wx.BORDER_NONE)
vertical_box_left_bottom = wx.BoxSizer(wx.VERTICAL)
# Here!!!!
list_1 = ListCtrlLeft(panel_left_bottom, -1)
# ----------
vertical_box_left_bottom.Add(list_1, 1, wx.EXPAND)
panel_left_bottom.SetSizer(vertical_box_left_bottom)
vertical_box_left.Add(panel_left_top, 0, wx.EXPAND)
vertical_box_left.Add(panel_left_bottom, 1, wx.EXPAND)
panel_left.SetSizer(vertical_box_left)
# right
vertical_box_right = wx.BoxSizer(wx.VERTICAL)
panel_right = wx.Panel(splitter, -1)
# ......
panel_right.SetSizer(vertical_box_right)
horizontal_box.Add(splitter, -1, wx.EXPAND | wx.TOP, 1)
self.SetSizer(horizontal_box)
splitter.SplitVertically(panel_left, panel_right, 250)
def on_quit(self, evt):
self.Close()
evt.Skip()
if __name__ == "__main__":
app = wx.App()
Memo(None, -1, 'PyMemo', (500, 300))
app.MainLoop()
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30070300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827183/"
] | Follow the below steps to get SHA1 fingerprint Certificate in Android Studio in 2.2v.
>
> Open Android Studio Open your Project Click on Gradle (From Right Side
> Panel, you will see Gradle Bar)
>
>
> Click on Refresh (Click on Refresh from Gradle Bar, you will see List
> Gradle scripts of your Project)
>
>
> Click on Your Project (Your Project Name form List (root))
>
>
> Click on Tasks
>
>
> Click on Android
>
>
> Double Click on signing-report (You will get SHA1 and MD5 in Run Bar)
> Then click this button:  (top left of
> the error log) and you will get your SHA1 key.
>
>
> | [](https://i.stack.imgur.com/QvqG8.png)
After clicking signingReport You will get SHA-1 finger certificate for your application
I am here if you need any other help |
72,304,877 | super new to python and having an error on one of my codecademy projects that i cant seem to understand, even referencing the walkthrough and altering line 17 multiple times i cant quiet understand why this is returning an error. could somebody help me understand the error so i can learn from it? this is my code thats returning a type error:
```
lovely_loveseat_description = """Lovely Loveseat. Tufted polyester blend on wood. 32 inches high X 40 inches wide X 30 inches deep. Available in Red or White."""
lovely_loveseat_price = 254.00
stylish_setee_description = """Stylish Settee. Faux leather on birch.
29.50 inches high X 54.75 inches wide X 28 inches deep. Available only in Black."""
stylish_settee_price = 150.50
luxurious_lamp_description = "Luxurious Lamp. Glass and iron. 36 inches tall. Available in Brown with a Stylish Beige shade."
luxurious_lamp_price = 52.15
#sales tax variable.
sales_tax = .088
#base shopping cart total value.
customer_one_total = 0
#shopping cart contents variable.
customer_one_itemization = ""
#shopping area.
customer_one_total =+ lovely_loveseat_price
customer_one_itemization =+ lovely_loveseat_description
customer_one_total =+ luxurious_lamp_price
customer_one_itemization =+ luxurious_lamp_description
customer_one_tax = customer_one_total * sales_tax
customer_one_total =+ customer_one_tax
print("Customer One Items:")
print(customer_one_itemization)
print("Customer One Total Cost:")
print(customer_one_total)```
and this is the error:
```Traceback (most recent call last):
File "script.py", line 17, in <module>
customer_one_itemization =+ lovely_loveseat_description
TypeError: bad operand type for unary +: 'str'```
thanks heaps guys.
``` | 2022/05/19 | [
"https://Stackoverflow.com/questions/72304877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19153697/"
] | If there is only one non empty value per groups use:
```
df = df.replace('',np.nan).groupby('ID', as_index=False).first().fillna('')
```
If possible multiple values and need unique values in original order use lambda function:
```
print (df)
ID LU MA ME JE VE SA DI
0 201 B C B
1 201 C C C B C
f = lambda x: ','.join(dict.fromkeys(x.dropna()).keys())
df = df.replace('',np.nan).groupby('ID', as_index=False).agg(f)
print (df)
ID LU MA ME JE VE SA DI
0 201 B,C C C B C
``` | This could be treated as a pivot. You'd need to melt the df first then pivot:
```
(df.melt(id_vars='ID')
.dropna()
.pivot(index='ID',columns='variable',values='value')
.fillna('')
.rename_axis(None, axis=1)
.reset_index()
)
``` |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | Calling the *function* `collections.namedtuple` gives you a new type that's a subclass of `tuple` (and no other classes) with a member named `_fields` that's a tuple whose items are all strings. So you could check for each and every one of these things:
```
def isnamedtupleinstance(x):
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return all(type(n)==str for n in f)
```
it IS possible to get a false positive from this, but only if somebody's going out of their way to make a type that looks a **lot** like a named tuple but isn't one;-). | IMO this might be the best solution for *Python 3.6* and later.
You can set a custom `__module__` when you instantiate your namedtuple, and check for it later
```py
from collections import namedtuple
# module parameter added in python 3.6
namespace = namedtuple("namespace", "foo bar", module=__name__ + ".namespace")
```
then check for `__module__`
`if getattr(x, "__module__", None) == "xxxx.namespace":` |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | Improving on what Lutz posted:
```
def isinstance_namedtuple(x):
return (isinstance(x, tuple) and
isinstance(getattr(x, '__dict__', None), collections.Mapping) and
getattr(x, '_fields', None) is not None)
``` | I use
```
isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
```
which to me appears to best reflect the dictionary aspect of the nature of named tuples.
It appears robust against some conceivable future changes too and might also work with many third-party namedtuple-ish classes, if such things happen to exist. |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | Calling the *function* `collections.namedtuple` gives you a new type that's a subclass of `tuple` (and no other classes) with a member named `_fields` that's a tuple whose items are all strings. So you could check for each and every one of these things:
```
def isnamedtupleinstance(x):
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return all(type(n)==str for n in f)
```
it IS possible to get a false positive from this, but only if somebody's going out of their way to make a type that looks a **lot** like a named tuple but isn't one;-). | 3.7+
```
def isinstance_namedtuple(obj) -> bool:
return (
isinstance(obj, tuple) and
hasattr(obj, '_asdict') and
hasattr(obj, '_fields')
)
``` |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | Calling the *function* `collections.namedtuple` gives you a new type that's a subclass of `tuple` (and no other classes) with a member named `_fields` that's a tuple whose items are all strings. So you could check for each and every one of these things:
```
def isnamedtupleinstance(x):
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return all(type(n)==str for n in f)
```
it IS possible to get a false positive from this, but only if somebody's going out of their way to make a type that looks a **lot** like a named tuple but isn't one;-). | If you need to check before calling namedtuple specific functions on it, then just call them and catch the exception instead. That's the preferred way to do it in python. |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | If you want to determine whether an object is an instance of a specific namedtuple, you can do this:
```
from collections import namedtuple
SomeThing = namedtuple('SomeThing', 'prop another_prop')
SomeOtherThing = namedtuple('SomeOtherThing', 'prop still_another_prop')
a = SomeThing(1, 2)
isinstance(a, SomeThing) # True
isinstance(a, SomeOtherThing) # False
``` | I use
```
isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
```
which to me appears to best reflect the dictionary aspect of the nature of named tuples.
It appears robust against some conceivable future changes too and might also work with many third-party namedtuple-ish classes, if such things happen to exist. |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | Calling the *function* `collections.namedtuple` gives you a new type that's a subclass of `tuple` (and no other classes) with a member named `_fields` that's a tuple whose items are all strings. So you could check for each and every one of these things:
```
def isnamedtupleinstance(x):
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple: return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple): return False
return all(type(n)==str for n in f)
```
it IS possible to get a false positive from this, but only if somebody's going out of their way to make a type that looks a **lot** like a named tuple but isn't one;-). | Improving on what Lutz posted:
```
def isinstance_namedtuple(x):
return (isinstance(x, tuple) and
isinstance(getattr(x, '__dict__', None), collections.Mapping) and
getattr(x, '_fields', None) is not None)
``` |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | 3.7+
```
def isinstance_namedtuple(obj) -> bool:
return (
isinstance(obj, tuple) and
hasattr(obj, '_asdict') and
hasattr(obj, '_fields')
)
``` | I use
```
isinstance(x, tuple) and isinstance(x.__dict__, collections.abc.Mapping)
```
which to me appears to best reflect the dictionary aspect of the nature of named tuples.
It appears robust against some conceivable future changes too and might also work with many third-party namedtuple-ish classes, if such things happen to exist. |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | 3.7+
```
def isinstance_namedtuple(obj) -> bool:
return (
isinstance(obj, tuple) and
hasattr(obj, '_asdict') and
hasattr(obj, '_fields')
)
``` | Improving on what Lutz posted:
```
def isinstance_namedtuple(x):
return (isinstance(x, tuple) and
isinstance(getattr(x, '__dict__', None), collections.Mapping) and
getattr(x, '_fields', None) is not None)
``` |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | If you want to determine whether an object is an instance of a specific namedtuple, you can do this:
```
from collections import namedtuple
SomeThing = namedtuple('SomeThing', 'prop another_prop')
SomeOtherThing = namedtuple('SomeOtherThing', 'prop still_another_prop')
a = SomeThing(1, 2)
isinstance(a, SomeThing) # True
isinstance(a, SomeOtherThing) # False
``` | Improving on what Lutz posted:
```
def isinstance_namedtuple(x):
return (isinstance(x, tuple) and
isinstance(getattr(x, '__dict__', None), collections.Mapping) and
getattr(x, '_fields', None) is not None)
``` |
2,166,818 | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | 2010/01/30 | [
"https://Stackoverflow.com/questions/2166818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55246/"
] | If you want to determine whether an object is an instance of a specific namedtuple, you can do this:
```
from collections import namedtuple
SomeThing = namedtuple('SomeThing', 'prop another_prop')
SomeOtherThing = namedtuple('SomeOtherThing', 'prop still_another_prop')
a = SomeThing(1, 2)
isinstance(a, SomeThing) # True
isinstance(a, SomeOtherThing) # False
``` | If you need to check before calling namedtuple specific functions on it, then just call them and catch the exception instead. That's the preferred way to do it in python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.