qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
having the soft keyboard disabled (only external keyboards enabled), I fixed it by moving the cursors at the end on the EditText:
```
editText.setSelection(editText.getText().length)
```
|
`edittext.requestFocus()` works for me in my `Activity` and `Fragment`
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
It has worked for me as follows.
```
ed1.requestFocus();
return; //Faça um return para retornar o foco
```
|
`edittext.requestFocus()` works for me in my `Activity` and `Fragment`
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
Yes, I got the answer.. just simply edit the `manifest` file as:
```
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
```
and set `EditText.requestFocus()` in `onCreate()`..
Thanks..
|
`edittext.requestFocus()` works for me in my `Activity` and `Fragment`
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
Programatically:
```
edittext.requestFocus();
```
Through xml:
```
<EditText...>
<requestFocus />
</EditText>
```
Or call onClick method manually.
|
I know its too late but only solution is working for me is
```
edittext.requestFocus()
edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,0f,0f,0))
edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_UP,0f,0f,0))
```
I used this to open keyboard programatically.
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
Programatically:
```
edittext.requestFocus();
```
Through xml:
```
<EditText...>
<requestFocus />
</EditText>
```
Or call onClick method manually.
|
Set to the Activity in Manifest:
```
android:windowSoftInputMode="adjustResize"
```
Set focus, when a view is ready:
```
fun setFocus(view: View, showKeyboard: Boolean = true){
view.post {
if (view.requestFocus() && showKeyboard)
activity?.openKeyboard() // call extension function
}
}
```
|
8,077,756
|
in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do something like:
```
for key, value in loc.items():
print key, loc[key], ctg[key], sctg[key], title[key], id[key]
```
but in django templates all i could come up with is this:
```
{% for lock, locv in loc.items %}
{% for ctgk, ctgv in ctg.items %}
{% for subctgk, subctgv in subctg.items %}
{% for titlek, titlev in titlu.items %}
{% for idk, idv in id.items %}
{% ifequal lock ctgk %}
{% ifequal ctgk subctgk %}
{% ifequal subctgk titlek %}
{% ifequal titlek idk %}
<br />{{ lock|date:"d b H:i" }} - {{ locv }} - {{ ctgv }} - {{ subctgv }} - {{ titlev }} - {{idv }}
.... {% endifequals & endfors %}
```
which of course is ugly and takes a lot of time to be rendered
right now i am looking into building a custom tag, but i was wondering if you guys have any feedback on this topic?
|
2011/11/10
|
[
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] |
Yes, I got the answer.. just simply edit the `manifest` file as:
```
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
```
and set `EditText.requestFocus()` in `onCreate()`..
Thanks..
|
`youredittext.requestFocus()` call it from activity
```
oncreate();
```
and use the above code there
|
34,169,770
|
I am trying to select sensors by placing a box around their geographic coordinates:
```
In [1]: lat_min, lat_max = lats(data)
lon_min, lon_max = lons(data)
print(np.around(np.array([lat_min, lat_max, lon_min, lon_max]), 5))
Out[1]: [ 32.87248 33.10181 -94.37297 -94.21224]
In [2]: select_sens = sens[(lat_min<=sens['LATITUDE']) & (sens['LATITUDE']<=lat_max) &
(lon_min<=sens['LONGITUDE']) & (sens['LONGITUDE']<=lon_max)].copy()
Out[2]: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-7881f6717415> in <module>()
4 lon_min, lon_max = lons(data)
5 select_sens = sens[(lat_min<=sens['LATITUDE']) & (sens['LATITUDE']<=lat_max) &
----> 6 (lon_min<=sens['LONGITUDE']) & (sens['LONGITUDE']<=lon_max)].copy()
7 sens_data = data[data['ID'].isin(select_sens['ID'])].copy()
8 sens_data.describe()
/home/kartik/miniconda3/lib/python3.5/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
703 return NotImplemented
704 elif isinstance(other, (np.ndarray, pd.Index)):
--> 705 if len(self) != len(other):
706 raise ValueError('Lengths must match to compare')
707 return self._constructor(na_op(self.values, np.asarray(other)),
TypeError: len() of unsized object
```
Of course, `sens` is a pandas DataFrame. Even when I use `.where()` it raises the same error. I am completely stumped, because it is a simple comparison that shouldn't raise any errors. Even the data types match:
```
In [3]: sens.dtypes
Out[3]: ID object
COUNTRY object
STATE object
COUNTY object
LENGTH float64
NUMBER object
NAME object
LATITUDE float64
LONGITUDE float64
dtype: object
```
So what is going on?!?
**-----EDIT------**
As per Ethan Furman's answer, I made the following changes:
```
In [2]: select_sens = sens[([lat_min]<=sens['LATITUDE']) & (sens['LATITUDE']<=[lat_max]) &
([lon_min]<=sens['LONGITUDE']) & (sens['LONGITUDE']<=[lon_max])].copy()
```
And (drumroll) it worked... But why?
|
2015/12/09
|
[
"https://Stackoverflow.com/questions/34169770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765319/"
] |
I'm not familiar with NumPy nor Pandas, but the error is saying that one of the objects in the comparison `if len(self) != len(other)` does not have a `__len__` method and therefore has no length.
Try doing `print(sens_data)` to see if you get a similar error.
|
I found a similar issue and think the problem may be related to the Python version you are using.
I wrote my code in Spyder
**Python 3.6.1 |Anaconda 4.4.0 (64-bit)**
but then passed it to someone using Spyder but
**Python 3.5.2 |Anaconda 4.2.0 (64-bit)**
I had one numpy.float64 object (as far as i understand, similar to lat\_min, lat\_max, lon\_min and lon\_max in your code) `MinWD.MinWD[i]`
```
In [92]: type(MinWD.MinWD[i])
Out[92]: numpy.float64
```
and a Pandas data frame `WatDemandCur` with one column called `Percentages`
```
In [96]: type(WatDemandCur)
Out[96]: pandas.core.frame.DataFrame
In [98]: type(WatDemandCur['Percentages'])
Out[98]: pandas.core.series.Series
```
and i wanted to do the following comparison
```
In [99]: MinWD.MinWD[i]==WatDemandCur.Percentages
```
There was no problem with this line when running the code in my machine (**Python 3.6.1**)
But my friend got something similar to you in (**Python 3.5.2**)
```
MinWD.MinWD[i]==WatDemandCur.Percentages
Traceback (most recent call last):
File "<ipython-input-99-3e762b849176>", line 1, in <module>
MinWD.MinWD[i]==WatDemandCur.Percentages
File "C:\Program Files\Anaconda3\lib\site-packages\pandas\core\ops.py", line 741, in wrapper
if len(self) != len(other):
TypeError: len() of unsized object
```
My solution to his problem was to change the code to
```
[MinWD.MinWD[i]==x for x in WatDemandCur.Percentages]
```
and it worked in both versions!
With this and your evidence, i would assume that it is not possible to compare numpy.float64 and perhaps numpy.integers objects with Pandas Series, and this could be partly related to the fact that the former have no **len** function.
Just for curiosity, i did some tests with float and integer objects (please tell the difference with numpy.float64 object)
```
In [122]: Temp=1
In [123]: Temp2=1.0
In [124]: type(Temp)
Out[124]: int
In [125]: type(Temp2)
Out[125]: float
In [126]: len(Temp)
Traceback (most recent call last):
File "<ipython-input-126-dc80ab11ca9c>", line 1, in <module>
len(Temp)
TypeError: object of type 'int' has no len()
In [127]: len(Temp2)
Traceback (most recent call last):
File "<ipython-input-127-a1b836f351d2>", line 1, in <module>
len(Temp2)
TypeError: object of type 'float' has no len()
Temp==WatDemandCur.Percentages
Temp2==WatDemandCur.Percentages
```
Both worked!
Conclusions
1. In another python version your code should work!
2. The problem with the comparison is specific for numpy.floats and perhaps numpy.integers
3. When you include [] or when I create the list with my solution, the type of object is changed from a numpy.float to a list, and in this way it works fine.
4. Although the problem seems to be related to the fact that numpy.float64 objects have no len function, floats and integers, which do not have a len function either, do work.
Hope some of this works for you or someone else facing a similar issue.
|
26,593,344
|
I'm writing a pandas Dataframe to a Postgres database:
```
from sqlalchemy import create_engine, MetaData
engine = create_engine(r'postgresql://user:password@localhost:5432/db')
meta = MetaData(engine, schema='data_quality')
meta.reflect(engine, schema='data_quality')
pdsql = pd.io.sql.PandasSQLAlchemy(engine, meta=meta)
pdsql.to_sql(dataframe, table_name)
```
It was working perfectly, but now SQLAlchemy is throwing the following error at the 5th line:
```
AttributeError: 'module' object has no attribute 'PandasSQLAlchemy'
```
I'm not sure if it's related, but Pandas broke at the same time - exactly like in this google-api-python-client issue:
[Could not Import Pandas: TypeError](https://stackoverflow.com/questions/26481285/could-not-import-pandas-)
I installed the google-api-python-client yesterday and uninstalling it fixed the problem with Pandas, but SQLAlchemy still doesn't work.
|
2014/10/27
|
[
"https://Stackoverflow.com/questions/26593344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3591836/"
] |
I suppose you are using pandas 0.15. `PandasSQLAlchemy` was not yet really public, and was renamed in pandas 0.15 to `SQLDatabase`. So if you replace that in your code, it should work (so `pdsql = pd.io.sql.SQLDatabase(engine, meta=meta)`).
However, starting from pandas 0.15, there is also schema support in the `read_sql_table` and `to_sql` functions, so it should not be needed to make a `MetaData` and `SQLDatabase` object manually. Instead, this should do it:
```
dataframe.to_sql(table_name, engine, schema='data_quality')
```
See the 0.15 release notes: <http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#improvements-in-the-sql-io-module>
|
I have encountered this error recently and it was solved my removing the .pyc files located in the same directory as .py files. These files (.pyc) holds the previous version information and time, date.
|
67,220,607
|
I'm trying to save a loop output into a text file with python. However, when I try to do so only the first line of the result gets printed on the file.
This is the line I want to print the result of:
```
with open('myfile.txt','w') as f_output:
f_output.write(
for k, v in mydic.items():
print(f"{k:11}{v[0]}{v[1]:12}"))
```
This prints only the first line of the result.
My dict looks like this:
```
mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}
```
I need it to print this to the file:
```
1 22 23
2 33 24
3 44 25
```
How can I do this?
|
2021/04/22
|
[
"https://Stackoverflow.com/questions/67220607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12763792/"
] |
Write in append mode with `a`:
```py
mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}
with open('myfile.txt','a') as f_output:
for k, v in mydic.items():
# Also need `\n` for newlines:
f_output.write(f"{k:11}{v[0]}{v[1]:12}\n")
```
Output:
```
1 22 23
2 33 24
3 44 25
```
|
Change the argument from 'w' (write) to 'a' (append).
```py
mydic = {'1': [22, 23], '2': [33, 24], '3': [44, 25]}
with open('myfile.txt','a') as f_output:
for k, v in mydic.items():
res=f"{k:11}{v[0]}{v[1]:12}"
f_output.write(f"{res}\n")
print(res)
```
|
45,317,767
|
```
def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
return res
print generate_n_chars(raw_input("Enter the integer value : "),raw_input("Enter the character : "))
```
I am beginner in python and I don't know why this loop going to infinity. Please someone correct my program
|
2017/07/26
|
[
"https://Stackoverflow.com/questions/45317767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7504540/"
] |
I personally have another mental model which doesn't deal directly with identity and memory and whatnot.
`prvalue` comes from "pure rvalue" while `xvalue` comes from "expiring value" and is this information I use in my mental model:
**Pure rvalue** refers to an object that is a temporary in the "pure sense": an expression for which the compiler can tell with absolute certainty that its evaluation is an object that is a temporary that has just been created and that is immediately expiring (unless we intervene to prolong it's lifetime by reference binding). The object was created during the evaluation of the expression and it will die according to the rules of the "mother expression".
By contrast, an **expiring value** is a expression that evaluates to a reference to an object that is *promised* to expire soon. That is it gives you a promise that you can do whatever you want to this object because it will be destroyed next anyway. But you don't know when this object was created, or when it is supposed to be destroyed. You just know that you "intercepted" it as it is just about to die.
In practice:
```
struct X;
auto foo() -> X;
```
```
X x = foo();
^~~~~
```
in this example evaluating `foo()` will result in a `prvalue`. Just by looking at this expression you know that this object was created as part of the return of `foo` and will be destroyed at the end of this full expression. Because you know all of these things you can prologue it's lifetime:
```
const X& rx = foo();
```
now the object returned by foo has it's lifetime prolongued to the lifetime of `rx`
```
auto bar() -> X&&
```
```
X x = bar();
^~~~
```
In this example evaluating `bar()` will result in a `xvalue`. `bar` *promises* you that is giving you an object that is about to expire, but you don't know when this object was created. It can be created way before the call to `bar` (as a temporary or not) and then `bar` gives you an `rvalue reference` to it. The advantage is you know you can do whatever you want with it because it won't be used afterwords (e.g. you can move from it). But you don't know when this object is supposed to be destroyed. As such you cannot extend it's lifetime - because you don't know what its original lifetime is in the first place:
```
const X& rx = bar();
```
this won't extend the lifetime.
|
When calling a `func(T&& t)` the caller is saying "there's a t here" and also "I don't care what you do to it". C++ does not specify the nature of "here".
On a platform where reference parameters are implemented as addresses, this means there must be an object present somewhere. On that platform identity == address. However this is not a requirement of the language, but of the platform calling convention.
A platform could implement references simply by arranging for the objects to be enregistered in a particular manner in both the caller and callee. Here an identity could be "register edi".
|
25,618,016
|
I have the following script which just isnt working for me :(. I essentially want to create 10 threads to port scan a range of 100 ports. It should seem simple but I dont know where I am going wrong. Im new to python and have been looking at how to get this working for the past two weeks and I know give up. When executed it just does nothing. Help please :).
EDIT: Updated the code but it now states none when I run it.
#Import Modules
from scapy.all import \*
from Queue import Queue
from threading import Thread
```
#Set Variables
threadCount = 10
destIP = "192.168.136.131"
portLength = 100
q = Queue(maxsize=0)
#Empty Arrays
openPorts = []
closedPorts = []
threads = []
def qProcessor(q):
while True:
try:
print q.get()
#getQ = q.get()
#getQ()
#if getQ() is None:
# break
#else:
q.task_done()
except Exception as e:
print 'error in qprocessor function'
print e
def portScan(port, dstIP):
scan = sr1(IP(dst=dstIP)/TCP(dport=port,flags="S"), verbose=0)
if scan.getlayer(TCP).flags == 0x12:
openPorts.append("IP: %s \t Port: %s"%(scan.getlayer(IP).src, scan.getlayer(TCP).sport))
sr1(IP(dst=dstIP)/TCP(dport=port,flags="R"),verbose=0)
if scan.getlayer(TCP).flags == 0x14:
closedPorts.append("IP: %s \t Port: %s"%(scan.getlayer(IP).src, scan.getlayer(TCP).sport))
def main():
try:
for i in range(threadCount):
worker = Thread(target=qProcessor, args =(q,))
worker.setDaemon(True)
worker.start()
except Exception as e:
print "error in worker section"
print e
for p in range(portLength):
q.put(portScan(p, destIP))
q.join()
if __name__ == '__main__':
main()
for port in openPorts:
print port
```
So i found the answer. This has killed me for two weeks and I ended up debugging the application with the pdb module and the '-v' switch. I have learnt a lot from this exercise and want to kill python after this lol. But working it out with the little hints from stackoverflow has been awesome. Here is the final script. I have commented the line that was giving me issues whilst I work out a way around it. BTW this works fine without threading.
```
#Import Modules
from scapy.all import *
from Queue import Queue
from threading import Thread
#Set Variables
threadCount = 10
destIP = "192.168.136.131"
portLength = 100
q = Queue(maxsize=0)
#Empty Arrays
openPorts = []
closedPorts = []
threads = []
def main():
try:
for i in range(threadCount):
worker = Thread(target=qProcessor, args =(q,))
worker.setDaemon(True)
worker.start()
except Exception as e:
print "error in worker section"
print e
for p in range(portLength):
q.put(portScan(p, destIP))
q.join()
def qProcessor(q):
while True:
try:
q.get()
q.task_done()
except Exception as e:
print 'error in qprocessor function'
print e
def portScan(port, dstIP):
scan = sr1(IP(dst=dstIP)/TCP(dport=port,flags="S"), verbose=0)
if scan.getlayer(TCP).flags == 0x12:
openPorts.append("IP: %s \t Port: %s"%(scan.getlayer(IP).src, scan.getlayer(TCP).sport))
# sr1(IP(dst=dstIP)/TCP(dport=port,flags="R"),verbose=0)
if scan.getlayer(TCP).flags == 0x14:
closedPorts.append("IP: %s \t Port: %s"%(scan.getlayer(IP).src, scan.getlayer(TCP).sport))
else:
pass
if __name__ == '__main__':
main()
for port in openPorts:
print port
```
|
2014/09/02
|
[
"https://Stackoverflow.com/questions/25618016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3999393/"
] |
You have an extra space after resource, have you tried removing that?
```
'resource ': {
```
|
It looks like you're doing extra encoding of the inserted rows. They should be sent as raw json, rather than encoding the whole row as a string. That is, something like this:
```
'rows': [
{
'insertId': 123456,
'json': {'id': 123,'name':'test1'}
}
]
```
(note the difference from what you have above is just that the `{'id': 123,'name':'test1'}` line isn't quoted.
|
70,943,395
|
I did the following in google colab notebook and get an error. Any idea?
```
%pip install pyenchant
import enchant
```
and get the following error:
ImportError Traceback (most recent call last)
in ()
----> 1 import enchant
1 frames
/usr/local/lib/python3.7/dist-packages/enchant/\_enchant.py in ()
159 """
160 )
--> 161 raise ImportError(msg)
162
163
ImportError: The 'enchant' C library was not found and needs to be installed.
See <https://pyenchant.github.io/pyenchant/install.html>
for details
|
2022/02/01
|
[
"https://Stackoverflow.com/questions/70943395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18092070/"
] |
After lots of research, I found the solution [here](https://github.com/googlecolab/colabtools/issues/441).
Run this code on goggle colab before `import enchant`
```
!apt update
!apt install enchant --fix-missing
!apt install -qq enchant
!pip install pyenchant
```
|
Yes enchant doesnt work on Google colab because of C libraries. You can use Jupyter notebook for this library and it will work just fine.
|
43,094,861
|
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the number in a single variable:
```
a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000
```
How to realise that in python 3?
Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!
|
2017/03/29
|
[
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] |
Look into [re](https://docs.python.org/2/library/re.html#re.findall)
```
import re
input = "'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'"
matches = re.findall('(\d+)', input)
# matches = ['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']
a, b, c = re.findall('(\d+)', input)
# a = '17899792270101010000000000'
# b = '17899792270102010000000000'
# c = '17899792270103010000000000'
```
edit:
If you want `int` not `str`, you can `map(int, matches)`
|
if it's already "format" at the input :
```
>>> BC1 = input("BC1: ")
BC1: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'
>>> a=int(BC1[0])
>>> b=int(BC1[1])
>>> c=int(BC1[2])
>>> a
17899792270101010000000000
>>> b
17899792270102010000000000
>>> c
17899792270103010000000000
```
|
43,094,861
|
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the number in a single variable:
```
a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000
```
How to realise that in python 3?
Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!
|
2017/03/29
|
[
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] |
Look into [re](https://docs.python.org/2/library/re.html#re.findall)
```
import re
input = "'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'"
matches = re.findall('(\d+)', input)
# matches = ['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']
a, b, c = re.findall('(\d+)', input)
# a = '17899792270101010000000000'
# b = '17899792270102010000000000'
# c = '17899792270103010000000000'
```
edit:
If you want `int` not `str`, you can `map(int, matches)`
|
If I understand you correctly, this should do the trick
```
BC1 = input("BC1: ")
numbers = [int(x.strip(' \'')) for x in BC1.split(',')]
```
And now your desired numbers are
```
numbers[0] == a # 17899792270101010000000000
numbers[1] == b # 17899792270102010000000000
numbers[2] == c # 17899792270103010000000000
```
* The [`split`](https://docs.python.org/3/library/stdtypes.html#str.split) function creates an array of your numbers, but includes the spaces and the quotes.
`["'17899792270101010000000000'", " '17899792270102010000000000'", " '17899792270103010000000000'"]`
* The [`strip`](https://docs.python.org/3/library/stdtypes.html#str.strip) function gets rid of the spaces and the quotes
`['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']`
* The [`int`](https://docs.python.org/3/library/functions.html#int) function parses the strings into an integer (number)
`[17899792270101010000000000, 17899792270102010000000000, 17899792270103010000000000]`
However, this requires the user to follow the format you specified. [Foryah's answer](https://stackoverflow.com/a/43095545/5272567) is more robust to different input formats.
|
43,094,861
|
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the number in a single variable:
```
a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000
```
How to realise that in python 3?
Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!
|
2017/03/29
|
[
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] |
If I understand you correctly, this should do the trick
```
BC1 = input("BC1: ")
numbers = [int(x.strip(' \'')) for x in BC1.split(',')]
```
And now your desired numbers are
```
numbers[0] == a # 17899792270101010000000000
numbers[1] == b # 17899792270102010000000000
numbers[2] == c # 17899792270103010000000000
```
* The [`split`](https://docs.python.org/3/library/stdtypes.html#str.split) function creates an array of your numbers, but includes the spaces and the quotes.
`["'17899792270101010000000000'", " '17899792270102010000000000'", " '17899792270103010000000000'"]`
* The [`strip`](https://docs.python.org/3/library/stdtypes.html#str.strip) function gets rid of the spaces and the quotes
`['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']`
* The [`int`](https://docs.python.org/3/library/functions.html#int) function parses the strings into an integer (number)
`[17899792270101010000000000, 17899792270102010000000000, 17899792270103010000000000]`
However, this requires the user to follow the format you specified. [Foryah's answer](https://stackoverflow.com/a/43095545/5272567) is more robust to different input formats.
|
if it's already "format" at the input :
```
>>> BC1 = input("BC1: ")
BC1: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'
>>> a=int(BC1[0])
>>> b=int(BC1[1])
>>> c=int(BC1[2])
>>> a
17899792270101010000000000
>>> b
17899792270102010000000000
>>> c
17899792270103010000000000
```
|
38,550,322
|
Hello everyone!
I'm new to python networking programming.
My development environments are as below.
* Windows 7
* Python 3.4
I am studying with "Python Network Programming Cookbook". In this book, there's an example of **ThreadingMixIn** socket server application.
This book's code is written in Python 2.7. So I've modified for python 3.4.
The code is...
```
# coding: utf-8
import socket
import threading
import socketserver
SERVER_HOST = 'localhost'
SERVER_PORT = 0 # tells the kernel to pick up a port dynamically
BUF_SIZE = 1024
def client(ip, port, message):
""" A client to test threading mixin server"""
# Connect to the server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
try:
message = bytes(message, encoding="utf-8")
sock.sendall(message)
response = sock.recv(BUF_SIZE)
print("Client received: {0}".format(response))
finally:
sock.close()
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
""" An example of threaded TCP request handler """
def handle(self):
data = self.request.recv(1024)
current_thread = threading.current_thread()
response = "{0}: {0}".format(current_thread.name, data)
response = bytes(response, encoding="utf-8")
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
"""Nothing to add here, inherited everything necessary from parents"""
pass
if __name__ == "__main__":
# Run server
server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT),
ThreadedTCPRequestHandler)
ip, port = server.server_address # retrieve ip address
# Start a thread with the server -- one thread per request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread exits
server_thread.daemon = True
server_thread.start()
print("Server loop running on thread: {0}".format(server_thread))
# Run clients
client(ip, port, "Hello from client 1")
client(ip, port, "Hello from client 2")
client(ip, port, "Hello from client 3")
```
This code works perfect. Every client's request processed by new thread. And when the client's request is over, program ends.
**I want to make server serves forever.** So when the additional client's request has come, server send its response to that client.
What should I do?
Thank you for reading my question.
P.S: Oh, one more. I always write say hello in top of my post of stack overflow. In preview it shows normally. But when the post has saved, first line always gone. Please anyone help me XD
|
2016/07/24
|
[
"https://Stackoverflow.com/questions/38550322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192555/"
] |
Your program exits because your server thread is a daemon:
```
# Exit the server thread when the main thread exits
server_thread.daemon = True
```
You can either remove that line or add `server_thread.join()` at the bottom of the code to prevent the main thread from exiting early.
|
You will have to run on an infinite loop and on each loop wait for some data to come from client. This way the connection will be kept alive.
Same infinite loop for the server to accept more clients.
However, you will have to somehow detect when a client closes the connection with the server because in most times the server won't be notified.
|
53,312,339
|
I need to install COCOAPI for Python 3.5 on my linux machine but when I do "make" it automatically installs it for 2.7. Is there an option to choose for a python version while using "make" ?
**EDIT 1 :**
Going to PythonAPI folder and installing it via python3 setup.py install gives the following error.
```
sudo python3 setup.py install
running install
running bdist_egg
running egg_info
creating pycocotools.egg-info
writing requirements to pycocotools.egg-info/requires.txt
writing dependency_links to pycocotools.egg-info/dependency_links.txt
writing top-level names to pycocotools.egg-info/top_level.txt
writing pycocotools.egg-info/PKG-INFO
writing manifest file 'pycocotools.egg-info/SOURCES.txt'
reading manifest file 'pycocotools.egg-info/SOURCES.txt'
writing manifest file 'pycocotools.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build
creating build/lib.linux-x86_64-3.5
creating build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/coco.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/__init__.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/mask.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/cocoeval.py -> build/lib.linux-x86_64-3.5/pycocotools
running build_ext
cythoning pycocotools/_mask.pyx to pycocotools/_mask.c
/home/pradyumn/.local/lib/python3.5/site-packages/Cython/Compiler/Main.py:367: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: /home/pradyumn/cocoapi-master/PythonAPI/pycocotools/_mask.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
building 'pycocotools._mask' extension
creating build/common
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/pycocotools
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/pradyumn/.local/lib/python3.5/site-packages/numpy/core/include -I../common -I/usr/include/python3.5m -c ../common/maskApi.c -o build/temp.linux-x86_64-3.5/../common/maskApi.o -Wno-cpp -Wno-unused-function -std=c99
../common/maskApi.c: In function ‘rleToBbox’:
../common/maskApi.c:141:31: warning: ‘xp’ may be used uninitialized in this function [-Wmaybe-uninitialized]
if(j%2==0) xp=x; else if(xp<x) { ys=0; ye=h-1; }
^
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/pradyumn/.local/lib/python3.5/site-packages/numpy/core/include -I../common -I/usr/include/python3.5m -c pycocotools/_mask.c -o build/temp.linux-x86_64-3.5/pycocotools/_mask.o -Wno-cpp -Wno-unused-function -std=c99
pycocotools/_mask.c:4:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
enter code here
```
**Edit 2**
I tried installing cython and then pycocotools but that gives me the following error.
```
pip3 install pycocotools
Collecting pycocotools
Using cached https://files.pythonhosted.org/packages/96/84/9a07b1095fd8555ba3f3d519517c8743c2554a245f9476e5e39869f948d2/pycocotools-2.0.0.tar.gz
Building wheels for collected packages: pycocotools
Running setup.py bdist_wheel for pycocotools ... error
Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-p1jp5iir/pycocotools/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-xirt_d3c --python-tag cp35:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.5
creating build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/__init__.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/coco.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/mask.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/cocoeval.py -> build/lib.linux-x86_64-3.5/pycocotools
running build_ext
building 'pycocotools._mask' extension
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/pycocotools
creating build/temp.linux-x86_64-3.5/common
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/pradyumn/.local/lib/python3.5/site-packages/numpy/core/include -Icommon -I/usr/include/python3.5m -c pycocotools/_mask.c -o build/temp.linux-x86_64-3.5/pycocotools/_mask.o -Wno-cpp -Wno-unused-function -std=c99
pycocotools/_mask.c:32:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Failed building wheel for pycocotools
Running setup.py clean for pycocotools
Failed to build pycocotools
Installing collected packages: pycocotools
Running setup.py install for pycocotools ... error
Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-p1jp5iir/pycocotools/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-pipcgtu8/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.5
creating build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/__init__.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/coco.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/mask.py -> build/lib.linux-x86_64-3.5/pycocotools
copying pycocotools/cocoeval.py -> build/lib.linux-x86_64-3.5/pycocotools
running build_ext
building 'pycocotools._mask' extension
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/pycocotools
creating build/temp.linux-x86_64-3.5/common
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/pradyumn/.local/lib/python3.5/site-packages/numpy/core/include -Icommon -I/usr/include/python3.5m -c pycocotools/_mask.c -o build/temp.linux-x86_64-3.5/pycocotools/_mask.o -Wno-cpp -Wno-unused-function -std=c99
pycocotools/_mask.c:32:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-p1jp5iir/pycocotools/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-pipcgtu8/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-p1jp5iir/pycocotools/
```
**EDIT 3**
To solve the error above run the below for appropriate version of python.
```
sudo apt-get install python3.5-dev
```
Then do the following:
```
pip3 install pycocotools --user
```
And then rerun the following:
```
sudo python3 setup.py install
```
|
2018/11/15
|
[
"https://Stackoverflow.com/questions/53312339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715275/"
] |
Clone the repo using `git clone https://github.com/cocodataset/cocoapi.git` then enter the dir where it is located and type `python3 setup.py install` which should install using python3.
If the above doesn't work, try `pip3 install cython` followed by `pip3 install pycocotools` (you can add the `--user` flag to all of these if necessary)
|
You can make sure the default `python` resolves in the one you are interested in, for example by symbolically linking `python` to `python2` wherever it is defined (possibly `/usr/bin`)
|
70,909,920
|
I'm trying to write a code that will search for specific data from multiple report files, and write them into columns in a single csv.
The report file lines i'm looking for aren't always on the same line, so i'm looking for the data associated on the lines below:
Estimate file: pog\_example.bef
Estimate ID: o1\_p1
61078 (100.0%) estimated.
And I want to write the data from each text file into columns in a csv as below:
example.bef, o1\_p1, 61078 (100.0%) estimated
So far I have this script which will list out the first of my criteria, but I can't figure out how to loop it through to find my second and third lines to populate the second and third columns
```
from glob import glob
import fileinput
import csv
with open('percentage_estimated.csv', 'w', newline='') as est_report:
writer = csv.writer(est_report)
for line in fileinput.input(glob('*.bef*')):
if 'Estimate file' in line:
writer.writerow([line.split('pog_')[1].strip()])
```
I'm pretty new to python so any help would be appreciated!
|
2022/01/29
|
[
"https://Stackoverflow.com/questions/70909920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17361896/"
] |
Liquid is not going to work on JSON like this. If you want to iterate through an array of JSON objects, use Javascript.
|
As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array.
|
70,909,920
|
I'm trying to write a code that will search for specific data from multiple report files, and write them into columns in a single csv.
The report file lines i'm looking for aren't always on the same line, so i'm looking for the data associated on the lines below:
Estimate file: pog\_example.bef
Estimate ID: o1\_p1
61078 (100.0%) estimated.
And I want to write the data from each text file into columns in a csv as below:
example.bef, o1\_p1, 61078 (100.0%) estimated
So far I have this script which will list out the first of my criteria, but I can't figure out how to loop it through to find my second and third lines to populate the second and third columns
```
from glob import glob
import fileinput
import csv
with open('percentage_estimated.csv', 'w', newline='') as est_report:
writer = csv.writer(est_report)
for line in fileinput.input(glob('*.bef*')):
if 'Estimate file' in line:
writer.writerow([line.split('pog_')[1].strip()])
```
I'm pretty new to python so any help would be appreciated!
|
2022/01/29
|
[
"https://Stackoverflow.com/questions/70909920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17361896/"
] |
For some reason when it is a multidimensional JSON array it acts weird. There is a simple fix for it, just add (-) at the end of your assigned variable:
```
{%- assign releases = product.metafields.artist.releases.value -%}
{% for release in releases.releases %}
{{ release.releaseName }}
{%- endfor -%}
```
Hope it solves your problem like it did mine!
|
As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array.
|
28,228,238
|
Hello guys I am really new to python and I am trying to sort the /etc/passwd file using PYTHON 3.4 based on the following criteria:
Input (regular /etc/passwd file on linux system:
```
raj:x:501:512::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
jwww:x:504:504::/htdocs/html:/sbin/nologin
wwwcorp:x:505:511::/htdocs/corp:/sbin/nologin
wwwint:x:506:507::/htdocs/intranet:/bin/bash
scpftp:x:507:507::/htdocs/ftpjail:/bin/bash
rsynftp:x:508:512::/htdocs/projets:/bin/bash
mirror:x:509:512::/htdocs:/bin/bash
jony:x:510:511::/home/jony:/bin/ksh
amyk:x:511:511::/home/amyk:/bin/ksh
```
Output that I am looking for either to the file or returned to the screen:
```
Group 511 : jony, amyk, wwwcorp
Group 512 : mirror, rsynftp, raj
Group 507 : wwwint, scpftp
and so on
```
Here is my plan:
```
1) Open and read the whole file or do it line by line
2) Loop through the file using python regex
3) Write it into temp file or create a dictionary
4) Print the dictionary keys and values
```
I will really appreciate the example how it can be done efficiently or apply any
sorting algorithm.
Thanks!
|
2015/01/30
|
[
"https://Stackoverflow.com/questions/28228238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214003/"
] |
You can open the file, throw it into a list and then throw all the users into some kinda hash table
```
with open("/etc/passwd") as f:
lines = f.readlines()
group_dict = {}
for line in lines:
split_line = line.split(":")
user = split_line[0]
gid = split_line[3]
# If the group id is not in the dict then put it in there with a list of users
# that are under that group
if gid not in group_dict:
group_dict[gid] = [user]
# If the group id does exist then add the new user to the list of users in
# the group
else:
group_dict[gid].append(user)
# Iterate over the groups and users we found. Keys (group) will be the first item in the tuple,
# and the list of users will be the second item. Print out the group and users as we go
for group, users in group_dict.iteritems():
print("Group {}, users: {}".format(group, ",".join(users)))
```
|
This should loop through your `/etc/passwd` and sort users by group. You don't have to do anything fancy to solve this problem.
```
with open('/etc/passwd', 'r') as f:
res = {}
for line in f:
parts = line.split(':')
try:
name, gid = parts[0], int(parts[3])
except IndexError:
print("Invalid line.")
continue
try:
res[gid].append(name)
except KeyError:
res[gid] = [name]
for key, value in res.items():
print(str(key) + ': ' + ', '.join(value))
```
|
26,643,705
|
So, I have tried this problem for what it seems like a hundred times this week alone.
It's filling in the blank for the following program...
You entered jackson and ville.
When these are combined, it makes jacksonville.
Taking every other letter gives us jcsnil.
The blanks I have filled are fine, but the rest of the blanks, I can't figure out. Here they are.
```
x = raw_input("Enter a word: ")
y = raw_input("Enter another word: ")
print("You entered %s and %s." % (x,y))
combined = x + y
print("When these are combined, it makes %s." % combined)
every_other = ""
counter = 0
for __________________ :
if ___________________ :
every_other = every_other + letter
____________
print("Taking every other letter gives us %s." % every_other)
```
I just need three blanks to this program. This is basic python, so nothing too complicated or something I can match wit the twenty options. Please, I appreciate your help!
|
2014/10/30
|
[
"https://Stackoverflow.com/questions/26643705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196499/"
] |
Assuming that each word is on it's own line, you should be reading the file more like...
```
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
```
Remember, if you open a resource, you are responsible for closing. See [The try-with-resources Statement](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) for more details...
Calculating the metrics can be done after reading the file, but since your here, you could do something like...
```
int totalWordLength = 0;
String longest = "";
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
totalWordLength += dictionaryword.length();
dictionary.add(dictionaryword);
if (dictionaryword.length() > longest.length()) {
longest = dictionaryword;
}
}
int averageLength = Math.round(totalWordLength / (float)dictionary.size());
```
But you could just as easily loop through the `dictionary` and use the same idea
(nb- I've used local variables, so you will either want to make them class fields or return them wrapped in some kind of "metrics" class - your choice)
|
Set a two counters and a variable that holds the current longest word found before you start reading in with your while loop. To find the average have one counter be incremented by one each time the line is read and have the second counter add up the total number of characters in each word (obviously the total number of characters entered, divided by the total number of words read -- as denoted by the total number of lines -- is the average length of each word.
As for the longest word, set the longest word to be the empty string or some dummy value like a single character. Each time you read in a line compare the current word with the previously found longest word (using the `.length()` method on the String to find its length) and if its longer set a new longest word found
Also, if you have all this in a file, I'd use a [buffered reader](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html) to read in your input data
|
26,643,705
|
So, I have tried this problem for what it seems like a hundred times this week alone.
It's filling in the blank for the following program...
You entered jackson and ville.
When these are combined, it makes jacksonville.
Taking every other letter gives us jcsnil.
The blanks I have filled are fine, but the rest of the blanks, I can't figure out. Here they are.
```
x = raw_input("Enter a word: ")
y = raw_input("Enter another word: ")
print("You entered %s and %s." % (x,y))
combined = x + y
print("When these are combined, it makes %s." % combined)
every_other = ""
counter = 0
for __________________ :
if ___________________ :
every_other = every_other + letter
____________
print("Taking every other letter gives us %s." % every_other)
```
I just need three blanks to this program. This is basic python, so nothing too complicated or something I can match wit the twenty options. Please, I appreciate your help!
|
2014/10/30
|
[
"https://Stackoverflow.com/questions/26643705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196499/"
] |
Assuming that each word is on it's own line, you should be reading the file more like...
```
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
```
Remember, if you open a resource, you are responsible for closing. See [The try-with-resources Statement](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) for more details...
Calculating the metrics can be done after reading the file, but since your here, you could do something like...
```
int totalWordLength = 0;
String longest = "";
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
totalWordLength += dictionaryword.length();
dictionary.add(dictionaryword);
if (dictionaryword.length() > longest.length()) {
longest = dictionaryword;
}
}
int averageLength = Math.round(totalWordLength / (float)dictionary.size());
```
But you could just as easily loop through the `dictionary` and use the same idea
(nb- I've used local variables, so you will either want to make them class fields or return them wrapped in some kind of "metrics" class - your choice)
|
May be this could help
```
String words = "Rookie never dissappoints, dont trust any Rookie";
// read your file to string if you get string while reading then you can use below code to do that.
String ss[] = words.split(" ");
List<String> list = Arrays.asList(ss);
Map<Integer,String> set = new Hashtable<Integer,String>();
int i =0;
for(String str : list)
{
set.put(str.length(), str);
System.out.println(list.get(i));
i++;
}
Set<Integer> keys = set.keySet();
System.out.println(keys);
System.out.println(set);
Object j[]= keys.toArray();
Arrays.sort(j);
Object max = j[j.length-1];
set.get(max);
System.out.println("Tha longest word is "+set.get(max));
System.out.println("Length is "+max);
```
|
61,160,595
|
I'm trying to write a function that takes in a list and returns true if it contains the numbers 0,0,7 in that order. When I run this code:
```
def prob11(abc):
if 7 and 0 and 0 not in abc:
return False
x = abc.index(0)
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
return True
else:
return False
```
I get this error:
```
File "<ipython-input-12-e2879221a9bf>", line 5
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
^
SyntaxError: invalid syntax
```
Whats wrong with my elif statement?
|
2020/04/11
|
[
"https://Stackoverflow.com/questions/61160595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13201582/"
] |
Your screenshot is showing data in Realtime Database, but your code is querying Firestore. They are completely different databases with different APIs. You can't use the Firestore SDK to query Realtime Database. If you want to work with Realtime Database, use the documentation [here](https://firebase.google.com/docs/database/ios/read-and-write).
|
There is `author` between `posts` and `username` field in your data structure.
Your code means that right under some specific post there is `username` field.
So such code will work because `date` right undes post:
```
db.collection("posts").whereField("date", isEqualTo: "some-bla-bla-date")
```
In your case you have two options as I see:
* duplicate `username` and place this field on the same level as
`date` and `guests`.
* re-write you code to check `username` inside `author` document.
Hope it will help you in your investigation.
|
61,160,595
|
I'm trying to write a function that takes in a list and returns true if it contains the numbers 0,0,7 in that order. When I run this code:
```
def prob11(abc):
if 7 and 0 and 0 not in abc:
return False
x = abc.index(0)
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
return True
else:
return False
```
I get this error:
```
File "<ipython-input-12-e2879221a9bf>", line 5
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
^
SyntaxError: invalid syntax
```
Whats wrong with my elif statement?
|
2020/04/11
|
[
"https://Stackoverflow.com/questions/61160595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13201582/"
] |
Your screenshot is showing data in Realtime Database, but your code is querying Firestore. They are completely different databases with different APIs. You can't use the Firestore SDK to query Realtime Database. If you want to work with Realtime Database, use the documentation [here](https://firebase.google.com/docs/database/ios/read-and-write).
|
So I changed my code to:
```
func loadData(url: URL){
let ref = Database.database().reference().child("posts")
let user = UserService.currentUserProfile!
ref.queryOrdered(byChild: "author/username").queryEqual(toValue: user.username).observe(.value, with: { snapshot in
if var post = snapshot.value as? [String : Any] {
print("updated all Posts")
post.updateValue(url.absoluteString, forKey: "photoUrl")
print(post.values)
}else{
print("fail")
}
})
}
```
It went through and I get the print statement of my values but the data didn't changed in the realtime database
|
34,271,807
|
I am trying to write a python script with several text files inside a subdirectory, e.g.
```
python script.py --inputdir ~/subdirectory
```
which will execute each file inside this subdirectory. How can one use argparse to do this? Should you write a function to access and open each file?
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--inputdir", help="path to your subdirectory",
required=True)
args = parser.parse_args()
```
Now, what do I do with `args.inputdir`? How do I extract files?
|
2015/12/14
|
[
"https://Stackoverflow.com/questions/34271807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596596/"
] |
I think your a mixing up the return value of setInterval.
setInterval returns an handle to the function scheduled, so you can call clearInterval().
From Mdn:
<https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval>
```
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
intervalID is a unique interval ID you can pass to clearInterval().
```
If you then call startTime + 1 in that function, what happens?
nothing is returned, startTime is not changed, is just evaluated and the function exit.
to count seconds passed, is an overkill to call a function every second and add 1, it will be also not precise probably.
Try to do like this:
```
when start button is pressed:
startTime = new Date().getTime();
```
when stop button is pressed:
```
millisecondsPassed = new Date().getTime() - startTime;
secondsPassed = Math.floor(millisecondPassed / 1000);
```
If the only meaning of the function is to increase time, you do not have to call it at all, no intervals to clear.
|
[`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) returns a reference to the interval you have just created, so that later you can stop the interval.
```
var myRef = setInterval(...);
clearInterval(myRef);
```
Every time `moveBall()` is called and you run this
```
startTime = setInterval(function(){ startTime + 1;}, 1000);
$('#time').html(startTime);
```
you are creating a new interval and outputting it's reference. In most browsers that is a simple counter that starts from 1. You should not modify the `startTime` value if you are planning on using later as you will have lost the reference value to your interval timer.
|
7,513,133
|
From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
```
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
From Python, run bash with `os.system`, `os.popen` or `subprocess` and pass the appropriate command-line arguments.
```
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
```
|
Bash should accept a command from args when using the -c flag:
```
C:\cygwin\bin\bash.exe -c "somecommand"
```
Combine that with C++'s [`exec`](http://linux.about.com/library/cmd/blcmdl3_execvp.htm) or python's `os.system` to run the command.
|
7,513,133
|
From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
```
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
From Python, run bash with `os.system`, `os.popen` or `subprocess` and pass the appropriate command-line arguments.
```
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
```
|
The following function will run Cygwin's Bash program while making sure the bin directory is in the system path, so you have access to non-built-in commands. This is an alternative to using the login (-l) option, which may redirect you to your home directory.
```py
def cygwin(command):
"""
Run a Bash command with Cygwin and return output.
"""
# Find Cygwin binary directory
for cygwin_bin in [r'C:\cygwin\bin', r'C:\cygwin64\bin']:
if os.path.isdir(cygwin_bin):
break
else:
raise RuntimeError('Cygwin not found!')
# Make sure Cygwin binary directory in path
if cygwin_bin not in os.environ['PATH']:
os.environ['PATH'] += ';' + cygwin_bin
# Launch Bash
p = subprocess.Popen(
args=['bash', '-c', command],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
# Raise exception if return code indicates error
if p.returncode != 0:
raise RuntimeError(p.stderr.read().rstrip())
# Remove trailing newline from output
return (p.stdout.read() + p.stderr.read()).rstrip()
```
Example use:
```
print cygwin('pwd')
print cygwin('ls -l')
print cygwin(r'dos2unix $(cygpath -u "C:\some\file.txt")')
print cygwin(r'md5sum $(cygpath -u "C:\another\file")').split(' ')[0]
```
|
7,513,133
|
From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
```
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
The following function will run Cygwin's Bash program while making sure the bin directory is in the system path, so you have access to non-built-in commands. This is an alternative to using the login (-l) option, which may redirect you to your home directory.
```py
def cygwin(command):
"""
Run a Bash command with Cygwin and return output.
"""
# Find Cygwin binary directory
for cygwin_bin in [r'C:\cygwin\bin', r'C:\cygwin64\bin']:
if os.path.isdir(cygwin_bin):
break
else:
raise RuntimeError('Cygwin not found!')
# Make sure Cygwin binary directory in path
if cygwin_bin not in os.environ['PATH']:
os.environ['PATH'] += ';' + cygwin_bin
# Launch Bash
p = subprocess.Popen(
args=['bash', '-c', command],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
# Raise exception if return code indicates error
if p.returncode != 0:
raise RuntimeError(p.stderr.read().rstrip())
# Remove trailing newline from output
return (p.stdout.read() + p.stderr.read()).rstrip()
```
Example use:
```
print cygwin('pwd')
print cygwin('ls -l')
print cygwin(r'dos2unix $(cygpath -u "C:\some\file.txt")')
print cygwin(r'md5sum $(cygpath -u "C:\another\file")').split(' ')[0]
```
|
Bash should accept a command from args when using the -c flag:
```
C:\cygwin\bin\bash.exe -c "somecommand"
```
Combine that with C++'s [`exec`](http://linux.about.com/library/cmd/blcmdl3_execvp.htm) or python's `os.system` to run the command.
|
67,915,835
|
I and my colleague is working on a django (python) project and pushing our code on same branch(lets say branch1), as a beginner i know how to push the code on a particular branch but have no idea how pull and merge can be done. what should i do if i want full project including his codes and my codes together without overriding the whole file(lets say he made views1.py and i made views2.py, then after merge and all, the result must be views3.py)
* now views3.py contains my code and his code.
Any kind of help would be appreciated.
|
2021/06/10
|
[
"https://Stackoverflow.com/questions/67915835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13963543/"
] |
For node.js subprocesses there is the [cluster module](https://nodejs.org/api/cluster.html) and I strongly recommend using this. For general subprocesses (e.g. bash scripts as you mentioned) you have to use `child_process` (-> execa). Communication between processes may then be accomplished via grpc. Your approach is fine, so you can consider moving forward with it.
|
I decided to go full with `pm2` for the time being, as they have an excellent [programmatic API](https://pm2.keymetrics.io/docs/usage/pm2-api/) - also (which I only just learned about) you can specify [different interpreters](https://pm2.keymetrics.io/docs/usage/process-management/#start-any-process-type) to run your script. So not only `node` apps are possible but also `bash`, `python`, `php` and so on - which is exactly what I am looking for.
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
`int &foo();` declares a function called `foo()` with return type `int&`. If you call this function without providing a body then you are likely to get an undefined reference error.
In your second attempt you provided a function `int foo()`. This has a different return type to the function declared by `int& foo();`. So you have two declarations of the same `foo` that don't match, which violates the One Definition Rule causing undefined behaviour (no diagnostic required).
For something that works, take out the local function declaration. They can lead to silent undefined behaviour as you have seen. Instead, only use function declarations outside of any function. Your program could look like:
```
int &foo()
{
static int i = 2;
return i;
}
int main()
{
++foo();
std::cout << foo() << '\n';
}
```
|
In that context the & means a reference - so foo returns a reference to an int, rather than an int.
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory where that int is.
So to summarize you're not assigning a value to a function call - you're using a function to get a reference, and then assigning the value being referenced to a new value. It's easy to think everything happens at once, but in reality the computer does everything in a precise order.
If you're wondering - the reason you're getting a segfault is because you're returning a numeric literal '2' - so it's the exact error you'd get if you were to define a const int and then try to modify its value.
If you haven't learned about pointers and dynamic memory yet then I'd recommend that first as there's a few concepts that I think are hard to understand unless you're learning them all at once.
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:
```
int& highest(int & i, int & j)
{
if (i > j)
{
return i;
}
return j;
}
int main()
{
int a{ 3};
int b{ 4 };
highest(a, b) = 11;
return 0;
}
```
Because `highest()` returns a reference, you can assign a value to it. When this runs, `b` will be changed to 11. If you changed the initialization so that `a` was, say, 8, then `a` would be changed to 11. This is some code that might actually serve a purpose, unlike the other examples.
|
The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:
```
int& foo()
{
static int x;
return x;
}
```
and would succeed by changing the value of x, when saying:
```
foo() = 10;
```
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
`int& foo();` is a function returning a reference to `int`. Your provided function returns `int` without reference.
You may do
```
int& foo()
{
static int i = 42;
return i;
}
int main()
{
int& foo();
foo() = 42;
}
```
|
The function you have, foo(), is a function that returns a reference to an integer.
So let's say originally foo returned 5, and later on, in your main function, you say `foo() = 10;`, then prints out foo, it will print 10 instead of 5.
I hope that makes sense :)
I'm new to programming as well. It's interesting to see questions like this that makes you think! :)
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
`int &foo();` declares a function called `foo()` with return type `int&`. If you call this function without providing a body then you are likely to get an undefined reference error.
In your second attempt you provided a function `int foo()`. This has a different return type to the function declared by `int& foo();`. So you have two declarations of the same `foo` that don't match, which violates the One Definition Rule causing undefined behaviour (no diagnostic required).
For something that works, take out the local function declaration. They can lead to silent undefined behaviour as you have seen. Instead, only use function declarations outside of any function. Your program could look like:
```
int &foo()
{
static int i = 2;
return i;
}
int main()
{
++foo();
std::cout << foo() << '\n';
}
```
|
`int& foo();` is a function returning a reference to `int`. Your provided function returns `int` without reference.
You may do
```
int& foo()
{
static int i = 42;
return i;
}
int main()
{
int& foo();
foo() = 42;
}
```
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
The explanation is assuming that there is some reasonable implementation for `foo` which returns an lvalue reference to a valid `int`.
Such an implementation might be:
```
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
```
Now, since `foo` returns an lvalue reference, we can assign something to the return value, like so:
```
foo() = 42;
```
This will update the global `a` with the value `42`, which we can check by accessing the variable directly or calling `foo` again:
```
int main() {
foo() = 42;
std::cout << a; //prints 42
std::cout << foo(); //also prints 42
}
```
|
```
int& foo();
```
Declares a function named foo that returns a reference to an `int`. What that examples fails to do is give you a definition of that function that you could compile. If we use
```
int & foo()
{
static int bar = 0;
return bar;
}
```
Now we have a function that returns a reference to `bar`. since bar is `static` it will live on after the call to the function so returning a reference to it is safe. Now if we do
```
foo() = 42;
```
What happens is we assign 42 to `bar` since we assign to the reference and the reference is just an alias for `bar`. If we call the function again like
```
std::cout << foo();
```
It would print 42 since we set `bar` to that above.
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
`int & foo();` means that `foo()` returns a reference to a variable.
Consider this code:
```
#include <iostream>
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
```
This code prints:
$ ./a.out
k=5
Because `foo()` returns a reference to the global variable `k`.
In your revised code, you are casting the returned value to a reference, which is then invalid.
|
The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:
```
int& foo()
{
static int x;
return x;
}
```
and would succeed by changing the value of x, when saying:
```
foo() = 10;
```
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
```
int& foo();
```
Declares a function named foo that returns a reference to an `int`. What that examples fails to do is give you a definition of that function that you could compile. If we use
```
int & foo()
{
static int bar = 0;
return bar;
}
```
Now we have a function that returns a reference to `bar`. since bar is `static` it will live on after the call to the function so returning a reference to it is safe. Now if we do
```
foo() = 42;
```
What happens is we assign 42 to `bar` since we assign to the reference and the reference is just an alias for `bar`. If we call the function again like
```
std::cout << foo();
```
It would print 42 since we set `bar` to that above.
|
`int & foo();` means that `foo()` returns a reference to a variable.
Consider this code:
```
#include <iostream>
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
```
This code prints:
$ ./a.out
k=5
Because `foo()` returns a reference to the global variable `k`.
In your revised code, you are casting the returned value to a reference, which is then invalid.
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
```
int& foo();
```
Declares a function named foo that returns a reference to an `int`. What that examples fails to do is give you a definition of that function that you could compile. If we use
```
int & foo()
{
static int bar = 0;
return bar;
}
```
Now we have a function that returns a reference to `bar`. since bar is `static` it will live on after the call to the function so returning a reference to it is safe. Now if we do
```
foo() = 42;
```
What happens is we assign 42 to `bar` since we assign to the reference and the reference is just an alias for `bar`. If we call the function again like
```
std::cout << foo();
```
It would print 42 since we set `bar` to that above.
|
The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:
```
int& foo()
{
static int x;
return x;
}
```
and would succeed by changing the value of x, when saying:
```
foo() = 10;
```
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:
```
int& highest(int & i, int & j)
{
if (i > j)
{
return i;
}
return j;
}
int main()
{
int a{ 3};
int b{ 4 };
highest(a, b) = 11;
return 0;
}
```
Because `highest()` returns a reference, you can assign a value to it. When this runs, `b` will be changed to 11. If you changed the initialization so that `a` was, say, 8, then `a` would be changed to 11. This is some code that might actually serve a purpose, unlike the other examples.
|
In that context the & means a reference - so foo returns a reference to an int, rather than an int.
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory where that int is.
So to summarize you're not assigning a value to a function call - you're using a function to get a reference, and then assigning the value being referenced to a new value. It's easy to think everything happens at once, but in reality the computer does everything in a precise order.
If you're wondering - the reason you're getting a segfault is because you're returning a numeric literal '2' - so it's the exact error you'd get if you were to define a const int and then try to modify its value.
If you haven't learned about pointers and dynamic memory yet then I'd recommend that first as there's a few concepts that I think are hard to understand unless you're learning them all at once.
|
36,477,552
|
I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "serialnr"])
result = # some operation
return result
```
Although this code works 100% fine when I run the python script manually from the command line (e.g. `python script.py`), it doesn't work at all when it's run by PPP from if-up. An exception is raised when `subprocess.check_output` is called: `[Errno 2] No such file or directory: 'fw_printenv'`.
I can only get it to work if I change the code to:
```
result = subprocess.check_output("fw_printenv serialnr", shell=True)
```
Why?
|
2016/04/07
|
[
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] |
The explanation is assuming that there is some reasonable implementation for `foo` which returns an lvalue reference to a valid `int`.
Such an implementation might be:
```
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
```
Now, since `foo` returns an lvalue reference, we can assign something to the return value, like so:
```
foo() = 42;
```
This will update the global `a` with the value `42`, which we can check by accessing the variable directly or calling `foo` again:
```
int main() {
foo() = 42;
std::cout << a; //prints 42
std::cout << foo(); //also prints 42
}
```
|
The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:
```
int& foo()
{
static int x;
return x;
}
```
and would succeed by changing the value of x, when saying:
```
foo() = 10;
```
|
39,637,164
|
How can i used the rt function, as i understand leading & trailing underscores `__and__()` is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,
```
class A(object):
def __rt__(self,r):
return "Yes special functions"
a=A()
print dir(a)
print a.rt('1') # AttributeError: 'A' object has no attribute 'rt'
```
But
```
class Room(object):
def __init__(self):
self.people = []
def add(self, person):
self.people.append(person)
def __len__(self):
return len(self.people)
room = Room()
room.add("Igor")
print len(room) #prints 1
```
|
2016/09/22
|
[
"https://Stackoverflow.com/questions/39637164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277603/"
] |
Python doesn't translate one name into another. Specific operations will *under the covers* call a `__special_method__` if it has been defined. For example, the `__and__` method is called by Python to hook into the `&` operator, because the Python interpreter *explicitly looks for that method* and documented how it should be used.
In other words, calling `object.rt()` is not translated to `object.__rt__()` anywhere, not automatically.
Note that Python *reserves* such names; future versions of Python may use that name for a specific purpose and then your existing code using a `__special_method__` name for your own purposes would break.
From the [*Reserved classes of identifiers* section](https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers):
>
> `__*__`
>
> System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the [Special method names](https://docs.python.org/3/reference/datamodel.html#specialnames) section and elsewhere. More will likely be defined in future versions of Python. Any use of `__*__` names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
>
>
>
You can ignore that advice of course. In that case, you'll have to write code that actually *calls your method*:
```
class SomeBaseClass:
def rt(self):
"""Call the __rt__ special method"""
try:
return self.__rt__()
except AttributeError:
raise TypeError("The object doesn't support this operation")
```
and subclass from `SomeBaseClass`.
Again, Python won't automatically call your new methods. You still need to actually write such code.
|
Because there are builtin methods that you can overriden and then you can use them, ex `__len__` -> `len()`, `__str__` -> `str()` and etc.
Here is the [list of these functions](https://docs.python.org/3/reference/datamodel.html#basic-customization)
>
> The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of x.name) for class instances.
>
>
>
|
65,571,031
|
I am trying to install a package on a python project but having some issues with python-Levenshtein library. I'm using a virtual environment on PyCharm which is running with Python3.8 and installed all libraries in requirements.txt with pip. However I am not able to install this library.
What I've tried so far:
1. try to install with pip and pip3
2. try to install with anaconda
3. try to install with brew (to make sure it's not like matplotlib [here](https://stackoverflow.com/questions/25701133/how-to-tell-homebrew-to-install-inside-virtualenv))
I share the error message below. Could you help me to solve this problem
```
Collecting python-Levenshtein==0.12.0
Using cached python-Levenshtein-0.12.0.tar.gz (48 kB)
Requirement already satisfied: setuptools in /Users/suleyman/Projects/venv/lib/python3.8/site-packages (from python-Levenshtein==0.12.0) (51.1.1)
Building wheels for collected packages: python-Levenshtein
Building wheel for python-Levenshtein (setup.py): started
Building wheel for python-Levenshtein (setup.py): finished with status 'error'
Running setup.py clean for python-Levenshtein
Failed to build python-Levenshtein
Installing collected packages: python-Levenshtein
Running setup.py install for python-Levenshtein: started
Running setup.py install for python-Levenshtein: finished with status 'error'
ERROR: Command errored out with exit status 1:
```
|
2021/01/04
|
[
"https://Stackoverflow.com/questions/65571031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5331231/"
] |
That index could be used if you wrote the query like this:
```
select rh."EventHistory"
from "RemittanceHistory" rh join "ClaimPaymentHistory" ph
on ph."EventHistory" @> jsonb_build_array(jsonb_build_object('rk',rh."RemittanceRefKey"))
where ph."ClaimRefKey" = 5;
```
However, this unlikely to have good performance unless "RemittanceHistory" has few rows in it.
>
> ...what would be my best options for indexing?
>
>
>
The obvious choice, if you don't have them already, would be regular (btree) indexes on rh."RemittanceRefKey" and ph."ClaimRefKey".
Also, look at (and show us) the `EXPLAIN (ANALYZE, BUFFERS)` for the original query you want to make faster.
|
I wound up refactoring the table structure. Instead of a join through `RemittanceRefKey` I added a JSONB column to `RemittanceHistory` called `ClaimRefKeys`. This is simply an array of integer values and now I can lookup the desired rows with:
```
select "EventHistory" from "RemittanceHistory" where "ClaimRefKeys" @> @ClaimRefKey;
```
This combined with the following index gives pretty fantastic performance.
```
CREATE INDEX remittance_history_claimrefkeys_gin_idx ON "RemittanceHistory" USING gin ("ClaimRefKeys" jsonb_path_ops);
```
|
57,593,041
|
```
>>> x = 1
>>> def f():
... print x
...
>>> f()
1
>>> x = 1
>>> def f():
... x = 3
... print x
...
>>> f()
3
>>> x
1
>>> x = 1
>>> def f():
... print x
... x = 5
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'x' referenced before assignment
>>> x = 1
>>> def f():
... global x
... print x
... x = 5
... print x
...
>>> f()
1
5
>>> x
5
```
How to treat the variable "**x**" inside the function as local without altering the global one when I have print statement above the variable assignment?
I expect the result of "**x**" to be 5 inside the function and the global x should be unaltered and remains the same in value (i.e) 1
I guess, there is no keyword called **local** in python contrary to **global**
```
>>> x = 1
>>> def f():
... print x
... global x
... x = 5
...
<stdin>:3: SyntaxWarning: name 'x' is used prior to global declaration
```
|
2019/08/21
|
[
"https://Stackoverflow.com/questions/57593041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335601/"
] |
>
> In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
>
>
>
[Source.](https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python)
It's true there's no `local` keyword in Python; instead, Python has this rule to decide which variables are local.
Any variable in your function is either local or global. It can't be local in one part of the function and global in another. If you have a local variable `x`, then the function can't access the global `x`. If you want a local variable while accessing the global `x`, you can call the local variable some other name.
|
The behaviour is already what you want. The presence of `x =` inside the function body makes `x` a local variable which entirely shadows the outer variable. You're merely trying to print it before you assign any value to it, which is causing an error. This would cause an error under any other circumstance too; you can't print what you didn't assign.
|
56,184,013
|
Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically?
|
2019/05/17
|
[
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] |
According to [this](https://github.com/tensorflow/tensorflow/issues/31377) thread, it is not.
|
You can force the computation to take place on a GPU:
```
import tensorflow as tf
with tf.device('/gpu:0'):
for i in range(10):
t = np.random.randint(len(x_test) )
...
```
Hope this helps.
|
56,184,013
|
Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically?
|
2019/05/17
|
[
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] |
one solution is to convert tflite to onnx and use onnxruntime-gpu
convert to onnx with <https://github.com/onnx/tensorflow-onnx>:
```
pip install tf2onnx
python3 -m tf2onnx.convert --opset 11 --tflite path/to/model.tflite --output path/to/model.onnx
```
then `pip install onnxruntime-gpu`
and run like:
```
session = onnxruntime.InferenceSession(('/path/to/model.onnx'))
raw_output = self.detection_session.run(['output_name'], {'input_name': img})
```
you can get the input and output names by:
```
for i in range(len(session.get_inputs)):
print(session.get_inputs()[i].name)
```
and the same but replace 'get\_inputs' with 'get\_outputs'
|
You can force the computation to take place on a GPU:
```
import tensorflow as tf
with tf.device('/gpu:0'):
for i in range(10):
t = np.random.randint(len(x_test) )
...
```
Hope this helps.
|
56,184,013
|
Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically?
|
2019/05/17
|
[
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] |
According to [this](https://github.com/tensorflow/tensorflow/issues/31377) thread, it is not.
|
one solution is to convert tflite to onnx and use onnxruntime-gpu
convert to onnx with <https://github.com/onnx/tensorflow-onnx>:
```
pip install tf2onnx
python3 -m tf2onnx.convert --opset 11 --tflite path/to/model.tflite --output path/to/model.onnx
```
then `pip install onnxruntime-gpu`
and run like:
```
session = onnxruntime.InferenceSession(('/path/to/model.onnx'))
raw_output = self.detection_session.run(['output_name'], {'input_name': img})
```
you can get the input and output names by:
```
for i in range(len(session.get_inputs)):
print(session.get_inputs()[i].name)
```
and the same but replace 'get\_inputs' with 'get\_outputs'
|
58,126,489
|
I follow the tutorial from Traversy Media on Youtube videos. When I put the command
>
> python manage.py migrate
>
>
>
Then I got such an error like this:
```
C:\Users\Acer\Project\djangoproject>python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\importlib\__
init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\contrib\auth\models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\contrib\auth\base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\models\base.py", line 117, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\models\base.py", line 321, in add_to_class
value.contribute_to_class(cls, name)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\models\options.py", line 204, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length(
))
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\__init__.py", line 28, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\utils.py", line 201, in __getitem__
backend = load_backend(db['ENGINE'])
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\utils.py", line 110, in load_backend
return import_module('%s.base' % backend_name)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\importlib\__
init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package
s\django\db\backends\mysql\base.py", line 36, in <module>
raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you hav
e %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is requ
ired; you have 0.9.3.
```
Btw, I already install the C++ Build Visual Studio from another error that I got, and I also installed already the **mysqlclient-1.4.4-cp37-cp37m-win32.whl** to get it done. But still, it gives me such an error.
Please help me, and thank you for those who already respond on this.
|
2019/09/27
|
[
"https://Stackoverflow.com/questions/58126489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11803617/"
] |
There are several dedicated packages for this. For example have a look at the `combine`, `subdocs` or `docmute` packages (A list with even more suggestions can be fond at <https://www.ctan.org/recommendations/docmute>).
Here a short example with the `docmute` package
```
\documentclass{book}
\usepackage{lipsum}
\usepackage{docmute}
\begin{document}
\tableofcontents
text
\chapter{imported paper}
\input{test}% assuming your paper is called test.tex
\end{document}
```
|
A Latex document cannot have multiple `\documentclass`. One solution would be to split the header/content of your latex document in overleaf:
* Create a `master.tex` with the documentclass and put all your content (text between `\begin{document}` and `\end{document}` in a second `content.tex`. In the master, just `\input{content}`.
* In your dissertation, just copy `content.tex`, its figure and add `\input{}` in the master file of your University which has the specific documentclass and bibliography settings.
|
43,736,163
|
I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Traceback (most recent call last):
File "<ipython-input-43-ed485b439a1c>", line 1, in <module>
reviews_new['review']
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__
return self._getitem_column(key)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column
return self._get_item_cache(key)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache
values = self._data.get(item)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\internals.py", line 3290, in get
loc = self.items.get_loc(item)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: 'review'
```
\*\*
Can someone help me in this ?
|
2017/05/02
|
[
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] |
I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:
```
print (reviews_new.columns.tolist())
```
---
I think there can be 2 problems (obviously):
**1.whitespaces in columns names (maybe in data also)**
Solutions are [`strip`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html) whitespaces in column names:
```
reviews_new.columns = reviews_new.columns.str.strip()
```
Or add parameter `skipinitialspace` to [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html):
```
reviews_new = pd.read_csv("D:\\aviva.csv", skipinitialspace=True)
```
**2.different separator as default `,`**
Solution is add parameter `sep`:
```
#sep is ;
reviews_new = pd.read_csv("D:\\aviva.csv", sep=';')
#sep is whitespace
reviews_new = pd.read_csv("D:\\aviva.csv", sep='\s+')
reviews_new = pd.read_csv("D:\\aviva.csv", delim_whitespace=True)
```
EDIT:
You get whitespace in column name, so need `1.solutions`:
```
print (reviews_new.columns.tolist())
['Name', ' Date', ' review']
^ ^
```
|
```
import pandas as pd
df=pd.read_csv("file.txt", skipinitialspace=True)
df.head()
df['review']
```
|
43,736,163
|
I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Traceback (most recent call last):
File "<ipython-input-43-ed485b439a1c>", line 1, in <module>
reviews_new['review']
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__
return self._getitem_column(key)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column
return self._get_item_cache(key)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache
values = self._data.get(item)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\internals.py", line 3290, in get
loc = self.items.get_loc(item)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: 'review'
```
\*\*
Can someone help me in this ?
|
2017/05/02
|
[
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] |
I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:
```
print (reviews_new.columns.tolist())
```
---
I think there can be 2 problems (obviously):
**1.whitespaces in columns names (maybe in data also)**
Solutions are [`strip`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html) whitespaces in column names:
```
reviews_new.columns = reviews_new.columns.str.strip()
```
Or add parameter `skipinitialspace` to [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html):
```
reviews_new = pd.read_csv("D:\\aviva.csv", skipinitialspace=True)
```
**2.different separator as default `,`**
Solution is add parameter `sep`:
```
#sep is ;
reviews_new = pd.read_csv("D:\\aviva.csv", sep=';')
#sep is whitespace
reviews_new = pd.read_csv("D:\\aviva.csv", sep='\s+')
reviews_new = pd.read_csv("D:\\aviva.csv", delim_whitespace=True)
```
EDIT:
You get whitespace in column name, so need `1.solutions`:
```
print (reviews_new.columns.tolist())
['Name', ' Date', ' review']
^ ^
```
|
```
dfObj['Hash Key'] = (dfObj['DEAL_ID'].map(str) +dfObj['COST_CODE'].map(str) +dfObj['TRADE_ID'].map(str)).apply(hash)
#for index, row in dfObj.iterrows():
# dfObj.loc[`enter code here`index,'hash'] = hashlib.md5(str(row[['COST_CODE','TRADE_ID']].values)).hexdigest()
print(dfObj['hash'])
```
|
43,736,163
|
I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Traceback (most recent call last):
File "<ipython-input-43-ed485b439a1c>", line 1, in <module>
reviews_new['review']
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__
return self._getitem_column(key)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column
return self._get_item_cache(key)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache
values = self._data.get(item)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\internals.py", line 3290, in get
loc = self.items.get_loc(item)
File "C:\Users\30216\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: 'review'
```
\*\*
Can someone help me in this ?
|
2017/05/02
|
[
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] |
```
import pandas as pd
df=pd.read_csv("file.txt", skipinitialspace=True)
df.head()
df['review']
```
|
```
dfObj['Hash Key'] = (dfObj['DEAL_ID'].map(str) +dfObj['COST_CODE'].map(str) +dfObj['TRADE_ID'].map(str)).apply(hash)
#for index, row in dfObj.iterrows():
# dfObj.loc[`enter code here`index,'hash'] = hashlib.md5(str(row[['COST_CODE','TRADE_ID']].values)).hexdigest()
print(dfObj['hash'])
```
|
28,952,282
|
I'm using REPL with sublime text 3 (latest version as of today) and I'm coding in python 3.4. As far as I understand the documentation on REPL if do: tools>sublimeREPL>python>python-RUN current file
then I should run the code I have typed in using REPL. However when I do this I get an error pop up saying:
FileNotFoundError(2, 'The system cannot find the file specified.',None,2)
I get this error whatever the code I typed in is (I tried print ("Hello World") on its own and also big long programs I've made before)
Can someone please help me with this and explain what the problem is, thanks :)
|
2015/03/09
|
[
"https://Stackoverflow.com/questions/28952282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4651552/"
] |
I also had this problem. This is most probably due to the default location of python. If you are running portable python,
```
{
...
"default_extend_env": {"PATH": "{PATH}:\\Programming\\Python\\Portable Python 2.7.6.1\\App\\"}
...
}
```
Otherwise,
```
{
"default_extend_env": {"PATH":"C:\\python27\\"},
}
```
would suffice. This code is to be pasted in:
```
Preferences -> Package Settings -> SublimeREPL -> Settings - User
```
|
I had the same problem, when I installed REPL for the first time. Now, that could sound crazy, but the way to solve the problem (at least, the trick worked for me!) is to restart once Sublime Text 3.
**Update**: As pointed out by Mark in the comments, apparently you could have to restart Sublime more than once to solve the problem.
|
63,650,186
|
Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my dollar sign in my ouputs appear next to the outputs themselves, they always appear a space away. ($ 400.00). I know that I can add a plus sign somewhere to smush the two together but I keep getting errors when I try. I'm not exactly sure what I'm doing wrong but I would appreciate any input. I'll paste the code that works without error below. I put spaces inbetween the lines so it can be seen more clearly.
```
wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)
```
|
2020/08/29
|
[
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] |
You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
```
|
Replace `,` with `+` because `,` leaves a space by default, for example:
```
print('Material cost of the project: $' + tot_mat)
print('Labor cost of the project: $' + tot_lab)
print('Total cost of the project: $' + project)
```
You can also use `f-strings` as so:
```
print(f'Material cost of the project: ${tot_mat}')
print(f'Labor cost of the project: ${tot_lab}')
print(f'Total cost of the project: ${project}')
```
|
63,650,186
|
Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my dollar sign in my ouputs appear next to the outputs themselves, they always appear a space away. ($ 400.00). I know that I can add a plus sign somewhere to smush the two together but I keep getting errors when I try. I'm not exactly sure what I'm doing wrong but I would appreciate any input. I'll paste the code that works without error below. I put spaces inbetween the lines so it can be seen more clearly.
```
wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)
```
|
2020/08/29
|
[
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] |
Use below :
```
print('Total cost of the project: $'+str(project))
```
Note: I have converted project into string with str function as it’s float . You can use same for all.
|
Replace `,` with `+` because `,` leaves a space by default, for example:
```
print('Material cost of the project: $' + tot_mat)
print('Labor cost of the project: $' + tot_lab)
print('Total cost of the project: $' + project)
```
You can also use `f-strings` as so:
```
print(f'Material cost of the project: ${tot_mat}')
print(f'Labor cost of the project: ${tot_lab}')
print(f'Total cost of the project: ${project}')
```
|
63,650,186
|
Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my dollar sign in my ouputs appear next to the outputs themselves, they always appear a space away. ($ 400.00). I know that I can add a plus sign somewhere to smush the two together but I keep getting errors when I try. I'm not exactly sure what I'm doing wrong but I would appreciate any input. I'll paste the code that works without error below. I put spaces inbetween the lines so it can be seen more clearly.
```
wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)
```
|
2020/08/29
|
[
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] |
You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
```
|
You could try using fstring syntax as well (Assuming you're using Python 3)
```
print(f'Material cost of the project: ${tot_mat}')
```
|
63,650,186
|
Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my dollar sign in my ouputs appear next to the outputs themselves, they always appear a space away. ($ 400.00). I know that I can add a plus sign somewhere to smush the two together but I keep getting errors when I try. I'm not exactly sure what I'm doing wrong but I would appreciate any input. I'll paste the code that works without error below. I put spaces inbetween the lines so it can be seen more clearly.
```
wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)
```
|
2020/08/29
|
[
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] |
Use below :
```
print('Total cost of the project: $'+str(project))
```
Note: I have converted project into string with str function as it’s float . You can use same for all.
|
You could try using fstring syntax as well (Assuming you're using Python 3)
```
print(f'Material cost of the project: ${tot_mat}')
```
|
63,650,186
|
Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my dollar sign in my ouputs appear next to the outputs themselves, they always appear a space away. ($ 400.00). I know that I can add a plus sign somewhere to smush the two together but I keep getting errors when I try. I'm not exactly sure what I'm doing wrong but I would appreciate any input. I'll paste the code that works without error below. I put spaces inbetween the lines so it can be seen more clearly.
```
wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)
```
|
2020/08/29
|
[
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] |
You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
```
|
In addition to other answers, also note that your code will crash if someone inputs something that is in any way incorrect (e. g. "3,9" will throw an error if you try to parse it as a float). Consider reading about `try/except`, catching and handling error in context of the `input()` function.
|
63,650,186
|
Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my dollar sign in my ouputs appear next to the outputs themselves, they always appear a space away. ($ 400.00). I know that I can add a plus sign somewhere to smush the two together but I keep getting errors when I try. I'm not exactly sure what I'm doing wrong but I would appreciate any input. I'll paste the code that works without error below. I put spaces inbetween the lines so it can be seen more clearly.
```
wth_room = (int(input('Enter the width of room in feet:')))
lth_room = (int(input('Enter the length of room in feet:')))
mat_cost = (float(input('Enter material cost of tile per square foot:')))
labor = (float(input('Enter labor installation cost of tile per square foot:')))
tot_tile = (float(wth_room * lth_room))
tot_mat = (float(tot_tile * mat_cost))
tot_lab = (float(labor * tot_tile))
project = (float(mat_cost + labor) * tot_tile)
print('Square feet of tile needed:', tot_tile, 'sqaure feet')
print('Material cost of the project: $', tot_mat)
print('Labor cost of the project: $', tot_lab)
print('Total cost of the project: $', project)
```
|
2020/08/29
|
[
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] |
Use below :
```
print('Total cost of the project: $'+str(project))
```
Note: I have converted project into string with str function as it’s float . You can use same for all.
|
In addition to other answers, also note that your code will crash if someone inputs something that is in any way incorrect (e. g. "3,9" will throw an error if you try to parse it as a float). Consider reading about `try/except`, catching and handling error in context of the `input()` function.
|
25,150,502
|
Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because I need to detect the first time the loop runs. So inside I can have something like
```
if index != 1:
```
|
2014/08/06
|
[
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] |
You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) function, like this
```
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
```
The `enumerate` function gives the current index of the item and the actual item itself. In this case, the second value is actually a tuple of key and value. So, we explicitly group them as a tuple, during the unpacking.
|
If you only need the index to do something special on the first iteration, you could also use `.popitem()`
```
key, val = mydict.popitem()
...
for key, val in mydict.items()
...
```
this will remove the first `key, val` pair from `mydict` (but perhaps that's not an issue for you?)
|
25,150,502
|
Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because I need to detect the first time the loop runs. So inside I can have something like
```
if index != 1:
```
|
2014/08/06
|
[
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] |
You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) function, like this
```
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
```
The `enumerate` function gives the current index of the item and the actual item itself. In this case, the second value is actually a tuple of key and value. So, we explicitly group them as a tuple, during the unpacking.
|
```
if mydict:
iterdict = mydict.iteritems()
firstkey, firstvalue = next(iterdict)
# do something special with first item
for key, value in iterdict:
# do something with the rest
```
|
25,150,502
|
Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because I need to detect the first time the loop runs. So inside I can have something like
```
if index != 1:
```
|
2014/08/06
|
[
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] |
If you only need the index to do something special on the first iteration, you could also use `.popitem()`
```
key, val = mydict.popitem()
...
for key, val in mydict.items()
...
```
this will remove the first `key, val` pair from `mydict` (but perhaps that's not an issue for you?)
|
```
if mydict:
iterdict = mydict.iteritems()
firstkey, firstvalue = next(iterdict)
# do something special with first item
for key, value in iterdict:
# do something with the rest
```
|
47,799,275
|
I need to be able to login into a remote server, switch user and then, do whatever it is required.
I played with ansible and found the "become" tool, so I tried it, after all... it allows dzdo.
My playbook became something like this:
```
- name: Create empty file
file: path=touchedFile.txt state=touch
become: true
become_method: dzdo
become_user: userid
```
I ran it and got:
"Sorry, user someuser is not allowed to execute '/bin/sh -c echo BECOME-SUCCESS-xklihidlmxpfvxxnbquvsqrgfjlyrsah; /usr/bin/python /tmp/ansible-tmp-1513185770.1-52571838933499/command.py'
Mmm... I thought that maybe it is trying to execute something like this:
```
dzdo touch touchedFile.txt
```
Unfortunately, it doesn't work like that in my company. The policy forces us to log in as ourselves and then switch to the required user like this:
```
dzdo su - userid
```
I did a bit of research and tried running several commands in a single block, my logic thought that if I switched users first, then everything else would be executed as the other user. My playbook was updated to look like this:
```
- name: Create empty file
shell: |
dzdo su - userid
touch touchedFile.txt
```
It failed and I tried this then:
```
- name: Create empty file
command: "{{ item }}"
with_items:
- dzdo su - userid
- touch touchedFile.txt
```
And failed again... both approaches create touchedFile.txt but as my user and not the one they should...
Is there a way to do what I need directly with Ansible? Or do I need to start looking for more complex alternatives?
In the past I achieved what I'm trying to do now with a script that mainly used "expect", but it was prone to errors... that's why I'm looking for better alternatives.
**EDIT 2018-01-08:**
I can now use "`sudo su - userid`" without the need of a password; but somehow Ansible always expect input from the user, a timeout occurs and my play fails:
```
fatal: [240]: FAILED! => {
"failed": true,
"msg": "Timeout (12s) waiting for privilege escalation prompt: "
}
```
One thing I noticed is that Ansible is doing the following:
```
EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no
-o 'IdentityFile="./.ssh/fatCamel"' -o KbdInteractiveAuthentication=no
-o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey
-o PasswordAuthentication=no -o User=login_userid -o ConnectTimeout=10
-o ControlPath=/Users/local_userid/.ansible/cp/446eee77f4
-tt server_url '/bin/sh -c '"'"'sudo su - sudo_userid -u root /bin/sh
-c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-hsyxhtaoxiepyjexaffecfiblmjezopu;
/usr/bin/python /u/users/login_userid/.ansible/tmp/ansible-tmp-1515438271.05-219108659465262/command.py;
rm -rf "/u/users/login_userid/.ansible/tmp/ansible-tmp-1515438271.05-219108659465262/"
> /dev/null 2>&1'"'"'"'"'"'"'"'"' && sleep 0'"'"''
```
This part is what I caught my attention **sudo su - sudo\_userid -u root**
If I try to run it in the server (copy&paste) it also fails... Why is Ansible adding the "-u root" and is there a way to prevent it from doing so? I will never be granted ROOT access to any server.
Also, I am setting the **ansible\_become\_pass** variable to the correct value... but it still fails.
By the way, I check several bugs reported to Ansible (like <https://github.com/ansible/ansible/issues/23921>), and my error is similar, but their work-arounds don't work with my case.
Any help will be much appreciated!!
|
2017/12/13
|
[
"https://Stackoverflow.com/questions/47799275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803228/"
] |
I have finally found a work-around for my problem, and I'm sharing this answer in case someone finds it useful.
Ansible become module is great, but for my company it is not working. As I explained in the question, it is adding a "**-u root**" at the end of the sudo, which makes the whole command to fail.
I was able to make it work with the following snippet:
```
- name: Create empty file as sudo_userid
command: "sudo su - sudo_userid -c 'touch touchedFile.txt'"
```
I did several tests, and all of them worked! I didn't even got an Ansible warning!
So, cheers everyone!
|
This playbook works for me in ansible 2.4 for your limited test case, I'm not sure how well it would work against larger / more complex tasks or modules. It basically just works around your site's dzdo/sudo limitations.
```
---
- hosts: 127.0.0.1
become: yes
become_method: dzdo
become_flags: "su - root -c"
gather_facts: no
tasks:
- name: Create empty file
file: path=touchedFile.txt state=touch
```
|
12,113,498
|
I'm trying to take the dot product of two lil\_matrix sparse matrices that are approx. 100,000 x 50,000 and 50,000 x 100,000 respectively.
```
from scipy import sparse
a = sparse.lil_matrix((100000, 50000))
b = sparse.lil_matrix((50000, 100000))
c = a.dot(b)
```
and getting this error:
```
File "/usr/lib64/python2.6/site-packages/scipy/sparse/base.py", line 211, in dot
return self * other
File "/usr/lib64/python2.6/site-packages/scipy/sparse/base.py", line 247, in __mul__
return self._mul_sparse_matrix(other)
File "/usr/lib64/python2.6/site-packages/scipy/sparse/base.py", line 300, in _mul_sparse_matrix
return self.tocsr()._mul_sparse_matrix(other)
File "/usr/lib64/python2.6/site-packages/scipy/sparse/compressed.py", line 290, in _mul_sparse_matrix
indices = np.empty(nnz, dtype=np.intc)
ValueError: negative dimensions are not allowed
```
Any ideas on what might be happening - running this on a machine with about 64GB of ram, and using about 13GB when executing the dot.
|
2012/08/24
|
[
"https://Stackoverflow.com/questions/12113498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623172/"
] |
This is a bad error message, but the "problem" quite simply is that your resulting matrix would be too big (has too many nonzero elements, not its dimension).
Scipy uses `int32` to store `indptr` and `indices` for the sparse formats. This means that your sparsematrix cannot have more then (approximatly) 2^31 nonzero elements. Maybe you could change the code in scipy to use `int64` or `uint32`, if this is not just a toy problem anyways. But maybe the use of sparse matrixes is not the best solution for solving this anyways?
**EDIT:** This is solved in the new scipy versions AFIAK.
|
Just to add to @seberg's answer.
There are two issues related to this on github.com/scipy/scipy.
[Issue #1833](https://github.com/scipy/scipy/issues/1833#ref-issue-13651914) (marked closed April 2013) and [Issue #442](https://github.com/scipy/scipy/pull/442) with some pull requests that haven't been merged (Nov 2013 - SciPy version 0.13.1) due to some missing tests etc. You should be able to pull those into your own installation and compile a version that supports larger sparse matrices.
|
32,369,147
|
I want to get the url of the link of tag. I have attached the class of the element to type selenium.webdriver.remote.webelement.WebElement in python:
```
elem = driver.find_elements_by_class_name("_5cq3")
```
and the html is:
```
<div class="_5cq3" data-ft="{"tn":"E"}">
<a class="_4-eo" href="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1" rel="theater" ajaxify="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1&src=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-xfp1%2Ft31.0-8%2F11894571_10153954245456840_9038620401603938613_o.jpg&smallsrc=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-prn2%2Fv%2Ft1.0-9%2F11903991_10153954245456840_9038620401603938613_n.jpg%3Foh%3D0c837ce6b0498cd833f83cfbaeb577e7%26oe%3D567D8819&size=651%2C1000&fbid=10153954245456840&player_origin=profile" style="width:256px;">
<div class="uiScaledImageContainer _4-ep" style="width:256px;height:394px;" id="u_jsonp_2_r">
<img class="scaledImageFitWidth img" src="https://fbcdn-photos-h-a.akamaihd.net/hphotos-ak-prn2/v/t1.0-0/s526x395/11903991_10153954245456840_9038620401603938613_n.jpg?oh=15f59e964665efe28943d12bd00cefd9&oe=5667BDBA&__gda__=1448928574_a7c6da855842af4c152c2fdf8096e1ef" alt="9GAG's photo." width="256" height="395">
</div>
</a>
</div>
```
I want the href value of the a tag falling inside the class `_5cq3`.
|
2015/09/03
|
[
"https://Stackoverflow.com/questions/32369147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159284/"
] |
Why not do it directly?
```
url = driver.find_element_by_class_name("_4-eo").get_attribute("href")
```
And if you need the div element first you can do it this way:
```
divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")
```
or another way via xpath (given that there is only one link element inside your 5cq3 Elements:
```
url = driver.find_element_by_xpath("//div[@class='_5cq3']/a").get_attribute("href")
```
|
You can use xpath for same
If you want to take href of "a" tag, 2nd line according to your HTML code then use
```
url = driver.find_element_by_xpath("//div[@class='_5cq3']/a[@class='_4-eo']").get_attribute("href")
```
If you want to take href of "img" tag, 4nd line according to your HTML code then use
```
url = driver.find_element_by_xpath("//div[@class='_5cq3']/a/div/img[@class='scaledImageFitWidth img']").get_attribute("href")
```
|
32,369,147
|
I want to get the url of the link of tag. I have attached the class of the element to type selenium.webdriver.remote.webelement.WebElement in python:
```
elem = driver.find_elements_by_class_name("_5cq3")
```
and the html is:
```
<div class="_5cq3" data-ft="{"tn":"E"}">
<a class="_4-eo" href="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1" rel="theater" ajaxify="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1&src=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-xfp1%2Ft31.0-8%2F11894571_10153954245456840_9038620401603938613_o.jpg&smallsrc=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-prn2%2Fv%2Ft1.0-9%2F11903991_10153954245456840_9038620401603938613_n.jpg%3Foh%3D0c837ce6b0498cd833f83cfbaeb577e7%26oe%3D567D8819&size=651%2C1000&fbid=10153954245456840&player_origin=profile" style="width:256px;">
<div class="uiScaledImageContainer _4-ep" style="width:256px;height:394px;" id="u_jsonp_2_r">
<img class="scaledImageFitWidth img" src="https://fbcdn-photos-h-a.akamaihd.net/hphotos-ak-prn2/v/t1.0-0/s526x395/11903991_10153954245456840_9038620401603938613_n.jpg?oh=15f59e964665efe28943d12bd00cefd9&oe=5667BDBA&__gda__=1448928574_a7c6da855842af4c152c2fdf8096e1ef" alt="9GAG's photo." width="256" height="395">
</div>
</a>
</div>
```
I want the href value of the a tag falling inside the class `_5cq3`.
|
2015/09/03
|
[
"https://Stackoverflow.com/questions/32369147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159284/"
] |
Why not do it directly?
```
url = driver.find_element_by_class_name("_4-eo").get_attribute("href")
```
And if you need the div element first you can do it this way:
```
divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")
```
or another way via xpath (given that there is only one link element inside your 5cq3 Elements:
```
url = driver.find_element_by_xpath("//div[@class='_5cq3']/a").get_attribute("href")
```
|
Use:
1)
`xpath` to specify the path to the `href` first.
```
x = '//a[@class="_4-eo"]'
k = driver.find_elements_by_xpath(x).get_attribute("href")
for url in k:
print url
```
2) Use @drkthng's solution(the simplest).
3)You can use:
```
parentElement = driver.find_elements_by_class("_4-eo")
elementList = parentElement.find_elements_by_tag_name("href")
```
You can use whatever you want in Selenium. there are 2-3 more ways to find the same.
And for image `src` use below `xpath`:
```
img_path = '//div[@class="uiScaledImageContainer _4-ep"]//img[@src]'
```
|
23,034,781
|
I am using scrapy 0.20 with python 2.7
According to [scrapy architecture](http://doc.scrapy.org/en/latest/topics/architecture.html), the spider sends requests to the engine. Then, after the whole crawling process, the item goes through the item pipeline.
So, the item pipeline has nothing to do when the spider opens or closes. Also, item pipeline components can't know when the spider opens or closes. So, how the `open_spider` method exists in item pipeline components according to [this page](http://doc.scrapy.org/en/latest/topics/item-pipeline.html#writing-your-own-item-pipeline)?
|
2014/04/12
|
[
"https://Stackoverflow.com/questions/23034781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] |
I had similar problem and then figured it out.
It is possible that all of your left-hand side values (V5) are the same. The error is thrown as a saying that no decision can be made as it is too easy.
My source: <http://kleinfelter.com/learning-r-painful-r-learnings>
|
After removing all 'NA', the problem has gone. Also, the first column has to be index column.
|
10,145,201
|
We moved our SQL Server 2005 database to a new physical server, and since then it has been terminating any connection that persist for 30 seconds.
We are experiencing this in Oracle SQL developer and when connecting from python using pyodbc
Everything worked perfectly before, and now python returns this error after 30 seconds:
('08S01', '[08S01] [FreeTDS][SQL Server]Read from the server failed (20004) (SQLExecDirectW)')
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10145201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931235/"
] |
First of all what you need is profile the sql server to see if any activity is happening. Look for slow running queries, CPU and memory bottlenecks.
Also you can include the timeout in the querystring like this:
"Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;Connection Timeout=30";
and extend that number if you want.
But remember "timeout" doesn't means time connection, this is just the time to wait while trying to establish a connection before terminating.
I think this problem is more about database performance or maybe a network issue.
|
Maybe check your remote query timeout? It should default to 600, but maybe it's set to 30? [Info here](http://msdn.microsoft.com/en-us/library/ms189040%28v=sql.90%29.aspx)
|
18,921,141
|
I keep getting an error that there's no such module.
The project name is gmblnew, and I have two subfolders- `core` and `gmblnew` - the app I'm working on is core.
My **urls.py** file is
```
from django.conf.urls import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gmblnew.views.home', name='home'),
# url(r'^gmblnew/', include('gmblnew.foo.urls')),
url(r'^league/', include('core.views.league')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
```
This seems to be fine. The **views.py** file is:
```
from django.http import HttpResponse
def league(request):
from core.models import Division
response = HttpResponse()
response['mimetype'] = 'text/plain'
response.write("<HTML><>BODY>\n")
response.write("< TABLE BORDER=1><CAPTION>League List</CAPTION><TR>\n")
all_leagues = Division.objects.all()
for league in all_leagues:
response.write("<TR>\n")
response.write("<TD> %s" % league)
response.write("</TD>\n")
response.write("</BODY></HTML>")
return response
```
Traceback:
```
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
103. resolver_match = resolver.resolve(request.path_info)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
319. for pattern in self.url_patterns:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
347. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
342. self._urlconf_module = import_module(self.urlconf_name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
File "/Users/chris/Dropbox/Django/gmblnew/gmblnew/urls.py" in <module>
12. url(r'^league/', include('core.views.league')),
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include
25. urlconf_module = import_module(urlconf_module)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
Exception Type: ImportError at /admin/
Exception Value: No module named league
```
I've tried a number of variants on the `url(r'^league/', include('core.views.league')),` line, including `gmblnew.core.views.league`, `views.league`, `views.view_league`, etc. I'm obviously missing something super simple on the structure of that line.
|
2013/09/20
|
[
"https://Stackoverflow.com/questions/18921141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293222/"
] |
Your problem is here:
```
url(r'^league/', include('core.views.league')),
```
By using `include` you are specifying a module, which does not exist.
[`include` is used to include other url confs](https://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs), and not to target view methods
What you want is refer to the view method `league`
```
url(r'^league/$', 'core.views.league'),
```
should work.
Also, note the `$` after `^league/` , which represents the *end* of the URL pattern.
|
`include` takes a path to a url file, not a view. Just write this instead:
```
url(r'^league/', 'core.views.league'),
```
|
8,575,713
|
I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
printFoo()
```
the result of `python test.py` is `Bar`.
How to mock the `printBar` to make it return `Foo` so that `printFoo` will print it?
EDIT: Without modifying any other file that `test.py`
|
2011/12/20
|
[
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] |
I'm guessing you are going to mock the function `returnBar`, you'd like to use [`patch` decorator](http://www.voidspace.org.uk/python/mock/patch.html):
```
from mock import patch
from foo import printFoo
@patch('foo.returnBar')
def test_printFoo(mockBar):
mockBar.return_value = 'Foo'
printFoo()
test_printFoo()
```
|
Just import the `bar` module before the `foo` module and mock it:
```
from mock import Mock
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
from foo import printFoo
printFoo()
```
When you are importing the `returnBar` in `foo.py`, you are binding the value of the module to a variable called `returnBar`. This variable is local so is put in the closure of the `printFoo()` function when `foo` is imported - and the values in the closure cannot be updated by code from outiside it. So, it should have the new value (that is, the mocking function) *before* the importing of `foo`.
**EDIT**: the previous solution workis but is not robust since it depends on ordering the imports. That is not much ideal. Another solution (that occurred me after the first one) is to import the `bar` module in `foo.py` instead of only import the `returnBar()` function:
```
from dirBar import bar
def printFoo():
print bar.returnBar()
```
This will work because the `returnBar()` is now retrieved directly from the `bar` module instead of the closure. So if I update the module, the new function will be retrieved.
|
8,575,713
|
I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
printFoo()
```
the result of `python test.py` is `Bar`.
How to mock the `printBar` to make it return `Foo` so that `printFoo` will print it?
EDIT: Without modifying any other file that `test.py`
|
2011/12/20
|
[
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] |
Just import the `bar` module before the `foo` module and mock it:
```
from mock import Mock
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
from foo import printFoo
printFoo()
```
When you are importing the `returnBar` in `foo.py`, you are binding the value of the module to a variable called `returnBar`. This variable is local so is put in the closure of the `printFoo()` function when `foo` is imported - and the values in the closure cannot be updated by code from outiside it. So, it should have the new value (that is, the mocking function) *before* the importing of `foo`.
**EDIT**: the previous solution workis but is not robust since it depends on ordering the imports. That is not much ideal. Another solution (that occurred me after the first one) is to import the `bar` module in `foo.py` instead of only import the `returnBar()` function:
```
from dirBar import bar
def printFoo():
print bar.returnBar()
```
This will work because the `returnBar()` is now retrieved directly from the `bar` module instead of the closure. So if I update the module, the new function will be retrieved.
|
Another way to deal with those case is to use some dependency injection.
An easy way to do it in python is to use the magical `**kwargs` :
foo.py
```
from dirBar.bar import returnBar
def printFoo(**kwargs):
real_returnBar = kwargs.get("returnBar", returnBar)
print real_returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dirBar import bar
mocked_returnBar = Mock(return_value='Foo')
printFoo(returnBar=mocked_returnBar)
```
this will lead to a more testable code (and increase modularity/reusability).
|
8,575,713
|
I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
printFoo()
```
the result of `python test.py` is `Bar`.
How to mock the `printBar` to make it return `Foo` so that `printFoo` will print it?
EDIT: Without modifying any other file that `test.py`
|
2011/12/20
|
[
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] |
I'm guessing you are going to mock the function `returnBar`, you'd like to use [`patch` decorator](http://www.voidspace.org.uk/python/mock/patch.html):
```
from mock import patch
from foo import printFoo
@patch('foo.returnBar')
def test_printFoo(mockBar):
mockBar.return_value = 'Foo'
printFoo()
test_printFoo()
```
|
Another way to deal with those case is to use some dependency injection.
An easy way to do it in python is to use the magical `**kwargs` :
foo.py
```
from dirBar.bar import returnBar
def printFoo(**kwargs):
real_returnBar = kwargs.get("returnBar", returnBar)
print real_returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dirBar import bar
mocked_returnBar = Mock(return_value='Foo')
printFoo(returnBar=mocked_returnBar)
```
this will lead to a more testable code (and increase modularity/reusability).
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get install libav-tools
```
|
Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
```
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get install libav-tools
```
|
If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb`
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get install libav-tools
```
|
```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04*
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get install libav-tools
```
|
I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can always try both if the one doesn't work.
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
```
|
If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb`
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04*
|
Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
```
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
```
|
I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can always try both if the one doesn't work.
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04*
|
If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb`
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can always try both if the one doesn't work.
|
If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb`
|
29,454,002
|
I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
When i run this program, it says:
```
*/usr/bin/python3.4 /home/rajendra/PycharmProjects/pythonProject5/myProgram.py
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:161: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
/usr/local/lib/python3.4/dist-packages/pydub/utils.py:174: RuntimeWarning: Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
warn("Couldn't find ffplay or avplay - defaulting to ffplay, but may not work", RuntimeWarning)
Traceback (most recent call last):
File "/home/rajendra/PycharmProjects/pythonProject5/myProgram.py", line 11, in <module>
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 355, in from_mp3
return cls.from_file(file, 'mp3')
File "/usr/local/lib/python3.4/dist-packages/pydub/audio_segment.py", line 339, in from_file
retcode = subprocess.call(convertion_command, stderr=open(os.devnull))
File "/usr/lib/python3.4/subprocess.py", line 533, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg'
Process finished with exit code 1*
```
Please help me! I've checked everything path but it's not working. I'm currently using Ubuntu.
Help would be appreciated!
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] |
```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04*
|
I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can always try both if the one doesn't work.
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.tolist() + ['a'] for ary in np.split(lst, np.where(np.array(lst) == 'a')[0])[1:-1]]
```
Output:
```
[['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.tolist() + ['a'] for ary in np.split(lst, np.where(np.array(lst) == 'a')[0])[1:-1]]
```
Output:
```
[['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
Firstly you can store the indices of `'a'` from the list.
```
oList = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
idx_a = list()
for idx, char in enumerate(oList):
if char == 'a':
idx_a.append(idx)
```
Then for every consecutive indices you can get the sub-list and store it in a list
```
ans = [oList[idx_a[x]:idx_a[x + 1] + 1] for x in range(len(idx_a))]
```
You can also get more such lists if you take in-between indices also.
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.tolist() + ['a'] for ary in np.split(lst, np.where(np.array(lst) == 'a')[0])[1:-1]]
```
Output:
```
[['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
You can do this with a single iteration and a simple state machine:
```
original_list = list('kabcadeabefjacab')
multiple_lists = []
for c in original_list:
if multiple_lists:
multiple_lists[-1].append(c)
if c == 'a':
multiple_lists.append([c])
if multiple_lists[-1][-1] != 'a':
multiple_lists.pop()
print(multiple_lists)
```
```
[['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.tolist() + ['a'] for ary in np.split(lst, np.where(np.array(lst) == 'a')[0])[1:-1]]
```
Output:
```
[['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
We can use `str.split()` to split the list once we `str.join()` it to a string, and then use a f-string to add back the stripped "a"s. Note that even if the list starts/ends with an "a", this the split list will have an empty string representing the substring before the split, so our unpacking logic that discards the first + last subsequences will still work as intended.
```py
def split(data):
_, *subseqs, _ = "".join(data).split("a")
return [list(f"a{seq}a") for seq in subseqs]
```
Output:
```py
>>> from pprint import pprint
>>> testdata = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
>>> pprint(split(testdata))
[['a', 'b', 'c', 'a'],
['a', 'd', 'e', 'a'],
['a', 'b', 'e', 'f', 'j', 'a'],
['a', 'c', 'a']]
```
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
Firstly you can store the indices of `'a'` from the list.
```
oList = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
idx_a = list()
for idx, char in enumerate(oList):
if char == 'a':
idx_a.append(idx)
```
Then for every consecutive indices you can get the sub-list and store it in a list
```
ans = [oList[idx_a[x]:idx_a[x + 1] + 1] for x in range(len(idx_a))]
```
You can also get more such lists if you take in-between indices also.
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
You can do this with a single iteration and a simple state machine:
```
original_list = list('kabcadeabefjacab')
multiple_lists = []
for c in original_list:
if multiple_lists:
multiple_lists[-1].append(c)
if c == 'a':
multiple_lists.append([c])
if multiple_lists[-1][-1] != 'a':
multiple_lists.pop()
print(multiple_lists)
```
```
[['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
70,375,415
|
For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a list of lists. I have tried a double for loop approach with `'a'` as the condition, but this is inefficient and not pythonic.
|
2021/12/16
|
[
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] |
One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
```
|
We can use `str.split()` to split the list once we `str.join()` it to a string, and then use a f-string to add back the stripped "a"s. Note that even if the list starts/ends with an "a", this the split list will have an empty string representing the substring before the split, so our unpacking logic that discards the first + last subsequences will still work as intended.
```py
def split(data):
_, *subseqs, _ = "".join(data).split("a")
return [list(f"a{seq}a") for seq in subseqs]
```
Output:
```py
>>> from pprint import pprint
>>> testdata = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
>>> pprint(split(testdata))
[['a', 'b', 'c', 'a'],
['a', 'd', 'e', 'a'],
['a', 'b', 'e', 'f', 'j', 'a'],
['a', 'c', 'a']]
```
|
55,697,976
|
I have this input `<input type="file" id="file" name="file" accept="image/*" multiple>` this allow the user select several images and I need to pass all of them to my `FormData` so I do this:
```
var formdata = new FormData();
var files = $('#file')[0].files[0];
formdata.append('file',files);
```
But that only take the first image from de list, How can i take all the images and store all of them in `var files`?
Thanks in advance
**EDIT:** The backend I use is `django/python` and if I use this way in my backend detect only one image from the list like this `[<InMemoryUploadedFile: img.png (image/png)>]` and using just `var files = $('#file')[0].files;` show me nothing.
|
2019/04/15
|
[
"https://Stackoverflow.com/questions/55697976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5727540/"
] |
There are many problems:
1. You can't redeclare the same variable if you want to keep its previous values
2. You need to change the index so that it's not saving to the same spot
3. $("#file") - shouldn't be an array, it's an object so i'm surprised it's not throwing an error
Let's say your code is legit. You could do this:
```
var files=[];
var length = $("#file").length;
for (i = 0; i < length; i++) {
files[i] = $('#file')[i];
}
formdata.append('file',files);
```
|
This was my solution
```
var formdata = new FormData();
var files=[];
var count = document.getElementById('file').files.length;
for (i = 0; i < cont; i++) {
files[i] = document.getElementById('file').files[i];
formdata.append('file',files[i]);
}
```
Using `JQuery` for length only brings me 1 element and gives me more problems so
I use puere `JavaScript` for this part and works fine
|
6,965,431
|
I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` using `--dump_request` and found the `authorization: OAuth XXX` header. Adding that token to my own requested worked, but the token seems to expire periodically (possibly daily), and I can't figure out how to re-generate it. For that matter, gtaskqueue\_sample itself no longer works (the call to `https://accounts.google.com/o/oauth2/token` fails with `No JSON object could be decoded`).
How does one take care of authentication? This is a server app so ideally I could generate a token that I could use from then on.
|
2011/08/06
|
[
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
These APIS work only for GAE server since the queues can be created only via queue.yaml and infact API does not expose any API for inserting queue and tasks or project.
|
The pull queues page has a [whole section](http://code.google.com/appengine/docs/python/taskqueue/overview-pull.html#Pulling_Tasks_from_Outside_App_Engine) about client libraries and sample code.
|
6,965,431
|
I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` using `--dump_request` and found the `authorization: OAuth XXX` header. Adding that token to my own requested worked, but the token seems to expire periodically (possibly daily), and I can't figure out how to re-generate it. For that matter, gtaskqueue\_sample itself no longer works (the call to `https://accounts.google.com/o/oauth2/token` fails with `No JSON object could be decoded`).
How does one take care of authentication? This is a server app so ideally I could generate a token that I could use from then on.
|
2011/08/06
|
[
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
This question is old, but it still applies, so I am going to attempt a better answer based on my recent experience.
It is possible to access pull task queues outside of appengine but as the asker stated, there are no good examples, so here is a more in depth guide. In my case I had a custom python script that needed to poll the queue for new jobs to run.
Before taking this route, you also have the option of rolling your own security and making a simple web wrapper to the appengine taskqueue calls. I was tempted to go that route after dealing with this, but since this is working I'm using it for now.
**Setup Your Machine**
* pip install --upgrade [google-api-python-client](https://developers.google.com/api-client-library/python/)
* easy\_install python-gflags
**Setup Your Account**
* Using [Google Cloud Console](https://cloud.google.com/console), create a Registered App (if you don't already have one. Click on your AppEngine project -> API's and auth -> Registered Apps. You can enter a name and application type and then accept the defaults. Once it is created, note the Client Id and Client Secret for later.
* Also Update your Consent Screen (API's and auth -> Consent Screen). Note that you will only need this consent screen to setup your oauth credentials for the first time. You will need to enter Email Address and a Product Name (I entered a HomePage Url also).
**Generate OAuth Credentials**
* You only need to generate a credentials file once, then it will be used for future calls in your python script. Run this python code which opens a browser and generates the credential file. A reference for this code is [here](https://developers.google.com/api-client-library/python/guide/aaa_oauth#acquiring).
```
from oauth2client.tools import run
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
import gflags
FLAGS = gflags.FLAGS
storage = Storage('credentials.json')
flow = OAuth2WebServerFlow(client_id='<your_client_id>',
client_secret='<your_client_secret>',
scope='https://www.googleapis.com/auth/taskqueue',
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
credentials = run(flow, storage )
```
**Make Your Taskqueue Calls**
* Make sure you have added a pull queue in your AppEngine [queue.yaml](https://developers.google.com/appengine/docs/python/config/queue#Python_Defining_pull_queues), with the email address you used in the oauth step above.
```
from oauth2client.tools import run
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
from apiclient.discovery import build
import httplib2
storage = Storage('credentials.json')
credentials = storage.get()
http = httplib2.Http()
http = credentials.authorize(http)
task_api = build('taskqueue', 'v1beta2')
tasks = task_api.tasks().lease(project='<your appengine project>',taskqueue='<pull queue name>', numTasks=1, leaseSecs=600).execute(http=http)
task = tasks['items'][0]
payload = task['payloadBase64']
payload = base64.b64decode(payload)
#then do your work and delete the task when done
task_api.tasks().delete(project='s~<your appengine project>',taskqueue='<pull queue name>', task=task['id']).execute(http=http)
```
* Task Queue [API Reference](https://developers.google.com/resources/api-libraries/documentation/taskqueue/v1beta2/python/latest/)
* Note the prefix 's~' in front of the project name in the delete call. It would only work if I added this and I believe it is a [bug](http://code.google.com/p/google-api-python-client/issues/detail?id=308).
---
**Update 7/1/2014**
So there is actually an easier way to make server to server calls. This way doesn't require you using the "flow" (logging on to google) to get an access key.
**Setup Your Machine**
* pip install --upgrade [google-api-python-client](https://developers.google.com/api-client-library/python/)
* pip install pyOpenSSL
**Setup Your Account**
* Using [Google Cloud Console](https://cloud.google.com/console), create a Registered App (if you don't already have one. Click on your AppEngine project -> API's & Auth -> Credentials. Click Create New Client ID, specify Service Account, then click Create Client ID.
A download box will pop up to download your private key, save this to your code directory (or wherever, I saved as client\_key.p12). On the web interface, note the Client ID and Email.
**Replace the Credential Code from Above**
```
from oauth2client.client import SignedJwtAssertionCredentials
email = '<***>.gserviceaccount.com'
f = file('client_key.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(email,
key,
scope='https://www.googleapis.com/auth/taskqueue')
```
|
The pull queues page has a [whole section](http://code.google.com/appengine/docs/python/taskqueue/overview-pull.html#Pulling_Tasks_from_Outside_App_Engine) about client libraries and sample code.
|
6,965,431
|
I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` using `--dump_request` and found the `authorization: OAuth XXX` header. Adding that token to my own requested worked, but the token seems to expire periodically (possibly daily), and I can't figure out how to re-generate it. For that matter, gtaskqueue\_sample itself no longer works (the call to `https://accounts.google.com/o/oauth2/token` fails with `No JSON object could be decoded`).
How does one take care of authentication? This is a server app so ideally I could generate a token that I could use from then on.
|
2011/08/06
|
[
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
This question is old, but it still applies, so I am going to attempt a better answer based on my recent experience.
It is possible to access pull task queues outside of appengine but as the asker stated, there are no good examples, so here is a more in depth guide. In my case I had a custom python script that needed to poll the queue for new jobs to run.
Before taking this route, you also have the option of rolling your own security and making a simple web wrapper to the appengine taskqueue calls. I was tempted to go that route after dealing with this, but since this is working I'm using it for now.
**Setup Your Machine**
* pip install --upgrade [google-api-python-client](https://developers.google.com/api-client-library/python/)
* easy\_install python-gflags
**Setup Your Account**
* Using [Google Cloud Console](https://cloud.google.com/console), create a Registered App (if you don't already have one. Click on your AppEngine project -> API's and auth -> Registered Apps. You can enter a name and application type and then accept the defaults. Once it is created, note the Client Id and Client Secret for later.
* Also Update your Consent Screen (API's and auth -> Consent Screen). Note that you will only need this consent screen to setup your oauth credentials for the first time. You will need to enter Email Address and a Product Name (I entered a HomePage Url also).
**Generate OAuth Credentials**
* You only need to generate a credentials file once, then it will be used for future calls in your python script. Run this python code which opens a browser and generates the credential file. A reference for this code is [here](https://developers.google.com/api-client-library/python/guide/aaa_oauth#acquiring).
```
from oauth2client.tools import run
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
import gflags
FLAGS = gflags.FLAGS
storage = Storage('credentials.json')
flow = OAuth2WebServerFlow(client_id='<your_client_id>',
client_secret='<your_client_secret>',
scope='https://www.googleapis.com/auth/taskqueue',
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
credentials = run(flow, storage )
```
**Make Your Taskqueue Calls**
* Make sure you have added a pull queue in your AppEngine [queue.yaml](https://developers.google.com/appengine/docs/python/config/queue#Python_Defining_pull_queues), with the email address you used in the oauth step above.
```
from oauth2client.tools import run
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
from apiclient.discovery import build
import httplib2
storage = Storage('credentials.json')
credentials = storage.get()
http = httplib2.Http()
http = credentials.authorize(http)
task_api = build('taskqueue', 'v1beta2')
tasks = task_api.tasks().lease(project='<your appengine project>',taskqueue='<pull queue name>', numTasks=1, leaseSecs=600).execute(http=http)
task = tasks['items'][0]
payload = task['payloadBase64']
payload = base64.b64decode(payload)
#then do your work and delete the task when done
task_api.tasks().delete(project='s~<your appengine project>',taskqueue='<pull queue name>', task=task['id']).execute(http=http)
```
* Task Queue [API Reference](https://developers.google.com/resources/api-libraries/documentation/taskqueue/v1beta2/python/latest/)
* Note the prefix 's~' in front of the project name in the delete call. It would only work if I added this and I believe it is a [bug](http://code.google.com/p/google-api-python-client/issues/detail?id=308).
---
**Update 7/1/2014**
So there is actually an easier way to make server to server calls. This way doesn't require you using the "flow" (logging on to google) to get an access key.
**Setup Your Machine**
* pip install --upgrade [google-api-python-client](https://developers.google.com/api-client-library/python/)
* pip install pyOpenSSL
**Setup Your Account**
* Using [Google Cloud Console](https://cloud.google.com/console), create a Registered App (if you don't already have one. Click on your AppEngine project -> API's & Auth -> Credentials. Click Create New Client ID, specify Service Account, then click Create Client ID.
A download box will pop up to download your private key, save this to your code directory (or wherever, I saved as client\_key.p12). On the web interface, note the Client ID and Email.
**Replace the Credential Code from Above**
```
from oauth2client.client import SignedJwtAssertionCredentials
email = '<***>.gserviceaccount.com'
f = file('client_key.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(email,
key,
scope='https://www.googleapis.com/auth/taskqueue')
```
|
These APIS work only for GAE server since the queues can be created only via queue.yaml and infact API does not expose any API for inserting queue and tasks or project.
|
18,401,385
|
I'm using Eclipse (on the PyDev perspective), and I just installed (using pip) the python 'requests' module.
Eclipse is giving me an error warning on the 'import requests' line, saying that it is an unresolved import, but I've run it it imports just fine. (But the error message won't go away).
Its really bugging me, and I can't right-click and delete the error either. (The option is gray).
Is there any way to fix this? (Even if it involves manually removing the error?)
I know that there is a similar problem here:
[Eclipse Pydev - Misdiplayed Import Error](https://stackoverflow.com/questions/18301970/eclipse-pydev-misdiplayed-import-error?rq=1)
but the answer to that was that PyDev had a bug specifically with PIL, so that is why I'm asking a different question.
|
2013/08/23
|
[
"https://Stackoverflow.com/questions/18401385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258464/"
] |
Sometimes, PyDev is a little buggy... When it happens, I usually right-click on the folder containing the file in the PyDev Package Explorer, then "PyDev->remove error markers". And then re-run code analysis.
If it still doesn't work, try removing and adding again the directory to your `requests` module to the PyDev Path. As I said, PyDev is a little buggy...
|
You should manually configure properties of you PyDev project.
Right click on your project name, select **PyDev - PYTHONPATH**, then in External Libraries tab press **Add source folder** and choose the root directory of your library.
|
71,792,025
|
My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't find anything.. (im a beginner with this library)
Code:
```
import nextcord
from nextcord.ext import commands
import wavelink
import random
import datetime
from datetime import datetime
import os
bot = commands.Bot(command_prefix=">")
@bot.event
async def on_wavelink_track_end(player:wavelink.Player,track:wavelink.Track,reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
emb = nextcord.Embed(description=f"Now playing {next_song.title}",color=nextcord.Color.magenta())
emb.set_image(url=next_song.thumbnail)
await ctx.send(embed=emb)
@bot.command(aliases=["p"])
async def play(ctx,*,search:wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
embe = nextcord.Embed(description=f"Now playing [{search.title}]({search.uri}) ",color=nextcord.Color.magenta())
embe.set_image(url=search.thumbnail)
await ctx.send(embed=embe)
else:
await vc.queue.put_wait(search)
emb = nextcord.Embed(description=f"Added [{search.title}]({search.uri}) to the queue.",color=nextcord.Color.magenta())
emb.set_image(url=search.thumbnail)
await ctx.send(embed=emb)
vc.ctx = ctx
setattr(vc,"loop",False)
@bot.command()
async def queue(ctx):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
emb = nextcord.Embed(description=f"{ctx.author.mention}: The queue is empty. Try adding songs.",color=nextcord.Color.red())
return await ctx.send(embed=emb)
lp = nextcord.Embed(title="Queue",color=nextcord.Color.blue())
queue = vc.queue.copy()
song_count = 0
for song in queue:
song_count += 1
lp.add_field(name=f"[{song_count}] Song",value=f"{song.title}")
return await ctx.send(embed=lp)
bot.run("TOKEN IS HERE JUST NOT LEAKING IT")
```
Error:
```
Traceback (most recent call last):
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/nextcord/client.py", line 417, in _run_event
await coro(*args, **kwargs)
File "main.py", line 181, in on_wavelink_track_end
song_count += 1
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/wavelink/queue.py", line 212, in get
raise QueueEmpty("No items in the queue.")
wavelink.errors.QueueEmpty: No items in the queue.
```
|
2022/04/08
|
[
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] |
It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement;
const root = createRoot(container)
root.render(
<React.StrictMode>
<h1>ZOO</h1>
</React.StrictMode>
);
}
});
```
|
The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is to be sure that the `createRoot` is called only once on **one DOM element** and after that `root.render(reactElement);` can be used to update and `createRoot` should not be used.
|
71,792,025
|
My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't find anything.. (im a beginner with this library)
Code:
```
import nextcord
from nextcord.ext import commands
import wavelink
import random
import datetime
from datetime import datetime
import os
bot = commands.Bot(command_prefix=">")
@bot.event
async def on_wavelink_track_end(player:wavelink.Player,track:wavelink.Track,reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
emb = nextcord.Embed(description=f"Now playing {next_song.title}",color=nextcord.Color.magenta())
emb.set_image(url=next_song.thumbnail)
await ctx.send(embed=emb)
@bot.command(aliases=["p"])
async def play(ctx,*,search:wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
embe = nextcord.Embed(description=f"Now playing [{search.title}]({search.uri}) ",color=nextcord.Color.magenta())
embe.set_image(url=search.thumbnail)
await ctx.send(embed=embe)
else:
await vc.queue.put_wait(search)
emb = nextcord.Embed(description=f"Added [{search.title}]({search.uri}) to the queue.",color=nextcord.Color.magenta())
emb.set_image(url=search.thumbnail)
await ctx.send(embed=emb)
vc.ctx = ctx
setattr(vc,"loop",False)
@bot.command()
async def queue(ctx):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
emb = nextcord.Embed(description=f"{ctx.author.mention}: The queue is empty. Try adding songs.",color=nextcord.Color.red())
return await ctx.send(embed=emb)
lp = nextcord.Embed(title="Queue",color=nextcord.Color.blue())
queue = vc.queue.copy()
song_count = 0
for song in queue:
song_count += 1
lp.add_field(name=f"[{song_count}] Song",value=f"{song.title}")
return await ctx.send(embed=lp)
bot.run("TOKEN IS HERE JUST NOT LEAKING IT")
```
Error:
```
Traceback (most recent call last):
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/nextcord/client.py", line 417, in _run_event
await coro(*args, **kwargs)
File "main.py", line 181, in on_wavelink_track_end
song_count += 1
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/wavelink/queue.py", line 212, in get
raise QueueEmpty("No items in the queue.")
wavelink.errors.QueueEmpty: No items in the queue.
```
|
2022/04/08
|
[
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] |
You're likely importing something from your entrypoint file, causing the entry point file to somehow run twice. I've had the same issue and solved it by making sure I was not importing anything from my entrypoint file.
|
The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is to be sure that the `createRoot` is called only once on **one DOM element** and after that `root.render(reactElement);` can be used to update and `createRoot` should not be used.
|
71,792,025
|
My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't find anything.. (im a beginner with this library)
Code:
```
import nextcord
from nextcord.ext import commands
import wavelink
import random
import datetime
from datetime import datetime
import os
bot = commands.Bot(command_prefix=">")
@bot.event
async def on_wavelink_track_end(player:wavelink.Player,track:wavelink.Track,reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
emb = nextcord.Embed(description=f"Now playing {next_song.title}",color=nextcord.Color.magenta())
emb.set_image(url=next_song.thumbnail)
await ctx.send(embed=emb)
@bot.command(aliases=["p"])
async def play(ctx,*,search:wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
embe = nextcord.Embed(description=f"Now playing [{search.title}]({search.uri}) ",color=nextcord.Color.magenta())
embe.set_image(url=search.thumbnail)
await ctx.send(embed=embe)
else:
await vc.queue.put_wait(search)
emb = nextcord.Embed(description=f"Added [{search.title}]({search.uri}) to the queue.",color=nextcord.Color.magenta())
emb.set_image(url=search.thumbnail)
await ctx.send(embed=emb)
vc.ctx = ctx
setattr(vc,"loop",False)
@bot.command()
async def queue(ctx):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
emb = nextcord.Embed(description=f"{ctx.author.mention}: The queue is empty. Try adding songs.",color=nextcord.Color.red())
return await ctx.send(embed=emb)
lp = nextcord.Embed(title="Queue",color=nextcord.Color.blue())
queue = vc.queue.copy()
song_count = 0
for song in queue:
song_count += 1
lp.add_field(name=f"[{song_count}] Song",value=f"{song.title}")
return await ctx.send(embed=lp)
bot.run("TOKEN IS HERE JUST NOT LEAKING IT")
```
Error:
```
Traceback (most recent call last):
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/nextcord/client.py", line 417, in _run_event
await coro(*args, **kwargs)
File "main.py", line 181, in on_wavelink_track_end
song_count += 1
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/wavelink/queue.py", line 212, in get
raise QueueEmpty("No items in the queue.")
wavelink.errors.QueueEmpty: No items in the queue.
```
|
2022/04/08
|
[
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] |
I don't know if it's a good way, but you might consider to pass created root as properties (`props`) to the target component to get rid of the warning.
For example;
in the **index.js**
```
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// pass created root as a property
<App root={root}/>
</React.StrictMode>
);
```
in the **App.js**
```
function App(props) {
function renderNewPage() {
const newContent =
<div className="text-center">
<p>This is a new page.</p>
</div>;
// use previously created root here
props.root.render(
newContent
);
}
return (
<div>
<button onClick={renderNewPage}>Click to render new page</button>
</div>
);
);
}
```
|
The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is to be sure that the `createRoot` is called only once on **one DOM element** and after that `root.render(reactElement);` can be used to update and `createRoot` should not be used.
|
71,792,025
|
My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't find anything.. (im a beginner with this library)
Code:
```
import nextcord
from nextcord.ext import commands
import wavelink
import random
import datetime
from datetime import datetime
import os
bot = commands.Bot(command_prefix=">")
@bot.event
async def on_wavelink_track_end(player:wavelink.Player,track:wavelink.Track,reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
emb = nextcord.Embed(description=f"Now playing {next_song.title}",color=nextcord.Color.magenta())
emb.set_image(url=next_song.thumbnail)
await ctx.send(embed=emb)
@bot.command(aliases=["p"])
async def play(ctx,*,search:wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
embe = nextcord.Embed(description=f"Now playing [{search.title}]({search.uri}) ",color=nextcord.Color.magenta())
embe.set_image(url=search.thumbnail)
await ctx.send(embed=embe)
else:
await vc.queue.put_wait(search)
emb = nextcord.Embed(description=f"Added [{search.title}]({search.uri}) to the queue.",color=nextcord.Color.magenta())
emb.set_image(url=search.thumbnail)
await ctx.send(embed=emb)
vc.ctx = ctx
setattr(vc,"loop",False)
@bot.command()
async def queue(ctx):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
emb = nextcord.Embed(description=f"{ctx.author.mention}: The queue is empty. Try adding songs.",color=nextcord.Color.red())
return await ctx.send(embed=emb)
lp = nextcord.Embed(title="Queue",color=nextcord.Color.blue())
queue = vc.queue.copy()
song_count = 0
for song in queue:
song_count += 1
lp.add_field(name=f"[{song_count}] Song",value=f"{song.title}")
return await ctx.send(embed=lp)
bot.run("TOKEN IS HERE JUST NOT LEAKING IT")
```
Error:
```
Traceback (most recent call last):
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/nextcord/client.py", line 417, in _run_event
await coro(*args, **kwargs)
File "main.py", line 181, in on_wavelink_track_end
song_count += 1
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/wavelink/queue.py", line 212, in get
raise QueueEmpty("No items in the queue.")
wavelink.errors.QueueEmpty: No items in the queue.
```
|
2022/04/08
|
[
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] |
It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement;
const root = createRoot(container)
root.render(
<React.StrictMode>
<h1>ZOO</h1>
</React.StrictMode>
);
}
});
```
|
You're likely importing something from your entrypoint file, causing the entry point file to somehow run twice. I've had the same issue and solved it by making sure I was not importing anything from my entrypoint file.
|
71,792,025
|
My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't find anything.. (im a beginner with this library)
Code:
```
import nextcord
from nextcord.ext import commands
import wavelink
import random
import datetime
from datetime import datetime
import os
bot = commands.Bot(command_prefix=">")
@bot.event
async def on_wavelink_track_end(player:wavelink.Player,track:wavelink.Track,reason):
ctx = player.ctx
vc: player = ctx.voice_client
if vc.loop:
return await vc.play(track)
next_song = vc.queue.get()
await vc.play(next_song)
emb = nextcord.Embed(description=f"Now playing {next_song.title}",color=nextcord.Color.magenta())
emb.set_image(url=next_song.thumbnail)
await ctx.send(embed=emb)
@bot.command(aliases=["p"])
async def play(ctx,*,search:wavelink.YouTubeTrack):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty and vc.is_playing:
await vc.play(search)
embe = nextcord.Embed(description=f"Now playing [{search.title}]({search.uri}) ",color=nextcord.Color.magenta())
embe.set_image(url=search.thumbnail)
await ctx.send(embed=embe)
else:
await vc.queue.put_wait(search)
emb = nextcord.Embed(description=f"Added [{search.title}]({search.uri}) to the queue.",color=nextcord.Color.magenta())
emb.set_image(url=search.thumbnail)
await ctx.send(embed=emb)
vc.ctx = ctx
setattr(vc,"loop",False)
@bot.command()
async def queue(ctx):
if not ctx.voice_client:
vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
elif not getattr(ctx.author.voice,"channel",None):
embed=nextcord.Embed(description=f"{ctx.author.mention}: No song(s) are playing.",color=nextcord.Color.blue())
return await ctx.send(embed=embed)
else:
vc:wavelink.Player = ctx.voice_client
if vc.queue.is_empty:
emb = nextcord.Embed(description=f"{ctx.author.mention}: The queue is empty. Try adding songs.",color=nextcord.Color.red())
return await ctx.send(embed=emb)
lp = nextcord.Embed(title="Queue",color=nextcord.Color.blue())
queue = vc.queue.copy()
song_count = 0
for song in queue:
song_count += 1
lp.add_field(name=f"[{song_count}] Song",value=f"{song.title}")
return await ctx.send(embed=lp)
bot.run("TOKEN IS HERE JUST NOT LEAKING IT")
```
Error:
```
Traceback (most recent call last):
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/nextcord/client.py", line 417, in _run_event
await coro(*args, **kwargs)
File "main.py", line 181, in on_wavelink_track_end
song_count += 1
File "/home/runner/Solved-Music/venv/lib/python3.8/site-packages/wavelink/queue.py", line 212, in get
raise QueueEmpty("No items in the queue.")
wavelink.errors.QueueEmpty: No items in the queue.
```
|
2022/04/08
|
[
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] |
It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement;
const root = createRoot(container)
root.render(
<React.StrictMode>
<h1>ZOO</h1>
</React.StrictMode>
);
}
});
```
|
I don't know if it's a good way, but you might consider to pass created root as properties (`props`) to the target component to get rid of the warning.
For example;
in the **index.js**
```
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// pass created root as a property
<App root={root}/>
</React.StrictMode>
);
```
in the **App.js**
```
function App(props) {
function renderNewPage() {
const newContent =
<div className="text-center">
<p>This is a new page.</p>
</div>;
// use previously created root here
props.root.render(
newContent
);
}
return (
<div>
<button onClick={renderNewPage}>Click to render new page</button>
</div>
);
);
}
```
|
51,539,051
|
I'm actually trying to send pictures(.jpg) saved on a directory of my computer to a FTP server with a python script and ftplib .
The path where are the images is : "D:/directory\_image".
I use python 2.7 and the command .storbinary from ftplib to send .jpg.
Despite my search, I get an error message that I can't resolve :
```
`AttributeError: 'str' object has no attribute 'storbinary'
```
Here's the part of my code that cause problems :
```
from ftplib import FTP
import time
import os
ftp = FTP('Host')
connect= ftp.login('user', 'passwd')
path = "D:/directory_image"
FichList = os.listdir( path )
i = len(FichList)
u = 0
While u < i :
image_name= FichList[u]
jpg_to_send = path + '/' + image_name
file_open = open (image_name, 'rb')
connect.storbinary('STOR '+ jpg_to_send, file_open)
file_open.close()
u = u + 1
```
I know that the file argument in Storbinary () must be an open file object instead of a string... But it's an open file object in my script, isn't it?
Thanks a lot,
Clara
|
2018/07/26
|
[
"https://Stackoverflow.com/questions/51539051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10138893/"
] |
[`@Transactional` can't work on private method](https://stackoverflow.com/questions/4396284/does-spring-transactional-attribute-work-on-a-private-method) because it's applied using an aspect (using dynamic proxies)
Basically you want the `retrieveAndSaveInformationFromBac()` to be a single unit of work, ie. a transaction.
So annotate it with `@Transactional`.
|
Since you are using `Hibernate` , you can handle this by a property:
```
<property name="hibernate.connection.autocommit">false</property>
```
Then you can commit with the transaction, like
```
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//do stuff and then
tx.commit();
```
|
40,499,481
|
I configured a new debug environment in Visual Studio Code under OS X.
```
{
"name": "Kivy",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "/Applications/Kivy3.app/Contents/Frameworks/python/3.5.0/bin",
"program": "${file}",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
},
```
When it runs, it said **"Error: spawn EACCES"**
I assume this is because my current user doesn't habe the according permission to this folder since it is under the root rather than my user folder.
I tried the 2 methods, nothing works, how to handle it?
1. create a soft link from that folder to my own folder, but still same error
2. sudo VSC, still the same
How to solve this problem?
|
2016/11/09
|
[
"https://Stackoverflow.com/questions/40499481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1321025/"
] |
@Albert Gao,
The path you have specified above doesn't contain the name of the python file. You need to provide the path to the file, include the file name. I believe you need to change it as follows:
`"pythonPath": "/Applications/Kivy3.app/Contents/Frameworks/python/3.5.0/bin/python",`
If that doesn't work, then type the following into your command (terminal) window:
- `which python`
- Next copy that path and paste it into `settings.json`
|
If you are getting the spawn error above while using **OpenOCD** for the Raspberry Pi Pico, make sure that your "**cortex-debug.openocdPath**" in "*settings.json*" is set to "*<Path\_to\_openocd\_executable>***/openocd**" for example:
`"cortex-debug.openocdPath": "/home/vbhunt/pico/openocd/src/openocd", "cortex-debug.gdbPath": "/bin/gdb-multiarch"`
This is a specific instance for the Raspberry Pi Pico of @Albert Gao's excellent answer.
|
24,043,499
|
Could any please help me convert this to python? I don't how to translate the conditional operators from C++ into python?
```
Math.easeInExpo = function (t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
```
|
2014/06/04
|
[
"https://Stackoverflow.com/questions/24043499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461304/"
] |
```
def easeInExpo( t, b, c, d ):
return b if t == 0 else c * pow( 2, 10 * (t/d - 1) ) + b
```
|
Use `if` / `else`:
```
return b if t == 0 else c * pow(2, 10 * (t/d - 1)) +b
```
|
24,043,499
|
Could any please help me convert this to python? I don't how to translate the conditional operators from C++ into python?
```
Math.easeInExpo = function (t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
```
|
2014/06/04
|
[
"https://Stackoverflow.com/questions/24043499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461304/"
] |
```
def easeInExpo( t, b, c, d ):
return b if t == 0 else c * pow( 2, 10 * (t/d - 1) ) + b
```
|
```
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
```
is equivalent to:
```
if (t == 0)
{
return b;
}
else
{
return c * Math.pow(2, 10 * (t/d - 1)) + b;
}
```
Hopefully that's enough to get you started.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.