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
|
|---|---|---|---|---|---|
38,043,683
|
I'm writing a git pre-commit hook, but it requires user input and hooks don't run in an interactive terminal. With Python I could do something like this to get access to user input:
```
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically supposed to have access to stdin.
# This hack works on MaxOS and Linux. Mileage may vary on Windows.
sys.stdin = open('/dev/tty')
result = input("Gimme some input: ")
```
What is the appropriate way to do this in Crystal?
|
2016/06/26
|
[
"https://Stackoverflow.com/questions/38043683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973/"
] |
by combining @julian-portalier's answer and @asterite's we have working way to redefine stdin:
```
STDIN.reopen(File.open("/dev/tty", "a+"))
```
Which, I believe, is just [FileDescriptor#reopen](http://crystal-lang.org/api/IO/FileDescriptor.html#reopen)
`STDIN`, `STDOUT`, and `STDERR` can all be reopened this way.
|
You may try:
```
STDIN.reopen("/dev/tty")
```
|
50,982,990
|
I'm designing an Application where username will be an `AutoIntegerField` and unique.
Here's my model.
```
class ModelA(models.Model):
username = models.BigAutoField(primary_key=True, db_index=False)
user_id = models.UUIDField(default=uuid.uuid4, unique=True,
editable=False)
```
Initially, I wanted user\_id to be a `primary_key`, but I can't create an AutoField which is not `primary_key`. As a result, I'd to let go off `user_id` as primary\_key and assigned `username` as the primary key.
Now, when I run the migrations, it throws an error saying,
```
django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
```
**Complete StackTrace:-**
```
Applying users.0005_auto_20180626_0914...Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
new_db_params, strict,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field
params,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type bigint
```
|
2018/06/22
|
[
"https://Stackoverflow.com/questions/50982990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1162512/"
] |
I think the issue is that you still have an old index on your `username` field that clashes with the new type. The `db_index=False` argument has no effect because `primary_key=True` always generates an index.
You might be able to solve this by removing `primary_key=True`, creating a migration, and then re-adding it and creating another migration. Alternatively, you can do it by hand by dropping and re-creating the index. If you want to go down that path, consult [this answer](https://stackoverflow.com/a/20284951/211960).
If your project is still in an early stage and you don't have any valuable data, you can take the easy way out and drop any tables related to your `users` app or even the complete database, delete all migrations in the `users` app and create them from scratch.
|
in my case I was connecting django to postgres at localhost pgadmin
first deleted all the migrations except default one and also in the pycache
then just run python manage.py makemigrations and python manage.py migrate in your terminal
|
716,386
|
I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:
```
from objc import YES, NO, IBAction, IBOutlet
from Foundation import *
from AppKit import *
import gv
class SceneView(NSOpenGLView):
def __init__(self):
NSOpenGLView.__init__(self)
self.renderer = None
def doinit(self):
self.renderer = gv.CoreRenderer()
def initWithFrame_(self, frame):
self = super(SceneView, self).initWithFrame_(frame)
if self:
self.doinit()
print self.__dict__
return self
def drawRect_(self, rect):
clearColor = [0.0,0.0,0.0,0.0]
print self.__dict__
self.renderer.clear(CF_Target|CF_ZBuffer,clearColor)
```
It outputs this when executed:
```
{'renderer': <gv.CoreRenderer; proxy of <Swig Object of type 'GV::CoreRenderer *' at 0x202c7d0> >}
{}
2009-04-03 19:13:30.941 geom-view-edit[50154:10b] An exception has occured:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjCTools/AppHelper.py", line 235, in runEventLoop
File "/mnt/gilead/amcharg/projects/geom-view-edit/build/Debug/geom-view-edit.app/Contents/Resources/SceneView.py", line 37, in drawRect_
self.renderer.clear(CF_Target|CF_ZBuffer,clearColor)
AttributeError: 'SceneView' object has no attribute 'renderer'
```
It seems to be losing my renderer variable which is not that surprising considering how funky the initWithFrame\_ code is but this was something xcode seemed to write which I suppose makes sense since objective C has the init separate from alloc idiom. It is still strange seeing it python however.
Is there anyways to salvage this or should I take it out behind the code shed shoot it and use QT or wxPython? I considered using objective-c but I want to test out these nifty swig bindings I just compiled =)
|
2009/04/04
|
[
"https://Stackoverflow.com/questions/716386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84805/"
] |
Depending on what's happening elsewhere in your app, your instance might actually be getting copied.
In this case, implement the `copyWithZone` method to ensure that the new copy gets the renderer as well. (Caveat, while I am a Python developer, and an Objective-C cocoa developer, I haven't used PyObjC myself, so I can't say for certain if you should be implementing `copyWithZone` or `__copy__`).
In fact, shoving a `copyWithZone` method into the class with a print will allow you to tell if the method is being called and if that's the reason renderer appears to have vanished.
---
**Edit**: Base on your feedback, I've pasted your code into a blank xcode python project (just substituting something else for gv.CoreRenderer, since I don't have that), and it works fine with some minor modifications. How are you instantiating your SceneView?
In my case I:
* Created a blank xcode project using the Cocoa-Python template
* Created a new file called `SceneView.py`. I pasted in your code.
* Opened the `MainMenu.xib` file, and dragged an NSOpenGLView box onto the window.
* With the NSOpenGLView box selected, I went to the attributes inspector and changed the class of the box to `SceneView`
* Back in xcode, I added `import SceneView` in the imports in `main.py` so that the class would be available when the xib file is loaded
* I implemented an `awakeFromNib` method in `SceneView.py` to handle setting up `self.renderer`. Note that `__init__`, and `initWithFrame` are not called for nib objects during your program execution... they are considered "serialized" into the nib file, and therefore already instantiated. I'm glossing over some details, but this is why awakeFromNib exists.
* Everything worked on run. The `__dict__` had appropriate values in the `drawRect_` call, and such.
Here's the awakeFromNib function:
```
def awakeFromNib(self):
print "Awake from nib"
self.renderer = gv.CoreRenderer()
```
So, I'm guessing there are just some crossed wires somewhere in how your object is being instantiated and/or added to the view. Are you using Interface Builder for your object, or are you manually creating it and adding it to a view later? I'm curious to see that you are getting loggin outputs from initWithFrame, which is why I'm asking how you are creating the SceneView.
|
Even if they weren't serialized, the \_\_init\_\_-constructor of python isn't supported by the ObjectiveC-bridge. So one needs to overload e.g. initWithFrame: for self-created Views.
|
23,894,545
|
I would like to use ArangoDB in Django, but I don't know which of the following options is better: using the [ArangoDB Python driver](http://blog.klymyshyn.com/2013/02/arangodb-driver-for-python.html) or building a new API with Foxx. I think that the ArangoDB Python driver is not based on Foxx and I don't know the pros and cons of building a new API from scratch, even if it is made easier by Foxx. In addition, I'm afraid that using javascript in the interface between Foxx and the backend could make things slower. Would it be faster if I used [Guacamole ODM](http://github.com/triAGENS/guacamole) together with Ruby on Rails?
|
2014/05/27
|
[
"https://Stackoverflow.com/questions/23894545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1960092/"
] |
Better option for your case is to use ArangoDB Python driver.
Here is couple of reasons:
* easy-to-start - just install driver and move on with development
* some similarity to Django ORM API
* have some documentation
* all your business logic will be in place and in Python which should be great advantage
And here is why Foxx is not the best option for your case:
* you have to build your own API which means:
+ bunch of code in JavaScript
+ some documentation to describe API
* additional logic level (in Foxx and in Django project) which increase tangling in your project
* it probably not increase performance because you still retrieve your data using HTTP
Foxx is good option when you build Single page APP using ArangoDB as data layer. Also probably Foxx will be great for building hight-level API's with Foxx as preprocessed/aggregated data provider.
|
I made a python ArangoDB driver (<https://github.com/saeschdivara/ArangoPy>)
and I created on top of that kind of a bridge for Django (<https://github.com/saeschdivara/ArangoDjango>). So you can use kind of an orm for ArangoDB and still use the Django Restframework to create your API.
|
4,205,697
|
My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and then send it on to the main program(s).
I have some basic examples of python scripts run using the built-in Apache server, by clicking submit on a form whose html is th:

e.g. [here](http://telliott99.blogspot.com/2010/11/simple-server-running-python-script-on_17.html). What I want to do now is do it *without* the server, just getting the form to invoke the script in the same directory. Do I have to learn javascript or ...? I'd be grateful for any leads you have. Thanks.
|
2010/11/17
|
[
"https://Stackoverflow.com/questions/4205697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215679/"
] |
Use an [AOP framework](http://www.postsharp.com) for this, to inject code when a certain method is hit. You can also do this native via the .NET framework with a [ContextBoundObject](http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx); which is probably what they've used in the framework.
|
You are thinking about this wrong. It's not that the attribute has a changing value, it's that its interpretation by the code that uses the attribute is based on runtime state. In the example you gave, it is probably the case that the code which checks for that attribute also does the checking of Thread.CurrentPrinciple and takes action based on that. The attribute does nothing but store a few constant fields. It's best if you do the same. Remember also that putting an attribute on a method (or anything else) doesn't magically do anything. You have to have code that by reflection grabs those attributes and interprets the data in them in some useful and relevant way. So it's up to your interpreter code, not the attribute.
|
4,205,697
|
My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and then send it on to the main program(s).
I have some basic examples of python scripts run using the built-in Apache server, by clicking submit on a form whose html is th:

e.g. [here](http://telliott99.blogspot.com/2010/11/simple-server-running-python-script-on_17.html). What I want to do now is do it *without* the server, just getting the form to invoke the script in the same directory. Do I have to learn javascript or ...? I'd be grateful for any leads you have. Thanks.
|
2010/11/17
|
[
"https://Stackoverflow.com/questions/4205697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215679/"
] |
Your understanding of .NET attributes seems to be a little muddy.
Attributes are a way of attaching meta-information to classes and assemblies for the purposes of reflection.
**Attributes typically do not contain behaviour. They are just data.**
What you're seeing with `PrincipalPermissionAttribute` is the .NET Runtime security system being invoked. The security process checks for security-related attributes on a method when the method is invoked. The presence of attributes direct the behaviour of the security process.
If you want to have an attribute change the behaviour of your program, you first need something to be actively looking for the attribute.
|
You are thinking about this wrong. It's not that the attribute has a changing value, it's that its interpretation by the code that uses the attribute is based on runtime state. In the example you gave, it is probably the case that the code which checks for that attribute also does the checking of Thread.CurrentPrinciple and takes action based on that. The attribute does nothing but store a few constant fields. It's best if you do the same. Remember also that putting an attribute on a method (or anything else) doesn't magically do anything. You have to have code that by reflection grabs those attributes and interprets the data in them in some useful and relevant way. So it's up to your interpreter code, not the attribute.
|
62,528,247
|
I've updated the initial script with a modified version of Bryan-Oakley's [answer](https://stackoverflow.com/a/6789351/10364425). It now has 2 canvas, 1 with the draggable rectangle, and 1 with the plot. I would like the rectangle to be dragged along the x-axis on the plot if that is possible?
```
import tkinter as tk # python 3
# import Tkinter as tk # python 2
import numpy as np
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
class Example(tk.Frame):
"""Illustrate how to drag items on a Tkinter canvas"""
def __init__(self, parent):
tk.Frame.__init__(self, parent)
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
#create a canvas
self.canvas = tk.Canvas(width=200, height=300)
self.canvas.pack(fill="both", expand=True)
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# this data is used to keep track of an
# item being dragged
self._drag_data = {"x": 0, "y": 0, "item": None}
# create a movable object
self.create_token(100, 150, "black")
# add bindings for clicking, dragging and releasing over
# any object with the "token" tag
self.canvas.tag_bind("token", "<ButtonPress-1>", self.drag_start)
self.canvas.tag_bind("token", "<ButtonRelease-1>", self.drag_stop)
self.canvas.tag_bind("token", "<B1-Motion>", self.drag)
def create_token(self, x, y, color):
"""Create a token at the given coordinate in the given color"""
self.canvas.create_rectangle(
x - 5,
y - 100,
x + 5,
y + 100,
outline=color,
fill=color,
tags=("token",),
)
def drag_start(self, event):
"""Begining drag of an object"""
# record the item and its location
self._drag_data["item"] = self.canvas.find_closest(event.x, event.y)[0]
self._drag_data["x"] = event.x
self._drag_data["y"] = event.y
def drag_stop(self, event):
"""End drag of an object"""
# reset the drag information
self._drag_data["item"] = None
self._drag_data["x"] = 0
self._drag_data["y"] = 0
def drag(self, event):
"""Handle dragging of an object"""
# compute how much the mouse has moved
delta_x = event.x - self._drag_data["x"]
delta_y = 0
# move the object the appropriate amount
self.canvas.move(self._drag_data["item"], delta_x, delta_y)
# record the new position
self._drag_data["x"] = event.x
self._drag_data["y"] = event.y
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
```
Any help is greatly appreciated.
|
2020/06/23
|
[
"https://Stackoverflow.com/questions/62528247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13796693/"
] |
The issue with your code is that you create two canvases, one for the matplotlib figure and one for the draggable rectangle while you want both on the same.
To solve this, I merged the current code of the question with the one before the edit, so the whole matplotlib figure is now embedded in the Tkinter window. The key modification I made to the `DraggableLine` class is that it now takes the canvas as an argument.
```
import tkinter as tk # python 3
# import Tkinter as tk # python 2
import numpy as np
import matplotlib.lines as lines
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
class DraggableLine:
def __init__(self, ax, canvas, XorY):
self.ax = ax
self.c = canvas
self.XorY = XorY
x = [XorY, XorY]
y = [-2, 2]
self.line = lines.Line2D(x, y, color='red', picker=5)
self.ax.add_line(self.line)
self.c.draw_idle()
self.sid = self.c.mpl_connect('pick_event', self.clickonline)
def clickonline(self, event):
if event.artist == self.line:
self.follower = self.c.mpl_connect("motion_notify_event", self.followmouse)
self.releaser = self.c.mpl_connect("button_press_event", self.releaseonclick)
def followmouse(self, event):
self.line.set_xdata([event.xdata, event.xdata])
self.c.draw_idle()
def releaseonclick(self, event):
self.XorY = self.line.get_xdata()[0]
self.c.mpl_disconnect(self.releaser)
self.c.mpl_disconnect(self.follower)
class Example(tk.Frame):
"""Illustrate how to drag items on a Tkinter canvas"""
def __init__(self, parent):
tk.Frame.__init__(self, parent)
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
ax = fig.add_subplot(111)
ax.plot(t, 2 * np.sin(2 * np.pi * t))
# create the canvas
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
self.line = DraggableLine(ax, canvas, 0.1)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
```
|
I'm not sure how to do it with tkinter or pyQt but I know how to make something like this with PyGame which is another GUI solution for python. I hope this example helps you:
```
import pygame
SCREEN_WIDTH = 430
SCREEN_HEIGHT = 410
WHITE = (255, 255, 255)
RED = (255, 0, 0)
FPS = 30
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
rectangle = pygame.rect.Rect(176, 134, 17, 170)
rectangle_draging = False
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if rectangle.collidepoint(event.pos):
rectangle_draging = True
mouse_x, mouse_y = event.pos
offset_x = rectangle.x - mouse_x
offset_y = rectangle.y - mouse_y
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
rectangle_draging = False
print("Line is at: (", rectangle.x, ";", rectangle.y,")")
elif event.type == pygame.MOUSEMOTION:
if rectangle_draging:
mouse_x, mouse_y = event.pos
rectangle.x = mouse_x + offset_x
rectangle.y = mouse_y + offset_y
screen.fill(WHITE)
pygame.draw.rect(screen, RED, rectangle)
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
```
And when you move the line around, the console prints the location that it is in.
|
29,826,430
|
I want to extract a variable named `value` that is set in a second, arbitrarily chosen, python script.
The process works when do it manually in pyhton's interactive mode, but when I run the main script from the command line, `value` is not imported.
The main script's input arguments are already successfully forwarded, but `value` seems to be in the local scope of the executed script.
I already tried to define `value` in the main script, and I also tried to set its accessibility to global.
This is the script I have so far
```py
import sys
import getopt
def main(argv):
try:
(opts, args) = getopt.getopt(argv, "s:o:a:", ["script=", "operations=", "args="])
except getopt.GetoptError as e:
print(e)
sys.exit(2)
# script to be called
script = ""
# arguments that are expected by script
operations = []
argv = []
for (opt, arg) in opts:
if opt in ("-o", "--operations"):
operations = arg.split(',')
print("operations = '%s'" % str(operations))
elif opt in ("-s", "--script"):
script = arg;
print("script = '%s'" % script)
elif opt in ("-a", "--args"):
argv = arg.split(',')
print("arguments = '%s'" % str(argv))
# script should define variable 'value'
exec(open(script).read())
print("Executed '%s'. Value is printed below." % script)
print("Value = '%s'" % value)
if __name__ == "__main__":
main(sys.argv[1:])
```
|
2015/04/23
|
[
"https://Stackoverflow.com/questions/29826430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1809463/"
] |
In my case I am using Handlebars for mandrill templates and I have solved this by sending HTML to the template `<br/>` instead of `\n` by replacing `\n` in my string with `<br/>` something like: `.Description.Replace("\n", "<br/>");`
And then on the mandrill template I put the variable inside {{{ variable }}} instead of {{ variable }}
<http://blog.mandrill.com/handlebars-for-templates-and-dynamic-content.html>
>
> **HTML escaping**
>
>
> Handlebars HTML-escapes values returned by an
> `{{expression}}`. If you don't want Handlebars to escape a value, use
> the "triple-stash", "{{{.
>
>
> In your template:
>
>
> `<div> {{{html_tag_content}}} </div>` In your API request:
>
>
>
```
"global_merge_vars": [ {
"name": "html_tag_content",
"content": "This example<br>is all about<br>the magical world of handlebars" } ]
```
>
> The result:
>
>
> This example
>
> is all about
>
> the magical world of handlebars
>
>
>
|
If you want to send more complex content, be it html, or variables with break lines and whatnot, you can first render the template and then send the message, instead of directly using `send-template`.
Render the template with a call to [`templates.render`](https://mandrillapp.com/api/docs/templates.JSON.html#method=render):
```
{
"key": "example key",
"template_name": "Example Template",
"template_content": [
{
"name": "editable",
"content": "<div>content to inject *|MERGE1|*</div>"
}
],
"merge_vars": [
{
"name": "merge1",
"content": "merge1 content\n contains line breaks"
}
]
}
```
Save the result to a variable `rendered_content`.
Send the message using the rendered template with [`messages.send`](https://mandrillapp.com/api/docs/messages.JSON.html#method=send):
```
{
"message": {
"html": rendered_content,
...
...
}
```
|
57,561,119
|
Using python 3, I'm trying to append a sheet from an existing excel file to another excel file.
I have conditional formats in this excel file so I can't just use pandas.
```
from openpyxl import load_workbook
final_wb = load_workbook("my_final_workbook_with_lots_of_sheets.xlsx")
new_wb = load_workbook("workbook_with_one_sheet.xlsx")
worksheet_new = new_wb['Sheet1']
final_wb.create_sheet(worksheet_new)
final_wb.save("my_final_workbook_with_lots_of_sheets.xlsx")
```
This code doesn't work because the `.create_sheet` method only makes a new blank sheet, I want to insert my `worksheet_new` that I loaded from the other file into the `final_wb`
|
2019/08/19
|
[
"https://Stackoverflow.com/questions/57561119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193105/"
] |
So another approach, without color ranges.
A couple of things are not going right in your code I think. First, you are drawing the contours on `thresh_binary`, but that already has the outer lines of the other cells as well - the lines you are trying to get rid off. I think that is why you use `opening`(?) while in this case you shouldn't.
To fix things, first a little information on how findContours works. findContours starts looking for white shapes on a black background and then looks for black shapes inside that white contour and so on. That means that the white outline of the cells in the `thresh_binary` are detected as a contour. Inside of it are other contours, including the one you want. [docs with examples](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contours_hierarchy/py_contours_hierarchy.html#contours-hierarchy)
What you should do is first look only for contours that have no contours inside of them. The findContours also returns a hierarchy of contours. It indicates whether a contour has 'childeren'. If it has none (value: -1) then you look at the size of the contour and disregard the ones that are to small. You could also just look for the largest, as that is probably the one you want. Finally you draw the contour on a black mask.
Result:
[](https://i.stack.imgur.com/YP0aj.png)
Code:
```
import cv2 as cv
import numpy as np
# load image as grayscale
cell1 = cv.imread("PjMQR.png",0)
# threshold image
ret,thresh_binary = cv.threshold(cell1,107,255,cv.THRESH_BINARY)
# findcontours
contours, hierarchy = cv.findContours(image =thresh_binary , mode = cv.RETR_TREE,method = cv.CHAIN_APPROX_SIMPLE)
# create an empty mask
mask = np.zeros(cell1.shape[:2],dtype=np.uint8)
# loop through the contours
for i,cnt in enumerate(contours):
# if the contour has no other contours inside of it
if hierarchy[0][i][2] == -1 :
# if the size of the contour is greater than a threshold
if cv2.contourArea(cnt) > 10000:
cv.drawContours(mask,[cnt], 0, (255), -1)
# display result
cv2.imshow("Mask", mask)
cv2.imshow("Img", cell1)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
Note: I used the image you uploaded, your image probably has far fewer pixels, so a smaller contourArea
Note2: `enumerate` loops through the contours, and returns both a contour and an index for each loop
|
Actually, in your code the 'box' is a legitimate extra contour. And you draw all contours on the final image, so that includes the 'box'. This could cause issues if any of the other colored cells are fully in the image.
A better approach is to separate out the color you want. The code below creates a binary mask that only displays the pixels that are in the defined range of red colors. You can use this mask with `findContours`.
Result:
[](https://i.stack.imgur.com/1pmg4.png)
Code:
```
import cv2
# load image
img = cv2.imread("PjMQR.png")
# Convert HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# define range of red color in HSV
lower_val = np.array([0,20,0])
upper_val = np.array([15,255,255])
# Threshold the HSV image to get only red colors
mask = cv2.inRange(hsv, lower_val, upper_val)
# display image
cv2.imshow("Mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
[This code](https://github.com/twenty-twenty/opencv_basic_color_separator) can help you understand how the different values in this process (HSV with inRange) works. [inRange docs](https://docs.opencv.org/3.4.5/d2/de8/group__core__array.html#ga48af0ab51e36436c5d04340e036ce981)
|
27,829,575
|
I have a python script that calls a system program and reads the output from a file `out.txt`, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens `out.txt` once and then keeps on reading from that old copy. How can I make the python script reread the file on each iteration? I saw a similar question here on SO but it was about a python script running alongside a program, not calling it, and the solution doesn't work. I tried closing the file before looping back but it didn't do anything.
EDIT:
I already tried closing and opening, it didn't work. Here's the code:
```
import subprocess, os, sys
filename = sys.argv[1]
file = open(filename,'r')
foo = open('foo','w')
foo.write(file.read().rstrip())
foo = open('foo','a')
crap = open(os.devnull,'wb')
numSolutions = 0
while True:
subprocess.call(["minisat", "foo", "out"], stdout=crap,stderr=crap)
out = open('out','r')
if out.readline().rstrip() == "SAT":
numSolutions += 1
clause = out.readline().rstrip()
clause = clause.split(" ")
print clause
clause = map(int,clause)
clause = map(lambda x: -x,clause)
output = ' '.join(map(lambda x: str(x),clause))
print output
foo.write('\n'+output)
out.close()
else:
break
print "There are ", numSolutions, " solutions."
```
|
2015/01/07
|
[
"https://Stackoverflow.com/questions/27829575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] |
You need to flush `foo` so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that minisat can see it.
```
foo.write('\n'+output)
foo.flush()
```
|
You take your file\_var and end the loop with file\_var.close().
```
for ... :
ga_file = open(out.txt, 'r')
... do stuff
ga_file.close()
```
Demo of an implementation below (as simple as possible, this is all of the Jython code needed)...
```
__author__ = ''
import time
var = 'false'
while var == 'false':
out = open('out.txt', 'r')
content = out.read()
time.sleep(3)
print content
out.close()
```
generates this output:
```
2015-01-09, 'stuff added'
2015-01-09, 'stuff added' # <-- this is when i just saved my update
2015-01-10, 'stuff added again :)' # <-- my new output from file reads
```
I strongly recommend reading the error messages. They hold quite a lot of information.
I think the full file name should be written for debug purposes.
|
27,829,575
|
I have a python script that calls a system program and reads the output from a file `out.txt`, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens `out.txt` once and then keeps on reading from that old copy. How can I make the python script reread the file on each iteration? I saw a similar question here on SO but it was about a python script running alongside a program, not calling it, and the solution doesn't work. I tried closing the file before looping back but it didn't do anything.
EDIT:
I already tried closing and opening, it didn't work. Here's the code:
```
import subprocess, os, sys
filename = sys.argv[1]
file = open(filename,'r')
foo = open('foo','w')
foo.write(file.read().rstrip())
foo = open('foo','a')
crap = open(os.devnull,'wb')
numSolutions = 0
while True:
subprocess.call(["minisat", "foo", "out"], stdout=crap,stderr=crap)
out = open('out','r')
if out.readline().rstrip() == "SAT":
numSolutions += 1
clause = out.readline().rstrip()
clause = clause.split(" ")
print clause
clause = map(int,clause)
clause = map(lambda x: -x,clause)
output = ' '.join(map(lambda x: str(x),clause))
print output
foo.write('\n'+output)
out.close()
else:
break
print "There are ", numSolutions, " solutions."
```
|
2015/01/07
|
[
"https://Stackoverflow.com/questions/27829575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] |
I rewrote it to hopefully be a bit easier to understand:
```
import os
from shutil import copyfile
import subprocess
import sys
TEMP_CNF = "tmp.in"
TEMP_SOL = "tmp.out"
NULL = open(os.devnull, "wb")
def all_solutions(cnf_fname):
"""
Given a file containing a set of constraints,
generate all possible solutions.
"""
# make a copy of original input file
copyfile(cnf_fname, TEMP_CNF)
while True:
# run minisat to solve the constraint problem
subprocess.call(["minisat", TEMP_CNF, TEMP_SOL], stdout=NULL,stderr=NULL)
# look at the result
with open(TEMP_SOL) as result:
line = next(result)
if line.startswith("SAT"):
# Success - return solution
line = next(result)
solution = [int(i) for i in line.split()]
yield solution
else:
# Failure - no more solutions possible
break
# disqualify found solution
with open(TEMP_CNF, "a") as constraints:
new_constraint = " ".join(str(-i) for i in sol)
constraints.write("\n")
constraints.write(new_constraint)
def main(cnf_fname):
"""
Given a file containing a set of constraints,
count the possible solutions.
"""
count = sum(1 for i in all_solutions(cnf_fname))
print("There are {} solutions.".format(count))
if __name__=="__main__":
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print("Usage: {} cnf.in".format(sys.argv[0]))
```
|
You take your file\_var and end the loop with file\_var.close().
```
for ... :
ga_file = open(out.txt, 'r')
... do stuff
ga_file.close()
```
Demo of an implementation below (as simple as possible, this is all of the Jython code needed)...
```
__author__ = ''
import time
var = 'false'
while var == 'false':
out = open('out.txt', 'r')
content = out.read()
time.sleep(3)
print content
out.close()
```
generates this output:
```
2015-01-09, 'stuff added'
2015-01-09, 'stuff added' # <-- this is when i just saved my update
2015-01-10, 'stuff added again :)' # <-- my new output from file reads
```
I strongly recommend reading the error messages. They hold quite a lot of information.
I think the full file name should be written for debug purposes.
|
27,829,575
|
I have a python script that calls a system program and reads the output from a file `out.txt`, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens `out.txt` once and then keeps on reading from that old copy. How can I make the python script reread the file on each iteration? I saw a similar question here on SO but it was about a python script running alongside a program, not calling it, and the solution doesn't work. I tried closing the file before looping back but it didn't do anything.
EDIT:
I already tried closing and opening, it didn't work. Here's the code:
```
import subprocess, os, sys
filename = sys.argv[1]
file = open(filename,'r')
foo = open('foo','w')
foo.write(file.read().rstrip())
foo = open('foo','a')
crap = open(os.devnull,'wb')
numSolutions = 0
while True:
subprocess.call(["minisat", "foo", "out"], stdout=crap,stderr=crap)
out = open('out','r')
if out.readline().rstrip() == "SAT":
numSolutions += 1
clause = out.readline().rstrip()
clause = clause.split(" ")
print clause
clause = map(int,clause)
clause = map(lambda x: -x,clause)
output = ' '.join(map(lambda x: str(x),clause))
print output
foo.write('\n'+output)
out.close()
else:
break
print "There are ", numSolutions, " solutions."
```
|
2015/01/07
|
[
"https://Stackoverflow.com/questions/27829575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] |
You need to flush `foo` so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that minisat can see it.
```
foo.write('\n'+output)
foo.flush()
```
|
I rewrote it to hopefully be a bit easier to understand:
```
import os
from shutil import copyfile
import subprocess
import sys
TEMP_CNF = "tmp.in"
TEMP_SOL = "tmp.out"
NULL = open(os.devnull, "wb")
def all_solutions(cnf_fname):
"""
Given a file containing a set of constraints,
generate all possible solutions.
"""
# make a copy of original input file
copyfile(cnf_fname, TEMP_CNF)
while True:
# run minisat to solve the constraint problem
subprocess.call(["minisat", TEMP_CNF, TEMP_SOL], stdout=NULL,stderr=NULL)
# look at the result
with open(TEMP_SOL) as result:
line = next(result)
if line.startswith("SAT"):
# Success - return solution
line = next(result)
solution = [int(i) for i in line.split()]
yield solution
else:
# Failure - no more solutions possible
break
# disqualify found solution
with open(TEMP_CNF, "a") as constraints:
new_constraint = " ".join(str(-i) for i in sol)
constraints.write("\n")
constraints.write(new_constraint)
def main(cnf_fname):
"""
Given a file containing a set of constraints,
count the possible solutions.
"""
count = sum(1 for i in all_solutions(cnf_fname))
print("There are {} solutions.".format(count))
if __name__=="__main__":
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print("Usage: {} cnf.in".format(sys.argv[0]))
```
|
74,448,363
|
I am trying to find out if a hex color is "blue". This might be a very subjective thing when comparing different (lighter/ darker) shades of blue or close to blue colors but in my case it does not have to be very precise. I just want to determine if a color is blue or not.
The more generalized question would be, is there a way to calculate which of the "basic colors" is closest to a given hex value? Basic colors being red, blue ,green, yellow, purple, etc. without being too specific.
I am looking for an implementation or library in python but a general solution would also suffice.
|
2022/11/15
|
[
"https://Stackoverflow.com/questions/74448363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4644897/"
] |
This is a somewhat complicated question, see more discussion here: <https://graphicdesign.stackexchange.com/questions/92984/how-can-i-tell-basic-color-a-hex-code-is-closest-to>
I don't know of any library or implementation that already exists for this. If you really need this functionality though and don't need it to be insanely precise, what you can do is use a color table with the colors you want to classify, e.g.
```
Black #000000 (0,0,0)
White #FFFFFF (255,255,255)
Red #FF0000 (255,0,0)
Lime #00FF00 (0,255,0)
Blue #0000FF (0,0,255)
Yellow #FFFF00 (255,255,0)
Cyan / Aqua #00FFFF (0,255,255)
Magenta / Fuchsia #FF00FF (255,0,255)
Silver #C0C0C0 (192,192,192)
Gray #808080 (128,128,128)
Maroon #800000 (128,0,0)
Olive #808000 (128,128,0)
Green #008000 (0,128,0)
Purple #800080 (128,0,128)
Teal #008080 (0,128,128)
Navy #000080 (0,0,128)
```
(from <https://www.rapidtables.com/web/color/RGB_Color.html>)
And calculate which of these the given hex color is closest to. This isn't going to be completely accurate because of the way we perceive specific colors on the spectrum, but I don't think this problem has a general solution anyways so approximation may be the only path forward.
|
I mean you could do:
```
hex = input()
if hex == '#0000FF':
print('Blue')
else:
print('Not blue')
```
If that is what you are looking for.
|
64,532,869
|
I'm very new to java but i have decent experience with c++ and python. So, I'm doing a question in which im required to implement an airplane booking system, which does the following -
1.initialize all seats to not occupied(false)
2.ask for input(eco or first class)
3.check if seat is not occupied
4.if seat is not occupied allocate seat else look for next seat
5.if economy seats are booked out, ask if user wants to bump up to first class
6.if user is negative display msg "next plane is in 3hrs"
but,
```
package oop;
import java.util.Arrays;
import java.util.Scanner;
public class AirplaneBooking {
private final static int MAX_ECO_SEATS = 5;
private final static int MAX_FIRST_CLASS_SEATS = 3;
private final static boolean[] ECO_SEATS = new boolean[MAX_ECO_SEATS];
private final static boolean[] FIRST_CLASS_SEATS = new boolean[MAX_FIRST_CLASS_SEATS];
private static int current_eco_seat = 0;
private static int current_first_class_seat = 0;
public static void initialilze_seats(boolean[] first_class_seats, boolean[] eco_class_seats){
Arrays.fill(first_class_seats, Boolean.FALSE);
Arrays.fill(eco_class_seats, Boolean.FALSE);
}
public static void display(boolean[] seats){
System.out.print("[");
for(boolean seat : seats){
System.out.print(seat + ",");
}
System.out.println("]");
}
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
public static int user_input() {
Scanner input = new Scanner(System.in);
System.out.print("Enter 1 for Economy class or 2 for First class : ");
int user_seat_prefrence = input.nextInt();
if (user_seat_prefrence == 1){
if(current_eco_seat < MAX_ECO_SEATS){
book_seat(ECO_SEATS, current_eco_seat);
}
else{
System.out.println("Looks like eco seats are full, would you like to book for first class insted(1/0) ?");
Scanner next_input = new Scanner(System.in);
int user_next_seat_prefrence = next_input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
user_seat_prefrence = 2;
}
else{
System.out.println("next flight leaves in 3 hrs");
}
}
}
else if (user_seat_prefrence == 2){
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
}
else {
System.out.println("Enter valid option");
}
return user_seat_prefrence;
}
public static void print_boarding_pass(int user_seat_prefrence){
if (user_seat_prefrence == 1){
System.out.println("eco");
System.out.println(current_eco_seat - 1);
}
else{
System.out.println("first class");
System.out.println(current_first_class_seat - 1);
}
}
public static void main(String args[]){
initialilze_seats(FIRST_CLASS_SEATS, ECO_SEATS);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
while(true){
int user_seat_prefrence = user_input();
print_boarding_pass(user_seat_prefrence);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
System.out.print("book another seat:");
Scanner choice = new Scanner(System.in);
boolean book_another_seat = choice.nextBoolean();
if (book_another_seat == false)
break;
}
}
}
```
The problem i'm having with this code is if the seats for eco class(for example) are full, the program is supposed to ask if i want to book for first class instead and wait for my input, if I press `1` it should book in first class but the program does not await for my input and proceeds to `else` statement instead.
Also, i use a `static` variable `current_eco_seat` and `current_first_class_seat` to keep track of the current seat being booked, and i pass that static variable to `book_seat` function, the program then books the seat and increments the `current_eco_seat` or `current_first_class_seat`(depending which is passed) so that next seat can be booked in next interation. But the static variable does not get incremented at all.
These are the only problems i have with the program.
Any help is appreciated, thanks
|
2020/10/26
|
[
"https://Stackoverflow.com/questions/64532869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617688/"
] |
As Java calls methods by value,
Your problem about static is you are passing the value of `current_seat` to the `book_seat` method, so changing the value doesn't affect that variable after returning from the method.
To solve it just call the method and do not pass your static vars. It's static, so you have access it from everywhere.
i.e:
```
public static void book_seat(boolean [] seats){
seats[current_seat] = true;
current_first_class_seat++;
System.out.println(current_seat);
}
```
|
1. Checking Inout stream
Not sure wether your question is related to "static" variables or more related to "How to handle Input Stream?".
Regarding:
>
> if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
>
>
>
You should think about "flushing" the Input Stream before reading again. [flush-clear-system-in-stdin-before-reading](https://stackoverflow.com/questions/18273751/flush-clear-system-in-stdin-before-reading)
2. Method Parameter usage
On the other hand this method is wrong
```
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
```
this command has no affect, but printing an information to the User. The variable you used in the caller "current\_eco\_seat" will not change at all.
|
64,532,869
|
I'm very new to java but i have decent experience with c++ and python. So, I'm doing a question in which im required to implement an airplane booking system, which does the following -
1.initialize all seats to not occupied(false)
2.ask for input(eco or first class)
3.check if seat is not occupied
4.if seat is not occupied allocate seat else look for next seat
5.if economy seats are booked out, ask if user wants to bump up to first class
6.if user is negative display msg "next plane is in 3hrs"
but,
```
package oop;
import java.util.Arrays;
import java.util.Scanner;
public class AirplaneBooking {
private final static int MAX_ECO_SEATS = 5;
private final static int MAX_FIRST_CLASS_SEATS = 3;
private final static boolean[] ECO_SEATS = new boolean[MAX_ECO_SEATS];
private final static boolean[] FIRST_CLASS_SEATS = new boolean[MAX_FIRST_CLASS_SEATS];
private static int current_eco_seat = 0;
private static int current_first_class_seat = 0;
public static void initialilze_seats(boolean[] first_class_seats, boolean[] eco_class_seats){
Arrays.fill(first_class_seats, Boolean.FALSE);
Arrays.fill(eco_class_seats, Boolean.FALSE);
}
public static void display(boolean[] seats){
System.out.print("[");
for(boolean seat : seats){
System.out.print(seat + ",");
}
System.out.println("]");
}
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
public static int user_input() {
Scanner input = new Scanner(System.in);
System.out.print("Enter 1 for Economy class or 2 for First class : ");
int user_seat_prefrence = input.nextInt();
if (user_seat_prefrence == 1){
if(current_eco_seat < MAX_ECO_SEATS){
book_seat(ECO_SEATS, current_eco_seat);
}
else{
System.out.println("Looks like eco seats are full, would you like to book for first class insted(1/0) ?");
Scanner next_input = new Scanner(System.in);
int user_next_seat_prefrence = next_input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
user_seat_prefrence = 2;
}
else{
System.out.println("next flight leaves in 3 hrs");
}
}
}
else if (user_seat_prefrence == 2){
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
}
else {
System.out.println("Enter valid option");
}
return user_seat_prefrence;
}
public static void print_boarding_pass(int user_seat_prefrence){
if (user_seat_prefrence == 1){
System.out.println("eco");
System.out.println(current_eco_seat - 1);
}
else{
System.out.println("first class");
System.out.println(current_first_class_seat - 1);
}
}
public static void main(String args[]){
initialilze_seats(FIRST_CLASS_SEATS, ECO_SEATS);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
while(true){
int user_seat_prefrence = user_input();
print_boarding_pass(user_seat_prefrence);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
System.out.print("book another seat:");
Scanner choice = new Scanner(System.in);
boolean book_another_seat = choice.nextBoolean();
if (book_another_seat == false)
break;
}
}
}
```
The problem i'm having with this code is if the seats for eco class(for example) are full, the program is supposed to ask if i want to book for first class instead and wait for my input, if I press `1` it should book in first class but the program does not await for my input and proceeds to `else` statement instead.
Also, i use a `static` variable `current_eco_seat` and `current_first_class_seat` to keep track of the current seat being booked, and i pass that static variable to `book_seat` function, the program then books the seat and increments the `current_eco_seat` or `current_first_class_seat`(depending which is passed) so that next seat can be booked in next interation. But the static variable does not get incremented at all.
These are the only problems i have with the program.
Any help is appreciated, thanks
|
2020/10/26
|
[
"https://Stackoverflow.com/questions/64532869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617688/"
] |
As Java calls methods by value,
Your problem about static is you are passing the value of `current_seat` to the `book_seat` method, so changing the value doesn't affect that variable after returning from the method.
To solve it just call the method and do not pass your static vars. It's static, so you have access it from everywhere.
i.e:
```
public static void book_seat(boolean [] seats){
seats[current_seat] = true;
current_first_class_seat++;
System.out.println(current_seat);
}
```
|
you don't need to insist incrementing the exact variable, just do the following :
1. make `book_seat()` to return incremented value
```java
public static int book_seat(boolean [] seats, int current_seat) {
seats[current_seat] = true;
System.out.println(current_seat + 1);
return current_seat + 1;
}
```
2. set returned value to `current_first_class_seat` or `current_eco_seat`
```java
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
current_first_class_seat = book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
current_eco_seat = book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
```
Then you can use `book_seat()` for both eco and first class reservations handling as previously you have intended.
|
2,284,666
|
I've been able to do this through the django environment shell, but hasn't worked on my actual site. Here is my model:
```
class ShoeReview(models.Model):
def __unicode__(self):
return self.title
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
keywords = models.TextField()
author = models.ForeignKey(User, related_name='reviews')
pub_date = models.DateTimeField(auto_now_add='true')
Shoe = models.OneToOneField(Shoe) # make this select those without a shoe review in admin area
owner_reviews = OwnerReview.objects.filter(Shoe__name=Shoe)
```
I'm sure this is something silly, but I've been at it for around 6 hours. It's part of the reason I haven't slept in the last 18 :S
**I'm trying to return all OwnerReview objects from the OwnerReview Model that match the current Shoe:**
```
class OwnerReview(models.Model):
def __unicode__(self):
return self.comments
name = models.CharField(max_length=50)
pub_date = models.DateTimeField(auto_now_add='true')
Shoe = models.ForeignKey(Shoe)
email = models.EmailField()
rating = models.PositiveSmallIntegerField()
comments = models.CharField(max_length=500)
```
Here is what i'm trying to accomplish done through "python manage.py shell":
```
>>> from runningshoesreview.reviews.models import Shoe, OwnerReview
>>> ariake = Shoe.objects.get(pk=1)
>>> ariake.name
u'Ariake'
>>> owner_reviews_for_current_shoe = OwnerReview.objects.filter(Shoe__name=ariake.name)
>>> owner_reviews_for_current_shoe
[<OwnerReview: great pk shoe!>, <OwnerReview: good shoes, sometimes tear easy though.>]
```
|
2010/02/17
|
[
"https://Stackoverflow.com/questions/2284666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200916/"
] |
```
ariake = Shoe.objects.get(pk=1)
# get the OwnerReviews
ariake.ownerreview_set.all()
# or the ShoeReviews
akiake.shoereview_set.all()
```
Or if you really want to use the OwnerReview class directly
```
OwnerReview.objects.filter(shoe=ariaki)
```
A question for you. Did you mean to use OnoToOneField(Shoe) and not ForeignKey(Shoe) in the ShoeReview class? ForeignKey makes more sense to me. I would lowercase the 'Shoe' field in both of your review models and remove the reference to OwnerReview in ShoeReview.
```
class ShoeReview(models.Model):
# ...
shoe = models.ForeignKey(Shoe)
#^^^ lowercase field and ^^^^ capitalized model
# VVV remove this next line VVV
#owner_reviews = OwnerReview.objects.filter(Shoe__name=Shoe)
```
My example assumes that you have switched from 'Shoe' to 'shoe' for the field name in your models.
|
The reason why you're getting an empty QuerySet is because on your ShoeReview model, your filter argument is wrong:
>
> `owner_reviews = OwnerReview.objects.filter(Shoe__name=Shoe)`
>
>
>
Change to this:
>
> `owner_reviews = OwnerReview.objects.filter(Shoe=Shoe) #without __name`
> or you can do like this also:
> `owner_reviews = OwnerReview.objects.filter(Shoe__name=Shoe.name)`
>
>
>
The point is that you can't compare the name attribute to the Shoe object. Either compare an object to an object or an attribute to an attribute.
|
37,209,213
|
I am working on a project with some friends and we're facing a bit of a problem with our implementation of `picamera`.
We're trying to import `cv2` and `picamera` at the start of the program (working with Python 3) and so far importing `cv2` works just fine.
When we're trying to import picamera it tells us this: `ImportError: No module named picamera`.
I made sure we installed `picamera` with "`sudo apt-get install python-picamera`" and with "`...python3-picamera`" and it tells me the modules are installed.
Does anyone know how to fix this problem?
Our goal is to take a photo every 0.5s and use it for our OpenCV-program, and we wanted to do that with `picamera`, and only that.
Might the problem be that our project is located on the Desktop and not in some kind of Project folder or something?
Thanks in advance.
|
2016/05/13
|
[
"https://Stackoverflow.com/questions/37209213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6140273/"
] |
I know this was posted a while ago, but for those who are experiencing the same issue, try this:
```
pip install "picamera[array]"
```
According to [piimagesearch.com](http://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/ "pyimagesearch.com") it's necessary to install the optional "array" sub-module for openCV to interface properly with picamera.
|
This should might help
```
sudo pip3 install picamera
```
I ran this on my desktop and something installed so it should work
if pip isn't installed you may have to run
```
sudo apt-get install python3-pip
```
sources:
[How to install pip with Python 3?](https://stackoverflow.com/questions/6587507/how-to-install-pip-with-python-3)
|
57,524,198
|
You won´t be able to run the script, sadly I don´t know why.
It's about EOL but I'm not that much into python so I need your help,
I´ve tried different stuff and didn't work. Also, my friend that actually is into phyton tried and failed.
this is just a menu code for running multiple antiviruses whenever I want to check my computer
```
import sys, string, os, arcgisscripting
def menu():
print ("Welcome To S1MPL3 MENU, an simple made antivirus for open Wi-Fi and Computer Repair.\n 1. Easy File Check \n 2.Total Time Security \n 3.Suspicius Ip Check")
choice = input()
if choice == "1":
print("Checking Files ... (The process wont take long !")
os.chdir 'C:\Users\alexa\Desktop\Core_Files\Projects\S1mpl3 Antivirus\Check\Files\File_Check.vbs\
menu()
if choice == "2":
print("TTS Chosen!")
os.chdir 'C:\Users\alexa\Desktop\Projects\S1mpl3_Antivirus\Check\\Files\Ip_Check\'
menu()
if choice == "3":
print("Checking For Suspicius Ip in your Home Wi-Fi")
os.chdir 'C:\Users\alexa\Desktop\Core_Files\Projects\S1mpl3 Antivirus\Check\Files\Ip_Check\'
menu()
menu()
```
The error should be in the S1m of choice 2
>
> Error: Syntax Error EOL while scanning string literal
>
>
>
|
2019/08/16
|
[
"https://Stackoverflow.com/questions/57524198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11935868/"
] |
You are using backslash characters '\' in your paths. While this is OK on the command line, it is (mostly) not correct in source code. The backslash character is used as escape character to change the meaning of the following character. In your case the trailing apostroph is escaped so that the path string is not closed.
You can use a raw string like @RonaldAaronson proposed:
```
r'C:\Users\alexa\Desktop\Projects\S1mpl3_Antivirus\Check\Files\Ip_Check\'
```
Or replace all single backslash with double like this:
```
'C:\\Users\\alexa\\Desktop\\Projects\\S1mpl3_Antivirus\\Check\\Files\\Ip_Check\\'
```
Many Windows function also work with the unixoid path separator '/', and `os.chdir()` does so, too:
```
os.chdir('C:/Users/alexa/Desktop/Projects/S1mpl3_Antivirus/Check/Files/Ip_Check')
```
The library `os` has `os.sep` and `os.altsep` that are pathname separators. Use these to write better portable code. Please read the documentation. This is always a good idea.
Second observation: You need to call `os.chdir()` with parentheses.
|
You are missing a single quote at the end of the line:
```
if choice == "1":
print("Checking Files ... (The process wont take long !")
os.chdir 'C:\Users\alexa\Desktop\Core_Files\Projects\S1mpl3 Antivirus\Check\Files\File_Check.vbs\ **<---here**
menu()
```
|
57,524,198
|
You won´t be able to run the script, sadly I don´t know why.
It's about EOL but I'm not that much into python so I need your help,
I´ve tried different stuff and didn't work. Also, my friend that actually is into phyton tried and failed.
this is just a menu code for running multiple antiviruses whenever I want to check my computer
```
import sys, string, os, arcgisscripting
def menu():
print ("Welcome To S1MPL3 MENU, an simple made antivirus for open Wi-Fi and Computer Repair.\n 1. Easy File Check \n 2.Total Time Security \n 3.Suspicius Ip Check")
choice = input()
if choice == "1":
print("Checking Files ... (The process wont take long !")
os.chdir 'C:\Users\alexa\Desktop\Core_Files\Projects\S1mpl3 Antivirus\Check\Files\File_Check.vbs\
menu()
if choice == "2":
print("TTS Chosen!")
os.chdir 'C:\Users\alexa\Desktop\Projects\S1mpl3_Antivirus\Check\\Files\Ip_Check\'
menu()
if choice == "3":
print("Checking For Suspicius Ip in your Home Wi-Fi")
os.chdir 'C:\Users\alexa\Desktop\Core_Files\Projects\S1mpl3 Antivirus\Check\Files\Ip_Check\'
menu()
menu()
```
The error should be in the S1m of choice 2
>
> Error: Syntax Error EOL while scanning string literal
>
>
>
|
2019/08/16
|
[
"https://Stackoverflow.com/questions/57524198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11935868/"
] |
You are using backslash characters '\' in your paths. While this is OK on the command line, it is (mostly) not correct in source code. The backslash character is used as escape character to change the meaning of the following character. In your case the trailing apostroph is escaped so that the path string is not closed.
You can use a raw string like @RonaldAaronson proposed:
```
r'C:\Users\alexa\Desktop\Projects\S1mpl3_Antivirus\Check\Files\Ip_Check\'
```
Or replace all single backslash with double like this:
```
'C:\\Users\\alexa\\Desktop\\Projects\\S1mpl3_Antivirus\\Check\\Files\\Ip_Check\\'
```
Many Windows function also work with the unixoid path separator '/', and `os.chdir()` does so, too:
```
os.chdir('C:/Users/alexa/Desktop/Projects/S1mpl3_Antivirus/Check/Files/Ip_Check')
```
The library `os` has `os.sep` and `os.altsep` that are pathname separators. Use these to write better portable code. Please read the documentation. This is always a good idea.
Second observation: You need to call `os.chdir()` with parentheses.
|
I have a similar problem while opening a directory. I used raw string and double backslashes and it works. Example:
```py
os.chdir(r"C:\\Users\\alexa\Desktop\\Core_Files\\Projects\\S1mpl3Antivirus\\Check\\Files\\")
```
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
I see that your GPU has **[compute capability 5.0](https://developer.nvidia.com/cuda-gpus)** which is OK, TensorFlow should like it. Thus I assume something went wrong during the environment setup. Please try creating a new environment using:
```
conda create --name tf_gpu tensorflow-gpu
```
Then install all other packages you want in ***tf\_gpu*** and try again.
P.S: it is really important that in the environment you have only one TensorFlow package (the gpu one). If you have more than one, there is no guarantee that
```
import tensorflow as tf
```
will import the one you want ...
|
Using `conda` to install TensorFlow is always a better way to manage the multi versions of TensorFlow itself as well as CUDA and CUDNN. I recently create a new conda environment and prepare to install the newest TensorFlow too. I also encountered the issue you mentioned. I checked the dependency list from `conda install tensorflow-gpu` and found that the `cudatoolkit` and `cudnn` packages are missing. As the latest version of tensorflow-gpu at Anaconda is 2.3, I think the problem was already pointed out by @GZ0's answer at the GitHub issue.
Here I list the output below:
Using `conda install tensorflow=2.3`:
```
PS > conda install tensorflow-gpu=2.3
## Package Plan ##
environment location: C:\Anaconda3\envs\test_cuda_38
added / updated specs:
- tensorflow-gpu=2.3
The following packages will be downloaded:
package | build
---------------------------|-----------------
absl-py-0.12.0 | py38haa95532_0 176 KB
aiohttp-3.7.4 | py38h2bbff1b_1 513 KB
astunparse-1.6.3 | py_0 17 KB
async-timeout-3.0.1 | py38haa95532_0 14 KB
blas-1.0 | mkl 6 KB
blinker-1.4 | py38haa95532_0 23 KB
brotlipy-0.7.0 |py38h2bbff1b_1003 412 KB
cachetools-4.2.1 | pyhd3eb1b0_0 13 KB
cffi-1.14.5 | py38hcd4344a_0 224 KB
chardet-3.0.4 |py38haa95532_1003 194 KB
click-7.1.2 | pyhd3eb1b0_0 64 KB
coverage-5.5 | py38h2bbff1b_2 272 KB
cryptography-3.4.7 | py38h71e12ea_0 643 KB
cython-0.29.23 | py38hd77b12b_0 1.7 MB
gast-0.4.0 | py_0 15 KB
google-auth-1.29.0 | pyhd3eb1b0_0 76 KB
google-auth-oauthlib-0.4.4 | pyhd3eb1b0_0 18 KB
google-pasta-0.2.0 | py_0 46 KB
grpcio-1.36.1 | py38hc60d5dd_1 1.7 MB
h5py-2.10.0 | py38h5e291fa_0 841 KB
hdf5-1.10.4 | h7ebc959_0 7.9 MB
icc_rt-2019.0.0 | h0cc432a_1 6.0 MB
idna-2.10 | pyhd3eb1b0_0 52 KB
importlib-metadata-3.10.0 | py38haa95532_0 34 KB
intel-openmp-2021.2.0 | haa95532_616 1.8 MB
keras-applications-1.0.8 | py_1 29 KB
keras-preprocessing-1.1.2 | pyhd3eb1b0_0 35 KB
libprotobuf-3.14.0 | h23ce68f_0 1.9 MB
markdown-3.3.4 | py38haa95532_0 144 KB
mkl-2021.2.0 | haa95532_296 115.5 MB
mkl-service-2.3.0 | py38h2bbff1b_1 49 KB
mkl_fft-1.3.0 | py38h277e83a_2 137 KB
mkl_random-1.2.1 | py38hf11a4ad_2 223 KB
multidict-5.1.0 | py38h2bbff1b_2 61 KB
numpy-1.20.1 | py38h34a8a5c_0 23 KB
numpy-base-1.20.1 | py38haf7ebc8_0 4.2 MB
oauthlib-3.1.0 | py_0 91 KB
opt_einsum-3.1.0 | py_0 54 KB
protobuf-3.14.0 | py38hd77b12b_1 242 KB
pyasn1-0.4.8 | py_0 57 KB
pyasn1-modules-0.2.8 | py_0 72 KB
pycparser-2.20 | py_2 94 KB
pyjwt-1.7.1 | py38_0 48 KB
pyopenssl-20.0.1 | pyhd3eb1b0_1 49 KB
pyreadline-2.1 | py38_1 145 KB
pysocks-1.7.1 | py38haa95532_0 31 KB
requests-2.25.1 | pyhd3eb1b0_0 52 KB
requests-oauthlib-1.3.0 | py_0 23 KB
rsa-4.7.2 | pyhd3eb1b0_1 28 KB
scipy-1.6.2 | py38h66253e8_1 13.0 MB
tensorboard-plugin-wit-1.6.0| py_0 630 KB
tensorflow-2.3.0 |mkl_py38h8557ec7_0 6 KB
tensorflow-base-2.3.0 |eigen_py38h75a453f_0 49.5 MB
tensorflow-estimator-2.3.0 | pyheb71bc4_0 271 KB
termcolor-1.1.0 | py38haa95532_1 9 KB
typing-extensions-3.7.4.3 | hd3eb1b0_0 12 KB
typing_extensions-3.7.4.3 | pyh06a4308_0 28 KB
urllib3-1.26.4 | pyhd3eb1b0_0 105 KB
werkzeug-1.0.1 | pyhd3eb1b0_0 239 KB
win_inet_pton-1.1.0 | py38haa95532_0 35 KB
wrapt-1.12.1 | py38he774522_1 49 KB
yarl-1.6.3 | py38h2bbff1b_0 153 KB
------------------------------------------------------------
Total: 210.0 MB
```
Using `conda install tensorflow=2.1`:
```
PS > conda install tensorflow-gpu=2.1
## Package Plan ##
environment location: C:\Anaconda3\envs\test_cuda
added / updated specs:
- tensorflow-gpu=2.1
The following packages will be downloaded:
package | build
---------------------------|-----------------
_tflow_select-2.1.0 | gpu 3 KB
absl-py-0.12.0 | py37haa95532_0 175 KB
aiohttp-3.7.4 | py37h2bbff1b_1 507 KB
astor-0.8.1 | py37haa95532_0 47 KB
async-timeout-3.0.1 | py37haa95532_0 14 KB
blas-1.0 | mkl 6 KB
blinker-1.4 | py37haa95532_0 23 KB
brotlipy-0.7.0 |py37h2bbff1b_1003 337 KB
cachetools-4.2.1 | pyhd3eb1b0_0 13 KB
cffi-1.14.5 | py37hcd4344a_0 220 KB
chardet-3.0.4 |py37haa95532_1003 192 KB
click-7.1.2 | pyhd3eb1b0_0 64 KB
coverage-5.5 | py37h2bbff1b_2 273 KB
cryptography-3.4.7 | py37h71e12ea_0 641 KB
cudatoolkit-10.1.243 | h74a9793_0 300.3 MB
cudnn-7.6.5 | cuda10.1_0 179.1 MB
cython-0.29.23 | py37hd77b12b_0 1.7 MB
gast-0.2.2 | py37_0 155 KB
google-auth-1.29.0 | pyhd3eb1b0_0 76 KB
google-auth-oauthlib-0.4.4 | pyhd3eb1b0_0 18 KB
google-pasta-0.2.0 | py_0 46 KB
grpcio-1.36.1 | py37hc60d5dd_1 1.7 MB
h5py-2.10.0 | py37h5e291fa_0 808 KB
hdf5-1.10.4 | h7ebc959_0 7.9 MB
icc_rt-2019.0.0 | h0cc432a_1 6.0 MB
idna-2.10 | pyhd3eb1b0_0 52 KB
importlib-metadata-3.10.0 | py37haa95532_0 34 KB
intel-openmp-2021.2.0 | haa95532_616 1.8 MB
keras-applications-1.0.8 | py_1 29 KB
keras-preprocessing-1.1.2 | pyhd3eb1b0_0 35 KB
libprotobuf-3.14.0 | h23ce68f_0 1.9 MB
markdown-3.3.4 | py37haa95532_0 144 KB
mkl-2021.2.0 | haa95532_296 115.5 MB
mkl-service-2.3.0 | py37h2bbff1b_1 48 KB
mkl_fft-1.3.0 | py37h277e83a_2 133 KB
mkl_random-1.2.1 | py37hf11a4ad_2 214 KB
multidict-5.1.0 | py37h2bbff1b_2 85 KB
numpy-1.20.1 | py37h34a8a5c_0 23 KB
numpy-base-1.20.1 | py37haf7ebc8_0 4.1 MB
oauthlib-3.1.0 | py_0 91 KB
opt_einsum-3.1.0 | py_0 54 KB
protobuf-3.14.0 | py37hd77b12b_1 240 KB
pyasn1-0.4.8 | py_0 57 KB
pyasn1-modules-0.2.8 | py_0 72 KB
pycparser-2.20 | py_2 94 KB
pyjwt-1.7.1 | py37_0 49 KB
pyopenssl-20.0.1 | pyhd3eb1b0_1 49 KB
pyreadline-2.1 | py37_1 143 KB
pysocks-1.7.1 | py37_1 28 KB
requests-2.25.1 | pyhd3eb1b0_0 52 KB
requests-oauthlib-1.3.0 | py_0 23 KB
rsa-4.7.2 | pyhd3eb1b0_1 28 KB
scipy-1.6.2 | py37h66253e8_1 12.8 MB
six-1.15.0 | py37haa95532_0 51 KB
tensorboard-plugin-wit-1.6.0| py_0 630 KB
tensorflow-2.1.0 |gpu_py37h7db9008_0 4 KB
tensorflow-base-2.1.0 |gpu_py37h55f5790_0 105.3 MB
tensorflow-estimator-2.1.0 | pyhd54b08b_0 251 KB
tensorflow-gpu-2.1.0 | h0d30ee6_0 3 KB
termcolor-1.1.0 | py37haa95532_1 9 KB
typing-extensions-3.7.4.3 | hd3eb1b0_0 12 KB
typing_extensions-3.7.4.3 | pyh06a4308_0 28 KB
urllib3-1.26.4 | pyhd3eb1b0_0 105 KB
werkzeug-0.16.1 | py_0 258 KB
win_inet_pton-1.1.0 | py37haa95532_0 35 KB
wrapt-1.12.1 | py37he774522_1 49 KB
yarl-1.6.3 | py37h2bbff1b_0 151 KB
------------------------------------------------------------
Total: 745.0 MB
```
Therefore, you may install the latest version (v2.3) of tensorflow-gpu from Anaconda on Windows platform using the advises from @GZ0 and @geometrikal, or just using `conda install tensorflow-gpu=2.1` to get the newest and right environment.
Notice that tensorflow-gpu v2.1 only support Python between 3.5-3.7.
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
I see that your GPU has **[compute capability 5.0](https://developer.nvidia.com/cuda-gpus)** which is OK, TensorFlow should like it. Thus I assume something went wrong during the environment setup. Please try creating a new environment using:
```
conda create --name tf_gpu tensorflow-gpu
```
Then install all other packages you want in ***tf\_gpu*** and try again.
P.S: it is really important that in the environment you have only one TensorFlow package (the gpu one). If you have more than one, there is no guarantee that
```
import tensorflow as tf
```
will import the one you want ...
|
As of August 2021, with TensorFlow 2.4.1, I believe it seems to install CUDA and CuDNN in a conda environment. Here's what I did to create a fresh conda env on an Ubuntu 18.04 machine:
```
conda create --name tftest python=3.7 -y && conda activate tftest
conda install ipython tensorflow-gpu==2.4.1 -y
```
The command above will list the following packages to be installed. For our purposes, *note how `cudatoolkit` and `cudnn` are listed*.
```
The following packages will be downloaded:
package | build
---------------------------|-----------------
_tflow_select-2.1.0 | gpu 2 KB
absl-py-0.13.0 | py37h06a4308_0 173 KB
aiohttp-3.7.4 | py37h27cfd23_1 536 KB
astor-0.8.1 | py37h06a4308_0 47 KB
astunparse-1.6.3 | py_0 17 KB
async-timeout-3.0.1 | py37h06a4308_0 13 KB
attrs-21.2.0 | pyhd3eb1b0_0 46 KB
backcall-0.2.0 | pyhd3eb1b0_0 13 KB
blas-1.0 | mkl 6 KB
blinker-1.4 | py37h06a4308_0 23 KB
brotlipy-0.7.0 |py37h27cfd23_1003 320 KB
c-ares-1.17.1 | h27cfd23_0 108 KB
cachetools-4.2.2 | pyhd3eb1b0_0 13 KB
cffi-1.14.6 | py37h400218f_0 223 KB
chardet-3.0.4 |py37h06a4308_1003 175 KB
charset-normalizer-2.0.4 | pyhd3eb1b0_0 35 KB
click-8.0.1 | pyhd3eb1b0_0 79 KB
coverage-5.5 | py37h27cfd23_2 254 KB
cryptography-3.4.7 | py37hd23ed53_0 904 KB
cudatoolkit-10.1.243 | h6bb024c_0 347.4 MB
cudnn-7.6.5 | cuda10.1_0 179.9 MB
cupti-10.1.168 | 0 1.4 MB
cython-0.29.24 | py37h295c915_0 1.9 MB
decorator-5.0.9 | pyhd3eb1b0_0 12 KB
gast-0.4.0 | pyhd3eb1b0_0 13 KB
google-auth-1.33.0 | pyhd3eb1b0_0 80 KB
google-auth-oauthlib-0.4.4 | pyhd3eb1b0_0 18 KB
google-pasta-0.2.0 | py_0 46 KB
grpcio-1.36.1 | py37h2157cd5_1 1.9 MB
h5py-2.10.0 | py37hd6299e0_1 902 KB
hdf5-1.10.6 | hb1b8bf9_0 3.7 MB
idna-3.2 | pyhd3eb1b0_0 48 KB
importlib-metadata-3.10.0 | py37h06a4308_0 33 KB
intel-openmp-2021.3.0 | h06a4308_3350 1.4 MB
ipython-7.26.0 | py37hb070fc8_0 1005 KB
ipython_genutils-0.2.0 | pyhd3eb1b0_1 27 KB
jedi-0.18.0 | py37h06a4308_1 911 KB
keras-preprocessing-1.1.2 | pyhd3eb1b0_0 35 KB
libgfortran-ng-7.5.0 | ha8ba4b0_17 22 KB
libgfortran4-7.5.0 | ha8ba4b0_17 995 KB
libprotobuf-3.17.2 | h4ff587b_1 2.0 MB
markdown-3.3.4 | py37h06a4308_0 127 KB
matplotlib-inline-0.1.2 | pyhd3eb1b0_2 12 KB
mkl-2021.3.0 | h06a4308_520 141.2 MB
mkl-service-2.4.0 | py37h7f8727e_0 56 KB
mkl_fft-1.3.0 | py37h42c9631_2 170 KB
mkl_random-1.2.2 | py37h51133e4_0 287 KB
multidict-5.1.0 | py37h27cfd23_2 66 KB
numpy-1.20.3 | py37hf144106_0 23 KB
numpy-base-1.20.3 | py37h74d4b33_0 4.5 MB
oauthlib-3.1.1 | pyhd3eb1b0_0 90 KB
opt_einsum-3.3.0 | pyhd3eb1b0_1 57 KB
parso-0.8.2 | pyhd3eb1b0_0 69 KB
pexpect-4.8.0 | pyhd3eb1b0_3 53 KB
pickleshare-0.7.5 | pyhd3eb1b0_1003 13 KB
prompt-toolkit-3.0.17 | pyh06a4308_0 256 KB
protobuf-3.17.2 | py37h295c915_0 319 KB
ptyprocess-0.7.0 | pyhd3eb1b0_2 17 KB
pyasn1-0.4.8 | py_0 57 KB
pyasn1-modules-0.2.8 | py_0 72 KB
pygments-2.10.0 | pyhd3eb1b0_0 725 KB
pyjwt-2.1.0 | py37h06a4308_0 32 KB
pyopenssl-20.0.1 | pyhd3eb1b0_1 49 KB
pysocks-1.7.1 | py37_1 27 KB
python-flatbuffers-1.12 | pyhd3eb1b0_0 24 KB
requests-2.26.0 | pyhd3eb1b0_0 59 KB
requests-oauthlib-1.3.0 | py_0 23 KB
rsa-4.7.2 | pyhd3eb1b0_1 28 KB
scipy-1.6.2 | py37had2a1c9_1 15.5 MB
six-1.16.0 | pyhd3eb1b0_0 18 KB
tensorboard-2.4.0 | pyhc547734_0 8.8 MB
tensorboard-plugin-wit-1.6.0| py_0 630 KB
tensorflow-2.4.1 |gpu_py37ha2e99fa_0 4 KB
tensorflow-base-2.4.1 |gpu_py37h29c2da4_0 195.2 MB
tensorflow-estimator-2.5.0 | pyh7b7c402_0 267 KB
tensorflow-gpu-2.4.1 | h30adc30_0 3 KB
termcolor-1.1.0 | py37h06a4308_1 9 KB
traitlets-5.0.5 | pyhd3eb1b0_0 81 KB
typing-extensions-3.10.0.0 | hd3eb1b0_0 8 KB
typing_extensions-3.10.0.0 | pyh06a4308_0 27 KB
urllib3-1.26.6 | pyhd3eb1b0_1 112 KB
wcwidth-0.2.5 | py_0 29 KB
werkzeug-1.0.1 | pyhd3eb1b0_0 239 KB
wrapt-1.12.1 | py37h7b6447c_1 49 KB
yarl-1.6.3 | py37h27cfd23_0 133 KB
zipp-3.5.0 | pyhd3eb1b0_0 13 KB
------------------------------------------------------------
Total: 915.9 MB
```
Next, run `ipython` and try:
```
In [1]: import tensorflow as tf
2021-08-29 12:26:36.582384: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.10.1
In [2]: tf.config.list_physical_devices('GPU')
2021-08-29 12:26:48.676151: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2021-08-29 12:26:48.679894: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcuda.so.1
2021-08-29 12:26:48.975002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 0 with properties:
pciBusID: 0000:04:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.979341: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 1 with properties:
pciBusID: 0000:08:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.981747: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 2 with properties:
pciBusID: 0000:09:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.990002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 3 with properties:
pciBusID: 0000:85:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.992488: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 4 with properties:
pciBusID: 0000:89:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.992523: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.10.1
2021-08-29 12:26:49.312793: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.10
2021-08-29 12:26:49.312907: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.10
2021-08-29 12:26:49.388961: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10
2021-08-29 12:26:49.413946: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10
2021-08-29 12:26:49.535055: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.10
2021-08-29 12:26:49.563142: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.10
2021-08-29 12:26:50.009291: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.7
2021-08-29 12:26:50.051301: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1862] Adding visible gpu devices: 0, 1, 2, 3, 4
Out[2]:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:1', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:2', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:3', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:4', device_type='GPU')]
In [3]: tf.test.is_built_with_cuda()
Out[3]: True
```
This machine has 5 GPUs, so the above output is correct.
What I'm not actually sure about is why CUDA 10.1 and CuDNN 7.6.5 are installed, since it seems like [from Google's TF compatibility chart](https://www.tensorflow.org/install/source#gpu) that 2.4.0 (and presumably 2.4.1?) work with CUDA 11.0 and CuDNN 8. If anyone has insights on that, feel free to chime in...
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
The `tensorflow` build automatically selected by Anaconda on Windows 10 during the installation of `tensorflow-gpu` 2.3 seems to be faulty. Please find a workaround [here](https://github.com/ContinuumIO/anaconda-issues/issues/12194#issuecomment-751700156) (consider upvoting the GitHub answer if you have a GitHub account).
**Windows only:**
Python 3.7: `conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py37h936c3e2_0`
Python 3.8: `conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0`
|
You will need to install cuDNN and the CUDA toolkit to use your GPU.
First check for the compatible version [here](https://www.tensorflow.org/install/source#gpu).
cuDNN can be found [here](https://developer.nvidia.com/cudnn) (requires free account).
CUDA toolkit can be found [here](https://developer.nvidia.com/cuda-toolkit-archive).
Again, check for a compatible version BEFORE installing. Newer versions are not backwards compatible.
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
@geometrikal solution almost worked for me. But in between installing tensorflow-gpu with conda and installing tensorflow 2.3 with pip, I needed to uninstall the tensorflow parts of the package tensorflow-gpu to avoid conistency warnings by pip. Conda would have uninstalled the whole package. I know [Conda does not recommend mixing pip with conda](https://www.anaconda.com/blog/using-pip-in-a-conda-environment) but this is the solution worked that worked and I am tired of spending another day with this issue.
```
conda create -n tfgpu python=3.7
conda activate tfgpu
conda install tensorflow-gpu=2.1
pip uninstall tensorflow
pip uninstall tensorflow-estimator
pip uninstall tensorboard
pip uninstall tensorboard-plugin-wit
pip install tensorflow==2.3
pip check
```
|
You will need to install cuDNN and the CUDA toolkit to use your GPU.
First check for the compatible version [here](https://www.tensorflow.org/install/source#gpu).
cuDNN can be found [here](https://developer.nvidia.com/cudnn) (requires free account).
CUDA toolkit can be found [here](https://developer.nvidia.com/cuda-toolkit-archive).
Again, check for a compatible version BEFORE installing. Newer versions are not backwards compatible.
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
The `tensorflow` build automatically selected by Anaconda on Windows 10 during the installation of `tensorflow-gpu` 2.3 seems to be faulty. Please find a workaround [here](https://github.com/ContinuumIO/anaconda-issues/issues/12194#issuecomment-751700156) (consider upvoting the GitHub answer if you have a GitHub account).
**Windows only:**
Python 3.7: `conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py37h936c3e2_0`
Python 3.8: `conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0`
|
I see that your GPU has **[compute capability 5.0](https://developer.nvidia.com/cuda-gpus)** which is OK, TensorFlow should like it. Thus I assume something went wrong during the environment setup. Please try creating a new environment using:
```
conda create --name tf_gpu tensorflow-gpu
```
Then install all other packages you want in ***tf\_gpu*** and try again.
P.S: it is really important that in the environment you have only one TensorFlow package (the gpu one). If you have more than one, there is no guarantee that
```
import tensorflow as tf
```
will import the one you want ...
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
You will need to install cuDNN and the CUDA toolkit to use your GPU.
First check for the compatible version [here](https://www.tensorflow.org/install/source#gpu).
cuDNN can be found [here](https://developer.nvidia.com/cudnn) (requires free account).
CUDA toolkit can be found [here](https://developer.nvidia.com/cuda-toolkit-archive).
Again, check for a compatible version BEFORE installing. Newer versions are not backwards compatible.
|
In my case (**In April 2022**):
```
conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0 cudatoolkit cudnn keras matplotlib
```
Works perfectly!! it installed tensorflow-gpu=2.3 - cudatoolkit 10.1.243 and cudnn 7.6.5
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
I also have been unable (yet) to get TF 2.3.0 to recognize my Nvidia Quadro Pro 620 GPU.
Note: I have 2 other 'environments' on this PC (windows Pro) All installed via Anaconda:
1. Python 3.7.8 TF 2.0.0... recognizes (and uses) the Nvidia GPU
2. Python 3.6.9 TF 2.1.0... recognizes (and uses) the Nvidia GPU
3. Python 3.8.6 TF 2.3.0... does NOT see the GPU
My Machine has Cuda 11.1; cuDNN 8.0.5
My next thought is to consider downgrading Python from 3.8.6 to 3.7.8 in the 3rd configuration where TF = 2.3.0
Steve
|
Using `conda` to install TensorFlow is always a better way to manage the multi versions of TensorFlow itself as well as CUDA and CUDNN. I recently create a new conda environment and prepare to install the newest TensorFlow too. I also encountered the issue you mentioned. I checked the dependency list from `conda install tensorflow-gpu` and found that the `cudatoolkit` and `cudnn` packages are missing. As the latest version of tensorflow-gpu at Anaconda is 2.3, I think the problem was already pointed out by @GZ0's answer at the GitHub issue.
Here I list the output below:
Using `conda install tensorflow=2.3`:
```
PS > conda install tensorflow-gpu=2.3
## Package Plan ##
environment location: C:\Anaconda3\envs\test_cuda_38
added / updated specs:
- tensorflow-gpu=2.3
The following packages will be downloaded:
package | build
---------------------------|-----------------
absl-py-0.12.0 | py38haa95532_0 176 KB
aiohttp-3.7.4 | py38h2bbff1b_1 513 KB
astunparse-1.6.3 | py_0 17 KB
async-timeout-3.0.1 | py38haa95532_0 14 KB
blas-1.0 | mkl 6 KB
blinker-1.4 | py38haa95532_0 23 KB
brotlipy-0.7.0 |py38h2bbff1b_1003 412 KB
cachetools-4.2.1 | pyhd3eb1b0_0 13 KB
cffi-1.14.5 | py38hcd4344a_0 224 KB
chardet-3.0.4 |py38haa95532_1003 194 KB
click-7.1.2 | pyhd3eb1b0_0 64 KB
coverage-5.5 | py38h2bbff1b_2 272 KB
cryptography-3.4.7 | py38h71e12ea_0 643 KB
cython-0.29.23 | py38hd77b12b_0 1.7 MB
gast-0.4.0 | py_0 15 KB
google-auth-1.29.0 | pyhd3eb1b0_0 76 KB
google-auth-oauthlib-0.4.4 | pyhd3eb1b0_0 18 KB
google-pasta-0.2.0 | py_0 46 KB
grpcio-1.36.1 | py38hc60d5dd_1 1.7 MB
h5py-2.10.0 | py38h5e291fa_0 841 KB
hdf5-1.10.4 | h7ebc959_0 7.9 MB
icc_rt-2019.0.0 | h0cc432a_1 6.0 MB
idna-2.10 | pyhd3eb1b0_0 52 KB
importlib-metadata-3.10.0 | py38haa95532_0 34 KB
intel-openmp-2021.2.0 | haa95532_616 1.8 MB
keras-applications-1.0.8 | py_1 29 KB
keras-preprocessing-1.1.2 | pyhd3eb1b0_0 35 KB
libprotobuf-3.14.0 | h23ce68f_0 1.9 MB
markdown-3.3.4 | py38haa95532_0 144 KB
mkl-2021.2.0 | haa95532_296 115.5 MB
mkl-service-2.3.0 | py38h2bbff1b_1 49 KB
mkl_fft-1.3.0 | py38h277e83a_2 137 KB
mkl_random-1.2.1 | py38hf11a4ad_2 223 KB
multidict-5.1.0 | py38h2bbff1b_2 61 KB
numpy-1.20.1 | py38h34a8a5c_0 23 KB
numpy-base-1.20.1 | py38haf7ebc8_0 4.2 MB
oauthlib-3.1.0 | py_0 91 KB
opt_einsum-3.1.0 | py_0 54 KB
protobuf-3.14.0 | py38hd77b12b_1 242 KB
pyasn1-0.4.8 | py_0 57 KB
pyasn1-modules-0.2.8 | py_0 72 KB
pycparser-2.20 | py_2 94 KB
pyjwt-1.7.1 | py38_0 48 KB
pyopenssl-20.0.1 | pyhd3eb1b0_1 49 KB
pyreadline-2.1 | py38_1 145 KB
pysocks-1.7.1 | py38haa95532_0 31 KB
requests-2.25.1 | pyhd3eb1b0_0 52 KB
requests-oauthlib-1.3.0 | py_0 23 KB
rsa-4.7.2 | pyhd3eb1b0_1 28 KB
scipy-1.6.2 | py38h66253e8_1 13.0 MB
tensorboard-plugin-wit-1.6.0| py_0 630 KB
tensorflow-2.3.0 |mkl_py38h8557ec7_0 6 KB
tensorflow-base-2.3.0 |eigen_py38h75a453f_0 49.5 MB
tensorflow-estimator-2.3.0 | pyheb71bc4_0 271 KB
termcolor-1.1.0 | py38haa95532_1 9 KB
typing-extensions-3.7.4.3 | hd3eb1b0_0 12 KB
typing_extensions-3.7.4.3 | pyh06a4308_0 28 KB
urllib3-1.26.4 | pyhd3eb1b0_0 105 KB
werkzeug-1.0.1 | pyhd3eb1b0_0 239 KB
win_inet_pton-1.1.0 | py38haa95532_0 35 KB
wrapt-1.12.1 | py38he774522_1 49 KB
yarl-1.6.3 | py38h2bbff1b_0 153 KB
------------------------------------------------------------
Total: 210.0 MB
```
Using `conda install tensorflow=2.1`:
```
PS > conda install tensorflow-gpu=2.1
## Package Plan ##
environment location: C:\Anaconda3\envs\test_cuda
added / updated specs:
- tensorflow-gpu=2.1
The following packages will be downloaded:
package | build
---------------------------|-----------------
_tflow_select-2.1.0 | gpu 3 KB
absl-py-0.12.0 | py37haa95532_0 175 KB
aiohttp-3.7.4 | py37h2bbff1b_1 507 KB
astor-0.8.1 | py37haa95532_0 47 KB
async-timeout-3.0.1 | py37haa95532_0 14 KB
blas-1.0 | mkl 6 KB
blinker-1.4 | py37haa95532_0 23 KB
brotlipy-0.7.0 |py37h2bbff1b_1003 337 KB
cachetools-4.2.1 | pyhd3eb1b0_0 13 KB
cffi-1.14.5 | py37hcd4344a_0 220 KB
chardet-3.0.4 |py37haa95532_1003 192 KB
click-7.1.2 | pyhd3eb1b0_0 64 KB
coverage-5.5 | py37h2bbff1b_2 273 KB
cryptography-3.4.7 | py37h71e12ea_0 641 KB
cudatoolkit-10.1.243 | h74a9793_0 300.3 MB
cudnn-7.6.5 | cuda10.1_0 179.1 MB
cython-0.29.23 | py37hd77b12b_0 1.7 MB
gast-0.2.2 | py37_0 155 KB
google-auth-1.29.0 | pyhd3eb1b0_0 76 KB
google-auth-oauthlib-0.4.4 | pyhd3eb1b0_0 18 KB
google-pasta-0.2.0 | py_0 46 KB
grpcio-1.36.1 | py37hc60d5dd_1 1.7 MB
h5py-2.10.0 | py37h5e291fa_0 808 KB
hdf5-1.10.4 | h7ebc959_0 7.9 MB
icc_rt-2019.0.0 | h0cc432a_1 6.0 MB
idna-2.10 | pyhd3eb1b0_0 52 KB
importlib-metadata-3.10.0 | py37haa95532_0 34 KB
intel-openmp-2021.2.0 | haa95532_616 1.8 MB
keras-applications-1.0.8 | py_1 29 KB
keras-preprocessing-1.1.2 | pyhd3eb1b0_0 35 KB
libprotobuf-3.14.0 | h23ce68f_0 1.9 MB
markdown-3.3.4 | py37haa95532_0 144 KB
mkl-2021.2.0 | haa95532_296 115.5 MB
mkl-service-2.3.0 | py37h2bbff1b_1 48 KB
mkl_fft-1.3.0 | py37h277e83a_2 133 KB
mkl_random-1.2.1 | py37hf11a4ad_2 214 KB
multidict-5.1.0 | py37h2bbff1b_2 85 KB
numpy-1.20.1 | py37h34a8a5c_0 23 KB
numpy-base-1.20.1 | py37haf7ebc8_0 4.1 MB
oauthlib-3.1.0 | py_0 91 KB
opt_einsum-3.1.0 | py_0 54 KB
protobuf-3.14.0 | py37hd77b12b_1 240 KB
pyasn1-0.4.8 | py_0 57 KB
pyasn1-modules-0.2.8 | py_0 72 KB
pycparser-2.20 | py_2 94 KB
pyjwt-1.7.1 | py37_0 49 KB
pyopenssl-20.0.1 | pyhd3eb1b0_1 49 KB
pyreadline-2.1 | py37_1 143 KB
pysocks-1.7.1 | py37_1 28 KB
requests-2.25.1 | pyhd3eb1b0_0 52 KB
requests-oauthlib-1.3.0 | py_0 23 KB
rsa-4.7.2 | pyhd3eb1b0_1 28 KB
scipy-1.6.2 | py37h66253e8_1 12.8 MB
six-1.15.0 | py37haa95532_0 51 KB
tensorboard-plugin-wit-1.6.0| py_0 630 KB
tensorflow-2.1.0 |gpu_py37h7db9008_0 4 KB
tensorflow-base-2.1.0 |gpu_py37h55f5790_0 105.3 MB
tensorflow-estimator-2.1.0 | pyhd54b08b_0 251 KB
tensorflow-gpu-2.1.0 | h0d30ee6_0 3 KB
termcolor-1.1.0 | py37haa95532_1 9 KB
typing-extensions-3.7.4.3 | hd3eb1b0_0 12 KB
typing_extensions-3.7.4.3 | pyh06a4308_0 28 KB
urllib3-1.26.4 | pyhd3eb1b0_0 105 KB
werkzeug-0.16.1 | py_0 258 KB
win_inet_pton-1.1.0 | py37haa95532_0 35 KB
wrapt-1.12.1 | py37he774522_1 49 KB
yarl-1.6.3 | py37h2bbff1b_0 151 KB
------------------------------------------------------------
Total: 745.0 MB
```
Therefore, you may install the latest version (v2.3) of tensorflow-gpu from Anaconda on Windows platform using the advises from @GZ0 and @geometrikal, or just using `conda install tensorflow-gpu=2.1` to get the newest and right environment.
Notice that tensorflow-gpu v2.1 only support Python between 3.5-3.7.
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
**August 2021** Conda install may be working now, as according to @ComputerScientist in the comments below, `conda install tensorflow-gpu==2.4.1` will give `cudatoolkit-10.1.243` and `cudnn-7.6.5`
**The following was written in Jan 2021 and is out of date**
Currently `conda install tensorflow-gpu` installs tensorflow v2.3.0 and does NOT install the conda cudnn or cudatoolkit packages. Installing them manually (e.g. with `conda install cudatoolkit=10.1`) does not seem to fix the problem either.
A solution is to install an earlier version of tensorflow, which does install cudnn and cudatoolkit, then upgrade with pip
```
conda install tensorflow-gpu=2.1
pip install tensorflow-gpu==2.3.1
```
(2.4.0 uses cuda 11.0 and cudnn 8.0, however cudnn 8.0 is not in anaconda as of 16/12/2020)
Edit: please also see @GZ0's answer, which links to a github discussion with a one-line solution
|
Updated April 26, 2022, tensorflow 2.6.0 does the job,
Python version 3.8.13
Recap - in Anaconda Jupyter, encountered the same "GPU no show" issue
'2.3.0'
Followed the procedure in this [link](https://medium.com/analytics-vidhya/solution-to-tensorflow-2-not-using-gpu-119fb3e04daa), again "GPU no show".
Trial and error: workaround below does the job.
1. Launch CMD window from Navigator (the same environment);
2. conda install tensorflow=2.6.0 –-channel conda-forge -y;
3. It will take some time (collecting package, resolving environment etc.);
4. In this case, automatically update CUDA and cuDNN versions to 11.3 and 8.2, respectively.
5. After it is done, exit Anaconda and restart the computer.
6. Return to Jupyter, run the cell:
[cell](https://i.stack.imgur.com/gzi1c.png)
and check result:
2.6.0
[PhysicalDevice(name='/physical\_device:CPU:0', device\_type='CPU'), PhysicalDevice(name='/physical\_device:GPU:0', device\_type='GPU')]
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
You will need to install cuDNN and the CUDA toolkit to use your GPU.
First check for the compatible version [here](https://www.tensorflow.org/install/source#gpu).
cuDNN can be found [here](https://developer.nvidia.com/cudnn) (requires free account).
CUDA toolkit can be found [here](https://developer.nvidia.com/cuda-toolkit-archive).
Again, check for a compatible version BEFORE installing. Newer versions are not backwards compatible.
|
As of August 2021, with TensorFlow 2.4.1, I believe it seems to install CUDA and CuDNN in a conda environment. Here's what I did to create a fresh conda env on an Ubuntu 18.04 machine:
```
conda create --name tftest python=3.7 -y && conda activate tftest
conda install ipython tensorflow-gpu==2.4.1 -y
```
The command above will list the following packages to be installed. For our purposes, *note how `cudatoolkit` and `cudnn` are listed*.
```
The following packages will be downloaded:
package | build
---------------------------|-----------------
_tflow_select-2.1.0 | gpu 2 KB
absl-py-0.13.0 | py37h06a4308_0 173 KB
aiohttp-3.7.4 | py37h27cfd23_1 536 KB
astor-0.8.1 | py37h06a4308_0 47 KB
astunparse-1.6.3 | py_0 17 KB
async-timeout-3.0.1 | py37h06a4308_0 13 KB
attrs-21.2.0 | pyhd3eb1b0_0 46 KB
backcall-0.2.0 | pyhd3eb1b0_0 13 KB
blas-1.0 | mkl 6 KB
blinker-1.4 | py37h06a4308_0 23 KB
brotlipy-0.7.0 |py37h27cfd23_1003 320 KB
c-ares-1.17.1 | h27cfd23_0 108 KB
cachetools-4.2.2 | pyhd3eb1b0_0 13 KB
cffi-1.14.6 | py37h400218f_0 223 KB
chardet-3.0.4 |py37h06a4308_1003 175 KB
charset-normalizer-2.0.4 | pyhd3eb1b0_0 35 KB
click-8.0.1 | pyhd3eb1b0_0 79 KB
coverage-5.5 | py37h27cfd23_2 254 KB
cryptography-3.4.7 | py37hd23ed53_0 904 KB
cudatoolkit-10.1.243 | h6bb024c_0 347.4 MB
cudnn-7.6.5 | cuda10.1_0 179.9 MB
cupti-10.1.168 | 0 1.4 MB
cython-0.29.24 | py37h295c915_0 1.9 MB
decorator-5.0.9 | pyhd3eb1b0_0 12 KB
gast-0.4.0 | pyhd3eb1b0_0 13 KB
google-auth-1.33.0 | pyhd3eb1b0_0 80 KB
google-auth-oauthlib-0.4.4 | pyhd3eb1b0_0 18 KB
google-pasta-0.2.0 | py_0 46 KB
grpcio-1.36.1 | py37h2157cd5_1 1.9 MB
h5py-2.10.0 | py37hd6299e0_1 902 KB
hdf5-1.10.6 | hb1b8bf9_0 3.7 MB
idna-3.2 | pyhd3eb1b0_0 48 KB
importlib-metadata-3.10.0 | py37h06a4308_0 33 KB
intel-openmp-2021.3.0 | h06a4308_3350 1.4 MB
ipython-7.26.0 | py37hb070fc8_0 1005 KB
ipython_genutils-0.2.0 | pyhd3eb1b0_1 27 KB
jedi-0.18.0 | py37h06a4308_1 911 KB
keras-preprocessing-1.1.2 | pyhd3eb1b0_0 35 KB
libgfortran-ng-7.5.0 | ha8ba4b0_17 22 KB
libgfortran4-7.5.0 | ha8ba4b0_17 995 KB
libprotobuf-3.17.2 | h4ff587b_1 2.0 MB
markdown-3.3.4 | py37h06a4308_0 127 KB
matplotlib-inline-0.1.2 | pyhd3eb1b0_2 12 KB
mkl-2021.3.0 | h06a4308_520 141.2 MB
mkl-service-2.4.0 | py37h7f8727e_0 56 KB
mkl_fft-1.3.0 | py37h42c9631_2 170 KB
mkl_random-1.2.2 | py37h51133e4_0 287 KB
multidict-5.1.0 | py37h27cfd23_2 66 KB
numpy-1.20.3 | py37hf144106_0 23 KB
numpy-base-1.20.3 | py37h74d4b33_0 4.5 MB
oauthlib-3.1.1 | pyhd3eb1b0_0 90 KB
opt_einsum-3.3.0 | pyhd3eb1b0_1 57 KB
parso-0.8.2 | pyhd3eb1b0_0 69 KB
pexpect-4.8.0 | pyhd3eb1b0_3 53 KB
pickleshare-0.7.5 | pyhd3eb1b0_1003 13 KB
prompt-toolkit-3.0.17 | pyh06a4308_0 256 KB
protobuf-3.17.2 | py37h295c915_0 319 KB
ptyprocess-0.7.0 | pyhd3eb1b0_2 17 KB
pyasn1-0.4.8 | py_0 57 KB
pyasn1-modules-0.2.8 | py_0 72 KB
pygments-2.10.0 | pyhd3eb1b0_0 725 KB
pyjwt-2.1.0 | py37h06a4308_0 32 KB
pyopenssl-20.0.1 | pyhd3eb1b0_1 49 KB
pysocks-1.7.1 | py37_1 27 KB
python-flatbuffers-1.12 | pyhd3eb1b0_0 24 KB
requests-2.26.0 | pyhd3eb1b0_0 59 KB
requests-oauthlib-1.3.0 | py_0 23 KB
rsa-4.7.2 | pyhd3eb1b0_1 28 KB
scipy-1.6.2 | py37had2a1c9_1 15.5 MB
six-1.16.0 | pyhd3eb1b0_0 18 KB
tensorboard-2.4.0 | pyhc547734_0 8.8 MB
tensorboard-plugin-wit-1.6.0| py_0 630 KB
tensorflow-2.4.1 |gpu_py37ha2e99fa_0 4 KB
tensorflow-base-2.4.1 |gpu_py37h29c2da4_0 195.2 MB
tensorflow-estimator-2.5.0 | pyh7b7c402_0 267 KB
tensorflow-gpu-2.4.1 | h30adc30_0 3 KB
termcolor-1.1.0 | py37h06a4308_1 9 KB
traitlets-5.0.5 | pyhd3eb1b0_0 81 KB
typing-extensions-3.10.0.0 | hd3eb1b0_0 8 KB
typing_extensions-3.10.0.0 | pyh06a4308_0 27 KB
urllib3-1.26.6 | pyhd3eb1b0_1 112 KB
wcwidth-0.2.5 | py_0 29 KB
werkzeug-1.0.1 | pyhd3eb1b0_0 239 KB
wrapt-1.12.1 | py37h7b6447c_1 49 KB
yarl-1.6.3 | py37h27cfd23_0 133 KB
zipp-3.5.0 | pyhd3eb1b0_0 13 KB
------------------------------------------------------------
Total: 915.9 MB
```
Next, run `ipython` and try:
```
In [1]: import tensorflow as tf
2021-08-29 12:26:36.582384: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.10.1
In [2]: tf.config.list_physical_devices('GPU')
2021-08-29 12:26:48.676151: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2021-08-29 12:26:48.679894: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcuda.so.1
2021-08-29 12:26:48.975002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 0 with properties:
pciBusID: 0000:04:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.979341: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 1 with properties:
pciBusID: 0000:08:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.981747: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 2 with properties:
pciBusID: 0000:09:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.990002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 3 with properties:
pciBusID: 0000:85:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.992488: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 4 with properties:
pciBusID: 0000:89:00.0 name: Tesla V100-PCIE-32GB computeCapability: 7.0
coreClock: 1.38GHz coreCount: 80 deviceMemorySize: 31.75GiB deviceMemoryBandwidth: 836.37GiB/s
2021-08-29 12:26:48.992523: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.10.1
2021-08-29 12:26:49.312793: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.10
2021-08-29 12:26:49.312907: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.10
2021-08-29 12:26:49.388961: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10
2021-08-29 12:26:49.413946: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10
2021-08-29 12:26:49.535055: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.10
2021-08-29 12:26:49.563142: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.10
2021-08-29 12:26:50.009291: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.7
2021-08-29 12:26:50.051301: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1862] Adding visible gpu devices: 0, 1, 2, 3, 4
Out[2]:
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:1', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:2', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:3', device_type='GPU'),
PhysicalDevice(name='/physical_device:GPU:4', device_type='GPU')]
In [3]: tf.test.is_built_with_cuda()
Out[3]: True
```
This machine has 5 GPUs, so the above output is correct.
What I'm not actually sure about is why CUDA 10.1 and CuDNN 7.6.5 are installed, since it seems like [from Google's TF compatibility chart](https://www.tensorflow.org/install/source#gpu) that 2.4.0 (and presumably 2.4.1?) work with CUDA 11.0 and CuDNN 8. If anyone has insights on that, feel free to chime in...
|
65,273,118
|
I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I went for the `conda install -c anaconda tensorflow-gpu` as written in their official website here: <https://anaconda.org/anaconda/tensorflow-gpu> .
However even after installing the gpu version in a fresh virtual environment (to avoid potential conflicts with pip installed libraries in the base env), tensorflow doesn't seem to even recognize my GPU for some mysterious reason.
Some of the code snippets I ran(in anaconda prompt) to understand that it wasn't recognizing my GPU:-
1.
```
>>>from tensorflow.python.client import device_lib
>>>print(device_lib.list_local_devices())
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 7692219132769779763
]
```
As you can see it completely ignores the GPU.
2.
```
>>>tf.debugging.set_log_device_placement(True)
>>>a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
2020-12-13 10:11:30.902956: I tensorflow/core/platform/cpu_feature_guard.cc:142] This
TensorFlow
binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU
instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
>>>b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
>>>c = tf.matmul(a, b)
>>>print(c)
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)
```
Here, it was supposed to indicate that it ran with a GPU by showing `Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0` (as written here: <https://www.tensorflow.org/guide/gpu>) but nothing like that is present. Also I am not sure what the message after the 2nd line means.
I have also searched for several solutions online including here but almost all of the issues are related to the first manual installation method which I haven't tried yet since everyone recommended this approach.
I don't use cmd anymore since the environment variables somehow got messed up after uninstalling tensorflow-cpu from the base env and on re-installing, it worked perfectly with anaconda prompt but not cmd. This is a separate issue (and widespread also) but I mentioned it in case that has a role to play here. I installed the gpu version in a fresh virtual environment to ensure a clean installation and as far as I understand path variables need to be set up only for manual installation of CUDA and cuDNN libraries.
The card which I use:-(which is CUDA enabled)
```
C:\WINDOWS\system32>wmic path win32_VideoController get name
Name
NVIDIA GeForce 940MX
Intel(R) HD Graphics 620
```
Tensorflow and python version I am using currently:-
```
>>> import tensorflow as tf
>>> tf.__version__
'2.3.0'
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
```
System information: Windows 10 Home, 64-bit operating system, x64-based processor.
Any help would be really appreciated. Thanks in advance.
|
2020/12/13
|
[
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] |
The `tensorflow` build automatically selected by Anaconda on Windows 10 during the installation of `tensorflow-gpu` 2.3 seems to be faulty. Please find a workaround [here](https://github.com/ContinuumIO/anaconda-issues/issues/12194#issuecomment-751700156) (consider upvoting the GitHub answer if you have a GitHub account).
**Windows only:**
Python 3.7: `conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py37h936c3e2_0`
Python 3.8: `conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0`
|
**Following Steps worked for me:**
Do the same as in the video.
<https://www.youtube.com/watch?v=r31jnE7pR-g>
Also install tensorflow estimator which is missing in the video. In picture you can see my environment which is working for me.
[my environment](https://i.stack.imgur.com/dpggv.png)
Maybe you have to change the versions to the same ones.
Now go in Visual Code and run your code with the anaconda environment you created before. See picture below.
[select your environment](https://i.stack.imgur.com/WjPSk.png)
In my case it it tf\_env, what i created and named.
Try to run your code. If Visual Code says something is missing try to install it with the anaconda terminal. Click the "play"-Button to start the terminal.
[play Button terminal](https://i.stack.imgur.com/fjruh.png)
Also close and open Visual Code when you do changes, sometimes anaconda too. Now try this code below.
```
> print("Num GPU: ", len(tf.config.list_physical_devices("GPU")))
>
> print(tf.test.is_gpu_available()) print(tf.test.is_built_with_cuda())
> OUTPUT
> Num GPU: 1
> WARNING:tensorflow:From <ipython-input-2-8748de971110>:3:
> is_gpu_available (from tensorflow.python.framework.test_util) is
> deprecated and will be removed in a future version. Instructions for
> updating: Use `tf.config.list_physical_devices('GPU')` instead.
> True
> True
```
If your output is the same, everything went fine. Now when you train a model you should see your gpu running in your task manager.
Hopefully it helps you guys :)
|
74,365,103
|
I have a small code created in python and from an api I would like to go through all the
`code = url.json()["data"][0]["name"]`
But I do not know how to do it
this is my little code:
```
import requests
swf = input("write: ")
url = requests.get(f"https://apihabbo.com/api/furnis?hotel=es&name={swf}")
code = url.json()["data"][0]["name"]
print(code)
```
Can someone help me, thank you very much in advance!
this is the url:
<https://apihabbo.com/api/furnis?hotel=es&name=ducha>
I have tried with this code, but no success
```
response = requests.get("https://apihabbo.com/api/furnis?hotel=es&name=Gorro%20con%20Pomp%C3%B3n")
data = response.json()
for i in data['data'][0]['code']:
print("{}".format(i['code']))
```
|
2022/11/08
|
[
"https://Stackoverflow.com/questions/74365103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452313/"
] |
`data['data'][0]['code']` is not a list. The list is `data['data']`, you need to loop over that.
```
for d in data['data']:
print(d['code'])
```
|
You have to iterate through the list of received data points.
```
response = requests.get("https://apihabbo.com/api/furnis?hotel=es&name=Gorro%20con%20Pomp%C3%B3n")
data = response.json()
for i in data['data']:
print("{}".format(i['code']))
```
|
61,235,115
|
**Mac OS**: when I try to run anything involving pip, I get
```
-bash: pip: command not found
```
This happened after I accidentally deleted the pip Unix file in `usr/local/bin` while trying to solve a different problem with pip. At this point, I've pretty much given up on solving the problem manually.
>
> Is there a way to just completely uninstall python and pip and start all over again?
>
>
>
|
2020/04/15
|
[
"https://Stackoverflow.com/questions/61235115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13322285/"
] |
In recent python versions pip is as module rather than as individual script. Try:
```
python -m pip
```
|
solution was surprisingly simple: deleted everything python related from my computer:
1. deleted `Python` App in `Applications` Folder
2. deleted all python and pip related files in `usr/local/bin`
3. deleted the `Python.framework` folder in `Libraray/Frameworks`
4. searched for and deleted all folders named `python`
Then I reinstalled Python via the official python page. Pip seems to work now.
|
11,616,003
|
I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts directly to /usr/bin, so I write
```
sudo /usr/bin/pip-2.6 install --install-option="--install-scripts=/usr/bin" virtualenv
```
But again it responds with
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Adding --upgrade doesn't help.
How can I install virtualenv scripts to /usr/bin ?
|
2012/07/23
|
[
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] |
Starting with iOS 6, you MUST set the audio session category to 'playback' before creating the UIWebView. This is all you have to do. It is not necessary to make the session active.
This should be used for html video as well, because if you don't configure the session, your video will be muted when the ringer switch is off.
```
#import <AVFoundation/AVFoundation.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
BOOL ok;
NSError *setCategoryError = nil;
ok = [audioSession setCategory:AVAudioSessionCategoryPlayback
error:&setCategoryError];
if (!ok) {
NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
}
```
Ensure that your target links to the AVFoundation framework.
---
If using Cordova, the file you need to modify is `platforms/ios/MyApp/Classes/AppDelegate.m`, and will end up looking like this:
```
#import "AppDelegate.h"
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
BOOL ok;
NSError *setCategoryError = nil;
ok = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!ok) {
NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
}
self.viewController = [[MainViewController alloc] init];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
```
Also, as mentioned in the comments, you need to link the AVFoundation Framework, as explained in [this answer](https://stackoverflow.com/questions/19337890/how-to-add-an-existing-framework-in-xcode-5/19337932#19337932):
* Open your project with xcode `open ./platforms/ios/MyApp.xcworkspace/`
* Project navigator > target My App > General
* Scroll to the bottom to find Linked Frameworks and Libraries
|
This plugin will make your app ignore the mute switch. It's basically the same code that's in the other answers but it's nicely wrapped into a plugin so that you don't have to do any manual objective c edits.
<https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio>
Run this command to add it to your project:
```
cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio.git
```
|
11,616,003
|
I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts directly to /usr/bin, so I write
```
sudo /usr/bin/pip-2.6 install --install-option="--install-scripts=/usr/bin" virtualenv
```
But again it responds with
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Adding --upgrade doesn't help.
How can I install virtualenv scripts to /usr/bin ?
|
2012/07/23
|
[
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] |
Starting with iOS 6, you MUST set the audio session category to 'playback' before creating the UIWebView. This is all you have to do. It is not necessary to make the session active.
This should be used for html video as well, because if you don't configure the session, your video will be muted when the ringer switch is off.
```
#import <AVFoundation/AVFoundation.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
BOOL ok;
NSError *setCategoryError = nil;
ok = [audioSession setCategory:AVAudioSessionCategoryPlayback
error:&setCategoryError];
if (!ok) {
NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
}
```
Ensure that your target links to the AVFoundation framework.
---
If using Cordova, the file you need to modify is `platforms/ios/MyApp/Classes/AppDelegate.m`, and will end up looking like this:
```
#import "AppDelegate.h"
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
BOOL ok;
NSError *setCategoryError = nil;
ok = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!ok) {
NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
}
self.viewController = [[MainViewController alloc] init];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
```
Also, as mentioned in the comments, you need to link the AVFoundation Framework, as explained in [this answer](https://stackoverflow.com/questions/19337890/how-to-add-an-existing-framework-in-xcode-5/19337932#19337932):
* Open your project with xcode `open ./platforms/ios/MyApp.xcworkspace/`
* Project navigator > target My App > General
* Scroll to the bottom to find Linked Frameworks and Libraries
|
Swift Syntax:
in AppDelegate:
```
import AVFoundation
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
do{
let audio = AVAudioSession.sharedInstance()
try audio.setCategory(AVAudioSession.Category.playback)
}catch let error as NSError{
print(error)
}
}
```
|
11,616,003
|
I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts directly to /usr/bin, so I write
```
sudo /usr/bin/pip-2.6 install --install-option="--install-scripts=/usr/bin" virtualenv
```
But again it responds with
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Adding --upgrade doesn't help.
How can I install virtualenv scripts to /usr/bin ?
|
2012/07/23
|
[
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] |
Starting with iOS 6, you MUST set the audio session category to 'playback' before creating the UIWebView. This is all you have to do. It is not necessary to make the session active.
This should be used for html video as well, because if you don't configure the session, your video will be muted when the ringer switch is off.
```
#import <AVFoundation/AVFoundation.h>
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
BOOL ok;
NSError *setCategoryError = nil;
ok = [audioSession setCategory:AVAudioSessionCategoryPlayback
error:&setCategoryError];
if (!ok) {
NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
}
```
Ensure that your target links to the AVFoundation framework.
---
If using Cordova, the file you need to modify is `platforms/ios/MyApp/Classes/AppDelegate.m`, and will end up looking like this:
```
#import "AppDelegate.h"
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
BOOL ok;
NSError *setCategoryError = nil;
ok = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
if (!ok) {
NSLog(@"%s setCategoryError=%@", __PRETTY_FUNCTION__, setCategoryError);
}
self.viewController = [[MainViewController alloc] init];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
```
Also, as mentioned in the comments, you need to link the AVFoundation Framework, as explained in [this answer](https://stackoverflow.com/questions/19337890/how-to-add-an-existing-framework-in-xcode-5/19337932#19337932):
* Open your project with xcode `open ./platforms/ios/MyApp.xcworkspace/`
* Project navigator > target My App > General
* Scroll to the bottom to find Linked Frameworks and Libraries
|
Here the SWIFT 2.0 version to set the audio session category to 'playback' before creating the UIWebView.
```
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch let error as NSError {
print(error)
}
do {
try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError {
print(error)
}
```
|
11,616,003
|
I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts directly to /usr/bin, so I write
```
sudo /usr/bin/pip-2.6 install --install-option="--install-scripts=/usr/bin" virtualenv
```
But again it responds with
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Adding --upgrade doesn't help.
How can I install virtualenv scripts to /usr/bin ?
|
2012/07/23
|
[
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] |
Swift Syntax:
in AppDelegate:
```
import AVFoundation
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
do{
let audio = AVAudioSession.sharedInstance()
try audio.setCategory(AVAudioSession.Category.playback)
}catch let error as NSError{
print(error)
}
}
```
|
This plugin will make your app ignore the mute switch. It's basically the same code that's in the other answers but it's nicely wrapped into a plugin so that you don't have to do any manual objective c edits.
<https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio>
Run this command to add it to your project:
```
cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio.git
```
|
11,616,003
|
I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts directly to /usr/bin, so I write
```
sudo /usr/bin/pip-2.6 install --install-option="--install-scripts=/usr/bin" virtualenv
```
But again it responds with
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Adding --upgrade doesn't help.
How can I install virtualenv scripts to /usr/bin ?
|
2012/07/23
|
[
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] |
This plugin will make your app ignore the mute switch. It's basically the same code that's in the other answers but it's nicely wrapped into a plugin so that you don't have to do any manual objective c edits.
<https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio>
Run this command to add it to your project:
```
cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio.git
```
|
Here the SWIFT 2.0 version to set the audio session category to 'playback' before creating the UIWebView.
```
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch let error as NSError {
print(error)
}
do {
try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError {
print(error)
}
```
|
11,616,003
|
I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts directly to /usr/bin, so I write
```
sudo /usr/bin/pip-2.6 install --install-option="--install-scripts=/usr/bin" virtualenv
```
But again it responds with
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Adding --upgrade doesn't help.
How can I install virtualenv scripts to /usr/bin ?
|
2012/07/23
|
[
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] |
Swift Syntax:
in AppDelegate:
```
import AVFoundation
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
do{
let audio = AVAudioSession.sharedInstance()
try audio.setCategory(AVAudioSession.Category.playback)
}catch let error as NSError{
print(error)
}
}
```
|
Here the SWIFT 2.0 version to set the audio session category to 'playback' before creating the UIWebView.
```
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}
catch let error as NSError {
print(error)
}
do {
try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError {
print(error)
}
```
|
15,616,139
|
I am python beginner struggling to create and save a list containing tuples from csv file in python.
The code I got for now is:
```
def load_file(filename):
fp = open(filename, 'Ur')
data_list = []
for line in fp:
data_list.append(line.strip().split(','))
fp.close()
return data_list
```
and then I would like to save the file
```
def save_file(filename, data_list):
fp = open(filename, 'w')
for line in data_list:
fp.write(','.join(line) + '\n')
fp.close()
```
Unfortunately, my code returns a list of lists, not a list of tuples... Is there a way to create one list containing multiple tuples without using csv module?
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15616139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2207588/"
] |
`split` returns a list, if you want a tuple, convert it to a tuple:
```
data_list.append(tuple(line.strip().split(',')))
```
Please use the `csv` module.
|
First question: why is a list of lists bad? In the sense of "duck-typing", this should be fine, so maybe you think about it again.
If you really need a list of tuples - only small changes are needed.
Change the line
```
data_list.append(line.strip().split(','))
```
to
```
data_list.append(tuple(line.strip().split(',')))
```
That's it.
If you ever want to get rid of custom code (less code is better code), you could stick to the [csv](http://docs.python.org/2/library/csv.html)-module. I'd strongly recommend using as many library methods as possible.
To show-off some advanced Python features: your `load_file`-method could also look like:
```
def load_file(filename):
with open(filename, 'Ur') as fp:
data_list = [tuple(line.strip().split(",") for line in fp]
```
I use a list comprehension here, it's very concise and easy to understand.
Additionally, I use the `with`-statement, which will close your file pointer, even if an exception occurred within your code. Please always use `with` when working with external resources, like files.
|
15,616,139
|
I am python beginner struggling to create and save a list containing tuples from csv file in python.
The code I got for now is:
```
def load_file(filename):
fp = open(filename, 'Ur')
data_list = []
for line in fp:
data_list.append(line.strip().split(','))
fp.close()
return data_list
```
and then I would like to save the file
```
def save_file(filename, data_list):
fp = open(filename, 'w')
for line in data_list:
fp.write(','.join(line) + '\n')
fp.close()
```
Unfortunately, my code returns a list of lists, not a list of tuples... Is there a way to create one list containing multiple tuples without using csv module?
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15616139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2207588/"
] |
`split` returns a list, if you want a tuple, convert it to a tuple:
```
data_list.append(tuple(line.strip().split(',')))
```
Please use the `csv` module.
|
Just wrap "tuple()" around the `line.strip().split(',')` and you'll get a list of tuples. You can see it in action in [this runnable gist](https://www.pythonanywhere.com/gists/5237115/load_tuples.py/ipython2/?affiliate_id=000003ec).
|
15,616,139
|
I am python beginner struggling to create and save a list containing tuples from csv file in python.
The code I got for now is:
```
def load_file(filename):
fp = open(filename, 'Ur')
data_list = []
for line in fp:
data_list.append(line.strip().split(','))
fp.close()
return data_list
```
and then I would like to save the file
```
def save_file(filename, data_list):
fp = open(filename, 'w')
for line in data_list:
fp.write(','.join(line) + '\n')
fp.close()
```
Unfortunately, my code returns a list of lists, not a list of tuples... Is there a way to create one list containing multiple tuples without using csv module?
|
2013/03/25
|
[
"https://Stackoverflow.com/questions/15616139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2207588/"
] |
First question: why is a list of lists bad? In the sense of "duck-typing", this should be fine, so maybe you think about it again.
If you really need a list of tuples - only small changes are needed.
Change the line
```
data_list.append(line.strip().split(','))
```
to
```
data_list.append(tuple(line.strip().split(',')))
```
That's it.
If you ever want to get rid of custom code (less code is better code), you could stick to the [csv](http://docs.python.org/2/library/csv.html)-module. I'd strongly recommend using as many library methods as possible.
To show-off some advanced Python features: your `load_file`-method could also look like:
```
def load_file(filename):
with open(filename, 'Ur') as fp:
data_list = [tuple(line.strip().split(",") for line in fp]
```
I use a list comprehension here, it's very concise and easy to understand.
Additionally, I use the `with`-statement, which will close your file pointer, even if an exception occurred within your code. Please always use `with` when working with external resources, like files.
|
Just wrap "tuple()" around the `line.strip().split(',')` and you'll get a list of tuples. You can see it in action in [this runnable gist](https://www.pythonanywhere.com/gists/5237115/load_tuples.py/ipython2/?affiliate_id=000003ec).
|
21,352,457
|
I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
`livestreamer.exe twitch.tv/streamer best`
And here is my python code so far:
```
import os
streamer=input("Streamer (full name): ")
quality=input("""Quality:
Best
High
Medium
Low
Mobile
: """).lower()
os.chdir("C:\Program Files (x86)\Livestreamer")
os.startfile("livestreamer.exe twitch.tv "+streamer+" "+quality)
```
I understand that the code is looking for a file not named livestreamer.exe (FileNotFoundError), but one with all the other code put in. Does anyone know how to launch the program with the arguments built in? Thanks.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21352457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925095/"
] |
```
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
arr.inject([]) do |hash, (v1, v2)|
hash << { category: v1, item: v2 }
end
```
I used [`inject`](http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-inject) to keep the code concise.
Next time you may want to show what you have tried in the question, just to demonstrate that you actually tried to do something before asking for code.
|
```
hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}
```
|
21,352,457
|
I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
`livestreamer.exe twitch.tv/streamer best`
And here is my python code so far:
```
import os
streamer=input("Streamer (full name): ")
quality=input("""Quality:
Best
High
Medium
Low
Mobile
: """).lower()
os.chdir("C:\Program Files (x86)\Livestreamer")
os.startfile("livestreamer.exe twitch.tv "+streamer+" "+quality)
```
I understand that the code is looking for a file not named livestreamer.exe (FileNotFoundError), but one with all the other code put in. Does anyone know how to launch the program with the arguments built in? Thanks.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21352457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925095/"
] |
Use [`Array#map`](http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-map):
```
arr = [["food", "eggs"], ["beverage", "milk"], ["desert", "cake"]]
arr.map { |category, item| { category: category, item: item } }
# => [
# {:category=>"food", :item=>"eggs"},
# {:category=>"beverage", :item=>"milk"},
# {:category=>"desert", :item=>"cake"}
# ]
```
|
```
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
arr.inject([]) do |hash, (v1, v2)|
hash << { category: v1, item: v2 }
end
```
I used [`inject`](http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-inject) to keep the code concise.
Next time you may want to show what you have tried in the question, just to demonstrate that you actually tried to do something before asking for code.
|
21,352,457
|
I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
`livestreamer.exe twitch.tv/streamer best`
And here is my python code so far:
```
import os
streamer=input("Streamer (full name): ")
quality=input("""Quality:
Best
High
Medium
Low
Mobile
: """).lower()
os.chdir("C:\Program Files (x86)\Livestreamer")
os.startfile("livestreamer.exe twitch.tv "+streamer+" "+quality)
```
I understand that the code is looking for a file not named livestreamer.exe (FileNotFoundError), but one with all the other code put in. Does anyone know how to launch the program with the arguments built in? Thanks.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21352457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925095/"
] |
```
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
arr.inject([]) do |hash, (v1, v2)|
hash << { category: v1, item: v2 }
end
```
I used [`inject`](http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-inject) to keep the code concise.
Next time you may want to show what you have tried in the question, just to demonstrate that you actually tried to do something before asking for code.
|
```
hash = array.map {|ary| Hash[[:category, :item].zip ary ]}
```
|
21,352,457
|
I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
`livestreamer.exe twitch.tv/streamer best`
And here is my python code so far:
```
import os
streamer=input("Streamer (full name): ")
quality=input("""Quality:
Best
High
Medium
Low
Mobile
: """).lower()
os.chdir("C:\Program Files (x86)\Livestreamer")
os.startfile("livestreamer.exe twitch.tv "+streamer+" "+quality)
```
I understand that the code is looking for a file not named livestreamer.exe (FileNotFoundError), but one with all the other code put in. Does anyone know how to launch the program with the arguments built in? Thanks.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21352457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925095/"
] |
Use [`Array#map`](http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-map):
```
arr = [["food", "eggs"], ["beverage", "milk"], ["desert", "cake"]]
arr.map { |category, item| { category: category, item: item } }
# => [
# {:category=>"food", :item=>"eggs"},
# {:category=>"beverage", :item=>"milk"},
# {:category=>"desert", :item=>"cake"}
# ]
```
|
```
hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}
```
|
21,352,457
|
I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
`livestreamer.exe twitch.tv/streamer best`
And here is my python code so far:
```
import os
streamer=input("Streamer (full name): ")
quality=input("""Quality:
Best
High
Medium
Low
Mobile
: """).lower()
os.chdir("C:\Program Files (x86)\Livestreamer")
os.startfile("livestreamer.exe twitch.tv "+streamer+" "+quality)
```
I understand that the code is looking for a file not named livestreamer.exe (FileNotFoundError), but one with all the other code put in. Does anyone know how to launch the program with the arguments built in? Thanks.
|
2014/01/25
|
[
"https://Stackoverflow.com/questions/21352457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925095/"
] |
Use [`Array#map`](http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-map):
```
arr = [["food", "eggs"], ["beverage", "milk"], ["desert", "cake"]]
arr.map { |category, item| { category: category, item: item } }
# => [
# {:category=>"food", :item=>"eggs"},
# {:category=>"beverage", :item=>"milk"},
# {:category=>"desert", :item=>"cake"}
# ]
```
|
```
hash = array.map {|ary| Hash[[:category, :item].zip ary ]}
```
|
47,810,110
|
I have a text file which has 30 multiple choice questions in the following pattern
1. question one goes here ?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
and so on to 30
Number of options is variable; there are minimum two and maximum six options.
I want to practice these questions in a interface like html/php quiz which allows me to select options and at last displays the result.
I tried reading the file in python and then tried to store questions and answers in separate lists but it did not work.
Below is my code:
```
#to prevent IndexError
question = ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','']
answers = ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','']
qOrA = "q"
mcq_file = "mcqs.txt"
mcq = open(mcq_file, "r")
data_list = mcq.readlines()
for i in range(len(data_list)):
element = list(data_list[i])
if element[0] == "A" and element[1] == ".":
qOrA = "a"
if qOrA == "q":
question[i] = question[i]+ " " + data_list[i]
elif qOrA == "a":
answers[i] = answers[i]+ " " + data_list[i]
```
mcq.readlines() output upto question no. 3 is given below
Note: Actually there are multiple line breaks so the file is not properly structured.
```
['\n', '1.\n', '\n', ' \n', '\n', 'Which computer component contains all the \n', '\n', 'circuitry necessary for all components or \n', '\n', 'devices to communicate with each other?\n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', 'A. Motherboard\n', '\n', ' \n', '\n', ' \n', '\n', 'B. Hard Drive\n', '\n', ' \n', '\n', ' \n', '\n', 'C. Expansion Bus\n', '\n', ' \n', '\n', ' \n', '\n', 'D. Adapter Card\n', '\n', ' \n', '\n', ' \n', '\n', '\n', '\n', '\n', '2. \n', '\n', 'Which case type is typically \n', '\n', 'used for servers?\n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', 'A.\n', '\n', ' \n', '\n', ' \n', '\n', 'Mini Tower\n', '\n', ' \n', '\n', ' \n', '\n', 'B.\n', '\n', ' \n', '\n', ' \n', '\n', 'Mid Tower\n', '\n', ' \n', '\n', ' \n', '\n', 'C.\n', '\n', ' \n', '\n', ' \n', '\n', 'Full Tower\n', '\n', ' \n', '\n', ' \n', '\n', 'D.\n', '\n', ' \n', '\n', ' \n', '\n', 'desktop\n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', '\n', '\n', '\n', '3.\n', '\n', ' \n', '\n', 'What is the most reliable way for users to buy the \n', '\n', 'correct RAM to upgrade a computer?\n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', 'A.\n', '\n', ' \n', '\n', ' \n', '\n', 'Buy RAM that is the same color as the memory sockets \n', '\n', 'on the motherboard.\n', '\n', ' \n', '\n', ' \n', '\n', 'B.\n', '\n', ' \n', '\n', ' \n', '\n', 'Ensure that the RAM chip is the same size as the ROM chip.\n', '\n', ' \n', '\n', ' \n', '\n', 'C.\n', '\n', ' \n', '\n', ' \n', '\n', 'Ensure that the RAM is \n', '\n', 'compatible\n', '\n', ' \n', '\n', 'with the peripherals \n', '\n', 'installed on the motherboard.\n', '\n', ' \n', '\n', ' \n', '\n', 'D.\n', '\n', ' \n', '\n', ' \n', '\n', 'Check the motherboard manual or manufacturer’s website.\n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', ' \n', '\n', '\n', '\n', '\n']
```
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47810110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3986321/"
] |
You just need to change your JS to:
```
$(document).ready(function(){
$('section').mouseenter(function(){
var id = $(this).attr('id');
$('a').removeClass('colorAdded');
$("a[href='#"+id+"']").addClass('colorAdded');
});
});
```
It was an issue with not including quotations in selecting the `a` tag with the `href` targeting.
|
I'm actually don't know why your codepen example is not working, I didn't look into your code carefully, but I tried to create simple code like bellow and it worked.
the thing you probably should care about is how you import JQuery into your page.
`<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>`
hopefully this following codes can help you.
```js
$(document).ready(function(){
$('button').mouseenter( function() {
console.log('hahaha');
})
});
```
```html
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="test">
<button class="test-button" > test button </button>
</div>
</body>
</html>
```
|
17,957,651
|
For those who need to know, I'm running a 64 bit Ubuntu 12.04, and trying to run the problematic script using a pip-installed python3.2
For a project I was writing I wanted to display an image in a tkinter window. To do this I installed Pillow via pip and installed tkinter for python 3 like so:
```
pip-3.2 install pillow #install stuff here
sudo apt-get install python3-tk
```
I then tried to run the following script
```
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
i = Image.open(<path_to_file>)
p = ImaageTk.PhotoImage(i)
```
There's more, but that block throws the errors. Anyways, when I try and run this I get the following error output
```
/usr/bin/python3.2 "/home/anish/PycharmProjects/Picture Renamer/default/Main.py"
Traceback (most recent call last):
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 184, in paste
tk.call("PyImagingPhoto", self.__photo, block.id)
_tkinter.TclError: invalid command name "PyImagingPhoto"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 26, in <module>
n = Main("/home/anish/Desktop/Images/")
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 11, in __init__
self.PictureList = self.MakeImageList(self.dir)
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 21, in MakeImageList
tkim = ImageTk.PhotoImage(temp_im)
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 123, in __init__
self.paste(image)
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 188, in paste
from PIL import _imagingtk
ImportError: cannot import name _imagingtk
Process finished with exit code 1
```
No amount of googling has given me a solution- the topics I find concerning this usually say to reinstall tkinter and/or pillow.
Here are the contents of my /usr/lib/python3.2/tkinter/
```
['dialog.py', 'scrolledtext.py', 'simpledialog.py', 'tix.py', 'dnd.py', 'ttk.py', '__main__.py', '_fix.py', 'font.py', '__pycache__', 'messagebox.py', '__init__.py', 'commondialog.py', 'constants.py', 'colorchooser.py', 'filedialog.py']
```
And here are the [many] files within my /usr/local/lib/python3.2/dist-packages/PIL/
```
['OleFileIO.py', 'ImageFileIO.py', 'ImageCms.py', 'GimpGradientFile.py', 'PSDraw.py', 'ImageDraw2.py', 'GimpPaletteFile.py', 'TiffImagePlugin.py', 'ImageChops.py', 'ImageShow.py', 'ImageStat.py', 'FliImagePlugin.py', 'ImageColor.py', 'XpmImagePlugin.py', 'ImageOps.py', 'ExifTags.py', 'FpxImagePlugin.py', 'PngImagePlugin.py', 'ImageFile.py', 'WalImageFile.py', 'PixarImagePlugin.py', 'PsdImagePlugin.py', '_util.py', 'ImageDraw.py', 'GribStubImagePlugin.py', 'ContainerIO.py', 'CurImagePlugin.py', 'JpegPresets.py', '_imagingft.cpython-32mu.so', '_imagingmath.cpython-32mu.so', 'PpmImagePlugin.py', 'BmpImagePlugin.py', 'XbmImagePlugin.py', 'DcxImagePlugin.py', 'PaletteFile.py', 'SunImagePlugin.py', 'BufrStubImagePlugin.py', 'JpegImagePlugin.py', 'SpiderImagePlugin.py', 'ImageEnhance.py', 'TgaImagePlugin.py', 'IcnsImagePlugin.py', 'MspImagePlugin.py', 'ImageSequence.py', 'GifImagePlugin.py', 'ImageTransform.py', 'FontFile.py', 'GbrImagePlugin.py', 'EpsImagePlugin.py', 'XVThumbImagePlugin.py', 'BdfFontFile.py', 'PcdImagePlugin.py', 'TarIO.py', 'FitsStubImagePlugin.py', 'ImageMode.py', 'ArgImagePlugin.py', 'IcoImagePlugin.py', '_imaging.cpython-32mu.so', 'McIdasImagePlugin.py', '_binary.py', '__pycache__', 'ImageQt.py', 'Hdf5StubImagePlugin.py', 'PalmImagePlugin.py', 'ImagePalette.py', 'WebPImagePlugin.py', 'ImageFont.py', 'ImagePath.py', 'TiffTags.py', 'ImImagePlugin.py', 'ImageWin.py', 'ImageFilter.py', '__init__.py', 'SgiImagePlugin.py', 'ImageTk.py', 'ImageMath.py', 'GdImageFile.py', 'WmfImagePlugin.py', 'PcfFontFile.py', 'ImageGrab.py', 'PdfImagePlugin.py', 'IptcImagePlugin.py', 'ImtImagePlugin.py', 'MpegImagePlugin.py', 'MicImagePlugin.py', 'Image.py', 'PcxImagePlugin.py']
```
Can you guys help with this? I'm totally unsure, this has been confusing me for a few days. I'm thinking that MAYBE Ubuntu's python3-tk package is incomplete, but I cant see that being the case. The same goes for pip's pillow. Any ideas?
|
2013/07/30
|
[
"https://Stackoverflow.com/questions/17957651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1543167/"
] |
So after posting an issue on [GitHub](https://github.com/python-imaging/Pillow/issues/322#issuecomment-23053260 "GitHub") I was told I was missing some libraries.
Specifically I needed to
`sudo apt-get install tk8.5-dev tcl8.5-dev`
and then
`pip install -I pillow`
to rebuild pillow. This worked on my raspberry pi running rasbian
|
I don't have the rep to comment, so I'll answer instead
I too was getting the error `can't from PIL import _imagingtk`
using python3 on Linux Mint 17
when trying to do a `tk_im = ImageTk(im)`
First I installed the tk8.6-dev and tcl8.6-dev as suggested above
Then I tried the `pip3 --upgrade route`, which didn't fix the problem
If I imported PIL in a shell, PIL.PILLOW\_VERSION was 2.7.0.
Using pip3 list however, it claimed to be 2.3.0.
so I did `sudo pip3 uninstall pillow`, followed by
`sudo pip3 install pillow`
Now, both methods of reading the version return 2.7.0
and the program works!
When/how I caught pillow 2.3, why it wouldn't upgrade with pip, and why it showed as 2.7 in the python shell I don't know, but the uninstall/install fixed it.
|
17,957,651
|
For those who need to know, I'm running a 64 bit Ubuntu 12.04, and trying to run the problematic script using a pip-installed python3.2
For a project I was writing I wanted to display an image in a tkinter window. To do this I installed Pillow via pip and installed tkinter for python 3 like so:
```
pip-3.2 install pillow #install stuff here
sudo apt-get install python3-tk
```
I then tried to run the following script
```
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
i = Image.open(<path_to_file>)
p = ImaageTk.PhotoImage(i)
```
There's more, but that block throws the errors. Anyways, when I try and run this I get the following error output
```
/usr/bin/python3.2 "/home/anish/PycharmProjects/Picture Renamer/default/Main.py"
Traceback (most recent call last):
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 184, in paste
tk.call("PyImagingPhoto", self.__photo, block.id)
_tkinter.TclError: invalid command name "PyImagingPhoto"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 26, in <module>
n = Main("/home/anish/Desktop/Images/")
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 11, in __init__
self.PictureList = self.MakeImageList(self.dir)
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 21, in MakeImageList
tkim = ImageTk.PhotoImage(temp_im)
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 123, in __init__
self.paste(image)
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 188, in paste
from PIL import _imagingtk
ImportError: cannot import name _imagingtk
Process finished with exit code 1
```
No amount of googling has given me a solution- the topics I find concerning this usually say to reinstall tkinter and/or pillow.
Here are the contents of my /usr/lib/python3.2/tkinter/
```
['dialog.py', 'scrolledtext.py', 'simpledialog.py', 'tix.py', 'dnd.py', 'ttk.py', '__main__.py', '_fix.py', 'font.py', '__pycache__', 'messagebox.py', '__init__.py', 'commondialog.py', 'constants.py', 'colorchooser.py', 'filedialog.py']
```
And here are the [many] files within my /usr/local/lib/python3.2/dist-packages/PIL/
```
['OleFileIO.py', 'ImageFileIO.py', 'ImageCms.py', 'GimpGradientFile.py', 'PSDraw.py', 'ImageDraw2.py', 'GimpPaletteFile.py', 'TiffImagePlugin.py', 'ImageChops.py', 'ImageShow.py', 'ImageStat.py', 'FliImagePlugin.py', 'ImageColor.py', 'XpmImagePlugin.py', 'ImageOps.py', 'ExifTags.py', 'FpxImagePlugin.py', 'PngImagePlugin.py', 'ImageFile.py', 'WalImageFile.py', 'PixarImagePlugin.py', 'PsdImagePlugin.py', '_util.py', 'ImageDraw.py', 'GribStubImagePlugin.py', 'ContainerIO.py', 'CurImagePlugin.py', 'JpegPresets.py', '_imagingft.cpython-32mu.so', '_imagingmath.cpython-32mu.so', 'PpmImagePlugin.py', 'BmpImagePlugin.py', 'XbmImagePlugin.py', 'DcxImagePlugin.py', 'PaletteFile.py', 'SunImagePlugin.py', 'BufrStubImagePlugin.py', 'JpegImagePlugin.py', 'SpiderImagePlugin.py', 'ImageEnhance.py', 'TgaImagePlugin.py', 'IcnsImagePlugin.py', 'MspImagePlugin.py', 'ImageSequence.py', 'GifImagePlugin.py', 'ImageTransform.py', 'FontFile.py', 'GbrImagePlugin.py', 'EpsImagePlugin.py', 'XVThumbImagePlugin.py', 'BdfFontFile.py', 'PcdImagePlugin.py', 'TarIO.py', 'FitsStubImagePlugin.py', 'ImageMode.py', 'ArgImagePlugin.py', 'IcoImagePlugin.py', '_imaging.cpython-32mu.so', 'McIdasImagePlugin.py', '_binary.py', '__pycache__', 'ImageQt.py', 'Hdf5StubImagePlugin.py', 'PalmImagePlugin.py', 'ImagePalette.py', 'WebPImagePlugin.py', 'ImageFont.py', 'ImagePath.py', 'TiffTags.py', 'ImImagePlugin.py', 'ImageWin.py', 'ImageFilter.py', '__init__.py', 'SgiImagePlugin.py', 'ImageTk.py', 'ImageMath.py', 'GdImageFile.py', 'WmfImagePlugin.py', 'PcfFontFile.py', 'ImageGrab.py', 'PdfImagePlugin.py', 'IptcImagePlugin.py', 'ImtImagePlugin.py', 'MpegImagePlugin.py', 'MicImagePlugin.py', 'Image.py', 'PcxImagePlugin.py']
```
Can you guys help with this? I'm totally unsure, this has been confusing me for a few days. I'm thinking that MAYBE Ubuntu's python3-tk package is incomplete, but I cant see that being the case. The same goes for pip's pillow. Any ideas?
|
2013/07/30
|
[
"https://Stackoverflow.com/questions/17957651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1543167/"
] |
So after posting an issue on [GitHub](https://github.com/python-imaging/Pillow/issues/322#issuecomment-23053260 "GitHub") I was told I was missing some libraries.
Specifically I needed to
`sudo apt-get install tk8.5-dev tcl8.5-dev`
and then
`pip install -I pillow`
to rebuild pillow. This worked on my raspberry pi running rasbian
|
I struggled with this for a long time. None of these solutions worked for me, other people were hostile claiming the problem had already been solved while pointing to python2.7 instead of python3 or that I must not be following the instructions. But on Ubuntu with more than one computer, I had this problem and here's how I finally solved it:
```
sudo apt-get purge python3-pil;
sudo apt-get install python3-pil python3-pil.imagetk
```
So basically the apt version of turning it off and turning it on again. :/
|
17,957,651
|
For those who need to know, I'm running a 64 bit Ubuntu 12.04, and trying to run the problematic script using a pip-installed python3.2
For a project I was writing I wanted to display an image in a tkinter window. To do this I installed Pillow via pip and installed tkinter for python 3 like so:
```
pip-3.2 install pillow #install stuff here
sudo apt-get install python3-tk
```
I then tried to run the following script
```
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
i = Image.open(<path_to_file>)
p = ImaageTk.PhotoImage(i)
```
There's more, but that block throws the errors. Anyways, when I try and run this I get the following error output
```
/usr/bin/python3.2 "/home/anish/PycharmProjects/Picture Renamer/default/Main.py"
Traceback (most recent call last):
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 184, in paste
tk.call("PyImagingPhoto", self.__photo, block.id)
_tkinter.TclError: invalid command name "PyImagingPhoto"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 26, in <module>
n = Main("/home/anish/Desktop/Images/")
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 11, in __init__
self.PictureList = self.MakeImageList(self.dir)
File "/home/anish/PycharmProjects/Picture Renamer/default/Main.py", line 21, in MakeImageList
tkim = ImageTk.PhotoImage(temp_im)
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 123, in __init__
self.paste(image)
File "/usr/local/lib/python3.2/dist-packages/PIL/ImageTk.py", line 188, in paste
from PIL import _imagingtk
ImportError: cannot import name _imagingtk
Process finished with exit code 1
```
No amount of googling has given me a solution- the topics I find concerning this usually say to reinstall tkinter and/or pillow.
Here are the contents of my /usr/lib/python3.2/tkinter/
```
['dialog.py', 'scrolledtext.py', 'simpledialog.py', 'tix.py', 'dnd.py', 'ttk.py', '__main__.py', '_fix.py', 'font.py', '__pycache__', 'messagebox.py', '__init__.py', 'commondialog.py', 'constants.py', 'colorchooser.py', 'filedialog.py']
```
And here are the [many] files within my /usr/local/lib/python3.2/dist-packages/PIL/
```
['OleFileIO.py', 'ImageFileIO.py', 'ImageCms.py', 'GimpGradientFile.py', 'PSDraw.py', 'ImageDraw2.py', 'GimpPaletteFile.py', 'TiffImagePlugin.py', 'ImageChops.py', 'ImageShow.py', 'ImageStat.py', 'FliImagePlugin.py', 'ImageColor.py', 'XpmImagePlugin.py', 'ImageOps.py', 'ExifTags.py', 'FpxImagePlugin.py', 'PngImagePlugin.py', 'ImageFile.py', 'WalImageFile.py', 'PixarImagePlugin.py', 'PsdImagePlugin.py', '_util.py', 'ImageDraw.py', 'GribStubImagePlugin.py', 'ContainerIO.py', 'CurImagePlugin.py', 'JpegPresets.py', '_imagingft.cpython-32mu.so', '_imagingmath.cpython-32mu.so', 'PpmImagePlugin.py', 'BmpImagePlugin.py', 'XbmImagePlugin.py', 'DcxImagePlugin.py', 'PaletteFile.py', 'SunImagePlugin.py', 'BufrStubImagePlugin.py', 'JpegImagePlugin.py', 'SpiderImagePlugin.py', 'ImageEnhance.py', 'TgaImagePlugin.py', 'IcnsImagePlugin.py', 'MspImagePlugin.py', 'ImageSequence.py', 'GifImagePlugin.py', 'ImageTransform.py', 'FontFile.py', 'GbrImagePlugin.py', 'EpsImagePlugin.py', 'XVThumbImagePlugin.py', 'BdfFontFile.py', 'PcdImagePlugin.py', 'TarIO.py', 'FitsStubImagePlugin.py', 'ImageMode.py', 'ArgImagePlugin.py', 'IcoImagePlugin.py', '_imaging.cpython-32mu.so', 'McIdasImagePlugin.py', '_binary.py', '__pycache__', 'ImageQt.py', 'Hdf5StubImagePlugin.py', 'PalmImagePlugin.py', 'ImagePalette.py', 'WebPImagePlugin.py', 'ImageFont.py', 'ImagePath.py', 'TiffTags.py', 'ImImagePlugin.py', 'ImageWin.py', 'ImageFilter.py', '__init__.py', 'SgiImagePlugin.py', 'ImageTk.py', 'ImageMath.py', 'GdImageFile.py', 'WmfImagePlugin.py', 'PcfFontFile.py', 'ImageGrab.py', 'PdfImagePlugin.py', 'IptcImagePlugin.py', 'ImtImagePlugin.py', 'MpegImagePlugin.py', 'MicImagePlugin.py', 'Image.py', 'PcxImagePlugin.py']
```
Can you guys help with this? I'm totally unsure, this has been confusing me for a few days. I'm thinking that MAYBE Ubuntu's python3-tk package is incomplete, but I cant see that being the case. The same goes for pip's pillow. Any ideas?
|
2013/07/30
|
[
"https://Stackoverflow.com/questions/17957651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1543167/"
] |
I struggled with this for a long time. None of these solutions worked for me, other people were hostile claiming the problem had already been solved while pointing to python2.7 instead of python3 or that I must not be following the instructions. But on Ubuntu with more than one computer, I had this problem and here's how I finally solved it:
```
sudo apt-get purge python3-pil;
sudo apt-get install python3-pil python3-pil.imagetk
```
So basically the apt version of turning it off and turning it on again. :/
|
I don't have the rep to comment, so I'll answer instead
I too was getting the error `can't from PIL import _imagingtk`
using python3 on Linux Mint 17
when trying to do a `tk_im = ImageTk(im)`
First I installed the tk8.6-dev and tcl8.6-dev as suggested above
Then I tried the `pip3 --upgrade route`, which didn't fix the problem
If I imported PIL in a shell, PIL.PILLOW\_VERSION was 2.7.0.
Using pip3 list however, it claimed to be 2.3.0.
so I did `sudo pip3 uninstall pillow`, followed by
`sudo pip3 install pillow`
Now, both methods of reading the version return 2.7.0
and the program works!
When/how I caught pillow 2.3, why it wouldn't upgrade with pip, and why it showed as 2.7 in the python shell I don't know, but the uninstall/install fixed it.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
Do you have a code sample of what your doing, or the format of the file you are reading?
Another good question would be how much of the stream are you keeping in memory at a time?
|
A general note:
1. High performance streaming isn't complicated. You usually have to modify the logic that uses the streamed data; **that's** complicated.
Actually, that's it.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
StreamReader is pretty good - how were you reading it in Python? It's possible that if you specify a simpler encoding (e.g. ASCII) then that may speed things up. How much CPU is the process taking?
You can increase the buffer size by using the appropriate StreamReader constructor, but I have no idea how much difference that's likely to make.
|
Sorry if I'm not a .NET guru, but in C/C++, if you have nice big buffers, you should be able to parse it with an LL1 parser not much slower than you can scan the bytes. I can give more detail if you want.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
If your own code is examining one character at a time, you want to use a *sentinel* to mark the end of a buffer or the end of file, so that you have **just one test in your inner loop**. In your case that one test will be for end of line, so you'll want to temporarily stick a newline at the end of each buffer, for example.
The Wikipedia article on sentinels is not helpful at all; it doesn't describe this case. You can find a description in any of Robert Sedgewick's algorithms textbooks.
You might also want to look at [`re2c`](http://re2c.org/), which can *generate* very fast code for scanning text data. It generates C code but you may be able to adapt it, and you can certainly learn the techniques by reading their paper about `re2c`.
|
A general note:
1. High performance streaming isn't complicated. You usually have to modify the logic that uses the streamed data; **that's** complicated.
Actually, that's it.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
Do you have a code sample of what your doing, or the format of the file you are reading?
Another good question would be how much of the stream are you keeping in memory at a time?
|
Sorry if I'm not a .NET guru, but in C/C++, if you have nice big buffers, you should be able to parse it with an LL1 parser not much slower than you can scan the bytes. I can give more detail if you want.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
StreamReader is pretty good - how were you reading it in Python? It's possible that if you specify a simpler encoding (e.g. ASCII) then that may speed things up. How much CPU is the process taking?
You can increase the buffer size by using the appropriate StreamReader constructor, but I have no idea how much difference that's likely to make.
|
A general note:
1. High performance streaming isn't complicated. You usually have to modify the logic that uses the streamed data; **that's** complicated.
Actually, that's it.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
If your own code is examining one character at a time, you want to use a *sentinel* to mark the end of a buffer or the end of file, so that you have **just one test in your inner loop**. In your case that one test will be for end of line, so you'll want to temporarily stick a newline at the end of each buffer, for example.
The Wikipedia article on sentinels is not helpful at all; it doesn't describe this case. You can find a description in any of Robert Sedgewick's algorithms textbooks.
You might also want to look at [`re2c`](http://re2c.org/), which can *generate* very fast code for scanning text data. It generates C code but you may be able to adapt it, and you can certainly learn the techniques by reading their paper about `re2c`.
|
Sorry if I'm not a .NET guru, but in C/C++, if you have nice big buffers, you should be able to parse it with an LL1 parser not much slower than you can scan the bytes. I can give more detail if you want.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
StreamReader is pretty good - how were you reading it in Python? It's possible that if you specify a simpler encoding (e.g. ASCII) then that may speed things up. How much CPU is the process taking?
You can increase the buffer size by using the appropriate StreamReader constructor, but I have no idea how much difference that's likely to make.
|
Try BufferedReader and BufferedWriter to speed up processing.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
Do you have a code sample of what your doing, or the format of the file you are reading?
Another good question would be how much of the stream are you keeping in memory at a time?
|
The default buffer sizes used by StreamReader/FileStream may not be optimal for the record lengths in your data, so you can try tweaking them. You can override the default buffer lengths in the constructors to both FileStream and the StreamReader which wraps it. You should probably make them the same size.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
If your own code is examining one character at a time, you want to use a *sentinel* to mark the end of a buffer or the end of file, so that you have **just one test in your inner loop**. In your case that one test will be for end of line, so you'll want to temporarily stick a newline at the end of each buffer, for example.
The Wikipedia article on sentinels is not helpful at all; it doesn't describe this case. You can find a description in any of Robert Sedgewick's algorithms textbooks.
You might also want to look at [`re2c`](http://re2c.org/), which can *generate* very fast code for scanning text data. It generates C code but you may be able to adapt it, and you can certainly learn the techniques by reading their paper about `re2c`.
|
Try BufferedReader and BufferedWriter to speed up processing.
|
414,896
|
I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O (which worries me because I keep hearing that Python 2.6's IO was relatively slow).
If there isn't faster .Net solution for this, would it be possible to write a solution faster than StreamReader or does it already use complicated buffer/algorithm/optimizations that I would never hope to beat?
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
Do you have a code sample of what your doing, or the format of the file you are reading?
Another good question would be how much of the stream are you keeping in memory at a time?
|
Try BufferedReader and BufferedWriter to speed up processing.
|
55,459,783
|
I am currently trying to code Uno in python for my Computer science principles class in school and I created a definition to draw cards from the deck into the player's hand and whenever I run the code I keep getting this error. I was just wondering how to fix it because I have tried a couple of things and have gotten nowhere.
I've tried adding items to the player's hand (which starts empty).
I tried using tuples. I've tried using making the drawing variable a list. `x` stipulates which player's hand it is while `y` is how many they draw and `z` is what cards are in the deck.
```py
import random
import time
import sys
def draw_cards(x,y,z):
for q in range(y):
draw = random.choice(z)
x = x.insert(0,draw)
z = z.remove(draw)
return x,z
cards_in_deck = ["red 0","red 1", "red 2", "red 3", "red 4", "red 5","red 6","red 7", "red 8", "red 9", "red skip", "red reverse","red +2","wild","yellow 0","yellow 1", "yellow 2", "yellow 3", "yellow 4", "yellow 5","yellow 6","yellow 7", "yellow 8", "yellow 9", "yellow skip", "yellow reverse","yellow +2","wild","green 0","green 1", "green 2", "green 3", "green 4", "green 5","green 6","green 7", "green 8", "green 9", "green skip", "green reverse","green +2","wild","blue 0","blue 1", "blue 2", "blue 3", "blue 4", "blue 5","blue 6","blue 7", "blue 8", "blue 9", "blue skip", "blue reverse","blue +2","wild","red 1", "red 2", "red 3", "red 4", "red 5","red 6","red 7", "red 8", "red 9", "red skip", "red reverse","red +2","wild +4","yellow 1", "yellow 2", "yellow 3", "yellow 4", "yellow 5","yellow 6","yellow 7", "yellow 8", "yellow 9", "yellow skip", "yellow reverse","yellow +2","wild +4","green 1", "green 2", "green 3", "green 4", "green 5","green 6","green 7", "green 8", "green 9", "green skip", "green reverse","green +2","wild +4","blue 1", "blue 2", "blue 3", "blue 4", "blue 5","blue 6","blue 7", "blue 8", "blue 9", "blue skip", "blue reverse","blue +2","wild +4"]
player_hand = []
ai_dusty_hand = []
ai_cutie_hand = []
ai_smooth_hand= []
draw_cards(ai_dusty_hand,7,cards_in_deck)
draw_cards(ai_cutie_hand,7,cards_in_deck)
draw_cards(ai_smooth_hand,7,cards_in_deck)
draw_cards(player_hand,7,cards_in_deck)
```
I expected the result to be each player having a starting hand but, the output ends in an error,
|
2019/04/01
|
[
"https://Stackoverflow.com/questions/55459783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11293669/"
] |
Lists in Python are mutable. So when you manipulate a list (even within the scope of a function) it will reflect everywhere that list is referenced.
```
x = x.insert(0,draw)
z = z.remove(draw)
```
These lines of code are assigning the return of the method calls on the list. Both of these method calls don't return anything (therefore they return `None`).
Remove the assignments of the lists in your function.
|
The problem comes from these two lines, because remove does not return the list :
```
x = x.insert(0, draw)
z = z.remove(draw)
```
`insert` and `remove` do not return anything. Do not reassign `x` and `z` and it should work:
```
x.insert(0, draw)
z.remove(draw)
```
In addition, you should return `z` to save the remaining cards:
```
def draw_cards(x,y,z):
for q in range(y):
draw = random.choice(z)
x.insert(0,draw)
z.remove(draw)
return z
cards_in_deck = draw_cards(ai_dusty_hand,7,cards_in_deck)
cards_in_deck = draw_cards(ai_cutie_hand,7,cards_in_deck)
cards_in_deck = draw_cards(ai_smooth_hand,7,cards_in_deck)
cards_in_deck = draw_cards(player_hand,7,cards_in_deck)
```
|
64,657,061
|
I'm trying to create a simple python calculator to calculate dose of a medication.
For a sample weighing 60kg. The dose should be (60\*15) divide by 80.
The supposed output should be 11.25 vials.
However, Im getting 7.575757575757576e+27. Please help me out to diagnose the problem here. Thanks
Here is the sample code that i've used.
```
# This is a program to calculate dose for IV Drug X
print('Hello Doctor!')
print('What is your name?')
myName= input()
print('It is good to meet you, ' 'Dr.' +myName)
print('What is the weight of patient?') # Patient weight
ptWeight = input()
print ('Number of vial is ' + str(int((ptWeight)*15) / 80)+ ' vials.')
```
And Here is the output that I got.
```
Hello Doctor!
What is your name?
Brian
It is good to meet you, Dr.Brian
What is the weight of patient?
60
Number of vial is 7.575757575757576e+27 vials.
```
|
2020/11/03
|
[
"https://Stackoverflow.com/questions/64657061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11362617/"
] |
You're multiplying the string
Try this:
```
print ('Number of vial is ' + str(int(ptWeight)*15 / 80)+ ' vials.')
```
|
You are multiplying as a sting. Try this instead
```
print('Hello Doctor!')
print('What is your name?')
myName= input()
print('It is good to meet you, ' 'Dr.' +myName)
print('What is the weight of patient?') # Patient weight
ptWeight = int(input())
vitals = round(int((ptWeight)*15) / 80,2)
print ('Number of vial is '+ str(vitals) +' vials.')
```
if you want the value to exact decimal places then use this
```
vitals = int((ptWeight)*15) / 80
```
round() function syntax
```
round(number, places)
```
|
10,137,026
|
So I have the directory struture like this
```
Execute_directory--> execute.py
|
Algorithm ---> algorithm.py
|
|--> data.txt
```
So I am inside execute directory and have included the following path to my python path.
```
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../Algorithm")
```
algorithm.py has a code to read data.txt
So when I run execute.py , execute.py calls algorithm.py which in turns read data.txt
I thought that above line should have done the job. it is able to find algorithm.py but not data.txt??
```
IOError: [Errno 2] No such file or directory:'data.txt'
```
Any clue what I am doing wrong ??
Thanks
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10137026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
Are you reading `data.txt` in `algorithm.py` like this:
```
open('data.txt')
```
Because that is relative to the *working directory* and not relative to the scripts directory.
In `algorithm.py` you could try this:
```
open(os.path.join(os.path.dirname(__file__), 'data.txt'))
```
|
This would usually be an issue with relative filenames not being relative to where you expect. Print the contents of `os.path.abspath(filename)` to check this. If it gives you something strange, specifying the absolute path in the first place (when you initialise `filename`) should fix it.
|
10,137,026
|
So I have the directory struture like this
```
Execute_directory--> execute.py
|
Algorithm ---> algorithm.py
|
|--> data.txt
```
So I am inside execute directory and have included the following path to my python path.
```
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../Algorithm")
```
algorithm.py has a code to read data.txt
So when I run execute.py , execute.py calls algorithm.py which in turns read data.txt
I thought that above line should have done the job. it is able to find algorithm.py but not data.txt??
```
IOError: [Errno 2] No such file or directory:'data.txt'
```
Any clue what I am doing wrong ??
Thanks
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10137026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
Are you reading `data.txt` in `algorithm.py` like this:
```
open('data.txt')
```
Because that is relative to the *working directory* and not relative to the scripts directory.
In `algorithm.py` you could try this:
```
open(os.path.join(os.path.dirname(__file__), 'data.txt'))
```
|
`sys.path` is used to tell Python where to look for modules when you use `import`. It does not affect looking for files with `open`. When you open a file, relative paths are relative to the "current working directory", which you can check with `os.getcwd` and change with `os.chdir`.
Bonus: if you check the value of `sys.path` at startup, you will see that it includes `''`. This tells Python to also check the current working directory for modules (as well as the hard-coded absolute paths in `sys.path`, which is why, if you start a Python interpreter while "in" (using a command prompt) the folder that contains your module, you don't have to tell it where to look for your module.
|
10,137,026
|
So I have the directory struture like this
```
Execute_directory--> execute.py
|
Algorithm ---> algorithm.py
|
|--> data.txt
```
So I am inside execute directory and have included the following path to my python path.
```
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../Algorithm")
```
algorithm.py has a code to read data.txt
So when I run execute.py , execute.py calls algorithm.py which in turns read data.txt
I thought that above line should have done the job. it is able to find algorithm.py but not data.txt??
```
IOError: [Errno 2] No such file or directory:'data.txt'
```
Any clue what I am doing wrong ??
Thanks
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10137026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] |
This would usually be an issue with relative filenames not being relative to where you expect. Print the contents of `os.path.abspath(filename)` to check this. If it gives you something strange, specifying the absolute path in the first place (when you initialise `filename`) should fix it.
|
`sys.path` is used to tell Python where to look for modules when you use `import`. It does not affect looking for files with `open`. When you open a file, relative paths are relative to the "current working directory", which you can check with `os.getcwd` and change with `os.chdir`.
Bonus: if you check the value of `sys.path` at startup, you will see that it includes `''`. This tells Python to also check the current working directory for modules (as well as the hard-coded absolute paths in `sys.path`, which is why, if you start a Python interpreter while "in" (using a command prompt) the folder that contains your module, you don't have to tell it where to look for your module.
|
38,060,383
|
I have the following sql query:
```
SELECT
pc.patente,
cs.cpc_group_codigo_cpc_group
FROM
patente_pc pc
,
patente_cpc cpc,
cpc_subgroup cs,
cpc_group cg
WHERE
pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND
cpc.cpc = cs.codigo_cpc_subgroup AND
cs.cpc_group_codigo_cpc_group = cg.codigo_cpc_group
GROUP BY
pc.patente, cs.cpc_group_codigo_cpc_group
```
I add this query to python, separating line by line the string in a tuple to not have a problem with the syntax..
and it executes correctly
but when I need to retrieve the data, I use
```
lista_cpcs = []
lista_patentes = []
for (pc.patente, cs.cpc_group_codigo_cpc_group) in cursor:
lista_cpcs.append(cs.cpc_group_codigo_cpc_group)
lista_patentes.append(pc.patente)
return [lista_cpcs, lista_patentes]
```
and I get the error `Global name 'pc' is not defined`
I get whats happening, it's interpreting pc and cs as python modules, but they are from the sql..
how to work in this?
Ps: I search for python mysql connector and didn't found anything with this.
|
2016/06/27
|
[
"https://Stackoverflow.com/questions/38060383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691244/"
] |
>
> Does Google allow third party access?
>
>
>
Yes. If you're going to be doing interactive programming using mainstream services, learn to use APIs. The Google API collection allows users to register their applications and sites for a *huge* variety of their services...including `Gmail`.
Look [here](https://console.developers.google.com/) for more details.
>
> How can I get started?
>
>
>
Read the documentation and instructions for overall Google-API usage in the link above, *and* the separate documentation for the service you want to use.
For `Gmail`, look [here](https://developers.google.com/gmail/api/).
|
I agree with the others its fairly well documented, particularly here would be relevant for you if you intend to get started using the Java API:
[Google docs](https://developers.google.com/gmail/api/quickstart/java#step_3_set_up_the_sample)
>
> To run this quickstart, you'll need:
>
>
> Java 1.7 or greater. Gradle 2.3 or greater. Access to the internet and
> a web browser. A Google account with Gmail enabled....
>
>
>
|
16,136,341
|
I need to optimize a function call that is in a loop, for a time-critical robotics application. My script is in python, which interfaces via ctypes with a C++ library I wrote, which then calls a microcontroller library.
The bottleneck is adding position-velocity-time points to the microcontroller buffer. According to my timing checks, calling the C++ function via ctypes takes about `0.45` seconds and on the C++ side the called function takes `0.17` seconds. I'm need to reduce this difference somehow.
Here is the relevant python code, where data is a 2D array of points and clibrary is loaded via ctypes:
```
data_np = np.vstack([nodes, positions, velocities, times]).transpose().astype(np.long)
data = ((c_long * 4) * N)()
for i in range(N):
data[i] = (c_long * 4)(*data_np[i])
timer = time()
clibrary.addPvtAll(N, data)
print("clibrary.addPvtAll() call: %f" % (time() - timer))
```
And here is the called C++ function:
```
void addPvtAll(int N, long data[][4]) {
clock_t t0, t1;
t0 = clock();
for(int i = 0; i < N; i++) {
unsigned short node = (unsigned short)data[i][0];
long p = data[i][1];
long v = data[i][2];
unsigned char t = (unsigned char)data[i][3];
VCS_AddPvtValueToIpmBuffer(device(node), node, p, v, t, &errorCode);
}
t1 = clock();
printf("addPvtAll() call: %f \n", (double(t1 - t0) / CLOCKS_PER_SEC));
}
```
I don't absolutely need to use ctypes but I don't want to have to compile the Python code every time I run it.
|
2013/04/21
|
[
"https://Stackoverflow.com/questions/16136341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901553/"
] |
The round-trip between Python and C++ can be expensive, especially when using *ctypes* (which is like an interpreted version of a normal C/Python wrapper).
Your goal should be to minimize the number of trips and do the most work possible per trip.
It looks to me like your code has too fine of a granularity (i.e. doing too many trips and doing too little work on each trip).
The *numpy* package can expose its data directly to C/C++. That will let you avoid the expensive boxing and unboxing of Python objects (with their attendant memory allocations) and it will let you pass a range of data points rather than a point at a time.
Modify your C++ code to process many points at a time rather than once per call (much like the *sqlite3* module does with *execute* vs. *executemany*).
|
You can just use `data_np.data.tobytes()`:
```
data_np = np.vstack([nodes, positions, velocities, times]).transpose().astype(np.long)
timer = time()
clibrary.addPvtAll(N, data_np.data.tobytes())
print("clibrary.addPvtAll() call: %f" % (time() - timer))
```
|
16,136,341
|
I need to optimize a function call that is in a loop, for a time-critical robotics application. My script is in python, which interfaces via ctypes with a C++ library I wrote, which then calls a microcontroller library.
The bottleneck is adding position-velocity-time points to the microcontroller buffer. According to my timing checks, calling the C++ function via ctypes takes about `0.45` seconds and on the C++ side the called function takes `0.17` seconds. I'm need to reduce this difference somehow.
Here is the relevant python code, where data is a 2D array of points and clibrary is loaded via ctypes:
```
data_np = np.vstack([nodes, positions, velocities, times]).transpose().astype(np.long)
data = ((c_long * 4) * N)()
for i in range(N):
data[i] = (c_long * 4)(*data_np[i])
timer = time()
clibrary.addPvtAll(N, data)
print("clibrary.addPvtAll() call: %f" % (time() - timer))
```
And here is the called C++ function:
```
void addPvtAll(int N, long data[][4]) {
clock_t t0, t1;
t0 = clock();
for(int i = 0; i < N; i++) {
unsigned short node = (unsigned short)data[i][0];
long p = data[i][1];
long v = data[i][2];
unsigned char t = (unsigned char)data[i][3];
VCS_AddPvtValueToIpmBuffer(device(node), node, p, v, t, &errorCode);
}
t1 = clock();
printf("addPvtAll() call: %f \n", (double(t1 - t0) / CLOCKS_PER_SEC));
}
```
I don't absolutely need to use ctypes but I don't want to have to compile the Python code every time I run it.
|
2013/04/21
|
[
"https://Stackoverflow.com/questions/16136341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901553/"
] |
Here is my solution, which effectively eliminates the measured time difference between Python and C. Credit to kirbyfan64sos for suggesting SWIG and Raymond Hettinger for C-arrays in numpy. I use a numpy array in Python which is sent to C purely as a pointer - the same memory block is accessed in both languages.
The C function remains identical except using `gettimeofday()` instead of `clock()`, which was giving inaccurate times:
```
void addPvtFrame(int pvt[6][4]) {
timeval start,stop,result;
gettimeofday(&start, NULL);
for(int i = 0; i < 6; i++) {
unsigned short node = (unsigned short)pvt[i][0];
long p = (long)pvt[i][1];
long v = (long)pvt[i][2];
unsigned char t = (unsigned char)pvt[i][3];
VCS_AddPvtValueToIpmBuffer(device(node), node, p, v, t, &errorCode);
}
gettimeofday(&stop, NULL);
timersub(&start,&stop,&result);
printf("Add PVT time in C code: %fs\n", -(result.tv_sec + result.tv_usec/1000000.0));
}
```
In addition, I installed SWIG and included the following in my interfaces file:
```
%include "numpy.i"
%init %{
import_array();
%}
%apply ( int INPLACE_ARRAY2[ANY][ANY] ) {(int pvt[6][4])}
```
Finally, my Python code constructs `pvt` as a contiguous array via numpy:
```
pvt = np.vstack([nodes, positions, velocities, times])
pvt = np.ascontiguousarray(pvt.transpose().astype(int))
timer = time()
xjus.addPvtFrame(pvt)
print("Add PVT time to C code: %fs" % (time() - timer))
```
The measured times now have about %1 difference on my machine.
|
You can just use `data_np.data.tobytes()`:
```
data_np = np.vstack([nodes, positions, velocities, times]).transpose().astype(np.long)
timer = time()
clibrary.addPvtAll(N, data_np.data.tobytes())
print("clibrary.addPvtAll() call: %f" % (time() - timer))
```
|
71,987,704
|
So here is the code in question. The error I get when I run the code is
File "D:\obj\windows-release\37amd64\_Release\msi\_python\zip\_amd64\random.py", line 259, in choice
TypeError: object of type 'type' has no len()
```
import random
import tkinter as tk
from tkinter import messagebox
root=tk.Tk()
root.title("Tragic 8 Ball")
def get_answer(entry, list):
if (entry.get() != ""):
messagebox.showwarning("Please ask question.")
else: (entry.get() == "")
messagebox.showwarning("Your answer", random.choice(list))
entry=tk.Entry(width=40)
entry.focus_set()
entry.grid()
get_answer(entry, list)
tk.Label(root, text="Ask a question:").grid(row=0)
tk.Button(root, text="Answer my question", command=get_answer(entry, list).grid(row=3), columd=0, sticky=tk.W, pady=4)
list=["It is certain.",
"Outlook good.",
"You may rely on it",
"Ask again later.",
"Concentrate and ask again.",
"Reply hazy, try again.",
"My reply is no.",
"My sources say no."]
root.mainloop()
'''
```
|
2022/04/24
|
[
"https://Stackoverflow.com/questions/71987704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18834663/"
] |
This is verging on an opinion-based question, but I think it is on-topic, since it helps to clarify the syntax and structure of ggplot calls.
In a sense you have already answered the question yourself:
>
> it does not seem to be documented anywhere in the ggplot2 help
>
>
>
This, and the near absence of examples in online tutorials, blogs and SO answers is a good enough reason not to use `aes` this way (or at least not to teach people to use it this way). It could lead to confusion and frustration on the part of new users.
>
> This fits a lot better into the logic of adding up layers
>
>
>
This is *sort of* true, but could be a bit misleading. What it actually does is to specify the *default* aesthetic mapping, that subsequent layers will inherit from the `ggplot` object itself. It should be considered a core *part* of the base plot, along with the default data object, and therefore "belongs" in the initial `ggplot` call, rather than something that is being added or layered on to the plot. If you create a default `ggplot` object without data and mapping, the slots are still there, but contain waivers rather than being `NULL` :
```r
p <- ggplot()
p$mapping
#> Aesthetic mapping:
#> <empty>
p$data
#> list()
#> attr(,"class")
#> [1] "waiver"
```
Note that unlike the scales and co-ordinate objects, for which you might argue that the same is also true, there can be no defaults for data and aesthetic mappings.
Does this mean you should *never* use this syntax? No, but it should be considered an advanced trick for folks who are well versed in ggplot. The most frequent use case I find for it is in changing the mapping of ggplots that are created in extension packages, such as `ggsurvplot` or `ggraph`, where the plotting functions use wrappers around `ggplot`. It can also be used to quickly create multiple plots with the same themes and colour scales:
```r
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_point(aes(color = Species)) +
theme_light()
library(patchwork)
p + (p + aes(Petal.Width, Petal.Length))
```
[](https://i.stack.imgur.com/E4D9W.png)
So the bottom line is that you can use this if you want, but best avoid teaching it to beginners
|
### TL;DR
I cannot see any strong reasons why not to use this pattern, but other patterns are recommended in the documentation, without elaboration.
### What does `+ aes()` do?
A ggplot has two types of aesthetics:
* the default one (typically supplied inside `ggplot()`), and
* `geom_*()` specific aesthetics
If `inherit.aes = TRUE` is set inside the geoms, then these two types of aesthetics are combined in the final plot. If the default aesthetic is not set, then the `geom_*` specific aesthetics must be set.
Using `ggplot(df) + aes(x, y)` changes the **default** aesthetic.
This is documented in `?"+.gg"`:
>
> An aes() object replaces the default aesthetics.
>
>
>
### Are there any reasons not to use it?
I cannot see any strong reasons not to. However, in the documentation of `?ggplot` it is stated that:
>
> There are three common ways to invoke ggplot():
>
>
> * ggplot(df, aes(x, y, other aesthetics))
> * ggplot(df)
> * ggplot()
>
>
> The first method is recommended if all layers use the same data and the same set of aesthetics.
>
>
>
As far as I can see, the typical use case for `+ aes()` is when all layers use the same aesthetics. So the documentation recommend the usual pattern `ggplot(df, aes(x, y, other aesthetics))`, but I cannot find an elaboration of why.
Further: even though the plots look identical, the objects returned by `ggplot(df, aes()` and `ggplot(df) + aes()` are not identical, so there might be some edge cases where one pattern would lead to errors or a different plot.
You can see the many small differences with this code:
```r
library(ggplot2)
a <- ggplot(mtcars, aes(hp, mpg)) + geom_point()
b <- ggplot(mtcars) + aes(hp, mpg) + geom_point()
waldo::compare(a, b, x_arg = "a", y_arg = "b")
```
|
39,086,368
|
I'm trying to read beyond the EOF in Python, but so far I'm failing (also tried to work with seek to position and read fixed size).
I've found a workaround which only works on Linux (and is quite slow, too) by working with debugfs and subprocess, but this is to slow and does not work on windows.
My Question: is it possible to read a file beyond EOF in python (which works on all platforms)?
|
2016/08/22
|
[
"https://Stackoverflow.com/questions/39086368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691944/"
] |
You can't read more bytes than is in the file. "End of file" literally means exactly that.
|
You can only move to the end using:
```
file.seek(0, 2)
```
Is that you're trying to do?
|
35,118,312
|
I am trying to install a python package that needs a Windos C++ compiler
The install procedure sent me to this link:
<https://wiki.python.org/moin/WindowsCompilers>
I am using Python 2.7 x86 on Win 7 x64
The version indicated on that page is not available anymore (Microsoft Visual C++ 9.0 standalone: Visual C++ Compiler for Python 2.7 (x86, x64) )
What can I do? Where can I find the above compiler ?
|
2016/01/31
|
[
"https://Stackoverflow.com/questions/35118312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059078/"
] |
Not sure what is happening with Microsoft today or these days but here is the direct link
<http://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi>
Alternatively you can search github, for "VCForPython27.msi site:github.com"
That will give you either the above link or links to files hosted on Github.
|
The [express versions of visual studio](https://www.visualstudio.com/products/visual-studio-express-vs) are free, I assume the command line compiler would work.
You might also need to read [Microsoft Visual C++ Compiler for Python 2.7](https://stackoverflow.com/questions/26140192/microsoft-visual-c-compiler-for-python-2-7?rq=1)
|
35,118,312
|
I am trying to install a python package that needs a Windos C++ compiler
The install procedure sent me to this link:
<https://wiki.python.org/moin/WindowsCompilers>
I am using Python 2.7 x86 on Win 7 x64
The version indicated on that page is not available anymore (Microsoft Visual C++ 9.0 standalone: Visual C++ Compiler for Python 2.7 (x86, x64) )
What can I do? Where can I find the above compiler ?
|
2016/01/31
|
[
"https://Stackoverflow.com/questions/35118312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059078/"
] |
The "Microsoft Visual C++ Compiler for Python 2.7" download has now been completely removed by Microsoft. (Which BTW, means the Chocolatey install won't work either as it was relying on the Microsoft website as a source.)
As a last resort, the file is available from the Internet Archive. Prefer any other source though, the last thing we want is to hammer the Wayback Machine with unnecessary download requests.
<https://web.archive.org/web/20210106040224/https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi>
Here are the hashes to verify integrity in case you grab the file from elsewhere:
```
SHA-1: 7800d037ba962f288f9b952001106d35ef57befe
SHA-256: 070474db76a2e625513a5835df4595df9324d820f9cc97eab2a596dcbc2f5cbf
SHA-512: 155b52a2ed59730983346899a96f42eb76ff5b4c2b7deb8b5946008b95bb0c6c1e6da31c80b7c68f5fe6881ddaa65ce321c6a52f3b0fc34ee98b4dd8dfa42772
```
|
The [express versions of visual studio](https://www.visualstudio.com/products/visual-studio-express-vs) are free, I assume the command line compiler would work.
You might also need to read [Microsoft Visual C++ Compiler for Python 2.7](https://stackoverflow.com/questions/26140192/microsoft-visual-c-compiler-for-python-2-7?rq=1)
|
58,862,894
|
I'm working in python using pandas and ultimately wanting to run a random forest. Python bugs out because I can't get this numeric column with spaces as nulls to be converted to a float. I tried fillna with zero and astype(float) but no success. Thanks all!
```
sm['PopHalfMile']
Out[64]:
0 2072
1 4392
2 2986
3
4
...
281 3350
282 1481
283 607
284 4708
285 4237
Name: PopHalfMile, Length: 286, dtype: object
In [65]:
sm['PopHalfMile'].fillna(value=0)
Out[65]:
0 2072
1 4392
2 2986
3
4
...
281 3350
282 1481
283 607
284 4708
285 4237
Name: PopHalfMile, Length: 286, dtype: object
So i looked at the csv file in notepad and their is a space where the data is null. ...comma space comma.
6, ,2103,
This is causing me to get this error after trying to convert the field to a float.
sm["PopHalfMile"] = sm.PopHalfMile.astype(float)
ValueError: could not convert string to float:
```
|
2019/11/14
|
[
"https://Stackoverflow.com/questions/58862894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12374239/"
] |
Unfortunately, I don't think there is any way to do regex matching on `if` conditional expressions yet.
One option is to use filtering on `push` events.
```
on:
push:
tags:
- 'v*.*.*'
```
Another option is to do the regex check in a separate step where it [creates a step output](https://help.github.com/en/actions/reference/development-tools-for-github-actions#set-an-output-parameter-set-output). This can then be used in an `if` conditional.
```
- name: Check Tag
id: check-tag
run: |
if [[ ${{ github.event.ref }} =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo ::set-output name=match::true
fi
- name: Build
if: steps.check-tag.outputs.match == 'true'
run: |
echo "Tag is a match"
```
|
As per [docs](https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet), you can do this:
```
on:
create:
tags:
- "v[0-9]+.[0-9]+"
```
I tried the above and can confirm it works. This is not full regex capability but should suffice for your needs.
|
58,862,894
|
I'm working in python using pandas and ultimately wanting to run a random forest. Python bugs out because I can't get this numeric column with spaces as nulls to be converted to a float. I tried fillna with zero and astype(float) but no success. Thanks all!
```
sm['PopHalfMile']
Out[64]:
0 2072
1 4392
2 2986
3
4
...
281 3350
282 1481
283 607
284 4708
285 4237
Name: PopHalfMile, Length: 286, dtype: object
In [65]:
sm['PopHalfMile'].fillna(value=0)
Out[65]:
0 2072
1 4392
2 2986
3
4
...
281 3350
282 1481
283 607
284 4708
285 4237
Name: PopHalfMile, Length: 286, dtype: object
So i looked at the csv file in notepad and their is a space where the data is null. ...comma space comma.
6, ,2103,
This is causing me to get this error after trying to convert the field to a float.
sm["PopHalfMile"] = sm.PopHalfMile.astype(float)
ValueError: could not convert string to float:
```
|
2019/11/14
|
[
"https://Stackoverflow.com/questions/58862894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12374239/"
] |
Unfortunately, I don't think there is any way to do regex matching on `if` conditional expressions yet.
One option is to use filtering on `push` events.
```
on:
push:
tags:
- 'v*.*.*'
```
Another option is to do the regex check in a separate step where it [creates a step output](https://help.github.com/en/actions/reference/development-tools-for-github-actions#set-an-output-parameter-set-output). This can then be used in an `if` conditional.
```
- name: Check Tag
id: check-tag
run: |
if [[ ${{ github.event.ref }} =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo ::set-output name=match::true
fi
- name: Build
if: steps.check-tag.outputs.match == 'true'
run: |
echo "Tag is a match"
```
|
I have managed to achieve this with a two part approach. The first part consists of filtering the tags that you want to run on. The second part is to create a condition on your `deploy` job.
A cut down version of my workflow looks like the following:
```yaml
name: CI-CD
on:
push:
branches:
- stable
tags:
- '[0-9]+.[0-9]+.[0-9]+'
- '[0-9]+.[0-9]+.[0-9]+rc[0-9]+'
pull_request:
branches:
- stable
jobs:
test:
steps:
...
deploy:
needs: test
if: startsWith(github.ref, 'refs/tags')
steps:
...
```
I run my workflows on pushes, tags, and pull request to specific branches. You can get creative with how exactly you want to filter your tags. [Check out the filter patterns](https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet).
The part I was struggling with a bit was how to set the right condition to run the `deploy` job. I settled on the following:
```yaml
needs: test
```
which ensures that it will only run when the `test` job has succeeded.
Then I abuse the fact that `github.ref` will be `'refs/heads/stable'` on a push to the branch and `'refs/tags/<your tag>'` on pushing a tag. So I simply test for that difference with the following condition.
```yaml
if: startsWith(github.ref, 'refs/tags')
```
Works like a charm for me but may depend on your setup.
You can also create separate workflows, of course, but in my case I always wanted to run the test suite first.
|
5,072,630
|
I am trying to create a simple form/script combination that will allow someone to replace the contents of a certain div in an html file with the text they input in an html form on a separate page.
The script works fine if everything is local : the script is local, i set the working directory to where my html file is, and i pass the parameter myself when I run the script. When I load everything to my hosted site server, however, it gives me a 500 error.
I have been able to execute a simple python script that i stored on my site, and JustHost, my hosting service, has told me that BeuatifulSoup has been added to my server.
Here is the script, with the parameter "textcontent" coming from an html form which works fine. My scirpt is rooted under public\_html/cgi-bin/ and the html I am trying to read and write resides on the root of public\_html. I'm guessing either the html file isn't being found or beautifulsoup isn't actually available on my server...anyway way to test that??
```
#!/usr/bin/python
#import beautifulsoup
from BeautifulSoup import BeautifulSoup
# Import modules for CGI handling
import cgi, cgitb, traceback
# Create instance of FieldStorage
try:
form = cgi.FieldStorage()
def text_replace(word):
f = open('/public_html/souptest2.html', 'r')
soup = BeautifulSoup(f.read())
f.close()
text = soup.find('div', attrs={'id': 'sampletext'}).string
text.replaceWith(word)
deploy_html = open('/public_html/souptest2.html', 'w')
deploy_html.write(str(soup))
deploy_html.close()
# Get data from fields
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
text_replace(text_content)
else:
text_content = "Not entered"
except:
deploy_html = open('../souptest2.html', 'w')
traceback.print_exc(deploy_html)
deploy_html.close()
```
I have tried to load that as a script and run it from a url and still get a 500 error, with no output on my output page in order to debug using traceback...
|
2011/02/21
|
[
"https://Stackoverflow.com/questions/5072630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/627466/"
] |
Yes, use:
```
range(1,7)
```
that should do it.
|
Use the [`range`](http://docs.python.org/library/functions.html#range) builtin.
```
range(1, 7)
```
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
If your motive is to just convert json to parquet, you can probably use pyspark API:
```
>>> data = [ { "a": "01", "b": "teste01" }, { "a": "02", "b": "teste02" } ]
>>> df = spark.createDataFrame(data)
>>> df.write.parquet("data.parquet")
```
Now, this DF is a spark dataframe, which can be saved in parquet.
|
Welcome to Stackoverflow, the library you are using shows that in example that you need to write the column names in the data frame.
Try using column names of your data frame and it will work.
```
# Given PyArrow schema
import pyarrow as pa
schema = pa.schema([
pa.field('my_column', pa.string),
pa.field('my_int', pa.int64),
])
convert_json(input_filename, output_filename, schema)
```
reference: [json2parquet](https://pypi.org/project/json2parquet/)
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
You can also directly read JSON files utilizing `pyarrow` as in the following example:
```
from pyarrow import json
import pyarrow.parquet as pq
table = json.read_json('C:/python/json_teste')
pq.write_table(table, 'C:/python/result.parquet') # save json/table as parquet
```
Reference: [reading and writing with pyarrow.parquet](https://arrow.apache.org/docs/python/parquet.html#reading-and-writing-single-files)
|
Welcome to Stackoverflow, the library you are using shows that in example that you need to write the column names in the data frame.
Try using column names of your data frame and it will work.
```
# Given PyArrow schema
import pyarrow as pa
schema = pa.schema([
pa.field('my_column', pa.string),
pa.field('my_int', pa.int64),
])
convert_json(input_filename, output_filename, schema)
```
reference: [json2parquet](https://pypi.org/project/json2parquet/)
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
Here's how to convert a JSON file to Apache Parquet format, using Pandas in Python. This is an easy method with a well-known library you may already be familiar with.
Firstly, make sure to install `pandas` and `pyarrow`. If you're using [Python with Anaconda](https://www.anaconda.com/products/individual#Downloads):
```
conda install pandas
conda install pyarrow
```
Then, here is the code:
```
import pandas as pd
data = pd.read_json(FILEPATH_TO_JSON_FILE)
data.to_parquet(PATH_WHERE_TO_SAVE_PARQUET_FILE)
```
I hope this helps, please let me know if I can clarify anything.
|
Welcome to Stackoverflow, the library you are using shows that in example that you need to write the column names in the data frame.
Try using column names of your data frame and it will work.
```
# Given PyArrow schema
import pyarrow as pa
schema = pa.schema([
pa.field('my_column', pa.string),
pa.field('my_int', pa.int64),
])
convert_json(input_filename, output_filename, schema)
```
reference: [json2parquet](https://pypi.org/project/json2parquet/)
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
You can achieve what you are looking for by pyspark as follows:
```
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("JsonToParquetPysparkExample") \
.getOrCreate()
json_df = spark.read.json("C://python/test.json", multiLine=True,)
json_df.printSchema()
json_df.write.parquet("C://python/output.parquet")
```
|
Welcome to Stackoverflow, the library you are using shows that in example that you need to write the column names in the data frame.
Try using column names of your data frame and it will work.
```
# Given PyArrow schema
import pyarrow as pa
schema = pa.schema([
pa.field('my_column', pa.string),
pa.field('my_int', pa.int64),
])
convert_json(input_filename, output_filename, schema)
```
reference: [json2parquet](https://pypi.org/project/json2parquet/)
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
If your motive is to just convert json to parquet, you can probably use pyspark API:
```
>>> data = [ { "a": "01", "b": "teste01" }, { "a": "02", "b": "teste02" } ]
>>> df = spark.createDataFrame(data)
>>> df.write.parquet("data.parquet")
```
Now, this DF is a spark dataframe, which can be saved in parquet.
|
You can also directly read JSON files utilizing `pyarrow` as in the following example:
```
from pyarrow import json
import pyarrow.parquet as pq
table = json.read_json('C:/python/json_teste')
pq.write_table(table, 'C:/python/result.parquet') # save json/table as parquet
```
Reference: [reading and writing with pyarrow.parquet](https://arrow.apache.org/docs/python/parquet.html#reading-and-writing-single-files)
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
If your motive is to just convert json to parquet, you can probably use pyspark API:
```
>>> data = [ { "a": "01", "b": "teste01" }, { "a": "02", "b": "teste02" } ]
>>> df = spark.createDataFrame(data)
>>> df.write.parquet("data.parquet")
```
Now, this DF is a spark dataframe, which can be saved in parquet.
|
Here's how to convert a JSON file to Apache Parquet format, using Pandas in Python. This is an easy method with a well-known library you may already be familiar with.
Firstly, make sure to install `pandas` and `pyarrow`. If you're using [Python with Anaconda](https://www.anaconda.com/products/individual#Downloads):
```
conda install pandas
conda install pyarrow
```
Then, here is the code:
```
import pandas as pd
data = pd.read_json(FILEPATH_TO_JSON_FILE)
data.to_parquet(PATH_WHERE_TO_SAVE_PARQUET_FILE)
```
I hope this helps, please let me know if I can clarify anything.
|
59,141,776
|
Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "teste01"
},
{
"a": "02",
"b": "teste02"
}
]
What am i doing wrong?
```
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
df = pd.read_json('C:/python/json_teste')
pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
```
Error:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-1b4ced833098> in <module>
----> 1 pq = pa.parquet.write_table(df, 'C:/python/parquet_teste')
C:\Anaconda\lib\site-packages\pyarrow\parquet.py in write_table(table, where, row_group_size, version, use_dictionary, compression, write_statistics, use_deprecated_int96_timestamps, coerce_timestamps, allow_truncated_timestamps, data_page_size, flavor, filesystem, **kwargs)
1256 try:
1257 with ParquetWriter(
-> 1258 where, table.schema,
1259 filesystem=filesystem,
1260 version=version,
C:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5066 return self[name]
-> 5067 return object.__getattribute__(self, name)
5068
5069 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'schema'
```
Print file:
```
#print
print(df)
a b
0 1 teste01
1 2 teste02
#following columns
df.columns
Index(['a', 'b'], dtype='object')
#following types
df.dtypes
a int64
b object
dtype: object
```
|
2019/12/02
|
[
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] |
If your motive is to just convert json to parquet, you can probably use pyspark API:
```
>>> data = [ { "a": "01", "b": "teste01" }, { "a": "02", "b": "teste02" } ]
>>> df = spark.createDataFrame(data)
>>> df.write.parquet("data.parquet")
```
Now, this DF is a spark dataframe, which can be saved in parquet.
|
You can achieve what you are looking for by pyspark as follows:
```
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("JsonToParquetPysparkExample") \
.getOrCreate()
json_df = spark.read.json("C://python/test.json", multiLine=True,)
json_df.printSchema()
json_df.write.parquet("C://python/output.parquet")
```
|
61,619,201
|
While adding groups with permission from Django Admin Panel and adding other M2M relationships too. I got this error!!
It says : **TypeError: \_bulk\_create() got an unexpected keyword argument 'ignore\_conflicts'**
I can't find the error, Probably a noob mistake.
```
class GroupSerializer(serializers.ModelSerializer):
permissions = PermissionSerializerGroup(many=True, required=False)
class Meta:
model = Group
fields = ('id', 'name', 'permissions')
extra_kwargs = {
'name': {'validators': []},
}
def create(self, validated_data):
print(validated_data)
permissions_data = validated_data.pop("permissions")
obj, group = Group.objects.update_or_create(name=validated_data["name"])
obj.permissions.clear()
for permission in permissions_data:
per = Permission.objects.get(codename=permission["codename"])
obj.permissions.add(per)
obj.save()
return obj
```
Here is the Traceback:
```
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1638, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1522, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1566, in _changeform_view
self.save_related(request, form, formsets, not add)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1107, in save_related
form.save_m2m()
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/forms/models.py", line 442, in _save_m2m
f.save_form_data(self.instance, cleaned_data[f.name])
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1618, in save_form_data
getattr(instance, self.attname).set(data)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1008, in set
self.add(*new_objs, through_defaults=through_defaults)
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 946, in add
through_defaults=through_defaults,
File "/home/suman/Desktop/suman1234/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1129, in _add_items
], ignore_conflicts=True)
TypeError: _bulk_create() got an unexpected keyword argument 'ignore_conflicts'
```
|
2020/05/05
|
[
"https://Stackoverflow.com/questions/61619201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8944012/"
] |
You should use:
```
@EventBusSubscriber
public static class Class {
@SubscribeEvent
public static void onEvent(EntityJoinWorldEvent event) {
if ((event.getEntity() instanceof PlayerEntity)) {
LogManager.getLogger().info("Joined!");
}
}
}
```
I thought maybe you'd need the instance of the player to be able to get it to work.
|
```java
...
@Mod(
modid = Kubecraft.MOD_ID,
name = Kubecraft.MOD_NAME,
version = Kubecraft.VERSION
)
public class Kubecraft {
...
@SubscribeEvent
public static void onEvent(EntityJoinWorldEvent event) {
Timer timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if(!sent) Minecraft.getMinecraft().player.sendChatMessage("/setblock ~ ~ ~ grass");
sent = true;
}
});
timer.setRepeats(false); // Only execute once
if(!sent) {
timer.start();
}
}
}
...
```
|
48,579,232
|
[enter image description here](https://i.stack.imgur.com/g89q0.jpg)i was trying to run the following command::
```
python populate_book.py
```
and stuck with this error::
```
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
```
The Whole Traceback is as follow::
```
Traceback (most recent call last):
File "populate_book.py", line 6, in <module>
from opac.models import Book, BookCopy
File "/home/prashant/Desktop/po/opac/models.py", line 6, in <module>
from transactions.models import EndUser
File "/home/prashant/Desktop/po/transactions/models.py", line 4, in <module>
class EndUser(models.Model):
File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
```
settings.py::
```
# Django settings for cope project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
ADMINS = (
('pulkit', 'data.pulkit@gmail.com'),
('shashank', 'shashankgrovy@gmail.com'),
('sourabh', 'sourabh.coder@gmail.com'),
('utsav', 'kumaruts@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'cope.db',
# Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '127.0.0.1',
# Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '3306',
# Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Kolkata'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(os.path.join(PROJECT_PATH, 'cope'), 'static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'li=xy2zchjmi=)$+t$*yi5soc77yankx#=au+5&fy17_j3-#e%'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'cope.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cope.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(os.path.join(PROJECT_PATH, 'cope'), 'templates'),
)
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
LOCAL_APPS = (
'opac',
'transactions',
)
THIRD_PARTY_APPS = (
'bootstrap_admin',
)
INSTALLED_APPS = THIRD_PARTY_APPS + LOCAL_APPS + DJANGO_APPS
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
```
populate\_book.py::
```
import os
from random import randint
if __name__ == '__main__':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cope.settings")
from opac.models import Book, BookCopy
def make_isbn():
return randint(1000000000000, 9999999999999)
titles = ['Gray Hat Python', 'Introduction to Algorithms', 'Pro Python',
'HTML5 and JavaScript Projects', 'NginX HTTP Server', 'Redis Cookbook',
'Python Fundamentals', 'Land of Lisp', 'Beginning iOS Game Development',
'Ruby on Rails for Dummies', 'Django, AJAX and jQuery']
authors = ['Seitz', 'Thomas H. Corman', 'Marty Alchin', 'Geanie Mayer', 'Clement',
'Tiago Macedo', 'Kent Lee', 'Courad', 'Patrick', 'Barry Burd', 'Jonathan Hayward']
publishers = ['No Starch Press', 'Stanford Press', 'Apress', 'Apress', 'Packt OpenSource',
'O\'Reilly', 'Springer', 'No Starch Press', 'WROK', 'For Dummies', 'Packt OpenSource']
imageurls = ['grayhat.png', 'introtoalgo.png', 'propython.png', 'htmljs.png', 'nginx.png',
'redis.png', 'pythonfundamentals.png', 'lisp.png', 'ios.png', 'ror.png', 'djangoajax.png']
def main():
for i in range(len(titles)):
isbn = make_isbn()
new_book = Book(title=titles[i], isbn=isbn, ddc=randint(100,999), authors = authors[i],
publisher=publishers[i], cost=randint(300,700), imageurl=imageurls[i], pages=randint(300,700))
new_book.save()
print '\n%4d | ISBN: %s | Title: %s' % (i+1, isbn, titles[i])
for j in range(randint(5,10)):
book_number = randint(50000,900000)
book_copy = BookCopy(book_number=book_number, book_category=new_book)
book_copy.save()
print '%10d | Book Number: %-6d | Category: %s' % (j+1, book_number, new_book.title)
if __name__ == '__main__':
main()
```
manage.py::
```
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cope.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
```
|
2018/02/02
|
[
"https://Stackoverflow.com/questions/48579232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9298418/"
] |
Three things that you should make sure,
* are all the apps you have in your `INSTALLED_APPS` setting installed
on your system?
* Have you perhaps forgotten to activate the virtualenv
where everything was installed in the first place?
* If you have both of the things above on your system then maybe you
forgot to install the apps from requirements in your venv? You can do this by `pip install -r requirements.txt`
Replace `requirements.txt` with whatever your requirements file's name is. Make sure you do this after activating the virtual environment.
|
<https://www.dangtrinh.com/2014/11/how-to-avoid-models-arent-loaded-yet.html>
My advice would strongly be to perform this sort of operation within a Custom Management Command though <https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/>.
|
927,150
|
I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great.
The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it.
So my question is what is wrong with the code, and also whether I need to pass special parameters to ensymble?
```
import appuifw, e32, sensor, xprofile
from appuifw import *
old_profil = xprofile.get_ap()
def get_sensor_data(status):
#decide profile
def exit_key_handler():
# Disconnect from the sensor and exit
acc_sensor.disconnect()
app_lock.signal()
app_lock = e32.Ao_lock()
appuifw.app.exit_key_handler = exit_key_handler
appuifw.app.title = u"Acc Silent"
appuifw.app.menu = [(u'Close', app_lock.signal)]
appuifw.app.body = Canvas()
# Retrieve the acceleration sensor
sensor_type= sensor.sensors()['AccSensor']
# Create an acceleration sensor object
acc_sensor= sensor.Sensor(sensor_type['id'],sensor_type['category'])
# Connect to the sensor
acc_sensor.connect(get_sensor_data)
# Wait for sensor data and the exit event
app_lock.wait()
```
The script starts at boot, using ensymble and my developer certificate.
Thanks in advance
|
2009/05/29
|
[
"https://Stackoverflow.com/questions/927150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88054/"
] |
I often use something like that at the top of my scripts:
```
import os.path, sys
PY_PATH = None
for p in ['c:\\Data\\Python', 'e:\\Data\\Python','c:\\Python','e:\\Python']:
if os.path.exists(p):
PY_PATH = p
break
if PY_PATH and PY_PATH not in sys.path: sys.path.append(PY_PATH)
```
|
xprofile is not a standard library, make sure you add path to it. My guess is that when run as SIS, it doesn't find xprofile and hangs up. When releasing your SIS, either instruct that users install that separately or include inside your SIS.
Where would you have it installed, use that path. Here's python default directory as sample:
```
# PyS60 1.9.x and above
sys.path.append('c:\\Data\\Python')
sys.path.append('e:\\Data\\Python')
# Pys60 1.4.x or below
sys.path.append('c:\\Python')
sys.path.append('e:\\Python')
```
Btw make clean exit, do this:
```
appuifw.app.menu = [(u'Close', exit_key_handler)]
```
|
61,082,945
|
So, I'm learning python in school and as a part of my current project I want to be able to make small "popups" on the screen. I've chosen to do this with wxpython but I've run into a problem. Right now I can't find a way to add a variable so I can print anything I want. I tried adding an extra variable both to the class and the **init** function but get an error for both. I'm not used to classes or how they work and I would really appreciate some help. Here is the code I am using:
```
import wx
class HelloFrame(wx.Frame):
def __init__(self, *args, **kw):
super(HelloFrame, self).__init__(*args, **kw)
pnl = wx.Panel(self)
st = wx.StaticText(pnl, label = "Betting")
font = st.GetFont()
font.PointSize += 10
font = font.Bold()
st.SetFont(font)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(st, wx.SizerFlags().Border(wx.TOP|wx.LEFT, 25))
pnl.SetSizer(sizer)
self.makeMenuBar()
self.CreateStatusBar()
self.SetStatusText("Welcome to wxPython!")
def makeMenuBar(self):
fileMenu = wx.Menu()
helloItem = fileMenu.Append(-1, "&Hello...\tCtrl-H",
"Help string shown in status bar for this menu item")
fileMenu.AppendSeparator()
exitItem = fileMenu.Append(wx.ID_EXIT)
helpMenu = wx.Menu()
aboutItem = helpMenu.Append(wx.ID_ABOUT)
menuBar = wx.MenuBar()
menuBar.Append(fileMenu, "&file")
menuBar.Append(helpMenu, "&help")
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.OnHello, helloItem)
self.Bind(wx.EVT_MENU, self.OnExit, exitItem)
self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)
def OnExit(self, event):
self.Close(True)
def OnHello(self, event):
wx.MessageBox("Hello again from wxPython")
def OnAbout(self, event):
wx.MessageBox("This is a wxPython Hello World Sample", "About Hello World 2", wx.OK|wx.ICON_INFORMATION)
if __name__ == '__main__':
x = number()
app = wx.App()
frm = HelloFrame(None, title='Betting predictions')
frm.Show()
app.MainLoop()
```
Now I want to be able to input anything as a label into the `st = wx.StaticText(pnl, label = "Betting")`
Instead of just "Betting" and have it show whatever text I want but for the life of me I can't figure it out. This is a relatively small part of my project since I'm done and have some extra time but I would really like to get it to work.
|
2020/04/07
|
[
"https://Stackoverflow.com/questions/61082945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13250047/"
] |
You almost have it. You just need to straighten out a few details. First, if the input fails, you want an empty input:
```
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []
```
Now you want to repeat the input until it is valid. You first need the syntax for a while loop:
```
while <condition>:
<body>
```
Where `condition` evaluates to a boolean and `<body>` is the lines to repeat. In this case, you want to repeat the `try...except`.
```
def main():
while move != []:
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []
x = move[0]
y = move[1]
```
When you get stuck on syntax issues like this, I suggest you read the documentation and tutorials at <https://python.org>. They explain how to correctly write a while loop or try...except and more.
|
You could do this with a nested function and a recursive call if the input doesn't conform to expectations.
```py
import re
def main():
def prompt():
digits = input("Select a cell (row,col) > ")
if not re.match(r'\d+,\d+', digits):
print('Error message')
prompt()
return digits.split(',')
move = prompt()
x = move[0]
y = move[1]
main()
```
|
61,082,945
|
So, I'm learning python in school and as a part of my current project I want to be able to make small "popups" on the screen. I've chosen to do this with wxpython but I've run into a problem. Right now I can't find a way to add a variable so I can print anything I want. I tried adding an extra variable both to the class and the **init** function but get an error for both. I'm not used to classes or how they work and I would really appreciate some help. Here is the code I am using:
```
import wx
class HelloFrame(wx.Frame):
def __init__(self, *args, **kw):
super(HelloFrame, self).__init__(*args, **kw)
pnl = wx.Panel(self)
st = wx.StaticText(pnl, label = "Betting")
font = st.GetFont()
font.PointSize += 10
font = font.Bold()
st.SetFont(font)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(st, wx.SizerFlags().Border(wx.TOP|wx.LEFT, 25))
pnl.SetSizer(sizer)
self.makeMenuBar()
self.CreateStatusBar()
self.SetStatusText("Welcome to wxPython!")
def makeMenuBar(self):
fileMenu = wx.Menu()
helloItem = fileMenu.Append(-1, "&Hello...\tCtrl-H",
"Help string shown in status bar for this menu item")
fileMenu.AppendSeparator()
exitItem = fileMenu.Append(wx.ID_EXIT)
helpMenu = wx.Menu()
aboutItem = helpMenu.Append(wx.ID_ABOUT)
menuBar = wx.MenuBar()
menuBar.Append(fileMenu, "&file")
menuBar.Append(helpMenu, "&help")
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.OnHello, helloItem)
self.Bind(wx.EVT_MENU, self.OnExit, exitItem)
self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)
def OnExit(self, event):
self.Close(True)
def OnHello(self, event):
wx.MessageBox("Hello again from wxPython")
def OnAbout(self, event):
wx.MessageBox("This is a wxPython Hello World Sample", "About Hello World 2", wx.OK|wx.ICON_INFORMATION)
if __name__ == '__main__':
x = number()
app = wx.App()
frm = HelloFrame(None, title='Betting predictions')
frm.Show()
app.MainLoop()
```
Now I want to be able to input anything as a label into the `st = wx.StaticText(pnl, label = "Betting")`
Instead of just "Betting" and have it show whatever text I want but for the life of me I can't figure it out. This is a relatively small part of my project since I'm done and have some extra time but I would really like to get it to work.
|
2020/04/07
|
[
"https://Stackoverflow.com/questions/61082945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13250047/"
] |
You almost have it. You just need to straighten out a few details. First, if the input fails, you want an empty input:
```
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []
```
Now you want to repeat the input until it is valid. You first need the syntax for a while loop:
```
while <condition>:
<body>
```
Where `condition` evaluates to a boolean and `<body>` is the lines to repeat. In this case, you want to repeat the `try...except`.
```
def main():
while move != []:
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []
x = move[0]
y = move[1]
```
When you get stuck on syntax issues like this, I suggest you read the documentation and tutorials at <https://python.org>. They explain how to correctly write a while loop or try...except and more.
|
You can do it by this way:
```
def main():
print('Enter the two points as comma seperated, e.g. 3,4')
while True:
try:
x, y = map(int, input().split(','))
except ValueError:
print('Enter the two points as comma seperated, e.g. 3,4')
continue
else:
break
main()
```
|
2,622,866
|
How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])
```
if request.is_ajax() and request.method == 'GET':
groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"]))
groups = groupSet.groups.all()
group_items = [] #list
groups_and_items = {} #dictionary
for group in groups:
group_items.extend([group_item for group_item in group.group_items.all()])
#use group as Key name and group_items (LIST) as the value
groups_and_items[group] = group_items
data = serializers.serialize("json", groups_and_items)
return HttpResponse(data, mimetype="application/json")
```
the result:
```
[{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}]
```
while the group\_items should have many group\_item and each group\_item should have "name", rather than only the Id, in this case the Id is 13.
I need to serialize the group name, as well as the group\_item's Id and name as JSON and pass back to javascript.
I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)
|
2010/04/12
|
[
"https://Stackoverflow.com/questions/2622866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314614/"
] |
Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.
```
import json
groups_and_items = {}
for group in groups:
group_items = []
for item in group.group_items.all():
group_items.append( {'id': item.id, 'name': item.name} )
# <OR> if you just want a list of the group_item names
#group_items = group.group_items.all().values_list('name', flat=True)
groups_and_items[group.name] = group_items
data = json.dumps(groups_and_items)
```
What exactly did you want you want your data to look like? The above should give you `data` like this :
```
[{ 'groupA': [{'id': 1, 'name': 'item-1'}],
'groupB': [{'id': 2, 'name': 'item-2'}, ...],
'groupC': []
}]
```
Or this if you just want the list of group\_item names:
```
[{ 'groupA': ['item-1'],
'groupB': ['item-2', ...],
'groupC': []
}]
```
|
You should use Python's [json](http://docs.python.org/library/json.html) module to encode your JSON.
Also, what indentation level do you have `data = serializers` at? It looks like it could be inside the for loop?
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
Note that you are trying to print the contents of two lists. This is a linear operation in time. Two loops just won't cut it - that's quadratic in time complexity. Furthermore, your second solution doesn't flatten `y`.
---
Define a helper function using `yield` and `yield from`.
```
def foo(l1, l2):
for x, y in zip(l1, l2):
yield x
yield from y
for i in foo(num, let):
print(i)
1
a
b
2
c
3
d
e
f
4
g
5
h
```
If you want a list instead, just call `foo` with a `list` wrapper around it:
```
print(list(foo(num, let)))
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
Note that `yield from` becomes available to use from python3.3 onwards.
|
just `zip` the lists and flatten twice applying `itertools.chain`
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
import itertools
result = list(itertools.chain.from_iterable(itertools.chain.from_iterable(zip(num,let))))
```
now `result` yields:
```
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
which you can print with:
```
print(*result,sep="\n")
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
Note that you are trying to print the contents of two lists. This is a linear operation in time. Two loops just won't cut it - that's quadratic in time complexity. Furthermore, your second solution doesn't flatten `y`.
---
Define a helper function using `yield` and `yield from`.
```
def foo(l1, l2):
for x, y in zip(l1, l2):
yield x
yield from y
for i in foo(num, let):
print(i)
1
a
b
2
c
3
d
e
f
4
g
5
h
```
If you want a list instead, just call `foo` with a `list` wrapper around it:
```
print(list(foo(num, let)))
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
Note that `yield from` becomes available to use from python3.3 onwards.
|
Flatten the list `let` using `pydash`. [pydash](http://pydash.readthedocs.io/en/latest/) is a utility library.
Print each element from the concatenated list (`num + pydash.flatten(let)`)
```
>>> import pydash as pyd
>>> num = ["1" , "2" ,"3" , "4" , "5" ]
>>> let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
>>> for i in [str(j) for j in num + pyd.flatten(let)]:
... print(i)
1
2
3
4
5
a
b
c
d
e
f
g
h
>>>
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
Note that you are trying to print the contents of two lists. This is a linear operation in time. Two loops just won't cut it - that's quadratic in time complexity. Furthermore, your second solution doesn't flatten `y`.
---
Define a helper function using `yield` and `yield from`.
```
def foo(l1, l2):
for x, y in zip(l1, l2):
yield x
yield from y
for i in foo(num, let):
print(i)
1
a
b
2
c
3
d
e
f
4
g
5
h
```
If you want a list instead, just call `foo` with a `list` wrapper around it:
```
print(list(foo(num, let)))
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
Note that `yield from` becomes available to use from python3.3 onwards.
|
```
numlet = [c for n, l in zip(num,let) for c in [n] + l]
for c in numlet:
print(c)
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
Note that you are trying to print the contents of two lists. This is a linear operation in time. Two loops just won't cut it - that's quadratic in time complexity. Furthermore, your second solution doesn't flatten `y`.
---
Define a helper function using `yield` and `yield from`.
```
def foo(l1, l2):
for x, y in zip(l1, l2):
yield x
yield from y
for i in foo(num, let):
print(i)
1
a
b
2
c
3
d
e
f
4
g
5
h
```
If you want a list instead, just call `foo` with a `list` wrapper around it:
```
print(list(foo(num, let)))
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
Note that `yield from` becomes available to use from python3.3 onwards.
|
this solution assumes that "num" and "let" have the same number of elements
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for i in range(len(num)):
print num[i]
print '\n'.join(let[i])
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
just `zip` the lists and flatten twice applying `itertools.chain`
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
import itertools
result = list(itertools.chain.from_iterable(itertools.chain.from_iterable(zip(num,let))))
```
now `result` yields:
```
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
which you can print with:
```
print(*result,sep="\n")
```
|
Flatten the list `let` using `pydash`. [pydash](http://pydash.readthedocs.io/en/latest/) is a utility library.
Print each element from the concatenated list (`num + pydash.flatten(let)`)
```
>>> import pydash as pyd
>>> num = ["1" , "2" ,"3" , "4" , "5" ]
>>> let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
>>> for i in [str(j) for j in num + pyd.flatten(let)]:
... print(i)
1
2
3
4
5
a
b
c
d
e
f
g
h
>>>
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
just `zip` the lists and flatten twice applying `itertools.chain`
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
import itertools
result = list(itertools.chain.from_iterable(itertools.chain.from_iterable(zip(num,let))))
```
now `result` yields:
```
['1', 'a', 'b', '2', 'c', '3', 'd', 'e', 'f', '4', 'g', '5', 'h']
```
which you can print with:
```
print(*result,sep="\n")
```
|
this solution assumes that "num" and "let" have the same number of elements
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for i in range(len(num)):
print num[i]
print '\n'.join(let[i])
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
```
numlet = [c for n, l in zip(num,let) for c in [n] + l]
for c in numlet:
print(c)
```
|
Flatten the list `let` using `pydash`. [pydash](http://pydash.readthedocs.io/en/latest/) is a utility library.
Print each element from the concatenated list (`num + pydash.flatten(let)`)
```
>>> import pydash as pyd
>>> num = ["1" , "2" ,"3" , "4" , "5" ]
>>> let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
>>> for i in [str(j) for j in num + pyd.flatten(let)]:
... print(i)
1
2
3
4
5
a
b
c
d
e
f
g
h
>>>
```
|
46,366,139
|
Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for x in num :
print(x)
for y in let :
print(y)
zipBoth = zip(num,let)
for x,y in zipBoth :
print(x)
print(y)
```
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] |
```
numlet = [c for n, l in zip(num,let) for c in [n] + l]
for c in numlet:
print(c)
```
|
this solution assumes that "num" and "let" have the same number of elements
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
for i in range(len(num)):
print num[i]
print '\n'.join(let[i])
```
|
3,248,194
|
Whats wrong in this code?
Here is my HTML:
```
<html><body>
<form action="iindex.py" method="POST" enctype="multipart/form-data">
<p>File: <input type="file" name="ssfilename"></p>
<p><input type="submit" value="Upload" name="submit"></p>
</form>
</body></html>
```
This is my Python script:
```
#! /usr/bin/env python
import os, sys;
from mod_python import apache
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage(keep_blank_values=1)
fileitem = form["ssfilename"]
.....
```
This is the line where I get KeyError.
```
File "/Applications/MAMP/python/framework/Python.framework/Versions/2.6/lib/python2.6/cgi.py", line 541, in __getitem__
raise KeyError, key
KeyError: 'ssfilename'
```
|
2010/07/14
|
[
"https://Stackoverflow.com/questions/3248194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392373/"
] |
Edit: Totally missed the part where you are `doing keep_blank_values = 1`; sorry, no idea what is wrong.
From <http://docs.python.org/library/cgi.html>:
>
> Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep\_blank\_values keyword parameter when creating the FieldStorage instance.
>
>
>
Therefore, this is happening because this field was left blank.
|
Check if you have no GET parameters in your form action URL.
If you need to pass on any data put it as form elements inside the form to be POSTed along with your upload file.
Then you find all your POSTed vars in `cgi.FieldStorage`.
|
3,248,194
|
Whats wrong in this code?
Here is my HTML:
```
<html><body>
<form action="iindex.py" method="POST" enctype="multipart/form-data">
<p>File: <input type="file" name="ssfilename"></p>
<p><input type="submit" value="Upload" name="submit"></p>
</form>
</body></html>
```
This is my Python script:
```
#! /usr/bin/env python
import os, sys;
from mod_python import apache
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage(keep_blank_values=1)
fileitem = form["ssfilename"]
.....
```
This is the line where I get KeyError.
```
File "/Applications/MAMP/python/framework/Python.framework/Versions/2.6/lib/python2.6/cgi.py", line 541, in __getitem__
raise KeyError, key
KeyError: 'ssfilename'
```
|
2010/07/14
|
[
"https://Stackoverflow.com/questions/3248194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392373/"
] |
I had the exact same problem, make sure you have the "enctype" set to "multipart/form-data" and use a default value in your field. So your form should look like this:
```
<form enctype="multipart/form-data" id="addFile" action="AddFile.py">
<input type="file" name="file" id="file" value=""/><br/>
<input type="submit" name="submit" value="Add File"/><br/>
</form>
```
I was also using a JQuery handler for my Form and was trying to serialize it and then posting it to my python handler, I bypassed that and it was going all fine, so you should try that also.
|
Check if you have no GET parameters in your form action URL.
If you need to pass on any data put it as form elements inside the form to be POSTed along with your upload file.
Then you find all your POSTed vars in `cgi.FieldStorage`.
|
59,432,477
|
I am working through an issue with scraping a webtable using python. I have been scraping what I would call 'standard' tables for a while and I feel like I understand that reasonably well. I define a standard table as having a structure like:
```
<table>
<tr class="row-class">
<th>Bill</th>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>
</table>
```
I have now come across a table instance which has a slightly different structure and I can't figure out how to get the data out of it in the format I need. The format I am now trying to scrape is:
```
<table>
<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>
</table>
```
The output I am trying to achieve is:
```
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
```
I assume the problem I am encountering is that because the header is stored in a separate tr row, I only get an output of:
```
Bill
Ben
Barry
```
I am wondering if the solution is to traverse the rows and determine if the next tag is a th or td and then perform an appropriate action? I'd appreciate any advice on how the code I am using to test this could be modified to achieve the desired output. The code is:
```
from bs4 import BeautifulSoup
t_obj = """<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>"""
soup = BeautifulSoup(t_obj)
trs = soup.find_all("tr", {"class":"row-class"})
for tr in trs:
for th in tr.findAll('th'):
print (th.get_text())
for td in tr.findAll('td'):
print(td.get_text())
print(td.get_text())
```
|
2019/12/20
|
[
"https://Stackoverflow.com/questions/59432477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10862305/"
] |
Here I use 3 methods how to pair the two `<tr>` tags together:
* 1st method is using `zip()` and CSS selector
* 2nd method is using BeautifulSoup's method `find_next_sibling()`
* 3rd method is using `zip()` and simple slicing with custom step
---
```
from bs4 import BeautifulSoup
t_obj = """<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>"""
soup = BeautifulSoup(t_obj, 'html.parser')
for tr1, tr2 in zip(soup.select('tr.row-class'), soup.select('tr.row-class ~ tr:not(.row-class)')):
print( ','.join(tag.get_text() for tag in tr1.select('th') + tr2.select('td')) )
print()
for tr in soup.select('tr.row-class'):
print( ','.join(tag.get_text() for tag in tr.select('th') + tr.find_next_sibling('tr').select('td')) )
print()
trs = soup.select('tr')
for tr1, tr2 in zip(trs[::2], trs[1::2]):
print( ','.join(tag.get_text() for tag in tr1.select('th') + tr2.select('td')) )
```
Prints:
```
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
```
|
You can use indexing:
```
from bs4 import BeautifulSoup as soup
d = soup(html, 'html.parser').find_all('tr')
result = [[d[i].text]+[c.text for c in d[i+1].find_all('td')] for i in range(0, len(d), 2)]
```
To print your result:
```
print('\n'.join(f'{a[1:]},{",".join(b)}' for a, *b in result))
```
Output:
```
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
```
|
59,432,477
|
I am working through an issue with scraping a webtable using python. I have been scraping what I would call 'standard' tables for a while and I feel like I understand that reasonably well. I define a standard table as having a structure like:
```
<table>
<tr class="row-class">
<th>Bill</th>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>
</table>
```
I have now come across a table instance which has a slightly different structure and I can't figure out how to get the data out of it in the format I need. The format I am now trying to scrape is:
```
<table>
<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>
</table>
```
The output I am trying to achieve is:
```
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
```
I assume the problem I am encountering is that because the header is stored in a separate tr row, I only get an output of:
```
Bill
Ben
Barry
```
I am wondering if the solution is to traverse the rows and determine if the next tag is a th or td and then perform an appropriate action? I'd appreciate any advice on how the code I am using to test this could be modified to achieve the desired output. The code is:
```
from bs4 import BeautifulSoup
t_obj = """<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>"""
soup = BeautifulSoup(t_obj)
trs = soup.find_all("tr", {"class":"row-class"})
for tr in trs:
for th in tr.findAll('th'):
print (th.get_text())
for td in tr.findAll('td'):
print(td.get_text())
print(td.get_text())
```
|
2019/12/20
|
[
"https://Stackoverflow.com/questions/59432477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10862305/"
] |
Here I use 3 methods how to pair the two `<tr>` tags together:
* 1st method is using `zip()` and CSS selector
* 2nd method is using BeautifulSoup's method `find_next_sibling()`
* 3rd method is using `zip()` and simple slicing with custom step
---
```
from bs4 import BeautifulSoup
t_obj = """<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>"""
soup = BeautifulSoup(t_obj, 'html.parser')
for tr1, tr2 in zip(soup.select('tr.row-class'), soup.select('tr.row-class ~ tr:not(.row-class)')):
print( ','.join(tag.get_text() for tag in tr1.select('th') + tr2.select('td')) )
print()
for tr in soup.select('tr.row-class'):
print( ','.join(tag.get_text() for tag in tr.select('th') + tr.find_next_sibling('tr').select('td')) )
print()
trs = soup.select('tr')
for tr1, tr2 in zip(trs[::2], trs[1::2]):
print( ','.join(tag.get_text() for tag in tr1.select('th') + tr2.select('td')) )
```
Prints:
```
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
Bill,1,2,3,4
Ben,2,3,4,1
Barry,3,4,1,2
```
|
Process HTML to fit
```
from simplified_scrapy.simplified_doc import SimplifiedDoc
t_obj = """<tr class="row-class">
<th>Bill</th></tr>
<tr><td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row-class">
<th>Ben</th></tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>1</td>
</tr>
<tr class="row-class">
<th>Barry</th></tr>
<tr>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
</tr>"""
doc = SimplifiedDoc()
doc.loadHtml(doc.replaceReg(t_obj,"</tr>\s*<tr>",''))# merge tr
trs = doc.trs # get all tr
for tr in trs:
tds = tr.children # get td and th
data = [td.text for td in tds]
print (data)
```
result:
```
['Bill', '1', '2', '3', '4']
['Ben', '2', '3', '4', '1']
['Barry', '3', '4', '1', '2']
```
|
10,061,124
|
I once read this entry in mailing list <http://archives.postgresql.org/pgsql-hackers/2005-06/msg01481.php>
```
SELECT *
FROM foo_func(
c => current_timestamp::timestamp with time zone,
a => 2,
b => 5
);
```
Now I need this kindof solution where I can pass associative array argument to a function.
Do I need to make a dummy table and then use that table as argument type ? or there is any straight forward fix for this ? or has this hack been implemented ?
or can I emulate the same using pl/python ?
|
2012/04/08
|
[
"https://Stackoverflow.com/questions/10061124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256007/"
] |
If you have `a` as your clustering key, then that column is included in all non-clustered indices on that table.
So your index on `c` also includes `a`, so the condition
```
where c= 3 and a = 3
```
can be found in that index using an index seek. Most likely, the query optimizer decided that doing a index seek to find `a` and `c` and a key lookup to get the rest of the data is faster/more efficient here than using an index scan.
BTW: why did you expect / prefer an index scan over an index seek? The index seek typically is faster and uses a lot less resources - I would always strive to get index seeks over scans.
|
>
> *This is fine, because the non clustered index doesn't have b as the key value. Hence it does an index scan from column a.*
>
>
>
This assumption is not right. index seek and scan has to deal with WHERE clause and not the select clause.
Now your question -
Where clause is optimised by sql optimizer and as there is a=3 condition, clustered index can be applied.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.