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
|
|---|---|---|---|---|---|
13,262,575
|
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive.
The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively?
```
from multiprocessing import Process
import time
import random
def timing1():
speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE
sleeptime=36/((random.randint(1,20)+speed)/5)
print (sleeptime)
time.sleep(sleeptime)
input('HERO ACTION')
def timing2():
speed=45
sleeptime=36/((random.randint(1,20)+speed)/5)
print (sleeptime)
time.sleep(sleeptime)
input('FOE ACTION')
if __name__ == '__main__':
p1=Process(target=timing1)
p1.start()
p2=Process(target=timing2)
p2.start()
p1.join()
p2.join()
```
|
2012/11/07
|
[
"https://Stackoverflow.com/questions/13262575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804903/"
] |
For Linux: <http://cristian-radulescu.ro/article/fix-netbeans-big-fonts-on-ubuntu.html>
That post recommends adding
```
--laf Nimbus -J-Dswing.aatext=true -J-Dawt.useSystemAAFontSettings=lcd
```
It certainly works on Ubuntu 12.04. I don't know if the same settings will work for Windows7 (but they could because they are Java settings, not OS settings).
|
A couple fellas (Muzaffar and GucciDiet) beat me to it on this question- but hope this helps someone :)
Below is my solution from 2 other similar questions [here](https://stackoverflow.com/a/65692939/4739826) and [here](https://stackoverflow.com/a/65693001/4739826)
>
> Literally NONE of these worked for me.
>
>
> I am using **NetBeans 11.1** on **Linux**. I found the solution by
> searching the Options menu. The issue was the **IDE Theme**- which has
> an "Override" font size.
>
>
> 1. Tools > Options > Appearance > *Darcula Look And Feel*
> 2. Uncheck *"Override Default fonts by [ Dialog 10 ]"*
> 3. (OR increase the override font to a bigger size)
> 4. Hit OK
> 5. Exit and restart NetBeans!
>
>
> Your environment preferences should be saved for future NetBeans
> sessions!
>
>
> [](https://i.stack.imgur.com/EEG6z.png)
>
>
>
|
13,262,575
|
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive.
The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively?
```
from multiprocessing import Process
import time
import random
def timing1():
speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE
sleeptime=36/((random.randint(1,20)+speed)/5)
print (sleeptime)
time.sleep(sleeptime)
input('HERO ACTION')
def timing2():
speed=45
sleeptime=36/((random.randint(1,20)+speed)/5)
print (sleeptime)
time.sleep(sleeptime)
input('FOE ACTION')
if __name__ == '__main__':
p1=Process(target=timing1)
p1.start()
p2=Process(target=timing2)
p2.start()
p1.join()
p2.join()
```
|
2012/11/07
|
[
"https://Stackoverflow.com/questions/13262575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804903/"
] |
I have a NetBeans plugin called 'UI-Editor' that you can use to customize virtually all Swing Settings (including Font types, sizes, and colors). Go to Tools->Plugins and search for UI-Editor. Or go here: <http://plugins.netbeans.org/plugin/55618/?show=true>
|
A couple fellas (Muzaffar and GucciDiet) beat me to it on this question- but hope this helps someone :)
Below is my solution from 2 other similar questions [here](https://stackoverflow.com/a/65692939/4739826) and [here](https://stackoverflow.com/a/65693001/4739826)
>
> Literally NONE of these worked for me.
>
>
> I am using **NetBeans 11.1** on **Linux**. I found the solution by
> searching the Options menu. The issue was the **IDE Theme**- which has
> an "Override" font size.
>
>
> 1. Tools > Options > Appearance > *Darcula Look And Feel*
> 2. Uncheck *"Override Default fonts by [ Dialog 10 ]"*
> 3. (OR increase the override font to a bigger size)
> 4. Hit OK
> 5. Exit and restart NetBeans!
>
>
> Your environment preferences should be saved for future NetBeans
> sessions!
>
>
> [](https://i.stack.imgur.com/EEG6z.png)
>
>
>
|
13,262,575
|
Making a turn based game using python 3. I want 2 characters (foe & enemy) to attack, pause based on random+speed, then attack again if they are still alive.
The problem I am running into is the time.sleep freezes both modules, not 1 or the other. Any suggestions to make this work effectively?
```
from multiprocessing import Process
import time
import random
def timing1():
speed=60#SPEED IS NORMALLY A KEY FROM LIST, USING 60 FOR EXAMPLE
sleeptime=36/((random.randint(1,20)+speed)/5)
print (sleeptime)
time.sleep(sleeptime)
input('HERO ACTION')
def timing2():
speed=45
sleeptime=36/((random.randint(1,20)+speed)/5)
print (sleeptime)
time.sleep(sleeptime)
input('FOE ACTION')
if __name__ == '__main__':
p1=Process(target=timing1)
p1.start()
p2=Process(target=timing2)
p2.start()
p1.join()
p2.join()
```
|
2012/11/07
|
[
"https://Stackoverflow.com/questions/13262575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1804903/"
] |
`Alt` + `scroll wheel` will increase / decrease the font size of the main code window
|
Go to the bin directory where Netbeans is installed. Generally the defualt is : `C:\Program Files\NetBeans <version>\bin`. Now through Command Prompt start netbeans by: `netbeans --fontsize <fontsize> --console suppress`. By using `--console suppress` you can close the cmd window, without the Netbeans window getting affected.
|
74,327,541
|
FAST CGI IS NOT WORKING PROPERLY IN DJANGO DEPLOYMENT ON IIS WINDOW SERVER
```
HTTP Error 500.0 - Internal Server Error
C:\Users\satish.pal\AppData\Local\Programs\Python\Python310\python.exe - The FastCGI process exited unexpectedly
Most likely causes:
•IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
•IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.
•IIS was not able to process configuration for the Web site or application.
•The authenticated user does not have permission to use this DLL.
•The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.
Things you can try:
•Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account.
•Check the event logs to see if any additional information was logged.
•Verify the permissions for the DLL.
•Install the .NET Extensibility feature if the request is mapped to a managed handler.
•Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here.
Detailed Error Information:
Module
FastCgiModule
Notification
ExecuteRequestHandler
Handler
fastcgiModule
Error Code
0x00000001
Requested URL
http://10.0.0.5:8097/
Physical Path
C:\inetpub\wwwroot\hcm.ariespro.com
Logon Method
Anonymous
Logon User
Anonymous
More Information:
This error means that there was a problem while processing the request. The request was received by the Web server, but during processing a fatal error occurred, causing the 500 error.
View more information »
Microsoft Knowledge Base Articles:
•294807
```
i HAVE TRIED EVERY THIN FROM GIVING APPpOOL PERMITTIONS TO CHANGING VERSIONS OF PYTHON AND WFASTCGI
BUT NOTHING IS WORKING FOR ME
PROJECT IS WORKING JUST FINE ON DJANGO SERVER
I HAVE ALSO DEPLOYED IT USING NGINX AND WAITRESS FROM WINDOYS SERVER BUT I NEED IT TO WORK WITH IIS
PLEASE hELP ME OUT-- AT ANY COST
|
2022/11/05
|
[
"https://Stackoverflow.com/questions/74327541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17904860/"
] |
As I see from your code, whenever you get an image from `imagePickerController` you store it into variable `self.image`. Then whenever you click Done you just upload this `self.image`
Make variable `self.image` can be nil then remember to unset it after uploading successfully
Code will be like this
```swift
var image : UIImage? = nil
@IBAction func updateProfile(_ sender: UIButton) {
uploadPic(arg: true, completion: { (success) -> Void in
if success {
addUrlToFirebaseProfile()
self.image = nil // reset image to nil if success
} else {
}
})
}
```
|
You are setting `self.image` if the user selects a photo.
But you are not *unsetting* `self.image` if the user *doesn't* select a photo. It needs to be set to `nil` (not to an empty `UIImage()`).
|
59,705,956
|
I'm working with `tensorflow-gpu` version `2.0.0` and **I have installed gpu driver and CUDA and cuDNN** (`CUDA version 10.1.243_426` and `cuDNN v7.6.5.32` and I'm using windows!)
When I compile my model or run:
```
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
```
It will print out:
```
2020-01-12 19:56:50.961755: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-01-12 19:56:50.974003: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-01-12 19:56:51.628299: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:
name: GeForce MX150 major: 6 minor: 1 memoryClockRate(GHz): 1.5315
pciBusID: 0000:01:00.0
2020-01-12 19:56:51.636256: I tensorflow/stream_executor/platform/default/dlopen_checker_stub.cc:25] GPU libraries are statically linked, skip dlopen check.
2020-01-12 19:56:51.642106: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1746] Adding visible gpu devices: 0
2020-01-12 19:56:52.386608: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1159] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-01-12 19:56:52.393162: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1165] 0
2020-01-12 19:56:52.396516: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1178] 0: N
2020-01-12 19:56:52.400632: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1304] Created TensorFlow device (/device:GPU:0 with 1356 MB memory) -> physical GPU (device: 0, na
me: GeForce MX150, pci bus id: 0000:01:00.0, compute capability: 6.1)
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 1008745203605650029
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 1422723891
locality {
bus_id: 1
links {
}
}
incarnation: 18036547379173389852
physical_device_desc: "device: 0, name: GeForce MX150, pci bus id: 0000:01:00.0, compute capability: 6.1"
]
```
Which is saying tensorflow is going to use gpu device for sure! But when I run my model, I can see that gpu isn't doing anything!
[](https://i.stack.imgur.com/QDeEL.png)
However you can see that a part of gpu memory is being used and even I can see a gpu activity which is my program!!
[](https://i.stack.imgur.com/cK50D.png)
What's going on?! Am I doing something wrong?! I have searched a lot and have checked a lot of questions in SO but nobody asked such a question!
|
2020/01/12
|
[
"https://Stackoverflow.com/questions/59705956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8342406/"
] |
Taken from the official documentation of TensorFlow.
```
import tensorflow as tf
tf.debugging.set_log_device_placement(True)
# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
```
If you run the code above (which should run on your GPU if your GPU is visible to TensorFlow), then your training will run on TensorFlow.
You must see an output like this one:
>
> Executing op MatMul in device
> /job:localhost/replica:0/task:0/device:GPU:0 tf.Tensor( [[22. 28.]
> [49. 64.]], shape=(2, 2), dtype=float32)
>
>
>
Also, you can see that you have a surge in the dedicated GPU memory usage in the Task Manager --> it appears that your GPU is being used, but for certainty run the code above.
|
Have also noted that Windows Task Manager is not useful for monitoring GPU(dual) activity. Try installing TechPowerUp GPU-Z. (I am running dual NVidia cards). This monitors CPU and GPU activity, power and temperatures.
|
23,968,716
|
I am using the following code to get remote PC CPU percentage of usage witch is slow and loading the remote PC because of SSHing.
```
per=(subprocess.check_output('ssh root@192.168.32.218 nohup python psutilexe.py',stdin=None,stderr=subprocess.STDOUT,shell=True)).split(' ')
print 'CPU %=',float(per[0])
print 'MEM %=',float(per[1])
```
where `psutilexe.py` is as follows:
```
import psutil
print psutil.cpu_percent(), psutil.virtual_memory()[2]
```
Would you please let me know if there is any alternate way to measure remote PC CPU % of usage using Python?
|
2014/05/31
|
[
"https://Stackoverflow.com/questions/23968716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3693882/"
] |
I would suggest taking look at Glances. It's written in python and can also be used for remote server monitoring:
<https://github.com/nicolargo/glances>
Using glances on remote server:
<http://mylinuxbook.com/glances-an-all-in-one-system-monitoring-tool/>
|
You don't need a custom Python script, since you can [have CPU usage directly with `top`](https://stackoverflow.com/a/9229692/240613), (or [with `sysstat`](https://stackoverflow.com/a/9229396/240613), if installed).
Have you **profiled** your app? Is it the custom script which is making it slow, or the SSHing itself? If it's the SSHing, then:
* Consider logging once if you're getting multiple values, or:
* Consider using message queue instead of SSHing: monitored machines will constantly send their CPU usage to a message queue service, which will be listened by the machine which is in charge of gathering the results.
|
23,968,716
|
I am using the following code to get remote PC CPU percentage of usage witch is slow and loading the remote PC because of SSHing.
```
per=(subprocess.check_output('ssh root@192.168.32.218 nohup python psutilexe.py',stdin=None,stderr=subprocess.STDOUT,shell=True)).split(' ')
print 'CPU %=',float(per[0])
print 'MEM %=',float(per[1])
```
where `psutilexe.py` is as follows:
```
import psutil
print psutil.cpu_percent(), psutil.virtual_memory()[2]
```
Would you please let me know if there is any alternate way to measure remote PC CPU % of usage using Python?
|
2014/05/31
|
[
"https://Stackoverflow.com/questions/23968716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3693882/"
] |
I would suggest taking look at Glances. It's written in python and can also be used for remote server monitoring:
<https://github.com/nicolargo/glances>
Using glances on remote server:
<http://mylinuxbook.com/glances-an-all-in-one-system-monitoring-tool/>
|
I had been looking for it for a while and I think WMI does what you need.
[WMI\_Python\_Documentation](https://pypi.org/project/WMI/)
```
import wmi
pc = wmi.WMI('PC_Name')
cpu = pc.Win32_Processor()
for i in cpu:
print (i.LoadPercentage)
```
Hopefully this is what you need.
|
50,547,218
|
Why does the python code below crash my website?
But the code at the very bottom does not crash the website
Here is the code that crashes the website:
```
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('learning_logs.urls')),
]
```
Here is the code that does not crash:
```
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
```
Thank you
|
2018/05/26
|
[
"https://Stackoverflow.com/questions/50547218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9852457/"
] |
You have a space between `url` and `patterns`. It should be all one word `urlpatterns`.
If you ever need to check the code for any of the other exercises in that book, they're all on github [here](https://github.com/ehmatthes/pcc).
|
I got to this point in the Crash Course, this area will break your site, temporarily. You will not have made all the files referenced in your code yet. In this case, you haven't made the urls.py file in learning\_logs. After this is made, you will not have updated your views.py nor made your index.html template. Keep going, it should be resolved later. See also: <https://ehmatthes.github.io/pcc/chapter_18/README.html#updates>
|
73,793,403
|
I frequently need to generate similar looking excel sheets for humans to read. Background colors and formatting should be similar. I'm looking to be able to read a template into python and have the values and cells filled in in Python.
It does not appear that xlsxwriter can read background color and formatting. It can output formatting, but it's taking a long time to code one template in manually.
openpyxl does not appear to have that function either.
I'm looking for a solution that would be able to read through a worksheet and say "A1 has a background color of red (or hex value), is bold, and has 'this is a template' in it." Does such a module exist?
|
2022/09/20
|
[
"https://Stackoverflow.com/questions/73793403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5775112/"
] |
Fill color is fgColor per the OOXML specs "For solid cell fills (no pattern), fgColor is used".
You can get the color from about three attributes, all should provide the same hex value unless the fill is grey in which case the index/value is 0 and the grey content is determined by tint
```
for cell in ws['A']:
print(cell)
if cell.fill.fgColor.index != 0:
print(cell.fill.fgColor.index)
print(cell.fill.fgColor.rgb)
print(cell.fill.fgColor.value)
else:
print(cell.fill.fgColor.tint)
print(cell.fill.patternType)
print("-------------")
```
|
There were no openstack answers I could find about reading existing background color formatting. The answers I did find were about formatting of the cell into things like percentage or currency.
Here is a solution I've found for background cell color from the openpyxl documentation, though fill color was not explicit in what I read.
```py
from openpyxl import load_workbook
from openpyxl.styles import Fill
wb = load_workbook("test.xlsx") # your specific template workbook name
ws = wb["Sheet1"] # your specific sheet name
style_dictionary = {}
for row in ws.rows:
for cell in row:
style_dictionary[cell] = cell.fill
style_dictionary
```
The background color will be under parameters rgb = ####.
I'm hopeful this dictionary can be used to template the background and pattern fill for other worksheets but I haven't gotten that far yet.
|
55,095,983
|
I'm having some trouble with the `replace()` function in python. Here is my code :
```
string = input()
word = string.find('word')
if word >= 1:
string = string.replace('word', 'word.2')
print(string)
```
The output gives `word`. Shouldn't it be `word.2`?
I'm confused. Any help?
Edit: After playing around with the issue for a bit, I've found that the question is now "Why is `string.find('word')` equal to 0 for input `word`?
|
2019/03/11
|
[
"https://Stackoverflow.com/questions/55095983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11182783/"
] |
Instead of
```
word >= 1
```
write
```
word >= 0
```
string.find() returns the first occurence of the word. If your string is 'word' and you find 'word', it'll return 0 as the word 'word' occurs at index 0 first.
In python, arrays start at 0. The first character in a string is at index 0.
Therefore, 'word' in 'word' is at the first location, i.e. 0.
|
There is no need to use the find function, just do:
```
string = input()
string = string.replace('word', 'word.2')
```
But nevertheless, if i ran it in Python3, your code is correct ;-)
How does your input look like?
|
55,095,983
|
I'm having some trouble with the `replace()` function in python. Here is my code :
```
string = input()
word = string.find('word')
if word >= 1:
string = string.replace('word', 'word.2')
print(string)
```
The output gives `word`. Shouldn't it be `word.2`?
I'm confused. Any help?
Edit: After playing around with the issue for a bit, I've found that the question is now "Why is `string.find('word')` equal to 0 for input `word`?
|
2019/03/11
|
[
"https://Stackoverflow.com/questions/55095983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11182783/"
] |
There is no need to use the find function, just do:
```
string = input()
string = string.replace('word', 'word.2')
```
But nevertheless, if i ran it in Python3, your code is correct ;-)
How does your input look like?
|
it happens because first occurrence is treated as zero position, use below code
```
string = input().replace('word','word.2')
print(string)
```
|
55,095,983
|
I'm having some trouble with the `replace()` function in python. Here is my code :
```
string = input()
word = string.find('word')
if word >= 1:
string = string.replace('word', 'word.2')
print(string)
```
The output gives `word`. Shouldn't it be `word.2`?
I'm confused. Any help?
Edit: After playing around with the issue for a bit, I've found that the question is now "Why is `string.find('word')` equal to 0 for input `word`?
|
2019/03/11
|
[
"https://Stackoverflow.com/questions/55095983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11182783/"
] |
Instead of
```
word >= 1
```
write
```
word >= 0
```
string.find() returns the first occurence of the word. If your string is 'word' and you find 'word', it'll return 0 as the word 'word' occurs at index 0 first.
In python, arrays start at 0. The first character in a string is at index 0.
Therefore, 'word' in 'word' is at the first location, i.e. 0.
|
it happens because first occurrence is treated as zero position, use below code
```
string = input().replace('word','word.2')
print(string)
```
|
54,093,253
|
I've been trying to work with BeautifulSoup because I want to try and scrape a webpage (<https://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1>). So far I scraped some elements with success but now I wanted to scrape a movie description but I've been struggling. The description is simply situated like this in html :
```
<div class="lister-item mode-advanced">
<div class="lister-item-content>
<p class="muted-text"> paragraph I don't need</p>
<p class="muted-text"> paragraph I need</p>
</div>
</div>
```
I want to scrape the second paragraph which seemed easy to do but everything I tried gave me 'None' as output. I've been digging around to find an answer. In an other stackoverflow post I found that
```
find('p:nth-of-type(1)')
```
or
```
find_elements_by_css_selector('.lister-item-mode >p:nth-child(1)')
```
could do the trick but it still gives me
```
none #as output
```
Below you can find a piece of my code it's a bit low grade code because I'm just trying out stuff to learn
```
import urllib2
from bs4 import BeautifulSoup
from requests import get
url = 'http://www.imdb.com/search/title?
release_date=2017&sort=num_votes,desc&page=1'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)
movie_containers = html_soup.find_all('div', class_='lister-item mode-
advanced')
first_movie = movie_containers[0]
first_title = first_movie.h3.a.text
print first_title
first_year = first_movie.h3.find('span', class_='lister-item-year text-muted unbold')
first_year = first_year.text
print first_year
first_imdb = float(first_movie.strong.text)
print first_imdb
# !!!! problem zone ---------------------------------------------
first_description = first_movie.find('p', class_='muted-text')
#first_description = first_description.text
print first_description
```
the above code gives me this output:
```
$ python scrape.py
Logan
(2017)
8.1
None
```
I would like to learn the correct method of selecting html tags because it will be useful to know for future projects.
|
2019/01/08
|
[
"https://Stackoverflow.com/questions/54093253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9441232/"
] |
>
> [find\_all()](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all) method looks through a tag’s descendants and retrieves
> all descendants that match your filters.
>
>
>
You can then use the list's index to get the element you need. Index starts at 0, so 1 will give the second item.
Change the first\_description to this.
```
first_description = first_movie.find_all('p', {"class":"text-muted"})[1].text.strip()
```
Full code
```
import urllib2
from bs4 import BeautifulSoup
from requests import get
url = 'http://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)
movie_containers = html_soup.find_all('div', class_='lister-item mode-advanced')
first_movie = movie_containers[0]
first_title = first_movie.h3.a.text
print first_title
first_year = first_movie.h3.find('span', class_='lister-item-year text-muted unbold')
first_year = first_year.text
print first_year
first_imdb = float(first_movie.strong.text)
print first_imdb
# !!!! problem zone ---------------------------------------------
first_description = first_movie.find_all('p', {"class":"text-muted"})[1].text.strip()
#first_description = first_description.text
print first_description
```
Output
```
Logan
(2017)
8.1
In the near future, a weary Logan cares for an ailing Professor X. However, Logan's attempts to hide from the world and his legacy are upended when a young mutant arrives, pursued by dark forces.
```
Read the [Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) to learn the correct method of selecting html tags.
Also consider moving to python 3.
|
Just playing around with `.next_sibling` was able to get it. There's probably a more elegant way though. At least might give you a start/some direction
```
from bs4 import BeautifulSoup
html = '''<div class="lister-item mode-advanced">
<div class="lister-item-content>
<p class="muted-text"> paragraph I don't need</p>
<p class="muted-text"> paragraph I need</p>
</div>
</div>'''
soup = BeautifulSoup(html, 'html.parser')
first_p = soup.find('div',{'class':'lister-item mode-advanced'}).text.strip()
second_p = soup.find('div',{'class':'lister-item mode-advanced'}).next_sibling.next_sibling.text.strip()
print (second_p)
```
**Output:**
```
print (second_p)
paragraph I need
```
|
54,093,253
|
I've been trying to work with BeautifulSoup because I want to try and scrape a webpage (<https://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1>). So far I scraped some elements with success but now I wanted to scrape a movie description but I've been struggling. The description is simply situated like this in html :
```
<div class="lister-item mode-advanced">
<div class="lister-item-content>
<p class="muted-text"> paragraph I don't need</p>
<p class="muted-text"> paragraph I need</p>
</div>
</div>
```
I want to scrape the second paragraph which seemed easy to do but everything I tried gave me 'None' as output. I've been digging around to find an answer. In an other stackoverflow post I found that
```
find('p:nth-of-type(1)')
```
or
```
find_elements_by_css_selector('.lister-item-mode >p:nth-child(1)')
```
could do the trick but it still gives me
```
none #as output
```
Below you can find a piece of my code it's a bit low grade code because I'm just trying out stuff to learn
```
import urllib2
from bs4 import BeautifulSoup
from requests import get
url = 'http://www.imdb.com/search/title?
release_date=2017&sort=num_votes,desc&page=1'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)
movie_containers = html_soup.find_all('div', class_='lister-item mode-
advanced')
first_movie = movie_containers[0]
first_title = first_movie.h3.a.text
print first_title
first_year = first_movie.h3.find('span', class_='lister-item-year text-muted unbold')
first_year = first_year.text
print first_year
first_imdb = float(first_movie.strong.text)
print first_imdb
# !!!! problem zone ---------------------------------------------
first_description = first_movie.find('p', class_='muted-text')
#first_description = first_description.text
print first_description
```
the above code gives me this output:
```
$ python scrape.py
Logan
(2017)
8.1
None
```
I would like to learn the correct method of selecting html tags because it will be useful to know for future projects.
|
2019/01/08
|
[
"https://Stackoverflow.com/questions/54093253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9441232/"
] |
>
> [find\_all()](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all) method looks through a tag’s descendants and retrieves
> all descendants that match your filters.
>
>
>
You can then use the list's index to get the element you need. Index starts at 0, so 1 will give the second item.
Change the first\_description to this.
```
first_description = first_movie.find_all('p', {"class":"text-muted"})[1].text.strip()
```
Full code
```
import urllib2
from bs4 import BeautifulSoup
from requests import get
url = 'http://www.imdb.com/search/title?release_date=2017&sort=num_votes,desc&page=1'
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)
movie_containers = html_soup.find_all('div', class_='lister-item mode-advanced')
first_movie = movie_containers[0]
first_title = first_movie.h3.a.text
print first_title
first_year = first_movie.h3.find('span', class_='lister-item-year text-muted unbold')
first_year = first_year.text
print first_year
first_imdb = float(first_movie.strong.text)
print first_imdb
# !!!! problem zone ---------------------------------------------
first_description = first_movie.find_all('p', {"class":"text-muted"})[1].text.strip()
#first_description = first_description.text
print first_description
```
Output
```
Logan
(2017)
8.1
In the near future, a weary Logan cares for an ailing Professor X. However, Logan's attempts to hide from the world and his legacy are upended when a young mutant arrives, pursued by dark forces.
```
Read the [Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) to learn the correct method of selecting html tags.
Also consider moving to python 3.
|
BeautifulSoup 4.71 support `:nth-child()` or any CSS4 selectors
```
first_description = soup.select_one('.lister-item-content p:nth-child(4)')
# or
#first_description = soup.select_one('.lister-item-content p:nth-of-type(2)')
print(desc)
```
|
64,754,032
|
I am trying to use SageMaker script mode for training a model on image data. I have multiple scripts for data preparation, model creation, and training. This is the content of my working directory:
```
WORKDIR
|-- config
| |-- hyperparameters.json
| |-- lossweights.json
| `-- lr.json
|-- dataset.py
|-- densenet.py
|-- resnet.py
|-- models.py
|-- train.py
|-- imagenet_utils.py
|-- keras_utils.py
|-- utils.py
`-- train.ipynb
```
The training script is `train.py` and it makes use of other scripts. To run the training script, I'm using the following code:
```py
bucket='ashutosh-sagemaker'
data_key = 'training'
data_location = 's3://{}/{}'.format(bucket, data_key)
print(data_location)
inputs = {'data':data_location}
print(inputs)
from sagemaker.tensorflow import TensorFlow
estimator = TensorFlow(entry_point='train.py',
role=role,
train_instance_count=1,
train_instance_type='ml.p2.xlarge',
framework_version='1.14',
py_version='py3',
script_mode=True,
hyperparameters={
'epochs': 10
}
)
estimator.fit(inputs)
```
On running this code, I get the following output:
```
2020-11-09 10:42:07 Starting - Starting the training job...
2020-11-09 10:42:10 Starting - Launching requested ML instances......
2020-11-09 10:43:24 Starting - Preparing the instances for training.........
2020-11-09 10:44:43 Downloading - Downloading input data....................................
2020-11-09 10:51:08 Training - Downloading the training image...
2020-11-09 10:51:40 Uploading - Uploading generated training model
Traceback (most recent call last):
File "train.py", line 5, in <module>
from dataset import WatchDataSet
ModuleNotFoundError: No module named 'dataset'
WARNING: Logging before flag parsing goes to stderr.
E1109 10:51:37.525632 140519531874048 _trainer.py:94] ExecuteUserScriptError:
Command "/usr/local/bin/python3.6 train.py --epochs 10 --model_dir s3://sagemaker-ap-northeast-1-485707876195/tensorflow-training-2020-11-09-10-42-06-234/model"
2020-11-09 10:51:47 Failed - Training job failed
```
What should I do to remove the `ModuleNotFoundError`? I tried to look for solutions but didn't find any relevant resources.
The contents of `train.py` file:
```
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from dataset import WatchDataSet
from models import BCNN
from utils import image_generator, val_image_generator
from utils import BCNNScheduler, LossWeightsModifier
from utils import restore_checkpoint, get_epoch_key
import argparse
from collections import defaultdict
import json
import keras
from keras import backend as K
from keras import optimizers
from keras.backend import tensorflow_backend
from keras.callbacks import LearningRateScheduler, TensorBoard
from math import ceil
import numpy as np
import os
import glob
from sklearn.model_selection import train_test_split
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=100, help='number of epoch of training')
parser.add_argument('--batch_size', type=int, default=32, help='size of the batches')
parser.add_argument('--data', type=str, default=os.environ.get('SM_CHANNEL_DATA'))
opt = parser.parse_args()
def main():
csv_config_dict = {
'csv': opt.data + 'train.csv',
'image_dir': opt.data + 'images',
'xlabel_column': opt.xlabel_column,
'brand_column': opt.brand_column,
'model_column': opt.model_column,
'ref_column': opt.ref_column,
'encording': opt.encoding
}
dataset = WatchDataSet(
csv_config_dict=csv_config_dict,
min_data_ref=opt.min_data_ref
)
X, y_c1, y_c2, y_fine = dataset.X, dataset.y_c1, dataset.y_c2, dataset.y_fine
brand_uniq, model_uniq, ref_uniq = dataset.brand_uniq, dataset.model_uniq, dataset.ref_uniq
print("ref. shape: ", y_fine.shape)
print("brand shape: ", y_c1.shape)
print("model shape: ", y_c2.shape)
height, width = 224, 224
channel = 3
# get pre-trained weights
if opt.mode == 'dense':
WEIGHTS_PATH = 'https://github.com/keras-team/keras-applications/releases/download/densenet/densenet121_weights_tf_dim_ordering_tf_kernels.h5'
elif opt.mode == 'res':
WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5'
weights_path, current_epoch, checkpoint = restore_checkpoint(opt.ckpt_path, WEIGHTS_PATH)
# split train/validation
y_ref_list = np.array([ref_uniq[np.argmax(i)] for i in y_fine])
index_list = np.array(range(len(X)))
train_index, test_index, _, _ = train_test_split(index_list, y_ref_list, train_size=0.8, random_state=23, stratify=None)
print("Train")
model = None
bcnn = BCNN(
height=height,
width=width,
channel=channel,
num_classes=len(ref_uniq),
coarse1_classes=len(brand_uniq),
coarse2_classes=len(model_uniq),
mode=opt.mode
)
if __name__ == '__main__':
main()
```
|
2020/11/09
|
[
"https://Stackoverflow.com/questions/64754032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7697327/"
] |
If you don't mind switching from TF 1.14 to TF 1.15.2+, you'll be able to bring a local code directory containing your custom modules to your SageMaker TensorFlow Estimator via the argument `source_dir`. Your entry point script shall be in that `source_dir`. Details in the SageMaker TensorFlow doc: <https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html#use-third-party-libraries>
|
This isn't exactly what the questioner asked but if anyone has come here wanting to know how to use custom libraries with SKLearn you can use `dependencies` as an argument like in the following:
```
import sagemaker
from sagemaker.sklearn.estimator import SKLearn
sess = sagemaker.Session()
role = sagemkaer.get_execution_role()
model = SKLearn(
entry_point='training.py',
role=role,
instance_type='ml.m5.large',
sagemaker_session=sess,
dependencies=['my_custom_file.py']
)
```
|
62,097,219
|
I am trying to connect to Google Sheets' API from a Django view. The bulk of the code I have taken from this link:
<https://developers.google.com/sheets/api/quickstart/python>
Anyway, here are the codes:
**sheets.py** (Copy pasted from the link above, function renamed)
```
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'
def test():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))
```
**urls.py**
```
urlpatterns = [
path('', views.index, name='index')
]
```
**views.py**
```
from django.http import HttpResponse
from django.shortcuts import render
from .sheets import test
# Views
def index(request):
test()
return HttpResponse('Hello world')
```
All the view function does is just call the `test()` method from the **sheets.py** module. Anyway, when I run my server and go the URL, another tab opens up for the Google oAuth2, which means that the credentials file is detected and everything. However, in this tab, the following error message is displayed from Google:
```
Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:65262/, does not match the ones authorized for the OAuth client.
```
In my API console, I have the callback URL set exactly to `127.0.0.1:8000` to match my Django's view URL. I don't even know where the `http://localhost:65262/` URL comes from. Any help in fixing this? And can someone explain to me why this is happening? Thanks in advance.
**EDIT**
I tried to remove the `port=0` in the flow method as mentioned in the comment, then the URL mismatch occurs with `http://localhost:8080/`, which is again pretty weird because my Django app is running in the `8000` port.
|
2020/05/30
|
[
"https://Stackoverflow.com/questions/62097219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056347/"
] |
You shouldn't be using [Flow.run\_local\_server()](https://github.com/googleapis/google-auth-library-python-oauthlib/blob/v0.4.1/google_auth_oauthlib/flow.py#L408) unless you don't have the intention of deploying the code. This is because `run_local_server` launches a browser on the server to complete the flow.
This works just fine if you're developing the project locally for yourself.
If you're intent on using the local server to negotiate the OAuth flow. The Redirect URI configured in your secrets must match that, the local server default for the host is [`localhost` and port is `8080`](https://github.com/googleapis/google-auth-library-python-oauthlib/blob/v0.4.1/google_auth_oauthlib/flow.py#L409).
If you're looking to deploy the code, you must perform the flow via an exchange between the user's browser, your server and Google.
Since you have a Django server already running, you can use that to negotiate the flow.
For example,
Say there is a tweets app in a Django project with `urls.py` module as follows.
```
from django.urls import path, include
from . import views
urlpatterns = [
path('google_oauth', views.google_oath, name='google_oauth'),
path('hello', views.say_hello, name='hello'),
]
urls = include(urlpatterns)
```
You could implement a guard for views that require credentials as follow.
```py
import functools
import json
import urllib
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from django.shortcuts import redirect
from django.http import HttpResponse
SCOPES = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid']
def provides_credentials(func):
@functools.wraps(func)
def wraps(request):
# If OAuth redirect response, get credentials
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES,
redirect_uri="http://localhost:8000/tweet/hello")
existing_state = request.GET.get('state', None)
current_path = request.path
if existing_state:
secure_uri = request.build_absolute_uri(
).replace('http', 'https')
location_path = urllib.parse.urlparse(existing_state).path
flow.fetch_token(
authorization_response=secure_uri,
state=existing_state
)
request.session['credentials'] = flow.credentials.to_json()
if location_path == current_path:
return func(request, flow.credentials)
# Head back to location stored in state when
# it is different from the configured redirect uri
return redirect(existing_state)
# Otherwise, retrieve credential from request session.
stored_credentials = request.session.get('credentials', None)
if not stored_credentials:
# It's strongly recommended to encrypt state.
# location is needed in state to remember it.
location = request.build_absolute_uri()
# Commence OAuth dance.
auth_url, _ = flow.authorization_url(state=location)
return redirect(auth_url)
# Hydrate stored credentials.
credentials = Credentials(**json.loads(stored_credentials))
# If credential is expired, refresh it.
if credentials.expired and creds.refresh_token:
creds.refresh(Request())
# Store JSON representation of credentials in session.
request.session['credentials'] = credentials.to_json()
return func(request, credentials=credentials)
return wraps
@provides_credentials
def google_oauth(request, credentials):
return HttpResponse('Google OAUTH <a href="/tweet/hello">Say Hello</a>')
@provides_credentials
def say_hello(request, credentials):
# Use credentials for whatever
return HttpResponse('Hello')
```
Note that this is only an example. If you decide to go this route, I recommend looking into extracting the OAuth flow to its very own Django App.
|
The redirect URI tells Google the location you would like the authorization to be returned to. This must be set up properly in google developer console to avoid anyone hijacking your client. It must match exactly.
To to [Google developer console](https://console.developers.google.com/). Edit the client you are currently using and add the following as a redirect uri
```
http://localhost:65262/
```
[](https://i.stack.imgur.com/W7NVf.png)
Tip click the little pencil icon to edit a client :)
TBH while in development its easier to just add the port that google says you are calling from then fiddle with the settings in your application.
|
62,097,219
|
I am trying to connect to Google Sheets' API from a Django view. The bulk of the code I have taken from this link:
<https://developers.google.com/sheets/api/quickstart/python>
Anyway, here are the codes:
**sheets.py** (Copy pasted from the link above, function renamed)
```
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'
def test():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))
```
**urls.py**
```
urlpatterns = [
path('', views.index, name='index')
]
```
**views.py**
```
from django.http import HttpResponse
from django.shortcuts import render
from .sheets import test
# Views
def index(request):
test()
return HttpResponse('Hello world')
```
All the view function does is just call the `test()` method from the **sheets.py** module. Anyway, when I run my server and go the URL, another tab opens up for the Google oAuth2, which means that the credentials file is detected and everything. However, in this tab, the following error message is displayed from Google:
```
Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:65262/, does not match the ones authorized for the OAuth client.
```
In my API console, I have the callback URL set exactly to `127.0.0.1:8000` to match my Django's view URL. I don't even know where the `http://localhost:65262/` URL comes from. Any help in fixing this? And can someone explain to me why this is happening? Thanks in advance.
**EDIT**
I tried to remove the `port=0` in the flow method as mentioned in the comment, then the URL mismatch occurs with `http://localhost:8080/`, which is again pretty weird because my Django app is running in the `8000` port.
|
2020/05/30
|
[
"https://Stackoverflow.com/questions/62097219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056347/"
] |
I had the same problem with the redirect\_uri error and it turned out (as implied above) that I created my credentials in the google console as type "Web server" instead of "desktop app". I created new creds as "desktop app", downloaded the JSON and it worked.
Ultimately, I want to use the GMAIL API for a web server, but that is a different flow than the sample.
|
The redirect URI tells Google the location you would like the authorization to be returned to. This must be set up properly in google developer console to avoid anyone hijacking your client. It must match exactly.
To to [Google developer console](https://console.developers.google.com/). Edit the client you are currently using and add the following as a redirect uri
```
http://localhost:65262/
```
[](https://i.stack.imgur.com/W7NVf.png)
Tip click the little pencil icon to edit a client :)
TBH while in development its easier to just add the port that google says you are calling from then fiddle with the settings in your application.
|
62,097,219
|
I am trying to connect to Google Sheets' API from a Django view. The bulk of the code I have taken from this link:
<https://developers.google.com/sheets/api/quickstart/python>
Anyway, here are the codes:
**sheets.py** (Copy pasted from the link above, function renamed)
```
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'
def test():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))
```
**urls.py**
```
urlpatterns = [
path('', views.index, name='index')
]
```
**views.py**
```
from django.http import HttpResponse
from django.shortcuts import render
from .sheets import test
# Views
def index(request):
test()
return HttpResponse('Hello world')
```
All the view function does is just call the `test()` method from the **sheets.py** module. Anyway, when I run my server and go the URL, another tab opens up for the Google oAuth2, which means that the credentials file is detected and everything. However, in this tab, the following error message is displayed from Google:
```
Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:65262/, does not match the ones authorized for the OAuth client.
```
In my API console, I have the callback URL set exactly to `127.0.0.1:8000` to match my Django's view URL. I don't even know where the `http://localhost:65262/` URL comes from. Any help in fixing this? And can someone explain to me why this is happening? Thanks in advance.
**EDIT**
I tried to remove the `port=0` in the flow method as mentioned in the comment, then the URL mismatch occurs with `http://localhost:8080/`, which is again pretty weird because my Django app is running in the `8000` port.
|
2020/05/30
|
[
"https://Stackoverflow.com/questions/62097219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056347/"
] |
You shouldn't be using [Flow.run\_local\_server()](https://github.com/googleapis/google-auth-library-python-oauthlib/blob/v0.4.1/google_auth_oauthlib/flow.py#L408) unless you don't have the intention of deploying the code. This is because `run_local_server` launches a browser on the server to complete the flow.
This works just fine if you're developing the project locally for yourself.
If you're intent on using the local server to negotiate the OAuth flow. The Redirect URI configured in your secrets must match that, the local server default for the host is [`localhost` and port is `8080`](https://github.com/googleapis/google-auth-library-python-oauthlib/blob/v0.4.1/google_auth_oauthlib/flow.py#L409).
If you're looking to deploy the code, you must perform the flow via an exchange between the user's browser, your server and Google.
Since you have a Django server already running, you can use that to negotiate the flow.
For example,
Say there is a tweets app in a Django project with `urls.py` module as follows.
```
from django.urls import path, include
from . import views
urlpatterns = [
path('google_oauth', views.google_oath, name='google_oauth'),
path('hello', views.say_hello, name='hello'),
]
urls = include(urlpatterns)
```
You could implement a guard for views that require credentials as follow.
```py
import functools
import json
import urllib
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from django.shortcuts import redirect
from django.http import HttpResponse
SCOPES = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid']
def provides_credentials(func):
@functools.wraps(func)
def wraps(request):
# If OAuth redirect response, get credentials
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES,
redirect_uri="http://localhost:8000/tweet/hello")
existing_state = request.GET.get('state', None)
current_path = request.path
if existing_state:
secure_uri = request.build_absolute_uri(
).replace('http', 'https')
location_path = urllib.parse.urlparse(existing_state).path
flow.fetch_token(
authorization_response=secure_uri,
state=existing_state
)
request.session['credentials'] = flow.credentials.to_json()
if location_path == current_path:
return func(request, flow.credentials)
# Head back to location stored in state when
# it is different from the configured redirect uri
return redirect(existing_state)
# Otherwise, retrieve credential from request session.
stored_credentials = request.session.get('credentials', None)
if not stored_credentials:
# It's strongly recommended to encrypt state.
# location is needed in state to remember it.
location = request.build_absolute_uri()
# Commence OAuth dance.
auth_url, _ = flow.authorization_url(state=location)
return redirect(auth_url)
# Hydrate stored credentials.
credentials = Credentials(**json.loads(stored_credentials))
# If credential is expired, refresh it.
if credentials.expired and creds.refresh_token:
creds.refresh(Request())
# Store JSON representation of credentials in session.
request.session['credentials'] = credentials.to_json()
return func(request, credentials=credentials)
return wraps
@provides_credentials
def google_oauth(request, credentials):
return HttpResponse('Google OAUTH <a href="/tweet/hello">Say Hello</a>')
@provides_credentials
def say_hello(request, credentials):
# Use credentials for whatever
return HttpResponse('Hello')
```
Note that this is only an example. If you decide to go this route, I recommend looking into extracting the OAuth flow to its very own Django App.
|
I had the same problem with the redirect\_uri error and it turned out (as implied above) that I created my credentials in the google console as type "Web server" instead of "desktop app". I created new creds as "desktop app", downloaded the JSON and it worked.
Ultimately, I want to use the GMAIL API for a web server, but that is a different flow than the sample.
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
Both Numpy and the internal random generators have instantiatable classes.
For just `random`:
```
import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072
```
And for Numpy:
```
import numpy
random_generator = numpy.random.RandomState()
random_generator.uniform(0, 1, 10)
#>>> array([ 0.98992857, 0.83503764, 0.00337241, 0.76597264, 0.61333436,
#>>> 0.0916262 , 0.52129459, 0.44857548, 0.86692693, 0.21150068])
```
|
Veedrac's answer did not address how one might generate independent streams.
The best way I could find to generate independent streams is to use a replacement for numpy's RandomState. This is provided by the [RandomGen package](https://bashtage.github.io/randomgen/index.html).
It supports [independent random streams](https://bashtage.github.io/randomgen/parallel.html#independent-streams), but these use one of three random number generators: PCG64, ThreeFry or Philox. If you want to use the more conventional MT19937, you can rely on [jumping](https://bashtage.github.io/randomgen/parallel.html#jump-advance-the-prng-state) instead.
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
Both Numpy and the internal random generators have instantiatable classes.
For just `random`:
```
import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072
```
And for Numpy:
```
import numpy
random_generator = numpy.random.RandomState()
random_generator.uniform(0, 1, 10)
#>>> array([ 0.98992857, 0.83503764, 0.00337241, 0.76597264, 0.61333436,
#>>> 0.0916262 , 0.52129459, 0.44857548, 0.86692693, 0.21150068])
```
|
You do not need to use the RandomGen package. Simply initiate two streams would suffice. For example:
```
import numpy as np
prng1 = np.random.RandomState()
prng2 = np.random.RandomState()
prng1.seed(1)
prng2.seed(1)
```
Now if you progress both streams using `prngX.rand()`, you will find that the two streams will give you identical results, which means they are independent streams with the same seed.
To use the `random` package, simply swap out `np.random.RandomState()` for `random.Random()`.
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
Both Numpy and the internal random generators have instantiatable classes.
For just `random`:
```
import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072
```
And for Numpy:
```
import numpy
random_generator = numpy.random.RandomState()
random_generator.uniform(0, 1, 10)
#>>> array([ 0.98992857, 0.83503764, 0.00337241, 0.76597264, 0.61333436,
#>>> 0.0916262 , 0.52129459, 0.44857548, 0.86692693, 0.21150068])
```
|
For the sake of reproducibility you can pass a seed directly to `random.Random()` and then call variables from there. Each initiated instance would then run independently from the other. For example, if you run:
```
import random
rg1 = random.Random(1)
rg2 = random.Random(2)
rg3 = random.Random(1)
for i in range(5): print(rg1.random())
print('')
for i in range(5): print(rg2.random())
print('')
for i in range(5): print(rg3.random())
```
You'll get:
```
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
0.956034271889
0.947827487059
0.0565513677268
0.0848719951589
0.835498878129
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
```
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
Both Numpy and the internal random generators have instantiatable classes.
For just `random`:
```
import random
random_generator = random.Random()
random_generator.random()
#>>> 0.9493959884174072
```
And for Numpy:
```
import numpy
random_generator = numpy.random.RandomState()
random_generator.uniform(0, 1, 10)
#>>> array([ 0.98992857, 0.83503764, 0.00337241, 0.76597264, 0.61333436,
#>>> 0.0916262 , 0.52129459, 0.44857548, 0.86692693, 0.21150068])
```
|
`numpy` added feature to generate independent streams of Random Numbers using `SeedSequence`. This process a user-provided seed, typically as an integer of some size, and to convert it into an initial state for a BitGenerator. It uses hashing techniques to ensure that low-quality seeds are turned into high quality initial states (at least, with very high probability).
```
from numpy.random import SeedSequence, default_rng
ss = SeedSequence(12345)
# Spawn off 10 child SeedSequences to pass to child processes.
child_seeds = ss.spawn(10)
streams = [default_rng(s) for s in child_seeds]
```
each stream is PCG64 generator. Random numbers can be generated sequentially as follows -
```
for i in 1:K
instance[i] = [s.uniform() for s in streams]
```
There are more ways to generate independent streams of random numbers, check [numpydocs](https://numpy.org/doc/stable/reference/random/parallel.html).
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
You do not need to use the RandomGen package. Simply initiate two streams would suffice. For example:
```
import numpy as np
prng1 = np.random.RandomState()
prng2 = np.random.RandomState()
prng1.seed(1)
prng2.seed(1)
```
Now if you progress both streams using `prngX.rand()`, you will find that the two streams will give you identical results, which means they are independent streams with the same seed.
To use the `random` package, simply swap out `np.random.RandomState()` for `random.Random()`.
|
Veedrac's answer did not address how one might generate independent streams.
The best way I could find to generate independent streams is to use a replacement for numpy's RandomState. This is provided by the [RandomGen package](https://bashtage.github.io/randomgen/index.html).
It supports [independent random streams](https://bashtage.github.io/randomgen/parallel.html#independent-streams), but these use one of three random number generators: PCG64, ThreeFry or Philox. If you want to use the more conventional MT19937, you can rely on [jumping](https://bashtage.github.io/randomgen/parallel.html#jump-advance-the-prng-state) instead.
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
For the sake of reproducibility you can pass a seed directly to `random.Random()` and then call variables from there. Each initiated instance would then run independently from the other. For example, if you run:
```
import random
rg1 = random.Random(1)
rg2 = random.Random(2)
rg3 = random.Random(1)
for i in range(5): print(rg1.random())
print('')
for i in range(5): print(rg2.random())
print('')
for i in range(5): print(rg3.random())
```
You'll get:
```
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
0.956034271889
0.947827487059
0.0565513677268
0.0848719951589
0.835498878129
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
```
|
Veedrac's answer did not address how one might generate independent streams.
The best way I could find to generate independent streams is to use a replacement for numpy's RandomState. This is provided by the [RandomGen package](https://bashtage.github.io/randomgen/index.html).
It supports [independent random streams](https://bashtage.github.io/randomgen/parallel.html#independent-streams), but these use one of three random number generators: PCG64, ThreeFry or Philox. If you want to use the more conventional MT19937, you can rely on [jumping](https://bashtage.github.io/randomgen/parallel.html#jump-advance-the-prng-state) instead.
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
You do not need to use the RandomGen package. Simply initiate two streams would suffice. For example:
```
import numpy as np
prng1 = np.random.RandomState()
prng2 = np.random.RandomState()
prng1.seed(1)
prng2.seed(1)
```
Now if you progress both streams using `prngX.rand()`, you will find that the two streams will give you identical results, which means they are independent streams with the same seed.
To use the `random` package, simply swap out `np.random.RandomState()` for `random.Random()`.
|
For the sake of reproducibility you can pass a seed directly to `random.Random()` and then call variables from there. Each initiated instance would then run independently from the other. For example, if you run:
```
import random
rg1 = random.Random(1)
rg2 = random.Random(2)
rg3 = random.Random(1)
for i in range(5): print(rg1.random())
print('')
for i in range(5): print(rg2.random())
print('')
for i in range(5): print(rg3.random())
```
You'll get:
```
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
0.956034271889
0.947827487059
0.0565513677268
0.0848719951589
0.835498878129
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
```
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
You do not need to use the RandomGen package. Simply initiate two streams would suffice. For example:
```
import numpy as np
prng1 = np.random.RandomState()
prng2 = np.random.RandomState()
prng1.seed(1)
prng2.seed(1)
```
Now if you progress both streams using `prngX.rand()`, you will find that the two streams will give you identical results, which means they are independent streams with the same seed.
To use the `random` package, simply swap out `np.random.RandomState()` for `random.Random()`.
|
`numpy` added feature to generate independent streams of Random Numbers using `SeedSequence`. This process a user-provided seed, typically as an integer of some size, and to convert it into an initial state for a BitGenerator. It uses hashing techniques to ensure that low-quality seeds are turned into high quality initial states (at least, with very high probability).
```
from numpy.random import SeedSequence, default_rng
ss = SeedSequence(12345)
# Spawn off 10 child SeedSequences to pass to child processes.
child_seeds = ss.spawn(10)
streams = [default_rng(s) for s in child_seeds]
```
each stream is PCG64 generator. Random numbers can be generated sequentially as follows -
```
for i in 1:K
instance[i] = [s.uniform() for s in streams]
```
There are more ways to generate independent streams of random numbers, check [numpydocs](https://numpy.org/doc/stable/reference/random/parallel.html).
|
24,204,582
|
I want to generate multiple streams of random numbers in python.
I am writing a program for simulating queues system and want one stream for the inter-arrival time and another stream for the service time and so on.
`numpy.random()` generates random numbers from a global stream.
In matlab there is [something called RandStream](http://www.mathworks.com/help/matlab/ref/randstream.html) which enables me to create multiple streams.
Is there any way to create something like RandStream in Python
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24204582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3429820/"
] |
For the sake of reproducibility you can pass a seed directly to `random.Random()` and then call variables from there. Each initiated instance would then run independently from the other. For example, if you run:
```
import random
rg1 = random.Random(1)
rg2 = random.Random(2)
rg3 = random.Random(1)
for i in range(5): print(rg1.random())
print('')
for i in range(5): print(rg2.random())
print('')
for i in range(5): print(rg3.random())
```
You'll get:
```
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
0.956034271889
0.947827487059
0.0565513677268
0.0848719951589
0.835498878129
0.134364244112
0.847433736937
0.763774618977
0.255069025739
0.495435087092
```
|
`numpy` added feature to generate independent streams of Random Numbers using `SeedSequence`. This process a user-provided seed, typically as an integer of some size, and to convert it into an initial state for a BitGenerator. It uses hashing techniques to ensure that low-quality seeds are turned into high quality initial states (at least, with very high probability).
```
from numpy.random import SeedSequence, default_rng
ss = SeedSequence(12345)
# Spawn off 10 child SeedSequences to pass to child processes.
child_seeds = ss.spawn(10)
streams = [default_rng(s) for s in child_seeds]
```
each stream is PCG64 generator. Random numbers can be generated sequentially as follows -
```
for i in 1:K
instance[i] = [s.uniform() for s in streams]
```
There are more ways to generate independent streams of random numbers, check [numpydocs](https://numpy.org/doc/stable/reference/random/parallel.html).
|
38,430,491
|
I'm writing a Python application that needs to fetch a Google document from Google Drive as markdown.
I'm looking for ideas for the design and existing open-source code.
As far as I know, Google doesn't provide export as markdown. I suppose this means I would have to figure out, which of the available download/export formats is the best for converting to markdown.
The contents of the document is ensured to not contain anything that markdown doesn't support.
EDIT: I would like to avoid non python software to keep the setup as simple as possible.
|
2016/07/18
|
[
"https://Stackoverflow.com/questions/38430491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852140/"
] |
You might want to take a look at [Pandoc](http://pandoc.org/ "Pandoc") which supports conversions i.e. from docx to markdown. There are several Python wrappers for Pandoc, such as [pypandoc](https://pypi.python.org/pypi/pypandoc/ "pypandoc").
After fetching a document from Google Drive in docx format, the conversion is as simple as:
```
import pypandoc
markdown_output = pypandoc.convert_file('Document.docx', 'markdown')
```
|
Google Drive offers a "Zipped HTML" export option.
[](https://i.stack.imgur.com/BosJ2.png)
Use the [Python module `html2text`](https://pypi.python.org/pypi/html2text) to convert the HTML into Markdown.
>
> html2text is a Python script that converts a page of HTML into clean, easy-to-read plain ASCII text. Better yet, that ASCII also happens to be valid Markdown (a text-to-HTML format).
>
>
>
```
>>> import html2text
>>>
>>> print(html2text.html2text("<p><strong>Zed's</strong> dead baby,
<em>Zed's</em> dead.</p>"))
**Zed's** dead baby, _Zed's_ dead.
```
|
9,753,885
|
I'd like to have the matplotlib "show" command return to the command line
while displaying the plot. Most other plot packages, like R, do this.
But pylab hangs until the plot window closes. For example:
```
import pylab
x = pylab.arange( 0, 10, 0.1)
y = pylab.sin(x)
pylab.plot(x,y, 'ro-')
pylab.show() # Python hangs here until the plot window is closed
```
I'd like to be able to view the plot while doing command line queries.
I'm running Debian squeeze with python 2.6.6.
My ~/.matplotlib/matplotlibrc contains
```
backend : GTKAgg
```
Thanks!
|
2012/03/17
|
[
"https://Stackoverflow.com/questions/9753885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647331/"
] |
Add `pylab.ion()` ([interactive mode](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ion)) before the `pylab.show()` call. That will make the UI run in a separate thread and the call to `show` will return immediately.
|
You need to run it as
```
$ ipython --pylab
```
and run your code as
```
In [8]: x = arange(0,10,.1)
In [9]: y = sin(x)
In [10]: plot(x,y,'ro-')
Out[10]: [<matplotlib.lines.Line2D at 0x2f2fd50>]
In [11]:
```
This gives you the prompt for cases where you would want to modify other parts or plot more.
|
52,711,988
|
I'm having trouble using Pipenv on my Windows 10 machine. Initially, I got a timeout error while trying to run `pipenv install <module>` and following [this answer](https://stackoverflow.com/a/52509038/5535114), I disabled Windows Defender.
That got rid of the timeout error and it then seems to successfully install the package at **~/.virtualenvs** but I get an error when it comes to creating **Pipfile.lock**:
```
Adding flask to Pipfile's [packages]...
Pipfile.lock not found, creating...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\utils.py", line 402, in resolve_deps
req_dir=req_dir
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\utils.py", line 250, in actually_resolve_deps
req = Requirement.from_line(dep)
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 704, in from_line
line, extras = _strip_extras(line)
TypeError: 'module' object is not callable
```
I've tried installing `requests` and `flask`, with the same results.
* **python**: Python 3.6.4 :: Anaconda, Inc.
* **pip**: pip 18.0 from c:\users\edgar\anaconda3\lib\site-packages\pip (python 3.6)
* **pipenv**: pipenv, version 2018.7.1
Any clues as to what is the problem/solution?
|
2018/10/09
|
[
"https://Stackoverflow.com/questions/52711988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535114/"
] |
Finally solved it. This is current issue, with a [workaround](https://github.com/pypa/pipenv/issues/2924#issuecomment-427383459) for Windows:
`pipenv run python -m pip install -U pip==18.0`
|
I got the same problem . It looks like problem happen with pip18.1 . However, you are using pip 18.0 . By the way,
I solved by these commands . You can try it.
`pipenv run pip install pip==18.0
pipenv install`
Reference:
<https://github.com/pypa/pipenv/issues/2924>
|
52,711,988
|
I'm having trouble using Pipenv on my Windows 10 machine. Initially, I got a timeout error while trying to run `pipenv install <module>` and following [this answer](https://stackoverflow.com/a/52509038/5535114), I disabled Windows Defender.
That got rid of the timeout error and it then seems to successfully install the package at **~/.virtualenvs** but I get an error when it comes to creating **Pipfile.lock**:
```
Adding flask to Pipfile's [packages]...
Pipfile.lock not found, creating...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\utils.py", line 402, in resolve_deps
req_dir=req_dir
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\utils.py", line 250, in actually_resolve_deps
req = Requirement.from_line(dep)
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 704, in from_line
line, extras = _strip_extras(line)
TypeError: 'module' object is not callable
```
I've tried installing `requests` and `flask`, with the same results.
* **python**: Python 3.6.4 :: Anaconda, Inc.
* **pip**: pip 18.0 from c:\users\edgar\anaconda3\lib\site-packages\pip (python 3.6)
* **pipenv**: pipenv, version 2018.7.1
Any clues as to what is the problem/solution?
|
2018/10/09
|
[
"https://Stackoverflow.com/questions/52711988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535114/"
] |
I recommend you to update your pipenv version by using
```
>>> python -m pip install --upgrade pip
```
`>>> pip install --upgrade pipenv`
And then try to install your module again
```
>>> pipenv install <module_name>
```
|
I got the same problem . It looks like problem happen with pip18.1 . However, you are using pip 18.0 . By the way,
I solved by these commands . You can try it.
`pipenv run pip install pip==18.0
pipenv install`
Reference:
<https://github.com/pypa/pipenv/issues/2924>
|
52,711,988
|
I'm having trouble using Pipenv on my Windows 10 machine. Initially, I got a timeout error while trying to run `pipenv install <module>` and following [this answer](https://stackoverflow.com/a/52509038/5535114), I disabled Windows Defender.
That got rid of the timeout error and it then seems to successfully install the package at **~/.virtualenvs** but I get an error when it comes to creating **Pipfile.lock**:
```
Adding flask to Pipfile's [packages]...
Pipfile.lock not found, creating...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\utils.py", line 402, in resolve_deps
req_dir=req_dir
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\utils.py", line 250, in actually_resolve_deps
req = Requirement.from_line(dep)
File "C:\Users\Edgar\AppData\Roaming\Python\Python36\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 704, in from_line
line, extras = _strip_extras(line)
TypeError: 'module' object is not callable
```
I've tried installing `requests` and `flask`, with the same results.
* **python**: Python 3.6.4 :: Anaconda, Inc.
* **pip**: pip 18.0 from c:\users\edgar\anaconda3\lib\site-packages\pip (python 3.6)
* **pipenv**: pipenv, version 2018.7.1
Any clues as to what is the problem/solution?
|
2018/10/09
|
[
"https://Stackoverflow.com/questions/52711988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5535114/"
] |
Finally solved it. This is current issue, with a [workaround](https://github.com/pypa/pipenv/issues/2924#issuecomment-427383459) for Windows:
`pipenv run python -m pip install -U pip==18.0`
|
I recommend you to update your pipenv version by using
```
>>> python -m pip install --upgrade pip
```
`>>> pip install --upgrade pipenv`
And then try to install your module again
```
>>> pipenv install <module_name>
```
|
33,845,726
|
For example this is my simple python code to send e-mail:
```
import smtplib
import getpass
mail = "example@example.com"
passs = getpass.getpass("pass: ")
sendto = "example1@example2.com"
title = "Subject: example\n"
body = "blabla\n"
msg = title + body
send = smtplib.SMTP("smtp.example.com",587)
send.ehlo()
send.starttls()
send.login(mail,passs)
send.sendmail(mail,sendto,msg)
```
and it works perfectly, but whenever i search for sending emails from python much more complicated code shows up, much more modules and lines, but they do the same thing! Why is that? Is my code good or bad?
|
2015/11/21
|
[
"https://Stackoverflow.com/questions/33845726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848384/"
] |
The simplest way is to ask for its `description`:
```
cell.priceLabel.text = productPrice.price.description;
```
(All those answers that suggest formatting with `"%@"` are using `description`, indirectly.)
But if it's a price, you probably want to format it like a price. For example, in the USA, prices in US dollars are normally formatted with two digits to the right of the decimal point and a comma before every group of three digits to the left of the decimal point. So instead of using `description`, you should add an `NSNumberFormatter` to your controller and use that:
.m
--
```
@interface ViewController ()
@property (nonatomic, strong) NSNumberFormatter *priceFormatter;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.priceFormatter = [[NSNumberFormatter alloc] init];
self.priceFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
// If you don't want a currency symbol like $ in the output, do this:
// self.priceFormatter.currencySymbol = nil;
}
- (void)showPrice:(NSDecimalNumber *)price inTextField:(UILabel *)label {
label.text = [self.priceFormatter stringFromNumber:price];
}
```
There are lots of other `NSNumberFormatter` properties you can use to tweak the output, so check the [class reference](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/) if you need to.
### UPDATE
Assuming `price` is declared as `NSArray`:
```
BUYProductVariant *productPrice = price[indexPath.row];
cell.priceLabel.test = [self.formatter stringWithNumber:productPrice.price];
```
|
A UILabel expects its text value to be an NSString, so you need to create a string using the value of product.price.
```
cell.priceLabel.text = [NSString stringWithFormat:@"%@", product.price];
```
What's important is that you can't simply cast (change) the type of NSDecimalNumber, you have to convert the value in some way.
|
12,665,574
|
I'm working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
```
>>> a = [1,2,3]
>>> a
[1,2,3]
```
what I'm getting, essentially:
```
>>> a = MyList([1,2,3])
>>> a
<MyList object at 0xdeadbeef>
```
I can't figure out which dunder method (if any) would allow me to customize this behavior?
I'd think it would be \_\_ get \_\_ ? although list() doesn't implement get/set/delete - i guess because it's a built-in?
|
2012/09/30
|
[
"https://Stackoverflow.com/questions/12665574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212685/"
] |
You should override the `__repr__` method in you class (and optionally the `__str__` method too), see this [post](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) for a discussion on the differences.
Something like this:
```
class MyList(object):
def __repr__(self):
# iterate over elements and add each one to resulting string
```
As pointed in the comments, `str()` calls `__repr__` if `__str__` isn't defined, but `repr()` doesn't call `__str__` if `__repr__` isn't defined.
|
Allow me to answer my own question - I believe it's the \_\_ repr \_\_ method that I'm looking for. Please correct me if i'm wrong. Here's what I came up with:
```
def __repr__(self):
return str([i for i in iter(self)])
```
|
12,665,574
|
I'm working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
```
>>> a = [1,2,3]
>>> a
[1,2,3]
```
what I'm getting, essentially:
```
>>> a = MyList([1,2,3])
>>> a
<MyList object at 0xdeadbeef>
```
I can't figure out which dunder method (if any) would allow me to customize this behavior?
I'd think it would be \_\_ get \_\_ ? although list() doesn't implement get/set/delete - i guess because it's a built-in?
|
2012/09/30
|
[
"https://Stackoverflow.com/questions/12665574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212685/"
] |
You should override the `__repr__` method in you class (and optionally the `__str__` method too), see this [post](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) for a discussion on the differences.
Something like this:
```
class MyList(object):
def __repr__(self):
# iterate over elements and add each one to resulting string
```
As pointed in the comments, `str()` calls `__repr__` if `__str__` isn't defined, but `repr()` doesn't call `__str__` if `__repr__` isn't defined.
|
A very simple example:
```
class MyList(object):
def __init__(self,arg):
self.mylist = arg
def __repr__(self):
return 'MyList(' + str(self.mylist) + ')'
def __str__(self):
return str(self.mylist)
def __getitem__(self,i):
return self.mylist[i]
a = MyList([1,2,3])
print a
print repr(a)
for x in a:
print x
```
Output:
```
[1, 2, 3]
MyList([1, 2, 3])
1
2
3
```
|
12,665,574
|
I'm working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
```
>>> a = [1,2,3]
>>> a
[1,2,3]
```
what I'm getting, essentially:
```
>>> a = MyList([1,2,3])
>>> a
<MyList object at 0xdeadbeef>
```
I can't figure out which dunder method (if any) would allow me to customize this behavior?
I'd think it would be \_\_ get \_\_ ? although list() doesn't implement get/set/delete - i guess because it's a built-in?
|
2012/09/30
|
[
"https://Stackoverflow.com/questions/12665574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212685/"
] |
The method you are looking for wolud be `__repr__`.
See also [http://docs.python.org/reference/datamodel.html#object.**repr**](http://docs.python.org/reference/datamodel.html#object.__repr__)
|
Allow me to answer my own question - I believe it's the \_\_ repr \_\_ method that I'm looking for. Please correct me if i'm wrong. Here's what I came up with:
```
def __repr__(self):
return str([i for i in iter(self)])
```
|
12,665,574
|
I'm working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
```
>>> a = [1,2,3]
>>> a
[1,2,3]
```
what I'm getting, essentially:
```
>>> a = MyList([1,2,3])
>>> a
<MyList object at 0xdeadbeef>
```
I can't figure out which dunder method (if any) would allow me to customize this behavior?
I'd think it would be \_\_ get \_\_ ? although list() doesn't implement get/set/delete - i guess because it's a built-in?
|
2012/09/30
|
[
"https://Stackoverflow.com/questions/12665574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212685/"
] |
The method you are looking for wolud be `__repr__`.
See also [http://docs.python.org/reference/datamodel.html#object.**repr**](http://docs.python.org/reference/datamodel.html#object.__repr__)
|
A very simple example:
```
class MyList(object):
def __init__(self,arg):
self.mylist = arg
def __repr__(self):
return 'MyList(' + str(self.mylist) + ')'
def __str__(self):
return str(self.mylist)
def __getitem__(self,i):
return self.mylist[i]
a = MyList([1,2,3])
print a
print repr(a)
for x in a:
print x
```
Output:
```
[1, 2, 3]
MyList([1, 2, 3])
1
2
3
```
|
12,665,574
|
I'm working with a class that emulates a python list. I want to return it as a python list() when I access it without an index.
with a normal list():
```
>>> a = [1,2,3]
>>> a
[1,2,3]
```
what I'm getting, essentially:
```
>>> a = MyList([1,2,3])
>>> a
<MyList object at 0xdeadbeef>
```
I can't figure out which dunder method (if any) would allow me to customize this behavior?
I'd think it would be \_\_ get \_\_ ? although list() doesn't implement get/set/delete - i guess because it's a built-in?
|
2012/09/30
|
[
"https://Stackoverflow.com/questions/12665574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212685/"
] |
A very simple example:
```
class MyList(object):
def __init__(self,arg):
self.mylist = arg
def __repr__(self):
return 'MyList(' + str(self.mylist) + ')'
def __str__(self):
return str(self.mylist)
def __getitem__(self,i):
return self.mylist[i]
a = MyList([1,2,3])
print a
print repr(a)
for x in a:
print x
```
Output:
```
[1, 2, 3]
MyList([1, 2, 3])
1
2
3
```
|
Allow me to answer my own question - I believe it's the \_\_ repr \_\_ method that I'm looking for. Please correct me if i'm wrong. Here's what I came up with:
```
def __repr__(self):
return str([i for i in iter(self)])
```
|
55,564,014
|
I am unable to import the tensorflow 2.0 module into my code i end up getting this error
```
Traceback (most recent call last):
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "C:\Users\Perseus\Anaconda3\lib\imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "C:\Users\Perseus\Anaconda3\lib\imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Perseus\Anaconda3\lib\runpy.py", line 183, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "C:\Users\Perseus\Anaconda3\lib\runpy.py", line 142, in _get_module_details
return _get_module_details(pkg_main_name, error)
File "C:\Users\Perseus\Anaconda3\lib\runpy.py", line 109, in _get_module_details
__import__(pkg_name)
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\__init__.py", line 27, in <module>
from tensorflow._api.v2 import audio
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\_api\v2\audio\__init__.py", line 8, in <module>
from tensorflow.python.ops.gen_audio_ops import decode_wav
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Users\Perseus\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "C:\Users\Perseus\Anaconda3\lib\imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "C:\Users\Perseus\Anaconda3\lib\imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: DLL load failed: The specified module could not be found.
Failed to load the native TensorFlow runtime.
See https://www.tensorflow.org/install/errors
for some common reasons and solutions. Include the entire stack trace
above this error message when asking for help.
```
|
2019/04/07
|
[
"https://Stackoverflow.com/questions/55564014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11258767/"
] |
I think you hit [this bug](https://github.com/tensorflow/tensorflow/issues/22794).
You can downgrade tensorflow to `v1.10.0`
```
pip install tensorflow-gpu==1.10.0
```
or make sure that you have these versions for CUDA, Tensorflow and CUDNN:
* CUDA v9.0
* tensorflow-gpu v1.12.0
* CUDNN 7.4.1.5
Alternatively, you can uninstall tensorflow and install it through conda:
```
pip uninstall tensorflow-gpu
conda install tensorflow-gpu
```
|
tensorflow 2.0 is now officially available. You can retry. This time it should work without any errors, if CUDA and CuDNN are properly installed.
|
63,160,976
|
I am trying to split my nested list of strings into nested lists of floats. My nested list is below:
```
nested = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]
```
My desired output would be a nested list where these values remain in their sublist and are converted to floats as seen below:
```
nested = [[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]
```
The difficulty has come when trying to handle sublists with multiple strings (I.e. the first element). I have found some examples such as here [How do I split strings within nested lists in Python?](https://stackoverflow.com/questions/29002067/how-do-i-split-strings-within-nested-lists-in-python), but this code only handles sublists with one string element and I'm unsure how to apply this to sublists with multiple strings.
I am trying to avoid hardcoding anything as this is part of a script for a larger dataset and the sublist length may vary.
If anyone has any ideas, I'd appreciate some help.
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63160976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13984141/"
] |
```
result = [[float(t) for s in sublist for t in s.split(', ')] for sublist in nested]
```
which is equivalent to
```
result = []
for sublist in nested:
inner = []
for s in sublist:
for t in s.split(', '):
inner.append(float(t))
result.append(inner)
```
|
OK, starting with your example:
myNestedList = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]
```
myOutputList = []
for subList in myNestedList:
tempList = []
for valueStr in sublist:
valueFloat = float( valueStr )
tempList.append( valueFloat )
myOutputList.append( tempList )
```
It will look something like that. (don't have time to try it out, but pretty close to correct)
|
63,160,976
|
I am trying to split my nested list of strings into nested lists of floats. My nested list is below:
```
nested = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]
```
My desired output would be a nested list where these values remain in their sublist and are converted to floats as seen below:
```
nested = [[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]
```
The difficulty has come when trying to handle sublists with multiple strings (I.e. the first element). I have found some examples such as here [How do I split strings within nested lists in Python?](https://stackoverflow.com/questions/29002067/how-do-i-split-strings-within-nested-lists-in-python), but this code only handles sublists with one string element and I'm unsure how to apply this to sublists with multiple strings.
I am trying to avoid hardcoding anything as this is part of a script for a larger dataset and the sublist length may vary.
If anyone has any ideas, I'd appreciate some help.
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63160976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13984141/"
] |
```
result = [[float(t) for s in sublist for t in s.split(', ')] for sublist in nested]
```
which is equivalent to
```
result = []
for sublist in nested:
inner = []
for s in sublist:
for t in s.split(', '):
inner.append(float(t))
result.append(inner)
```
|
```py
nested = [['0.3, 0.4, 0.2', '0.5, 0.1, 0.3'], ['0.7, 0.4, 0.2'], ['0.4, 0.1, 0.3']]
new_nested = [[float(number) for strings in sublist for number in strings.split(', ')] for sublist in nested]
print(new_nested)
new_nested = list()
for sublist in nested:
sublist_new_nested = list()
for strings in sublist:
for number in strings.split(', '):
sublist_new_nested.append(float(number))
new_nested.append(sublist_new_nested)
print(new_nested)
```
Output:
```
[[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]
[[0.3, 0.4, 0.2, 0.5, 0.1, 0.3], [0.7, 0.4, 0.2], [0.4, 0.1, 0.3]]
```
|
54,901,493
|
i have problem with my code when i want signup error appear `Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'` , i try solotion of other questions same like [Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'](https://stackoverflow.com/questions/17873855/manager-isnt-available-user-has-been-swapped-for-pet-person) but all of them asking to replace `User = User = get_user_model()` but i am not use any `User` in my code or i dont know where i used that.im new in django , python , js and etc so if my question is silly forgivme .
for more information :1) i used [Django Signup Tutorial](https://wsvincent.com/django-user-authentication-tutorial-signup/) for create signup method . first that was working well but after i expand my homework project i get error .2)in others app ("products" and "search") no where im not import User and even i dont use CustomUser too bez not need to work with User in this apps.just `memebers` work with User and CustomUser.
model.py :
```
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Meta:
verbose_name = "member"
verbose_name_plural = "members"
```
setting.py:
```
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'card.apps.CardConfig',
'members.apps.MembersConfig',
'search.apps.SearchConfig',
'products.apps.ProductsConfig',
'rest_framework',
]
AUTH_USER_MODEL = 'members.CustomUser'
```
admin.py:
```
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username']
admin.site.register(CustomUser, CustomUserAdmin)
```
form.py:
```
# users/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
```
error:
```
27/Feb/2019 12:36:01] "GET /signup/ HTTP/1.1" 200 5293
Internal Server Error: /signup/
Traceback (most recent call last):
File "C:\shopping\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 383, in full_clean
self._post_clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\forms.py", line 107, in _post_clean
super()._post_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\models.py", line 403, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\shopping\venv\lib\site-packages\django\db\models\base.py", line 1137, in full_clean
self.clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\models.py", line 338, in clean
self.email = self.__class__.objects.normalize_email(self.email)
File "C:\shopping\venv\lib\site-packages\django\db\models\manager.py", line 188, in __get__
cls._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'
[27/Feb/2019 12:36:04] "POST /signup/ HTTP/1.1" 500 113770
```
|
2019/02/27
|
[
"https://Stackoverflow.com/questions/54901493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10642829/"
] |
Modify views.py
```
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
```
to
```
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
```
|
In your forms.py make changes as:
```
from django.contrib.auth import get_user_model
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
```
Also add this script in your members/**init.py** file:
```
default_app_config = 'members.apps.MembersConfig'
```
|
14,447,202
|
Heroku seems to prefer the apps deployed have a certain structure, mostly that the .git and manage.py is at root level and everything else is below that.
I have inherited a Django app I'm trying to deploy for testing purposes and I don't think I can restructure it so I was wondering if I have an alternative.
The structure I've inherited has most of the files in the root folder:
```
./foo:
__init__.py,
.git,
Procfile,
settings.py,
manage.py,
bar/
models.py, etc
```
From within foo I can run `python manage.py shell` and in there `from foo.bar import models` works.
However, when I push this to Heroku, it puts the root in `/app`, so `foo` becomes `app` and `from foo.bar import models` no longer works.
Is there any magic settings that would allow me to indicate that `app` is really `foo` and allow me to continue without refactoring the app structure and/or all the imports?
*Similar question*: I think my question is similar to [Heroku - Django: Had to change every mentioning of `myproject` into `app` to get my site working. How to best avoid this in the future?](https://stackoverflow.com/questions/11972817/heroku-django-had-to-change-every-mentioning-of-myproject-into-app-to-get), except I'm asking if there's anything I can do without changing the site structure.
|
2013/01/21
|
[
"https://Stackoverflow.com/questions/14447202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998312/"
] |
Just in case someone else has this trouble, my findings are:
There is nothing to solve -- the sandbox is just really slow, sometimes it took a couple days for the profile to become active and send the IPN. In other words, sandbox isn't good to test these functions at all, just go live and refund a couple tests. Even live sometimes takes a bit of time... I've seen it take a few hours sometimes, so don't go crazy.
|
From PayPal doco:
"By default, PayPal does not activate the profile if the initial payment amount fails. To override this default behavior, set the FAILEDINITAMTACTION field to ContinueOnFailure. If the initial payment amount fails, ContinueOnFailure instructs PayPal to add the failed payment amount to the outstanding balance due on this recurring payment profile.
If you do not set FAILEDINITAMTACTION or set it to CancelOnFailure, PayPal creates the recurring payment profile. However, PayPal places the profile into a pending status until the initial payment completes. If the initial payment clears, PayPal notifies you by Instant Payment Notification (IPN) that it has activated the pending profile. If the payment fails, PayPal notifies you by IPN that it has canceled the pending profile"
from <https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_WPRecurringPayments>, just below Table 6.
|
25,317,140
|
I may be going about this the wrong way but that's why I'm asking the question.
I have a source of serial data that is connected to a SOC then streams the serial data up to a socket on my server over UDP. The baud rate of the raw data is 57600, I'm trying to use Python to receive and parse the data. I tested that I'm receiving the data successfully on the port via the script below (found here: <https://wiki.python.org/moin/UdpCommunication>)
```
import socket
UDP_IP = "MY IP"
UDP_PORT = My PORT
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
```
Since I'm not reading the data with the .serial lib in Python or setting the baud rate to read at it comes all garbled, as would be expected. My end goal is to be able to receive and parse the data for server side processing and also have another client connect to the raw data stream piped back out from the server (proxy) which is why I'm not processing the data directly from the serial port on the device.
So my question is, how can I have Python treat the socket as a serial port that I can set a baud rate on and #import serial and .read from? I can't seem to find any examples online which makes me think I'm overlooking something simple or am trying to do something stupid.
sadface
=======
|
2014/08/14
|
[
"https://Stackoverflow.com/questions/25317140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993775/"
] |
You can't treat a socket as a serial line. A socket can only send and receive data (data stream for TCP, packets for UDP). If you would need a facility to control the serial line on the SOC you would need to build an appropriate control protocol over the socket, i.e. either use another socket for control like FTP does or use in-band control and distinguish between controlling and data like HTTP does. And of course both sides of the connection have to understand this protocol.
|
Build on facts
--------------
A first thing to start with is to summarise facts -- **begining from the very SystemOnChip** (SOC) all the way up ...:
1. an originator serial-bitstream parameters ::= **57600** Bd, **X**-<*dataBIT*>-s, **Y**-<*stopBIT*>, **Z**-<*parityBIT*>,
2. a mediator receiving process de-framing <*data*> from a raw-bitstream
3. a mediator upStream sending to server-process integration needs specification ( FSA-model of a multi-party hand-shaking, fault-detection, failure-state-resilience, logging, ... )
4. T.B.C. ...
Design as per a valid requirement list
--------------------------------------
A few things work as a just bunch of SLOC one-liners. Design carefully against the validated Requirement List as a principle. It saves both your side and the cooperating Team(s).
Test on models
--------------
Worth a time to test on-the-fly, during the efforts to progress from simple parts to more complex, multiparty scenarios.
Integrate on smarter frameworks
-------------------------------
Definitely a waste of time to reinvent wheel. Using a smart framework for server-side integration will unlock a lot of your time and energy on your ProblemDOMAIN-specific tasks, rather than to waste both the former and the latter for writing your just-another-socket-framework ( destined in majority of cases to failure ... )
Try **ZeroMQ** or a **nanomsg** Scale-able Formal Communication Patterns Framework for smart-services to send de-framed data from your serial-bitStream source and you are almost there.
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
If you're not avert to using external packages, [`pandas.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame) might be a viable candidate since it looks like you'll be using a table:
```
import pandas as pd
df = pd.DataFrame(
index=pd.MultiIndex.from_product([d['weather'], d['season']]),
columns=d['lateness'], data=0
)
```
Result:
```
ontime delayed
windy summer 0 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 0
```
And you can easily make changes with [indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html):
```
df.loc[('windy', 'summer'), 'ontime'] = 1
df.loc['calm', 'autumn']['delayed'] = 2
# Result:
ontime delayed
windy summer 1 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 2
```
The table can be constructed dynamically if you will always use the last key for columns, *assuming your keys are in the desired insertion order*:
```
df = pd.DataFrame(
index=pd.MultiIndex.from_product(list(d.values())[:-1]),
columns=list(d.values())[-1], data=0
)
```
---
Since you're interested in `pandas`, given your structure, I would also recommend giving a good read over on [MultiIndex and Advance Indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html), just to get some idea on how to play around with your data. Here are some examples:
```
# Gets the sum of 'delayed' items in all of 'calm'
# Filters all the 'delayed' data in 'calm'
df.loc['calm', 'delayed']
# summer 5
# winter 0
# spring 0
# autumn 2
# Name: delayed, dtype: int64
# Apply a sum:
df.loc['calm', 'delayed'].sum()
# 7
# Gets the mean of all 'summer' (notice the `slice(None)` is required to return all of the 'calm' and 'windy' group)
df.loc[(slice(None), 'summer'), :].mean()
# ontime 0.5
# delayed 2.5
# dtype: float64
```
It definitely is very handy and versatile, but before you get too deep into it you might will definitely want to read up first, the framework might take some getting used to.
---
Otherwise, if you still prefer `dict`, there's nothing wrong with that. Here's a recursive function to generate based on the given keys *(assuming your keys are in the desired insertion order)*:
```
def gen_dict(d, level=0):
if level >= len(d):
return 0
key = tuple(d.keys())[level]
return {val: gen_dict(d, level+1) for val in d.get(key)}
gen_dict(d)
```
Result:
```
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
|
Yes, you can achieve this using the following code:
```
import copy
structure = ['weather', 'season', 'lateness']
data = {'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed'], }
d_tree = dict()
n = len(structure) # length of the structure list
prev_val = 0 # the innermost value
while n > 0:
n -= 1
keys = data.get(structure[n]) or list() # get the list of values from data
# Idea here is to start with inner most dict and keep moving outer
d_tree.clear()
for key in keys:
d_tree[key] = copy.copy(prev_val)
prev_val = copy.copy(d_tree) # Copy the d_tree to put as value to outer dict
print(d_tree)
```
Hope this helps!!
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
I think this might work for you.
```
def get_output(category, order, i=0):
output = {}
for key in order[i:i+1]:
for value in category[key]:
output[value] = get_output(category, order, i+1)
if output == {}:
return 0
return output
```
|
Yes, you can achieve this using the following code:
```
import copy
structure = ['weather', 'season', 'lateness']
data = {'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed'], }
d_tree = dict()
n = len(structure) # length of the structure list
prev_val = 0 # the innermost value
while n > 0:
n -= 1
keys = data.get(structure[n]) or list() # get the list of values from data
# Idea here is to start with inner most dict and keep moving outer
d_tree.clear()
for key in keys:
d_tree[key] = copy.copy(prev_val)
prev_val = copy.copy(d_tree) # Copy the d_tree to put as value to outer dict
print(d_tree)
```
Hope this helps!!
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
You could use [`itertools.product`](https://docs.python.org/3.8/library/itertools.html#itertools.product) to get the cartesian product between the dictionary values(assuming you want the same key order). Then we can iterate every key except the last, insert/update dictionaries with `setdefault`. Then we can set the inner most key with a count of `0`.
```
from itertools import product
from pprint import pprint
d = {
"weather": ["windy", "calm"],
"season": ["summer", "winter", "spring", "autumn"],
"lateness": ["ontime", "delayed"],
}
result = {}
for comb in product(*d.values()):
current = result
for key in comb[:-1]:
current = current.setdefault(key, {})
current[comb[-1]] = 0
pprint(result)
```
**Output:**
```
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
If we want a custom order(might be useful for older python versions with no guaranteed key order), we can pass a list to `product()`:
```
order = ['weather', 'season', 'lateness']
result = {}
for comb in product(*map(d.get, order)):
current = result
for key in comb[:-1]:
current = current.setdefault(key, {})
current[comb[-1]] = 0
```
|
Yes, you can achieve this using the following code:
```
import copy
structure = ['weather', 'season', 'lateness']
data = {'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed'], }
d_tree = dict()
n = len(structure) # length of the structure list
prev_val = 0 # the innermost value
while n > 0:
n -= 1
keys = data.get(structure[n]) or list() # get the list of values from data
# Idea here is to start with inner most dict and keep moving outer
d_tree.clear()
for key in keys:
d_tree[key] = copy.copy(prev_val)
prev_val = copy.copy(d_tree) # Copy the d_tree to put as value to outer dict
print(d_tree)
```
Hope this helps!!
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
Here's a recursive solution that is slightly different from the one provided by r.ook in the excellent accepted answer:
```
category_cases = {'weather': ['windy', 'calm'],
'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed']}
order = ['weather', 'season', 'lateness']
def gen_tree(category_cases, order):
if len(order) == 0:
return 0
return {x:gen_tree(category_cases, order[1:]) for x in category_cases[order[0]]}
```
It does *not* assume that the dictionary preserves the order of the keys, so it should be more backwards compatible.
|
Yes, you can achieve this using the following code:
```
import copy
structure = ['weather', 'season', 'lateness']
data = {'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed'], }
d_tree = dict()
n = len(structure) # length of the structure list
prev_val = 0 # the innermost value
while n > 0:
n -= 1
keys = data.get(structure[n]) or list() # get the list of values from data
# Idea here is to start with inner most dict and keep moving outer
d_tree.clear()
for key in keys:
d_tree[key] = copy.copy(prev_val)
prev_val = copy.copy(d_tree) # Copy the d_tree to put as value to outer dict
print(d_tree)
```
Hope this helps!!
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
If you're not avert to using external packages, [`pandas.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame) might be a viable candidate since it looks like you'll be using a table:
```
import pandas as pd
df = pd.DataFrame(
index=pd.MultiIndex.from_product([d['weather'], d['season']]),
columns=d['lateness'], data=0
)
```
Result:
```
ontime delayed
windy summer 0 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 0
```
And you can easily make changes with [indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html):
```
df.loc[('windy', 'summer'), 'ontime'] = 1
df.loc['calm', 'autumn']['delayed'] = 2
# Result:
ontime delayed
windy summer 1 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 2
```
The table can be constructed dynamically if you will always use the last key for columns, *assuming your keys are in the desired insertion order*:
```
df = pd.DataFrame(
index=pd.MultiIndex.from_product(list(d.values())[:-1]),
columns=list(d.values())[-1], data=0
)
```
---
Since you're interested in `pandas`, given your structure, I would also recommend giving a good read over on [MultiIndex and Advance Indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html), just to get some idea on how to play around with your data. Here are some examples:
```
# Gets the sum of 'delayed' items in all of 'calm'
# Filters all the 'delayed' data in 'calm'
df.loc['calm', 'delayed']
# summer 5
# winter 0
# spring 0
# autumn 2
# Name: delayed, dtype: int64
# Apply a sum:
df.loc['calm', 'delayed'].sum()
# 7
# Gets the mean of all 'summer' (notice the `slice(None)` is required to return all of the 'calm' and 'windy' group)
df.loc[(slice(None), 'summer'), :].mean()
# ontime 0.5
# delayed 2.5
# dtype: float64
```
It definitely is very handy and versatile, but before you get too deep into it you might will definitely want to read up first, the framework might take some getting used to.
---
Otherwise, if you still prefer `dict`, there's nothing wrong with that. Here's a recursive function to generate based on the given keys *(assuming your keys are in the desired insertion order)*:
```
def gen_dict(d, level=0):
if level >= len(d):
return 0
key = tuple(d.keys())[level]
return {val: gen_dict(d, level+1) for val in d.get(key)}
gen_dict(d)
```
Result:
```
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
|
I think this might work for you.
```
def get_output(category, order, i=0):
output = {}
for key in order[i:i+1]:
for value in category[key]:
output[value] = get_output(category, order, i+1)
if output == {}:
return 0
return output
```
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
If you're not avert to using external packages, [`pandas.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame) might be a viable candidate since it looks like you'll be using a table:
```
import pandas as pd
df = pd.DataFrame(
index=pd.MultiIndex.from_product([d['weather'], d['season']]),
columns=d['lateness'], data=0
)
```
Result:
```
ontime delayed
windy summer 0 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 0
```
And you can easily make changes with [indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html):
```
df.loc[('windy', 'summer'), 'ontime'] = 1
df.loc['calm', 'autumn']['delayed'] = 2
# Result:
ontime delayed
windy summer 1 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 2
```
The table can be constructed dynamically if you will always use the last key for columns, *assuming your keys are in the desired insertion order*:
```
df = pd.DataFrame(
index=pd.MultiIndex.from_product(list(d.values())[:-1]),
columns=list(d.values())[-1], data=0
)
```
---
Since you're interested in `pandas`, given your structure, I would also recommend giving a good read over on [MultiIndex and Advance Indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html), just to get some idea on how to play around with your data. Here are some examples:
```
# Gets the sum of 'delayed' items in all of 'calm'
# Filters all the 'delayed' data in 'calm'
df.loc['calm', 'delayed']
# summer 5
# winter 0
# spring 0
# autumn 2
# Name: delayed, dtype: int64
# Apply a sum:
df.loc['calm', 'delayed'].sum()
# 7
# Gets the mean of all 'summer' (notice the `slice(None)` is required to return all of the 'calm' and 'windy' group)
df.loc[(slice(None), 'summer'), :].mean()
# ontime 0.5
# delayed 2.5
# dtype: float64
```
It definitely is very handy and versatile, but before you get too deep into it you might will definitely want to read up first, the framework might take some getting used to.
---
Otherwise, if you still prefer `dict`, there's nothing wrong with that. Here's a recursive function to generate based on the given keys *(assuming your keys are in the desired insertion order)*:
```
def gen_dict(d, level=0):
if level >= len(d):
return 0
key = tuple(d.keys())[level]
return {val: gen_dict(d, level+1) for val in d.get(key)}
gen_dict(d)
```
Result:
```
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
|
You could use [`itertools.product`](https://docs.python.org/3.8/library/itertools.html#itertools.product) to get the cartesian product between the dictionary values(assuming you want the same key order). Then we can iterate every key except the last, insert/update dictionaries with `setdefault`. Then we can set the inner most key with a count of `0`.
```
from itertools import product
from pprint import pprint
d = {
"weather": ["windy", "calm"],
"season": ["summer", "winter", "spring", "autumn"],
"lateness": ["ontime", "delayed"],
}
result = {}
for comb in product(*d.values()):
current = result
for key in comb[:-1]:
current = current.setdefault(key, {})
current[comb[-1]] = 0
pprint(result)
```
**Output:**
```
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
If we want a custom order(might be useful for older python versions with no guaranteed key order), we can pass a list to `product()`:
```
order = ['weather', 'season', 'lateness']
result = {}
for comb in product(*map(d.get, order)):
current = result
for key in comb[:-1]:
current = current.setdefault(key, {})
current[comb[-1]] = 0
```
|
61,831,953
|
I am looking for a way in python to make a dictionary of dictionaries based on the desired structure dynamically.
I have the data bellow:
```py
{'weather': ['windy', 'calm'], 'season': ['summer', 'winter', 'spring', 'autumn'], 'lateness': ['ontime', 'delayed']}
```
I give the structure I want them to be like:
```py
['weather', 'season', 'lateness']
```
and finally get the data in this format:
```py
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
This is the manual way that I thought for achieving this:
```py
dtree = {}
for cat1 in category_cases['weather']:
dtree.setdefault(cat1, {})
for cat2 in category_cases['season']:
dtree[cat1].setdefault(cat2, {})
for cat3 in category_cases['lateness']:
dtree[cat1][cat2].setdefault(cat3, 0)
```
Can you think of a way to be able to just change the structure I wrote and having the desired result?
Keep in mind that the structure might not be the same size every time.
Also if you think of another way except dictionaries that I can access the result, it will also work for me.
|
2020/05/16
|
[
"https://Stackoverflow.com/questions/61831953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4377632/"
] |
If you're not avert to using external packages, [`pandas.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html#pandas.DataFrame) might be a viable candidate since it looks like you'll be using a table:
```
import pandas as pd
df = pd.DataFrame(
index=pd.MultiIndex.from_product([d['weather'], d['season']]),
columns=d['lateness'], data=0
)
```
Result:
```
ontime delayed
windy summer 0 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 0
```
And you can easily make changes with [indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html):
```
df.loc[('windy', 'summer'), 'ontime'] = 1
df.loc['calm', 'autumn']['delayed'] = 2
# Result:
ontime delayed
windy summer 1 0
winter 0 0
spring 0 0
autumn 0 0
calm summer 0 0
winter 0 0
spring 0 0
autumn 0 2
```
The table can be constructed dynamically if you will always use the last key for columns, *assuming your keys are in the desired insertion order*:
```
df = pd.DataFrame(
index=pd.MultiIndex.from_product(list(d.values())[:-1]),
columns=list(d.values())[-1], data=0
)
```
---
Since you're interested in `pandas`, given your structure, I would also recommend giving a good read over on [MultiIndex and Advance Indexing](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html), just to get some idea on how to play around with your data. Here are some examples:
```
# Gets the sum of 'delayed' items in all of 'calm'
# Filters all the 'delayed' data in 'calm'
df.loc['calm', 'delayed']
# summer 5
# winter 0
# spring 0
# autumn 2
# Name: delayed, dtype: int64
# Apply a sum:
df.loc['calm', 'delayed'].sum()
# 7
# Gets the mean of all 'summer' (notice the `slice(None)` is required to return all of the 'calm' and 'windy' group)
df.loc[(slice(None), 'summer'), :].mean()
# ontime 0.5
# delayed 2.5
# dtype: float64
```
It definitely is very handy and versatile, but before you get too deep into it you might will definitely want to read up first, the framework might take some getting used to.
---
Otherwise, if you still prefer `dict`, there's nothing wrong with that. Here's a recursive function to generate based on the given keys *(assuming your keys are in the desired insertion order)*:
```
def gen_dict(d, level=0):
if level >= len(d):
return 0
key = tuple(d.keys())[level]
return {val: gen_dict(d, level+1) for val in d.get(key)}
gen_dict(d)
```
Result:
```
{'calm': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}},
'windy': {'autumn': {'delayed': 0, 'ontime': 0},
'spring': {'delayed': 0, 'ontime': 0},
'summer': {'delayed': 0, 'ontime': 0},
'winter': {'delayed': 0, 'ontime': 0}}}
```
|
Here's a recursive solution that is slightly different from the one provided by r.ook in the excellent accepted answer:
```
category_cases = {'weather': ['windy', 'calm'],
'season': ['summer', 'winter', 'spring', 'autumn'],
'lateness': ['ontime', 'delayed']}
order = ['weather', 'season', 'lateness']
def gen_tree(category_cases, order):
if len(order) == 0:
return 0
return {x:gen_tree(category_cases, order[1:]) for x in category_cases[order[0]]}
```
It does *not* assume that the dictionary preserves the order of the keys, so it should be more backwards compatible.
|
37,912,206
|
Given a list:
```
l1 = [0, 211, 576, 941, 1307, 1672, 2037]
```
What is the most pythonic way of getting the index of the last element of the list. Given that Python lists are zero-indexed, is it:
```
len(l1) - 1
```
Or, is it the following which uses Python's list operations:
```
l1.index(l1[-1])
```
Both return the same value, that is 6.
|
2016/06/19
|
[
"https://Stackoverflow.com/questions/37912206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3096712/"
] |
Only the first is correct:
```
>>> lst = [1, 2, 3, 4, 1]
>>> len(lst) - 1
4
>>> lst.index(lst[-1])
0
```
However it depends on what do you mean by "the index of the last element".
Note that `index` must traverse the whole list in order to provide an answer:
```
In [1]: %%timeit lst = list(range(100000))
...: lst.index(lst[-1])
...:
1000 loops, best of 3: 1.82 ms per loop
In [2]: %%timeit lst = list(range(100000))
len(lst)-1
...:
The slowest run took 80.20 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 109 ns per loop
```
Note that the second timing is in **nanoseconds** versus **milliseconds** for the first one.
|
You should use the first. Why?
```
>>> l1 = [1,2,3,4,3]
>>> l1.index(l1[-1])
2
```
|
37,912,206
|
Given a list:
```
l1 = [0, 211, 576, 941, 1307, 1672, 2037]
```
What is the most pythonic way of getting the index of the last element of the list. Given that Python lists are zero-indexed, is it:
```
len(l1) - 1
```
Or, is it the following which uses Python's list operations:
```
l1.index(l1[-1])
```
Both return the same value, that is 6.
|
2016/06/19
|
[
"https://Stackoverflow.com/questions/37912206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3096712/"
] |
Only the first is correct:
```
>>> lst = [1, 2, 3, 4, 1]
>>> len(lst) - 1
4
>>> lst.index(lst[-1])
0
```
However it depends on what do you mean by "the index of the last element".
Note that `index` must traverse the whole list in order to provide an answer:
```
In [1]: %%timeit lst = list(range(100000))
...: lst.index(lst[-1])
...:
1000 loops, best of 3: 1.82 ms per loop
In [2]: %%timeit lst = list(range(100000))
len(lst)-1
...:
The slowest run took 80.20 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 109 ns per loop
```
Note that the second timing is in **nanoseconds** versus **milliseconds** for the first one.
|
Bakuriu's answer is great!
In addition, it should be mentioned that you rarely need this value. There are usually other and better ways to do what you want to do. Consider this answer as a sidenote :)
As you mention, getting the last element can be done this way:
```
lst = [1,2,4,2,3]
print lst[-1] # 3
```
If you need to iterate over a list, you should do this:
```
for element in lst:
# do something with element
```
If you still need the index, this is the preferred method:
```
for i, element in enumerate(lst):
# i is the index, element is the actual list element
```
|
37,912,206
|
Given a list:
```
l1 = [0, 211, 576, 941, 1307, 1672, 2037]
```
What is the most pythonic way of getting the index of the last element of the list. Given that Python lists are zero-indexed, is it:
```
len(l1) - 1
```
Or, is it the following which uses Python's list operations:
```
l1.index(l1[-1])
```
Both return the same value, that is 6.
|
2016/06/19
|
[
"https://Stackoverflow.com/questions/37912206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3096712/"
] |
You should use the first. Why?
```
>>> l1 = [1,2,3,4,3]
>>> l1.index(l1[-1])
2
```
|
Bakuriu's answer is great!
In addition, it should be mentioned that you rarely need this value. There are usually other and better ways to do what you want to do. Consider this answer as a sidenote :)
As you mention, getting the last element can be done this way:
```
lst = [1,2,4,2,3]
print lst[-1] # 3
```
If you need to iterate over a list, you should do this:
```
for element in lst:
# do something with element
```
If you still need the index, this is the preferred method:
```
for i, element in enumerate(lst):
# i is the index, element is the actual list element
```
|
41,788,056
|
I am following [this tutorial](https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python) on setting up cloud endpoints in python on googles app engine and keep on getting an import error
```
ImportError: No module named control
```
on the **Generating the OpenAPI configuration file** step when I input
```
python lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname echo-api.endpoints.projectid.cloud.goog
```
I followed these steps on a new account and still got this error. No idea what I am doing wrong/steps I am skipping.
here is the traceback:
```
Traceback (most recent call last):
File "lib/endpoints/endpointscfg.py", line 625, in <module>
main(sys.argv)
File "lib/endpoints/endpointscfg.py", line 621, in main
args.callback(args)
File "lib/endpoints/endpointscfg.py", line 479, in _GenOpenApiSpecCallback
application_path=args.application)
File "lib/endpoints/endpointscfg.py", line 324, in _GenOpenApiSpec
application_path=application_path)
File "lib/endpoints/endpointscfg.py", line 181, in GenApiConfig
module = __import__(module_name, fromlist=base_service_class_name)
File "/home/hairyhenry/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/main.py", line 19, in <module>
import endpoints
File "/home/hairyhenry/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/lib/endpoints/__init__.py", line 29, in <module>
from apiserving import *
File "/home/hairyhenry/python-docs-samples/appengine/standard/endpoints-frameworks-v2/echo/lib/endpoints/apiserving.py", line 74, in <module>
from google.api.control import client as control_client
ImportError: No module named control
```
any insight would be fabulous
|
2017/01/22
|
[
"https://Stackoverflow.com/questions/41788056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5327279/"
] |
You have to indent all the statements after your while loops and a single iteration version of your program should work. Proper indentation is critical in python. Lots of sites talk about python indentation (see [here](http://www.peachpit.com/articles/article.aspx?p=1312792&seqNum=3) for example). You were also missing the outer loop that would allow it to loop indefinitely.
Additionally you can clear the graph after each iteration.
```
import pylab
import math
xs=[]
ys=[]
x0=-4.0
x1=+4.0
x=x0
n=500
dx=(x1-x0)/n
while True:
a=input("Enter a: ")
b=input("Enter b: ")
c=input("Enter c: ")
a=int(a)
b=int(b)
c=int(c)
xs=[]
ys=[]
x=x0
while x<=x1:
xs.append(x)
y=(a*x**2)+(b*x+c)
x+=dx
ys.append(y)
pylab.plot(xs,ys,"rx-")
print(xs)
print(ys)
pylab.show()
pylab.clf()
```
|
First, you have to do your indentation correctly in the while-loop.
Second, your while loop only create the lists, `xs` and `ys`. That's why you can't keep the prompt and plot running again and again. So you have to use another loop to repeat your code above. Here is an example.
```
import matplotlib.pyplot as plt
import math
def interactiveQPlot():
xs=[]
ys=[]
x0=-4.0
x1=+4.0
x=x0
n=500
dx=(x1-x0)/n
a= input("Enter a: ")
b = input("Enter b: ")
c= input("Enter c: ")
a=int(a)
b=int(b)
c=int(c)
while x<=x1:
xs.append(x)
y=(a*x**2)+(b*x+c)
ys.append(y)
x+=dx
plt.plot(xs,ys,"rx-")
print(xs)
print(ys)
plt.show()
while True:
interactiveQPlot()
```
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
In case of upgrading your python on mac os 10.7 and pkg\_resources doesn't work, the simplest way to fix this is just reinstall setuptools as Ned mentioned above.
```
sudo pip install setuptools --upgrade
or sudo easy_install install setuptools --upgrade
```
|
Try this only if you are ok with uninstalling python.
I uninstalled python using
```
brew uninstall python
```
then later installed using
```
brew install python
```
then it worked!
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
On my system (OSX 10.6) that package is at
```
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py
```
I hope that helps you figure out if it's missing or just not on your path.
|
I got this error on **Ubuntu**, and the following worked for me:
Removed the dropbox binaries and download them again, by running:
```
sudo rm -rf /var/lib/dropbox/.dropbox-dist
dropbox start -i
```
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
The reason might be because the IPython module is not in your PYTHONPATH.
If you donwload IPython and then do
python setup.py install
The setup doesn't add the module IPython to your python path.
You might want to add it to your PYTHONPATH manually. It should work after you do :
export PYTHONPATH=/pathtoIPython:$PYTHONPATH
Add this line in your .bashrc or .profile to make it permanent.
|
I got this error on **Ubuntu**, and the following worked for me:
Removed the dropbox binaries and download them again, by running:
```
sudo rm -rf /var/lib/dropbox/.dropbox-dist
dropbox start -i
```
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
[UPDATE] TL;DR `pkg_resources` is provided by either [Distribute](http://pypi.python.org/pypi/distribute/) or [setuptools](http://pypi.python.org/pypi/setuptools/).
[UPDATE 2] As announced at PyCon 2013, the `Distribute` and `setuptools` projects have re-merged. `Distribute` is now deprecated and you should just use the new current `setuptools`. Try this:
```
curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py
```
Or, better, use a current [`pip`](https://pypi.python.org/pypi/pip) as the high level interface and which will use `setuptools` under the covers.
[Longer answer for OP's specific problem]:
You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use `/usr/local/lib` by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search `$PATH` (that is, typing `python2.6` invokes it as expected); the python2.6 installer should have modified your `.bash_profile` to put its framework bin directory at the front of `$PATH`. Then install `easy_install` using [setuptools](http://pypi.python.org/pypi/setuptools/) following the instructions there. The `pkg_resources` module is also automatically installed by this step.
Then use the newly-installed version of `easy_install` (or `pip`) to install `ipython`.
```
easy_install ipython
```
or
```
pip install ipython
```
It should automatically get installed to the correct `site-packages` location for that python instance and you should be good to go.
|
Try this only if you are ok with uninstalling python.
I uninstalled python using
```
brew uninstall python
```
then later installed using
```
brew install python
```
then it worked!
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
The reason might be because the IPython module is not in your PYTHONPATH.
If you donwload IPython and then do
python setup.py install
The setup doesn't add the module IPython to your python path.
You might want to add it to your PYTHONPATH manually. It should work after you do :
export PYTHONPATH=/pathtoIPython:$PYTHONPATH
Add this line in your .bashrc or .profile to make it permanent.
|
I encountered with the same problem when i am working on autobahn related project.
1) So I download the setuptools.-0.9.8.tar.gz form <https://pypi.python.org/packages/source/s/setuptools/> and extract it.
2 )Then i get the pkg\_resources module and copy it to the folder where it needed.
\*\*in my case that folder was C:\Python27\Lib\site-packages\autobahn
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
[UPDATE] TL;DR `pkg_resources` is provided by either [Distribute](http://pypi.python.org/pypi/distribute/) or [setuptools](http://pypi.python.org/pypi/setuptools/).
[UPDATE 2] As announced at PyCon 2013, the `Distribute` and `setuptools` projects have re-merged. `Distribute` is now deprecated and you should just use the new current `setuptools`. Try this:
```
curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py
```
Or, better, use a current [`pip`](https://pypi.python.org/pypi/pip) as the high level interface and which will use `setuptools` under the covers.
[Longer answer for OP's specific problem]:
You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use `/usr/local/lib` by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search `$PATH` (that is, typing `python2.6` invokes it as expected); the python2.6 installer should have modified your `.bash_profile` to put its framework bin directory at the front of `$PATH`. Then install `easy_install` using [setuptools](http://pypi.python.org/pypi/setuptools/) following the instructions there. The `pkg_resources` module is also automatically installed by this step.
Then use the newly-installed version of `easy_install` (or `pip`) to install `ipython`.
```
easy_install ipython
```
or
```
pip install ipython
```
It should automatically get installed to the correct `site-packages` location for that python instance and you should be good to go.
|
On my system (OSX 10.6) that package is at
```
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py
```
I hope that helps you figure out if it's missing or just not on your path.
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
I encountered the same `ImportError`. Somehow the `setuptools` package had been deleted in my Python environment.
To fix the issue, run the setup script for `setuptools`:
```
curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python
```
If you have any version of [`distribute`](http://pythonhosted.org/setuptools/merge-faq.html), or any `setuptools` below 0.6, you will have to uninstall it first.\*
See [Installation Instructions](https://pypi.python.org/pypi/setuptools/0.9.8#installation-instructions) for further details.
---
\* If you already have a working `distribute`, upgrading it to the "compatibility wrapper" that switches you over to `setuptools` is easier. But if things are already broken, don't try that.
|
I realize this is not related to OSX, but on an embedded system (Beagle Bone Angstrom) I had the exact same error message. Installing the following ipk packages solved it.
```
opkg install python-setuptools
opkg install python-pip
```
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
I encountered the same `ImportError`. Somehow the `setuptools` package had been deleted in my Python environment.
To fix the issue, run the setup script for `setuptools`:
```
curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python
```
If you have any version of [`distribute`](http://pythonhosted.org/setuptools/merge-faq.html), or any `setuptools` below 0.6, you will have to uninstall it first.\*
See [Installation Instructions](https://pypi.python.org/pypi/setuptools/0.9.8#installation-instructions) for further details.
---
\* If you already have a working `distribute`, upgrading it to the "compatibility wrapper" that switches you over to `setuptools` is easier. But if things are already broken, don't try that.
|
Try this only if you are ok with uninstalling python.
I uninstalled python using
```
brew uninstall python
```
then later installed using
```
brew install python
```
then it worked!
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
[UPDATE] TL;DR `pkg_resources` is provided by either [Distribute](http://pypi.python.org/pypi/distribute/) or [setuptools](http://pypi.python.org/pypi/setuptools/).
[UPDATE 2] As announced at PyCon 2013, the `Distribute` and `setuptools` projects have re-merged. `Distribute` is now deprecated and you should just use the new current `setuptools`. Try this:
```
curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py
```
Or, better, use a current [`pip`](https://pypi.python.org/pypi/pip) as the high level interface and which will use `setuptools` under the covers.
[Longer answer for OP's specific problem]:
You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use `/usr/local/lib` by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search `$PATH` (that is, typing `python2.6` invokes it as expected); the python2.6 installer should have modified your `.bash_profile` to put its framework bin directory at the front of `$PATH`. Then install `easy_install` using [setuptools](http://pypi.python.org/pypi/setuptools/) following the instructions there. The `pkg_resources` module is also automatically installed by this step.
Then use the newly-installed version of `easy_install` (or `pip`) to install `ipython`.
```
easy_install ipython
```
or
```
pip install ipython
```
It should automatically get installed to the correct `site-packages` location for that python instance and you should be good to go.
|
I encountered with the same problem when i am working on autobahn related project.
1) So I download the setuptools.-0.9.8.tar.gz form <https://pypi.python.org/packages/source/s/setuptools/> and extract it.
2 )Then i get the pkg\_resources module and copy it to the folder where it needed.
\*\*in my case that folder was C:\Python27\Lib\site-packages\autobahn
|
1,756,721
|
I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-packages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages']
```
Apparently that is not all the required paths because I can't run iPython.
```
$ ipython
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named `pkg_resources`
```
I've done Google searches and I can't really figure out how to install `pkg_resources` or make sure it's on the path.
What do I need to do to fix this?
|
2009/11/18
|
[
"https://Stackoverflow.com/questions/1756721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86731/"
] |
I encountered the same `ImportError`. Somehow the `setuptools` package had been deleted in my Python environment.
To fix the issue, run the setup script for `setuptools`:
```
curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python
```
If you have any version of [`distribute`](http://pythonhosted.org/setuptools/merge-faq.html), or any `setuptools` below 0.6, you will have to uninstall it first.\*
See [Installation Instructions](https://pypi.python.org/pypi/setuptools/0.9.8#installation-instructions) for further details.
---
\* If you already have a working `distribute`, upgrading it to the "compatibility wrapper" that switches you over to `setuptools` is easier. But if things are already broken, don't try that.
|
I encountered with the same problem when i am working on autobahn related project.
1) So I download the setuptools.-0.9.8.tar.gz form <https://pypi.python.org/packages/source/s/setuptools/> and extract it.
2 )Then i get the pkg\_resources module and copy it to the folder where it needed.
\*\*in my case that folder was C:\Python27\Lib\site-packages\autobahn
|
42,838,366
|
I think this question has been asked many times, but I can't find the answer. I am probably not using the correct words in my searches.
I am a beginner in python and I am learning to make simple games, with the pygame library. I would like to create a variable `character`, containing x and y coordinates.
I would like something like `character[x=default_value,y=default_value]`, and then edit these coordinates for example by typing `character[x]=new_value`.
Is there a way to achieve something like that in python ?
EDIT : Thank you all, I used dictionary like that `character= {'x':'value', 'y':'value'}` and it works perfectly!
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42838366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682871/"
] |
You could use a dictionary like this:
```
character = {'Name': 'Mary', 'xPos': 0, 'yPos': 0}
character['xPos'] = 10
```
|
You can use dictionary.
```
character = dict()
character['x']= default_value
character['y']= default_value
```
You might want to have a look at this [Documentation](https://learnpythonthehardway.org/book/ex39.html)
|
42,838,366
|
I think this question has been asked many times, but I can't find the answer. I am probably not using the correct words in my searches.
I am a beginner in python and I am learning to make simple games, with the pygame library. I would like to create a variable `character`, containing x and y coordinates.
I would like something like `character[x=default_value,y=default_value]`, and then edit these coordinates for example by typing `character[x]=new_value`.
Is there a way to achieve something like that in python ?
EDIT : Thank you all, I used dictionary like that `character= {'x':'value', 'y':'value'}` and it works perfectly!
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42838366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682871/"
] |
A dict would work, but a [class](https://docs.python.org/3/tutorial/classes.html) is a better fit IMO.
```
class Character:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
arthur = Character(9, 9)
arthur.x = 15
```
*Due credit to [AChampion](https://stackoverflow.com/users/2750492/achampion) for posting the class in [a comment](https://stackoverflow.com/questions/42838366/create-a-list-with-variable-names-in-it#comment72786589_42838366)*
|
You can use dictionary.
```
character = dict()
character['x']= default_value
character['y']= default_value
```
You might want to have a look at this [Documentation](https://learnpythonthehardway.org/book/ex39.html)
|
42,838,366
|
I think this question has been asked many times, but I can't find the answer. I am probably not using the correct words in my searches.
I am a beginner in python and I am learning to make simple games, with the pygame library. I would like to create a variable `character`, containing x and y coordinates.
I would like something like `character[x=default_value,y=default_value]`, and then edit these coordinates for example by typing `character[x]=new_value`.
Is there a way to achieve something like that in python ?
EDIT : Thank you all, I used dictionary like that `character= {'x':'value', 'y':'value'}` and it works perfectly!
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42838366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682871/"
] |
You could use a dictionary like this:
```
character = {'Name': 'Mary', 'xPos': 0, 'yPos': 0}
character['xPos'] = 10
```
|
A dict would work, but a [class](https://docs.python.org/3/tutorial/classes.html) is a better fit IMO.
```
class Character:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
arthur = Character(9, 9)
arthur.x = 15
```
*Due credit to [AChampion](https://stackoverflow.com/users/2750492/achampion) for posting the class in [a comment](https://stackoverflow.com/questions/42838366/create-a-list-with-variable-names-in-it#comment72786589_42838366)*
|
39,919,586
|
I know this is probably really easy question, but i'm struggling to split a string in python. My regex has group separators like this:
```
myRegex = "(\W+)"
```
And I want to parse this string into words:
```
testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", testString)
```
Here's the results:
```
['This', ' ', 'is', ' ', 'my', ' ', 'test', ' ', 'string', ', ', 'hopefully', ' ', 'I', ' ', 'can', ' ', 'get', ' ', 'the', ' ', 'word', ' ', 'i', ' ', 'need']
```
Which isn't what I expected. I am expecting the list to contain:
```
['This','is','my','test']......etc
```
Now I know it's something to do with the grouping in my regex, and I can fix the issue by removing the brackets. **But how can I keep the brackets and get the result above?**
Sorry about this question, I have read the official python documentation on regex spliting with groups, but I still don't understand why the empty spaces are in my list
|
2016/10/07
|
[
"https://Stackoverflow.com/questions/39919586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5613356/"
] |
As described in this answer, [How to split but ignore separators in quoted strings, in python?](https://stackoverflow.com/questions/2785755/how-to-split-but-ignore-separators-in-quoted-strings-in-python), you can simply slice the array once it's split. It's easy to do so because you want every other member, starting with the first one (so 1,3,5,7)
You can use the [start:end:step] notation as described below:
```
testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", testString)
testAgain = testAgain[0::2]
```
Also, I must point out that `\W` matches any non-word characters, including punctuation. If you want to keep your punctuation, you'll need to change your regex.
|
You can simly do:
```
testAgain = testString.split() # built-in split with space
```
Different `regex` ways of doing this:
```
testAgain = re.split(r"\s+", testString) # split with space
testAgain = re.findall(r"\w+", testString) # find all words
testAgain = re.findall(r"\S+", testString) # find all non space characters
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
You can randomly switch the values :
```
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
newarray[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int r = rand.Next(n);
int tmp = newarray[y];
newarray[y] = newarray[r];
newarray[r] = tmp;
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
This is the simplest way to do it using a random comparison.
```
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
int[] array= { 1, 2, 3, 4, 5, 6 };
int[] newarray=new int[array.Length];
array.CopyTo(newarray, 0);
Array.Sort(newarray, (i, j) => rnd.NextDouble()<0.5?-1:1);
// newarray is now randomly ordered
}
}
```
|
You can randomly switch the values :
```
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
newarray[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int r = rand.Next(n);
int tmp = newarray[y];
newarray[y] = newarray[r];
newarray[r] = tmp;
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
use following code
```
int[] array = new int[n];
int[] randomPosition = new int[n];
Enumerable.Range(0, n ).ToList().ForEach(o => array[o] = o+1);
Random r = new Random();
Enumerable.Range(0, n).ToList().ForEach(o => randomPosition[o] = r.Next(0, n - 1));
foreach (var m in randomPosition)
{
var randomNumber = array[m];
//write randomnumber
}
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
The reason you're not seeing any output is because the code isn't running to completion - it ends up bouncing between case 1 and 2 because
```
if (newarray[y] == newarray[z - 1])
```
is always true.
My recommendation would be to debug (i.e. step through) your code so you can really see why this is the case, then you'll be able to fix the code yourself :)
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
It seems to get into an infinite loop. Try changing this bit:
```
case 2:
for (int z = y; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
```
|
use following code
```
int[] array = new int[n];
int[] randomPosition = new int[n];
Enumerable.Range(0, n ).ToList().ForEach(o => array[o] = o+1);
Random r = new Random();
Enumerable.Range(0, n).ToList().ForEach(o => randomPosition[o] = r.Next(0, n - 1));
foreach (var m in randomPosition)
{
var randomNumber = array[m];
//write randomnumber
}
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
The reason you're not seeing any output is because the code isn't running to completion - it ends up bouncing between case 1 and 2 because
```
if (newarray[y] == newarray[z - 1])
```
is always true.
My recommendation would be to debug (i.e. step through) your code so you can really see why this is the case, then you'll be able to fix the code yourself :)
|
use following code
```
int[] array = new int[n];
int[] randomPosition = new int[n];
Enumerable.Range(0, n ).ToList().ForEach(o => array[o] = o+1);
Random r = new Random();
Enumerable.Range(0, n).ToList().ForEach(o => randomPosition[o] = r.Next(0, n - 1));
foreach (var m in randomPosition)
{
var randomNumber = array[m];
//write randomnumber
}
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
It seems to get into an infinite loop. Try changing this bit:
```
case 2:
for (int z = y; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
What you are trying to do is to generate a random permutation. You could try the following:
```
var rand = new Random();
var left = Enumerable.Range(1, n).ToList();
for(int i=0; i<n; ++i)
{
int j = rand.Next(n-i);
Console.Out.WriteLine(left[j]);
left[j].RemoveAt(j);
}
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
You can do it like this:
```
...
n = Int32.Parse(Console.ReadLine());
// Initial array filled with 1..n values
int[] data = Enumerable.Range(1, n).ToArray();
// data array indice to show, initially 0..n-1
List<int> indice = Enumerable.Range(0, n - 1).ToList();
Random gen = new Random();
for (int i = 0; i < n; ++i) {
if (i != 0)
Console.Write(' ');
index = gen.Next(indice.Count);
Console.Write(data[indice[index]]);
// Index has been shown, let's remove it since we're not going to show it again
indice.RemoveAt(index);
}
...
```
|
21,458,037
|
I am using Ubuntu 12.04 LTS.
In Windows Azure account .cer file uploaded.
my python script is:
```
#!/usr/bin/python
from azure import *
from azure.servicemanagement import *
azureId = "XXXXXXXXXXXXXXXXXXXXX";
certificate_path= "/home/dharampal/Desktop/azure.pem";
sms = ServiceManagementService(azureId,certificate_path)
print sms
result = sms.list_locations()
print result
```
when scripts runs that time getting ServiceManagementService object but certificate related error thrown.
output of the script is :
```
<azure.servicemanagement.servicemanagementservice.ServiceManagementService object at 0xb7259f2c>
Traceback (most recent call last):
File "available_locations_list.py", line 13, in <module>
result = sms.list_locations()
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementservice.py", line 796, in list_locations
Locations)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 96, in _perform_get
response = self._perform_request(request)
File "/usr/local/lib/python2.7/dist-packages/azure/servicemanagement/servicemanagementclient.py", line 83, in _perform_request
resp = self._filter(request)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 144, in perform_request
self.send_request_headers(connection, request.headers)
File "/usr/local/lib/python2.7/dist-packages/azure/http/httpclient.py", line 125, in send_request_headers
connection.endheaders()
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
```
where am i doing wrong ?
if any one faced same issue and got solution, please help me.
did google but unable to find solution.
|
2014/01/30
|
[
"https://Stackoverflow.com/questions/21458037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3086379/"
] |
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new `IComparer` that returns the comparison randomly:
```
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
```
Now, sort your array:
```
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
```
It's really that simple. See this demonstration at [IDEOne.com](http://ideone.com/4XTZAg)
|
This is the simplest way to do it using a random comparison.
```
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
int[] array= { 1, 2, 3, 4, 5, 6 };
int[] newarray=new int[array.Length];
array.CopyTo(newarray, 0);
Array.Sort(newarray, (i, j) => rnd.NextDouble()<0.5?-1:1);
// newarray is now randomly ordered
}
}
```
|
72,521,192
|
Given a reproducible dataframe, I want to find the number of unique values in each column not including missing (NA) values. Below code counts NA values, as a result the cardinality of `nat_country` column shows as 4 in `n_unique_values` dataframe (it is supposed to be 3). In python there exists `nunique()` function which does not take NA values into consideration. In r how can one achieve this?
```r
nat_country = c("United-States", "Germany", "United-States", "United-States", "United-States", "United-States", "Taiwan", NA)
age = c(14,15,45,78,96,58,25,36)
dat = data.frame(nat_country, age)
n_unique_values = t(data.frame(apply(dat, 2, function(x) length(unique(x)))))
```
|
2022/06/06
|
[
"https://Stackoverflow.com/questions/72521192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10617194/"
] |
You can use `dplyr::n_distinct` with `na.rm = T`:
```r
library(dplyr)
sapply(dat, n_distinct, na.rm = T)
#map_dbl(dat, n_distinct, na.rm = T)
#nat_country age
# 3 8
```
---
In base R, you can use `na.omit` as well:
```r
sapply(dat, \(x) length(unique(na.omit(x))))
#nat_country age
# 3 8
```
|
We could use `map` or `map_dfr` with `n_distinct`:
```
library(dplyr)
library(purrr)
dat %>%
map_dfr(., n_distinct, na.rm = TRUE)
nat_country age
<int> <int>
1 3 8
```
```
library(dplyr)
library(purrr)
dat %>%
map(., n_distinct, na.rm = TRUE) %>%
unlist()
```
```
nat_country age
3 8
```
|
72,521,192
|
Given a reproducible dataframe, I want to find the number of unique values in each column not including missing (NA) values. Below code counts NA values, as a result the cardinality of `nat_country` column shows as 4 in `n_unique_values` dataframe (it is supposed to be 3). In python there exists `nunique()` function which does not take NA values into consideration. In r how can one achieve this?
```r
nat_country = c("United-States", "Germany", "United-States", "United-States", "United-States", "United-States", "Taiwan", NA)
age = c(14,15,45,78,96,58,25,36)
dat = data.frame(nat_country, age)
n_unique_values = t(data.frame(apply(dat, 2, function(x) length(unique(x)))))
```
|
2022/06/06
|
[
"https://Stackoverflow.com/questions/72521192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10617194/"
] |
You can use `dplyr::n_distinct` with `na.rm = T`:
```r
library(dplyr)
sapply(dat, n_distinct, na.rm = T)
#map_dbl(dat, n_distinct, na.rm = T)
#nat_country age
# 3 8
```
---
In base R, you can use `na.omit` as well:
```r
sapply(dat, \(x) length(unique(na.omit(x))))
#nat_country age
# 3 8
```
|
In **base R** you can use `table`. It also has a parameter `useNA` if you want to change the default behavior.
```
sapply(dat, function(x) length(table(x)))
nat_country age
3 8
```
|
72,521,192
|
Given a reproducible dataframe, I want to find the number of unique values in each column not including missing (NA) values. Below code counts NA values, as a result the cardinality of `nat_country` column shows as 4 in `n_unique_values` dataframe (it is supposed to be 3). In python there exists `nunique()` function which does not take NA values into consideration. In r how can one achieve this?
```r
nat_country = c("United-States", "Germany", "United-States", "United-States", "United-States", "United-States", "Taiwan", NA)
age = c(14,15,45,78,96,58,25,36)
dat = data.frame(nat_country, age)
n_unique_values = t(data.frame(apply(dat, 2, function(x) length(unique(x)))))
```
|
2022/06/06
|
[
"https://Stackoverflow.com/questions/72521192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10617194/"
] |
We could use `map` or `map_dfr` with `n_distinct`:
```
library(dplyr)
library(purrr)
dat %>%
map_dfr(., n_distinct, na.rm = TRUE)
nat_country age
<int> <int>
1 3 8
```
```
library(dplyr)
library(purrr)
dat %>%
map(., n_distinct, na.rm = TRUE) %>%
unlist()
```
```
nat_country age
3 8
```
|
In **base R** you can use `table`. It also has a parameter `useNA` if you want to change the default behavior.
```
sapply(dat, function(x) length(table(x)))
nat_country age
3 8
```
|
41,604,223
|
I am trying to read N lines of file in python.
This is my code
```
N = 10
counter = 0
lines = []
with open(file) as f:
if counter < N:
lines.append(f:next())
else:
break
```
Assuming the file is a super large text file. Is there anyway to write this better. I understand in production code, its advised not to use break in loops so as to achieve better readability. But i cannot think of a good way not to use break and to achieve the same effect.
I am a new developer and am just trying to improve my code quality.
Any advice is greatly appreciated. Thanks.
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41604223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1939166/"
] |
try using
`gem install nokogiri -v 1.7.0.1 -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/libxml2`
|
try:
gem update --system
then:
xcode-select --install
then:
gem install nokogiri
and finally:
install the rails gem
|
68,368,323
|
I want to run a Macro with python. I am doing:
```
import win32com.client as w3c
def ejecuntar_macro():
xlApp_mrapp = w3c.Dispatch("Excel.Application")
pw_str = str('Plantilla123')
mrapp = r'D:\Proyectos\Tablero estados\Tablero.xlsm'
xlApp_mrapp.Visible = True
xlApp_mrapp.DisplayAlerts = False
wb = xlApp_mrapp.Workbooks.Open(mrapp, False, False, None, pw_str)
xlApp_mrapp.Application.Run("'" + mrapp + "'" + "!Módulo1.guardar_archivo")
wb.Close(True)
xlApp_mrapp.Quit()
ejecuntar_macro()
```
but I keep getting an error:
>
> File ".\ejecucion.py", line 244, in ejecuntar\_macro
> xlApp\_mrapp.Application.Run("'" + mrapp + "'" +
> "!Módulo1.guardar\_archivo") File "", line 14, in Run File
> "C:\Users\Ruben\AppData\Roaming\Python\Python37\site-packages\win32com\client\dynamic.py",
> line 314, in ApplyTypes result = self.oleobj.InvokeTypes(\*(dispid,
> LCID, wFlags, retType, argTypes) + args) pywintypes.com\_error:
> (-2147352567, 'Ocurrió una excepción.', (0, None, None, None, 0,
> -2146788248), None)
>
>
>
Please, Can You help me to solve it?.
|
2021/07/13
|
[
"https://Stackoverflow.com/questions/68368323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16053579/"
] |
Use `text-align: center;`
Link: <https://developer.mozilla.org/en-US/docs/Web/CSS/text-align>
```html
<div style="text-align:center; width: 150px;">
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
</div>
```
|
Give the property `text-align: center` to the element containing the text.
|
68,368,323
|
I want to run a Macro with python. I am doing:
```
import win32com.client as w3c
def ejecuntar_macro():
xlApp_mrapp = w3c.Dispatch("Excel.Application")
pw_str = str('Plantilla123')
mrapp = r'D:\Proyectos\Tablero estados\Tablero.xlsm'
xlApp_mrapp.Visible = True
xlApp_mrapp.DisplayAlerts = False
wb = xlApp_mrapp.Workbooks.Open(mrapp, False, False, None, pw_str)
xlApp_mrapp.Application.Run("'" + mrapp + "'" + "!Módulo1.guardar_archivo")
wb.Close(True)
xlApp_mrapp.Quit()
ejecuntar_macro()
```
but I keep getting an error:
>
> File ".\ejecucion.py", line 244, in ejecuntar\_macro
> xlApp\_mrapp.Application.Run("'" + mrapp + "'" +
> "!Módulo1.guardar\_archivo") File "", line 14, in Run File
> "C:\Users\Ruben\AppData\Roaming\Python\Python37\site-packages\win32com\client\dynamic.py",
> line 314, in ApplyTypes result = self.oleobj.InvokeTypes(\*(dispid,
> LCID, wFlags, retType, argTypes) + args) pywintypes.com\_error:
> (-2147352567, 'Ocurrió una excepción.', (0, None, None, None, 0,
> -2146788248), None)
>
>
>
Please, Can You help me to solve it?.
|
2021/07/13
|
[
"https://Stackoverflow.com/questions/68368323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16053579/"
] |
Give the property `text-align: center` to the element containing the text.
|
Try doing this example (remember to replace text in div with your own).
`<div style="text-align: center; width=200px">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu sapien vitae sem blandit pulvinar.</div>`
|
68,368,323
|
I want to run a Macro with python. I am doing:
```
import win32com.client as w3c
def ejecuntar_macro():
xlApp_mrapp = w3c.Dispatch("Excel.Application")
pw_str = str('Plantilla123')
mrapp = r'D:\Proyectos\Tablero estados\Tablero.xlsm'
xlApp_mrapp.Visible = True
xlApp_mrapp.DisplayAlerts = False
wb = xlApp_mrapp.Workbooks.Open(mrapp, False, False, None, pw_str)
xlApp_mrapp.Application.Run("'" + mrapp + "'" + "!Módulo1.guardar_archivo")
wb.Close(True)
xlApp_mrapp.Quit()
ejecuntar_macro()
```
but I keep getting an error:
>
> File ".\ejecucion.py", line 244, in ejecuntar\_macro
> xlApp\_mrapp.Application.Run("'" + mrapp + "'" +
> "!Módulo1.guardar\_archivo") File "", line 14, in Run File
> "C:\Users\Ruben\AppData\Roaming\Python\Python37\site-packages\win32com\client\dynamic.py",
> line 314, in ApplyTypes result = self.oleobj.InvokeTypes(\*(dispid,
> LCID, wFlags, retType, argTypes) + args) pywintypes.com\_error:
> (-2147352567, 'Ocurrió una excepción.', (0, None, None, None, 0,
> -2146788248), None)
>
>
>
Please, Can You help me to solve it?.
|
2021/07/13
|
[
"https://Stackoverflow.com/questions/68368323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16053579/"
] |
Use `text-align: center;`
Link: <https://developer.mozilla.org/en-US/docs/Web/CSS/text-align>
```html
<div style="text-align:center; width: 150px;">
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
</div>
```
|
Try doing this example (remember to replace text in div with your own).
`<div style="text-align: center; width=200px">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu sapien vitae sem blandit pulvinar.</div>`
|
60,306,244
|
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.
Lets say we have a table named `table1`
Steps:
```
1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.
```
For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).
Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.
|
2020/02/19
|
[
"https://Stackoverflow.com/questions/60306244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768610/"
] |
This is not currently supported, but I am 80% sure it is in the roadmap.
An alternative would be to use the SDK to create the same pipeline using `ModuleStep` where I *believe* you can reference a Designer Module by its name to use it like a `PythonScriptStep`
|
The export Designer graph to notebook is in our roadmap. For now, please take a look at the ModuleStep in SDK and let us know if you have any questions.
Thanks,
Lu Zhang | Senior Program Manager | Azure Machine Learning
|
60,306,244
|
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.
Lets say we have a table named `table1`
Steps:
```
1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.
```
For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).
Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.
|
2020/02/19
|
[
"https://Stackoverflow.com/questions/60306244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768610/"
] |
This is not currently supported, but I am 80% sure it is in the roadmap.
An alternative would be to use the SDK to create the same pipeline using `ModuleStep` where I *believe* you can reference a Designer Module by its name to use it like a `PythonScriptStep`
|
Here are the instructions to Use the studio to [deploy models trained in the designer - Azure Machine Learning | Microsoft Docs](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-model-designer) and document that explains how we can get access to score.py and conda\_env.yaml files under Output + logs tab for Train module.
|
60,306,244
|
We are automating the process of creating/modifying tables on our database. We keep our ddls in github repo. Our objective is to drop and create the table again if the definition has changed. Otherwise, no change.
Lets say we have a table named `table1`
Steps:
```
1. Query database to get ddl for table1.
2. Get ddl from github repo, check if there is any difference between github & ddl from database server.
3. If there is a difference, drop and create again
4. Else, no change.
```
For comparing, doing string comparison is very naive ( change in space(s) doesn't mean change in schema).
Is there any API for comparison? I am specifically looking for python APIs. Standard diff utility doesn't do a good job of comparing 2 sql files. It will create a diff if the order the fields are different but the overall ddl may be same.
|
2020/02/19
|
[
"https://Stackoverflow.com/questions/60306244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768610/"
] |
The export Designer graph to notebook is in our roadmap. For now, please take a look at the ModuleStep in SDK and let us know if you have any questions.
Thanks,
Lu Zhang | Senior Program Manager | Azure Machine Learning
|
Here are the instructions to Use the studio to [deploy models trained in the designer - Azure Machine Learning | Microsoft Docs](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-model-designer) and document that explains how we can get access to score.py and conda\_env.yaml files under Output + logs tab for Train module.
|
2,859,081
|
I'm trying to create a database connection in a python script to my DB2 database. When the connection is done I've to run some different SQL statements.
I googled the problem and has read the ibm\_db API (<http://code.google.com/p/ibm-db/wiki/APIs>) but just can't seem to get it right.
Here is what I got so far:
```
import sys
import getopt
import timeit
import multiprocessing
import random
import os
import re
import ibm_db
import time
from string import maketrans
query_str = None
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt, "SELECT COUNT(*) FROM accounts")
result = ibm_db.fetch_assoc()
print result
status = ibm_db.close(conn)
```
but I get an error. I really tried everything (or, not everything but pretty damn close) and I can't get it to work.
I just need to make a automatic test python script that can test different queries with different indexes and so on and for that I need to create and remove indexes a long the way.
Hope someone has a solutions or maybe knows about some example codes out there I can download and study.
Thanks
Mestika
|
2010/05/18
|
[
"https://Stackoverflow.com/questions/2859081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188082/"
] |
it should be:
```
query_str = "SELECT COUNT(*) FROM accounts"
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt)
```
|
I'm sorry, of cause you need to error message. When trying to run my script it gives me this error:
```
Traceback (most recent call last):
File "test.py", line 16, in <module>
ibm_db.execute(query_stmt, "SELECT COUNT(*) FROM accounts")
Exception: Param is not a tuple
```
I'm pretty sure that it is my parameter "SELECT COUNT(\*) FROM accounts" that is the problem, but I have no idea how to fix it or what to put in its place.
|
69,818,851
|
I am running a simple React/Django app with webpack that is receiving this error on build:
```
ERROR in ./src/index.js
Module build failed (from ./node_modules/eslint-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'getFormatter')
at getFormatter (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:52:20)
at getOptions (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:30:23)
at Object.loader (**[Relative path]**/frontend/node_modules/eslint-loader/dist/index.js:17:43)
```
Here's my `package.json`
```
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "webpack serve --config webpack.config.dev.js --port 3000",
"clean:build": "rimraf ../static && mkdir ../static",
"prebuild": "run-p clean:build",
"build": "webpack --config webpack.config.prod.js",
"postbuild": "rimraf ../static/index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"redux": "^4.1.2",
"redux-thunk": "^2.4.0",
"reselect": "^4.1.1"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/node": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"@babel/preset-react": "^7.16.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.3",
"babel-polyfill": "^6.26.0",
"css-loader": "^6.5.0",
"cssnano": "^5.0.9",
"eslint": "^8.1.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.4.3",
"npm-run-all": "^4.1.5",
"postcss-loader": "^6.2.0",
"redux-immutable-state-invariant": "^2.1.0",
"rimraf": "^3.0.2",
"style-loader": "^3.3.1",
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
}
}
```
And my `webpack.config.dev.js`
```
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = 'development';
module.exports = {
mode: 'development',
target: 'web',
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill', './src/index'],
output: {
path: path.resolve(__dirname),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
// stats: 'minimal',
client: {
overlay: true
},
historyApiFallback: true,
// disableHostCheck: true,
headers: { 'Access-Control-Allow-Origin': '*' },
https: false
},
plugins: [
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify('http://localhost:8000/api/')
}),
new HtmlWebpackPlugin({
template: './src/index.html',
favicon: './src/favicon.ico'
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
},
'eslint-loader'
]
},
{
test: /(\.css)$/,
use: ['style-loader', 'css-loader']
}
]
}
};
```
Unsure if I need to make changes to my config file or if it's an issue with a package I have installed. Any guidance would be helpful as I am not very familiar with webpack's inner workings.
Versions:
* node: v17.0.1
* npm: 8.1.2
* python: 3.9.6 (pretty sure it's a js/webpack issue)
* Django: 3.2.8 (^^^)
|
2021/11/03
|
[
"https://Stackoverflow.com/questions/69818851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7359966/"
] |
eslint-loader is deprecated:
<https://www.npmjs.com/package/eslint-loader>
You may use eslint-webpack-plugin instead:
<https://www.npmjs.com/package/eslint-webpack-plugin>
|
I found an issue <https://github.com/webpack-contrib/eslint-loader/issues/331> about this in the eslint-loader github, but I don't know if it will be useful for you.
. It would help to have a git repository to store the code that would be wrong for better testing. :)
|
69,818,851
|
I am running a simple React/Django app with webpack that is receiving this error on build:
```
ERROR in ./src/index.js
Module build failed (from ./node_modules/eslint-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'getFormatter')
at getFormatter (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:52:20)
at getOptions (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:30:23)
at Object.loader (**[Relative path]**/frontend/node_modules/eslint-loader/dist/index.js:17:43)
```
Here's my `package.json`
```
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "webpack serve --config webpack.config.dev.js --port 3000",
"clean:build": "rimraf ../static && mkdir ../static",
"prebuild": "run-p clean:build",
"build": "webpack --config webpack.config.prod.js",
"postbuild": "rimraf ../static/index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"redux": "^4.1.2",
"redux-thunk": "^2.4.0",
"reselect": "^4.1.1"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/node": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"@babel/preset-react": "^7.16.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.3",
"babel-polyfill": "^6.26.0",
"css-loader": "^6.5.0",
"cssnano": "^5.0.9",
"eslint": "^8.1.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.4.3",
"npm-run-all": "^4.1.5",
"postcss-loader": "^6.2.0",
"redux-immutable-state-invariant": "^2.1.0",
"rimraf": "^3.0.2",
"style-loader": "^3.3.1",
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
}
}
```
And my `webpack.config.dev.js`
```
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = 'development';
module.exports = {
mode: 'development',
target: 'web',
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill', './src/index'],
output: {
path: path.resolve(__dirname),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
// stats: 'minimal',
client: {
overlay: true
},
historyApiFallback: true,
// disableHostCheck: true,
headers: { 'Access-Control-Allow-Origin': '*' },
https: false
},
plugins: [
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify('http://localhost:8000/api/')
}),
new HtmlWebpackPlugin({
template: './src/index.html',
favicon: './src/favicon.ico'
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
},
'eslint-loader'
]
},
{
test: /(\.css)$/,
use: ['style-loader', 'css-loader']
}
]
}
};
```
Unsure if I need to make changes to my config file or if it's an issue with a package I have installed. Any guidance would be helpful as I am not very familiar with webpack's inner workings.
Versions:
* node: v17.0.1
* npm: 8.1.2
* python: 3.9.6 (pretty sure it's a js/webpack issue)
* Django: 3.2.8 (^^^)
|
2021/11/03
|
[
"https://Stackoverflow.com/questions/69818851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7359966/"
] |
eslint-loader is deprecated:
<https://www.npmjs.com/package/eslint-loader>
You may use eslint-webpack-plugin instead:
<https://www.npmjs.com/package/eslint-webpack-plugin>
|
```
"dependencies": {
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"react-router-dom": "^6.0.1",
"redux": "^4.1.2",
"redux-thunk": "^2.4.0",
"reselect": "^4.1.1"
},
"devDependencies": {
"@babel/core": "^7.15.0",
"@babel/node": "^7.14.9",
"@babel/preset-env": "^7.15.0",
"@babel/preset-react": "^7.14.5",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"babel-polyfill": "^6.26.0",
"css-loader": "^6.2.0",
"cssnano": "^5.0.7",
"eslint": "^7.32.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.24.0",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-react-hooks": "^4.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.2.0",
"npm-run-all": "^4.1.5",
"postcss-loader": "^6.1.1",
"redux-immutable-state-invariant": "^2.1.0",
"rimraf": "^3.0.2",
"style-loader": "^3.2.1",
"webpack": "^5.50.0",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^3.11.2"
}
```
I reverted back to these versions (a past project worked on them) and it is now working properly. I believe it has something to do with `eslint` and `eslint-loader`.
|
69,818,851
|
I am running a simple React/Django app with webpack that is receiving this error on build:
```
ERROR in ./src/index.js
Module build failed (from ./node_modules/eslint-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'getFormatter')
at getFormatter (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:52:20)
at getOptions (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:30:23)
at Object.loader (**[Relative path]**/frontend/node_modules/eslint-loader/dist/index.js:17:43)
```
Here's my `package.json`
```
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "webpack serve --config webpack.config.dev.js --port 3000",
"clean:build": "rimraf ../static && mkdir ../static",
"prebuild": "run-p clean:build",
"build": "webpack --config webpack.config.prod.js",
"postbuild": "rimraf ../static/index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"redux": "^4.1.2",
"redux-thunk": "^2.4.0",
"reselect": "^4.1.1"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/node": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"@babel/preset-react": "^7.16.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.3",
"babel-polyfill": "^6.26.0",
"css-loader": "^6.5.0",
"cssnano": "^5.0.9",
"eslint": "^8.1.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.4.3",
"npm-run-all": "^4.1.5",
"postcss-loader": "^6.2.0",
"redux-immutable-state-invariant": "^2.1.0",
"rimraf": "^3.0.2",
"style-loader": "^3.3.1",
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
}
}
```
And my `webpack.config.dev.js`
```
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = 'development';
module.exports = {
mode: 'development',
target: 'web',
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill', './src/index'],
output: {
path: path.resolve(__dirname),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
// stats: 'minimal',
client: {
overlay: true
},
historyApiFallback: true,
// disableHostCheck: true,
headers: { 'Access-Control-Allow-Origin': '*' },
https: false
},
plugins: [
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify('http://localhost:8000/api/')
}),
new HtmlWebpackPlugin({
template: './src/index.html',
favicon: './src/favicon.ico'
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
},
'eslint-loader'
]
},
{
test: /(\.css)$/,
use: ['style-loader', 'css-loader']
}
]
}
};
```
Unsure if I need to make changes to my config file or if it's an issue with a package I have installed. Any guidance would be helpful as I am not very familiar with webpack's inner workings.
Versions:
* node: v17.0.1
* npm: 8.1.2
* python: 3.9.6 (pretty sure it's a js/webpack issue)
* Django: 3.2.8 (^^^)
|
2021/11/03
|
[
"https://Stackoverflow.com/questions/69818851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7359966/"
] |
eslint-loader is deprecated:
<https://www.npmjs.com/package/eslint-loader>
You may use eslint-webpack-plugin instead:
<https://www.npmjs.com/package/eslint-webpack-plugin>
|
eslint-loader has been deprecated now, and i change to use eslint-webpack-plugin which really works now!! I am so greatful, this problem has been troubling me a lot!
It really solve my problem thanks to the top answer, but I cannot comment directly on that answer due to my low reputation.
In addition, this is a plugin rather than loader, so you should add it to plugins and don't forget to "new".[enter link description here](https://www.npmjs.com/package/eslint-webpack-plugin)
|
69,818,851
|
I am running a simple React/Django app with webpack that is receiving this error on build:
```
ERROR in ./src/index.js
Module build failed (from ./node_modules/eslint-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'getFormatter')
at getFormatter (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:52:20)
at getOptions (**[Relative path]**/frontend/node_modules/eslint-loader/dist/getOptions.js:30:23)
at Object.loader (**[Relative path]**/frontend/node_modules/eslint-loader/dist/index.js:17:43)
```
Here's my `package.json`
```
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "webpack serve --config webpack.config.dev.js --port 3000",
"clean:build": "rimraf ../static && mkdir ../static",
"prebuild": "run-p clean:build",
"build": "webpack --config webpack.config.prod.js",
"postbuild": "rimraf ../static/index.html"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"redux": "^4.1.2",
"redux-thunk": "^2.4.0",
"reselect": "^4.1.1"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/node": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"@babel/preset-react": "^7.16.0",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.3",
"babel-polyfill": "^6.26.0",
"css-loader": "^6.5.0",
"cssnano": "^5.0.9",
"eslint": "^8.1.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-react": "^7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.4.3",
"npm-run-all": "^4.1.5",
"postcss-loader": "^6.2.0",
"redux-immutable-state-invariant": "^2.1.0",
"rimraf": "^3.0.2",
"style-loader": "^3.3.1",
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
}
}
```
And my `webpack.config.dev.js`
```
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = 'development';
module.exports = {
mode: 'development',
target: 'web',
devtool: 'cheap-module-source-map',
entry: ['babel-polyfill', './src/index'],
output: {
path: path.resolve(__dirname),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
// stats: 'minimal',
client: {
overlay: true
},
historyApiFallback: true,
// disableHostCheck: true,
headers: { 'Access-Control-Allow-Origin': '*' },
https: false
},
plugins: [
new webpack.DefinePlugin({
'process.env.API_URL': JSON.stringify('http://localhost:8000/api/')
}),
new HtmlWebpackPlugin({
template: './src/index.html',
favicon: './src/favicon.ico'
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
},
'eslint-loader'
]
},
{
test: /(\.css)$/,
use: ['style-loader', 'css-loader']
}
]
}
};
```
Unsure if I need to make changes to my config file or if it's an issue with a package I have installed. Any guidance would be helpful as I am not very familiar with webpack's inner workings.
Versions:
* node: v17.0.1
* npm: 8.1.2
* python: 3.9.6 (pretty sure it's a js/webpack issue)
* Django: 3.2.8 (^^^)
|
2021/11/03
|
[
"https://Stackoverflow.com/questions/69818851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7359966/"
] |
eslint-loader is deprecated:
<https://www.npmjs.com/package/eslint-loader>
You may use eslint-webpack-plugin instead:
<https://www.npmjs.com/package/eslint-webpack-plugin>
|
Find out that my versions of eslint and eslint-loader were incompatible
those works for me
"eslint": "^7.32.0",
"eslint-loader": "^4.0.2",
|
51,113,531
|
I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
depends_on:
- db
build: .
env_file: ./docker-compose.env
command: bash ./run_web_local.sh
volumes:
- .:/srv/project
ports:
- 8001:8001
links:
- db
- rabbit
restart: always
```
**Dockerfile:**
```
### STAGE 1: Build ###
# We label our stage as 'builder'
FROM node:8-alpine as builder
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app
### STAGE 2: Setup ###
FROM python:3
# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project
# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs
# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]
# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ
COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules
# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ
# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000
CMD ["./run_web.sh"]
```
**docker-compose.env:**
```
C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
```
**run\_web\_local.sh:**
```
#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
```
When I call `docker-compose up web` I get the following error:
>
> web\_1 | bash: ./run\_web\_local.sh: No such file or directory
>
>
>
* I checked the line endings, they are UNIX
* the file exists on the file system as well as inside the container
* I can call `bash run_web_local.sh` from my windows powershell and inside the container
* I changed the UNIX permissions inside the container
* I left out the `bash` in the `command` in the `docker-compose` command. And tried with backslash, no dot etc.
* I reinstalled docker
* I tried switching to version 3
* docker claims to have a connection to my shared drive C
And: The exact same setup **works** on my other laptop.
Any ideas? All the two million github posts didn't solve the problem for me.
Thanks!
**Update**
Removing `volumes:` from the docker-compose makes it work [like stated here](https://github.com/docker/compose/issues/2548) but I don't have an instant mapping. That's kind of important for me...
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] |
I had same issue recently and the problems goes away using any advanced editor and changing line ending to unix style on sh entrypoint scripts.
In my case, not sure why, because git handle it very well depending on linux or windows host I ended up in same situation.
If you have files mounted in container and host(in windows)
it dependes on how you edit them may be changed to linux from inside container but that affects outside windows host.
After that git stated file .sh changed but no additions no deletions.
a graphical compare tool showed up that only new line where changed.
Another workaround to trouble shooting you can start your container overriden entrypoint script by sh for example and then from there you can check on the started container how linux sees the entrypoint script, even you can test it and will see exact same error.
|
Do not use -d at the end.
Instead of this command
**docker-compose -f start\_tools.yaml up –d**
Use
**docker-compose -f start\_tools.yaml up**
|
51,113,531
|
I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
depends_on:
- db
build: .
env_file: ./docker-compose.env
command: bash ./run_web_local.sh
volumes:
- .:/srv/project
ports:
- 8001:8001
links:
- db
- rabbit
restart: always
```
**Dockerfile:**
```
### STAGE 1: Build ###
# We label our stage as 'builder'
FROM node:8-alpine as builder
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app
### STAGE 2: Setup ###
FROM python:3
# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project
# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs
# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]
# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ
COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules
# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ
# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000
CMD ["./run_web.sh"]
```
**docker-compose.env:**
```
C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
```
**run\_web\_local.sh:**
```
#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
```
When I call `docker-compose up web` I get the following error:
>
> web\_1 | bash: ./run\_web\_local.sh: No such file or directory
>
>
>
* I checked the line endings, they are UNIX
* the file exists on the file system as well as inside the container
* I can call `bash run_web_local.sh` from my windows powershell and inside the container
* I changed the UNIX permissions inside the container
* I left out the `bash` in the `command` in the `docker-compose` command. And tried with backslash, no dot etc.
* I reinstalled docker
* I tried switching to version 3
* docker claims to have a connection to my shared drive C
And: The exact same setup **works** on my other laptop.
Any ideas? All the two million github posts didn't solve the problem for me.
Thanks!
**Update**
Removing `volumes:` from the docker-compose makes it work [like stated here](https://github.com/docker/compose/issues/2548) but I don't have an instant mapping. That's kind of important for me...
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] |
I had same issue recently and the problems goes away using any advanced editor and changing line ending to unix style on sh entrypoint scripts.
In my case, not sure why, because git handle it very well depending on linux or windows host I ended up in same situation.
If you have files mounted in container and host(in windows)
it dependes on how you edit them may be changed to linux from inside container but that affects outside windows host.
After that git stated file .sh changed but no additions no deletions.
a graphical compare tool showed up that only new line where changed.
Another workaround to trouble shooting you can start your container overriden entrypoint script by sh for example and then from there you can check on the started container how linux sees the entrypoint script, even you can test it and will see exact same error.
|
On thing I noticed in Ubuntu 18.04.3 is that you need to install docker-compose on top of docker.io to get docker-compose to work
* sudo apt install docker.io
* sudo apt install docker-compose
After I did that, I got docker-compose [filename.yml] up to work without issue
|
51,113,531
|
I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
depends_on:
- db
build: .
env_file: ./docker-compose.env
command: bash ./run_web_local.sh
volumes:
- .:/srv/project
ports:
- 8001:8001
links:
- db
- rabbit
restart: always
```
**Dockerfile:**
```
### STAGE 1: Build ###
# We label our stage as 'builder'
FROM node:8-alpine as builder
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app
### STAGE 2: Setup ###
FROM python:3
# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project
# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs
# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]
# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ
COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules
# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ
# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000
CMD ["./run_web.sh"]
```
**docker-compose.env:**
```
C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
```
**run\_web\_local.sh:**
```
#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
```
When I call `docker-compose up web` I get the following error:
>
> web\_1 | bash: ./run\_web\_local.sh: No such file or directory
>
>
>
* I checked the line endings, they are UNIX
* the file exists on the file system as well as inside the container
* I can call `bash run_web_local.sh` from my windows powershell and inside the container
* I changed the UNIX permissions inside the container
* I left out the `bash` in the `command` in the `docker-compose` command. And tried with backslash, no dot etc.
* I reinstalled docker
* I tried switching to version 3
* docker claims to have a connection to my shared drive C
And: The exact same setup **works** on my other laptop.
Any ideas? All the two million github posts didn't solve the problem for me.
Thanks!
**Update**
Removing `volumes:` from the docker-compose makes it work [like stated here](https://github.com/docker/compose/issues/2548) but I don't have an instant mapping. That's kind of important for me...
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] |
I had same issue recently and the problems goes away using any advanced editor and changing line ending to unix style on sh entrypoint scripts.
In my case, not sure why, because git handle it very well depending on linux or windows host I ended up in same situation.
If you have files mounted in container and host(in windows)
it dependes on how you edit them may be changed to linux from inside container but that affects outside windows host.
After that git stated file .sh changed but no additions no deletions.
a graphical compare tool showed up that only new line where changed.
Another workaround to trouble shooting you can start your container overriden entrypoint script by sh for example and then from there you can check on the started container how linux sees the entrypoint script, even you can test it and will see exact same error.
|
You should issue the following command before cloning the repository:
```
git config --global core.autocrlf false
```
This will change the line-ending to UNIX-style.
Then clone the repository and proceed.
|
51,113,531
|
I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
depends_on:
- db
build: .
env_file: ./docker-compose.env
command: bash ./run_web_local.sh
volumes:
- .:/srv/project
ports:
- 8001:8001
links:
- db
- rabbit
restart: always
```
**Dockerfile:**
```
### STAGE 1: Build ###
# We label our stage as 'builder'
FROM node:8-alpine as builder
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app
### STAGE 2: Setup ###
FROM python:3
# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project
# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs
# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]
# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ
COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules
# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ
# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000
CMD ["./run_web.sh"]
```
**docker-compose.env:**
```
C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
```
**run\_web\_local.sh:**
```
#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
```
When I call `docker-compose up web` I get the following error:
>
> web\_1 | bash: ./run\_web\_local.sh: No such file or directory
>
>
>
* I checked the line endings, they are UNIX
* the file exists on the file system as well as inside the container
* I can call `bash run_web_local.sh` from my windows powershell and inside the container
* I changed the UNIX permissions inside the container
* I left out the `bash` in the `command` in the `docker-compose` command. And tried with backslash, no dot etc.
* I reinstalled docker
* I tried switching to version 3
* docker claims to have a connection to my shared drive C
And: The exact same setup **works** on my other laptop.
Any ideas? All the two million github posts didn't solve the problem for me.
Thanks!
**Update**
Removing `volumes:` from the docker-compose makes it work [like stated here](https://github.com/docker/compose/issues/2548) but I don't have an instant mapping. That's kind of important for me...
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] |
You should issue the following command before cloning the repository:
```
git config --global core.autocrlf false
```
This will change the line-ending to UNIX-style.
Then clone the repository and proceed.
|
Do not use -d at the end.
Instead of this command
**docker-compose -f start\_tools.yaml up –d**
Use
**docker-compose -f start\_tools.yaml up**
|
51,113,531
|
I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
depends_on:
- db
build: .
env_file: ./docker-compose.env
command: bash ./run_web_local.sh
volumes:
- .:/srv/project
ports:
- 8001:8001
links:
- db
- rabbit
restart: always
```
**Dockerfile:**
```
### STAGE 1: Build ###
# We label our stage as 'builder'
FROM node:8-alpine as builder
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app
### STAGE 2: Setup ###
FROM python:3
# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project
# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs
# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]
# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ
COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules
# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ
# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000
CMD ["./run_web.sh"]
```
**docker-compose.env:**
```
C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
```
**run\_web\_local.sh:**
```
#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
```
When I call `docker-compose up web` I get the following error:
>
> web\_1 | bash: ./run\_web\_local.sh: No such file or directory
>
>
>
* I checked the line endings, they are UNIX
* the file exists on the file system as well as inside the container
* I can call `bash run_web_local.sh` from my windows powershell and inside the container
* I changed the UNIX permissions inside the container
* I left out the `bash` in the `command` in the `docker-compose` command. And tried with backslash, no dot etc.
* I reinstalled docker
* I tried switching to version 3
* docker claims to have a connection to my shared drive C
And: The exact same setup **works** on my other laptop.
Any ideas? All the two million github posts didn't solve the problem for me.
Thanks!
**Update**
Removing `volumes:` from the docker-compose makes it work [like stated here](https://github.com/docker/compose/issues/2548) but I don't have an instant mapping. That's kind of important for me...
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] |
You should issue the following command before cloning the repository:
```
git config --global core.autocrlf false
```
This will change the line-ending to UNIX-style.
Then clone the repository and proceed.
|
If possible can you please provide all the files related to this, so that i can try to reproduce the issue.
Seems like command is not executing is the dir where run\_web\_local.sh exist.
You can check the current workdir by replacing command in docker-compose.yml as
`command: pwd && bash ./run_web_local.sh`
|
51,113,531
|
I am setting up `docker-for-windows` on my private pc.
When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.
So I am stuck with this:
I have a docker-working project (on my other computer) with a `docker-compose.yml` like this:
```
version: '2'
services:
web:
depends_on:
- db
build: .
env_file: ./docker-compose.env
command: bash ./run_web_local.sh
volumes:
- .:/srv/project
ports:
- 8001:8001
links:
- db
- rabbit
restart: always
```
**Dockerfile:**
```
### STAGE 1: Build ###
# We label our stage as 'builder'
FROM node:8-alpine as builder
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app
### STAGE 2: Setup ###
FROM python:3
# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt
# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project
# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs
# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]
# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ
COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules
# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ
# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000
CMD ["./run_web.sh"]
```
**docker-compose.env:**
```
C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
```
**run\_web\_local.sh:**
```
#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
```
When I call `docker-compose up web` I get the following error:
>
> web\_1 | bash: ./run\_web\_local.sh: No such file or directory
>
>
>
* I checked the line endings, they are UNIX
* the file exists on the file system as well as inside the container
* I can call `bash run_web_local.sh` from my windows powershell and inside the container
* I changed the UNIX permissions inside the container
* I left out the `bash` in the `command` in the `docker-compose` command. And tried with backslash, no dot etc.
* I reinstalled docker
* I tried switching to version 3
* docker claims to have a connection to my shared drive C
And: The exact same setup **works** on my other laptop.
Any ideas? All the two million github posts didn't solve the problem for me.
Thanks!
**Update**
Removing `volumes:` from the docker-compose makes it work [like stated here](https://github.com/docker/compose/issues/2548) but I don't have an instant mapping. That's kind of important for me...
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51113531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331671/"
] |
You should issue the following command before cloning the repository:
```
git config --global core.autocrlf false
```
This will change the line-ending to UNIX-style.
Then clone the repository and proceed.
|
It may be because the bash file is not in the root path or in the root path of workdir.
Check where is it in the container and verify if the path is correct.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.