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
35,859,927
For say in terminal I did `cd Desktop` you should know it moves you to that directory, but how do I do that in python but with use Desktop with `raw_input("")` to pick my command?
2016/03/08
[ "https://Stackoverflow.com/questions/35859927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your code structure is very unconventional and I suspect you're rather new to scheme/racket. Your procedure can be written in a much more idiomatic way. The first criticism I'd probably make about your code is that it makes the assumption that the lists you're unzipping will only have 2 elements each. * What about unzipping 3 lists of 5 elements or 5 lists of 3 elements ? * What about unzipping 4 lists of 4 elemens ? * What about unzipping 1 list of 7 elements or 7 lists of 1 element ? * What about unzipping nothing ? These questions all point to a fundamental concept that helps shape well-structured procedures: ***"What is a "total" procedure ?"*** A **total procedure** is one that is defined for all values of an accepted type. What that means to us is that, if we write an `unzip` procedure, it should * accept an empty list * accept any number of lists * accept lists of any length1 Let's take a look at an `unzip` procedure that does that now. It's likely this procedure can be improved, but at the very least, it's easy to read and comprehend ``` (define (unzip xs (ys empty)) ; if no xs are given, return ys (cond [(empty? xs) empty] ; if the first input is empty, return the final answer; reversed [(empty? (car xs)) (reverse ys)] ; otherwise, unzip the tail of each xs, and attach each head to ys [else (unzip (map cdr xs) (cons (map car xs) ys))])) (unzip '((1 2) (3 4) (5 6))) ; => '((1 3 5) (2 4 6)) ``` Let's step through the evaluation. ``` ; initial call (unzip '((1 2) (3 4) (5 6))) ; (empty? xs) nope ; (empty? (car xs)) nope ; (unzip (map cdr xs) (cons (map car xs) ys)) ; substitue values (unzip (map cdr '((1 2) (3 4) (5 6))) (cons (map car '((1 2) (3 4) (5 6))) empty)) ; eval (map cdr xs) (unzip '((2) (4) (6)) (cons (map car '((1 2) (3 4) (5 6))) empty)) ; eval (map car xs) (unzip '((2) (4) (6)) (cons '(1 3 5) empty)) ; eval cons ; then recurse unzip (unzip '((2) (4) (6)) '((1 3 5))) ; (empty? xs) nope ; (empty? (car xs)) nope ; (unzip (map cdr xs) (cons (map car xs) ys)) ; substitue values (unzip (map cdr '((2) (4) (6))) (cons (map car '((2) (4) (6))) '((1 3 5)))) ; eval (map cdr xs) (unzip '(() () ()) (cons (map car '((2) (4) (6))) '((1 3 5)))) ; eval (map car xs) (unzip '(() () ()) (cons '(2 4 5) '((1 3 5)))) ; eval cons ; then recurse (unzip '(() () ()) '((2 4 5) (1 3 5))) ; (empty? xs) nope ; (empty? (car xs)) yup! ; (reverse ys) ; substituion (reverse '((2 4 5) (1 3 5))) ; return '((1 3 5) (2 4 5)) ``` Here's another thing to think about. Did you notice that `unzip` is basically doing the same thing as `zip` ? Let's look at your input little closer ``` '((1 2) (3 4) (5 6)) ^ ^ ``` Look at the columns. If we were to `zip` these, we'd get ``` '((1 3 5) (2 4 6)) ``` ***"Wait, so do you mean that a `unzip` is just another `zip` and vice versa ?"*** Yup. ``` (unzip '((1 2) (3 4) (5 6))) ; => '((1 3 5) (2 4 6)) (unzip (unzip '((1 2) (3 4) (5 6)))) ; '((1 2) (3 4) (5 6)) (unzip (unzip (unzip '((1 2) (3 4) (5 6))))) ; '((1 3 5) (2 4 6)) ``` Knowing this, if you already had a `zip` procedure, your definition to `unzip` becomes insanely easy ``` (define unzip zip) ``` Which basically means: **You don't need an `unzip` procedure**, just re-`zip` it ``` (zip '((1 2) (3 4) (5 6))) ; => '((1 3 5) (2 4 6)) (zip (zip '((1 2) (3 4) (5 6)))) ; '((1 2) (3 4) (5 6)) (zip (zip (zip '((1 2) (3 4) (5 6))))) ; '((1 3 5) (2 4 6)) ``` Anyway, I'm guessing your `unzip` procedure implementation is a bit of homework. The long answer your professor is expecting is probably something along the lines of the procedure I originally provided. The sneaky answer is `(define unzip zip)` --- ***"So is this `unzip` procedure considered a total procedure ?"*** * What about unzipping 3 lists of 5 elements or 5 lists of 3 elements ? ``` (unzip '((a b c d e) (f g h i j) (k l m n o p))) ; => '((a f k) (b g l) (c h m) (d i n) (e j o)) (unzip '((a b c) (d e f) (g h i) (k l m) (n o p))) ; => '((a d g k n) (b e h l o) (c f i m p)) ``` * What about unzipping 4 lists of 4 elemens ? ``` (unzip '((a b c d) (e f g h) (i j k l) (m n o p))) ; => '((a e i m) (b f j n) (c g k o) (d h l p)) ``` * What about unzipping 1 list of 7 elements or 7 lists of 1 element ? ``` (unzip '((a b c d e f g))) ; => '((a) (b) (c) (d) (e) (f) (g)) (unzip '((a) (b) (c) (d) (e) (f) (g))) ; => '((a b c d e f g)) ``` * What about unzipping nothing ? ``` (unzip '()) ; => '() ``` * What about unzipping 3 empty lists ? ``` (unzip '(() () ())) ; => '() ``` > > **1** We said that `unzip` should "accept lists of any length" but we're bending the rules just a little bit here. It's true that `unzip` accepts lists of any length, but it's also true that each list much be the same length as the others. For lists of varying length, an objective "correct" solution is not possible and for this lesson, we'll leave the behavior for mixed-length lists as *undefined*. > > > > ``` > ; mixed length input is undefined > (unzip '((a) (b c d) (e f))) ; => ??? > > ``` > > --- **A couple side notes** Things like ``` (car (car x)) (car (cdr (car x))) ``` Can be simplified to ``` (caar x) (cadar x) ``` The following [pair accessor short-hand procedures](https://docs.racket-lang.org/reference/pairs.html#%28part._.Pair_.Accessor_.Shorthands%29) exist ``` caar ; (car (car x)) cadr ; (car (cdr x)) cdar ; (cdr (car x)) cddr ; (cdr (cdr x)) caaar ; (car (car (car x))) caadr ; (car (car (cdr x))) cadar ; (car (cdr (car x))) caddr ; (car (cdr (cdr x))) cdaar ; (cdr (car (car x))) cdadr ; (cdr (car (cdr x))) cddar ; (cdr (cdr (car x))) cdddr ; (cdr (cdr (cdr x))) caaaar ; (car (car (car (car x)))) caaadr ; (car (car (car (cdr x)))) caadar ; (car (car (cdr (car x)))) caaddr ; (car (car (cdr (cdr x)))) cadaar ; (car (cdr (car (car x)))) cadadr ; (car (cdr (car (cdr x)))) caddar ; (car (cdr (cdr (car x)))) cadddr ; (car (cdr (cdr (cdr x)))) cdaaar ; (cdr (car (car (car x)))) cdaadr ; (cdr (car (car (cdr x)))) cdadar ; (cdr (car (cdr (car x)))) cdaddr ; (cdr (car (cdr (cdr x)))) cddaar ; (cdr (cdr (car (car x)))) cddadr ; (cdr (cdr (car (cdr x)))) cdddar ; (cdr (cdr (cdr (car x)))) cddddr ; (cdr (cdr (cdr (cdr x)))) ```
It is combining the lists correctly, but it's not combining the correct lists. Extracting the local definitions makes them testable in isolation: ``` (define (front a) (if (null? a) '() (cons (car (car a)) (unzip (cdr a))))) (define (back b) (if (null? b) '() (cons (car (cdr (car b))) (unzip (cdr b))))) (define (unzip l) (list (front l) (back l))) (define test '((1 2) (3 4) (5 6))) ``` Test: ``` > (front test) '(1 (3 (5 () ()) (6 () ())) (4 (5 () ()) (6 () ()))) > (front '((1 2))) '(1 () ()) > (back '((1 2))) '(2 () ()) ``` Weird... ``` > (unzip '()) '(() ()) > (unzip '((1 2))) '((1 () ()) (2 () ())) ``` It looks like *something* is correct, but the lists' tails are wrong. If you look carefully at the definitions of `front` and `back`, they're recursing to `unzip`. But they should recurse to themselves - `front` is the "first first" followed by the rest of the "firsts", and `back` is the "first second" followed by the rest of the "seconds". `unzip` has nothing to do with this. ``` (define (front a) (if (null? a) '() (cons (car (car a)) (front (cdr a))))) (define (back b) (if (null? b) '() (cons (car (cdr (car b))) (back (cdr b))))) ``` And now... ``` > (front test) '(1 3 5) > (back test) '(2 4 6) > (unzip test) '((1 3 5) (2 4 6)) ```
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
This usually happens when you're opening someone else's project after unzipping it and your current Android Studio Version is older to the version the project was compiled in. The way to solve it is 1. Go to Help and about to see your android studio version 2. go to File>Project Structure> and set your Android Gradle Plugin version to your android studio version 3. Change the Gradle version to the one you usually use. Build the project and it should run without any errors **Edit**: It is tough to get the android gradle plugin version directly due to the new naming convention going forward(2020.3.1). Refer to this guide for such cases [Android Gradle plugin release](https://developer.android.com/studio/releases/gradle-plugin) or use an older Gradle Plugin like 4.2. If it is higher than 7.0.0 use 7.0.2 or 7.0.3 If everything else fails download the Android Studio Canary build and run your project there **EDIT FEB 2022** Sometimes when you go to File>Project Structure> the Gradle plugin will not show the option. In this case go to the project level build.gradle file Change the below ``` id 'com.android.application' version '7.0.3' apply false id 'com.android.library' version '7.0.2' apply false id 'org.jetbrains.kotlin.android' version '1.5.21' apply false ``` versions from whatever you have to a lower one. (make sure that it exists).
Check the version of Android Studio, or the IDEA Plugin. For example, Android Studio **4.0** and Android Plugin 10.**4.0** require a 4.0.x version of the Android tools. Therefore in build.gradle, change e.g. `com.android.tools.build:gradle:4.2.0-beta2"` to `com.android.tools.build:gradle:4.0.2"`. **Update:** This doesn't apply for 7+ as IntelliJ have changed their version numbers to be date-based. Tools version 7.1 works with Android Studio/Plugin 2021.1, and 7.0 works with 2020.3.
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
Check the version of Android Studio, or the IDEA Plugin. For example, Android Studio **4.0** and Android Plugin 10.**4.0** require a 4.0.x version of the Android tools. Therefore in build.gradle, change e.g. `com.android.tools.build:gradle:4.2.0-beta2"` to `com.android.tools.build:gradle:4.0.2"`. **Update:** This doesn't apply for 7+ as IntelliJ have changed their version numbers to be date-based. Tools version 7.1 works with Android Studio/Plugin 2021.1, and 7.0 works with 2020.3.
The error message says: > > This version of the Android Support plugin for IntelliJ IDEA (or > Android Studio) cannot open this project, please retry with version > 4.2 or newer. > > > And as you can clearly see from the error message, it's happening because Android Studio (**also known as "Android Support Plugin for IntelliJ IDEA"** because Android Studio is basically IntelliJ IDEA IDE with that extra plugin) cannot open the project. The reason why it cannot open the project is also stated above -- it's because the project was created with Android Studio 4.2 and your current version is older than 4.2. So, the proper and non-hacky way of solving the problem is obviously updating your Android Studio. Go here: <https://developer.android.com/studio>, download the latest version and install it.
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
**Simply update your android studio** go to Help > check for updates > update and restart.
I have faced the same issue and it will resolve in two ways 1. Change the gradle version in *Project-Level* **build.gradle** Earlier i have used below one ``` classpath 'com.android.tools.build:gradle:4.1.2' ``` Now changed with ``` classpath 'com.android.tools.build:gradle:4.2.1' ``` 2. Update your Android Studio as per latest version available
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
**kindly change your class path if you are using older version of android studio** ``` classpath 'com.android.tools.build:gradle:7.0.4' ``` **to** ``` classpath "com.android.tools.build:gradle:4.2.1" ``` **or remain the class path to 7.0.4 and update your android studio**
Change gradle version into build.gradel file (inside of app). ``` classpath "com.android.tools.build:gradle:4.0.2" ```
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
Another way to update your studio is go to **File>Settings>Appearance and Behavior> System Settings> Updates>** Check "**Automatically check for updates**" box. Select your channel (**stable** for stable updates) and click **check now**. Wait once update is complete you can run your project.
in my case i change **project level of build.gradle** classpath "com.android.tools.build:gradle:4.1.1" and in **gradle-wrapper.properties** distributionUrl=https://services.gradle.org/distributions/gradle-6.5-all.zip you can easily fix this issue by changing this way,you can create a new project and just checked the running project what exactly version taking then you can do just copy paste of these two codes in your project
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
In my case, the solution was simple, update Android Studio to the last version (Bumblebee)
In my case I created the project in android preview version and when I opened the project in stable android studio I got this issue, I updated the stable android studio to latest version and it asked me to update the project. After this the problem was fixed.
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
**kindly change your class path if you are using older version of android studio** ``` classpath 'com.android.tools.build:gradle:7.0.4' ``` **to** ``` classpath "com.android.tools.build:gradle:4.2.1" ``` **or remain the class path to 7.0.4 and update your android studio**
I have faced the same issue and it will resolve in two ways 1. Change the gradle version in *Project-Level* **build.gradle** Earlier i have used below one ``` classpath 'com.android.tools.build:gradle:4.1.2' ``` Now changed with ``` classpath 'com.android.tools.build:gradle:4.2.1' ``` 2. Update your Android Studio as per latest version available
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
If u r here because of Android Jetpack Compose, I have solved that problem by using the Arctic Fox Canary Build u can download it from here: <https://redirector.gvt1.com/edgedl/android/studio/ide-zips/2020.3.1.12/android-studio-2020.3.1.12-mac.zip>
Change gradle version into build.gradel file (inside of app). ``` classpath "com.android.tools.build:gradle:4.0.2" ```
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
**Simply update your android studio** go to Help > check for updates > update and restart.
Simply Update Android Studio or downgrade gradle version...
62,678,802
I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible? I am assuming the best bet would be to transform the .py file into a .exe file but am unsure of how to do this if I have packages that need to be installed before the program can be run. Are there websites that exist that allow you to easily host complex .py files on them to be run by anyone that accesses the URL?
2020/07/01
[ "https://Stackoverflow.com/questions/62678802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12512519/" ]
**Simply update your android studio** go to Help > check for updates > update and restart.
In my case, the solution was simple, update Android Studio to the last version (Bumblebee)
55,125,763
I'm trying to find the size, *in points*, of some text using Pillow in python. As I understand it, font sizes in points correspond to real physical inches on a target display or surface, with 72 points per inch. When I use Pillow's `textsize` method, I can find the size in pixels of some text rendered at a given font size (in points), but don't know how to get back to a coordinate system based in inches, because I don't have (and can't set) the pixel density of the image: ``` from PIL import Image, ImageFont, ImageDraw image = Image.new('RGBA', (400, 300), (255, 255, 255)) font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 16) image.info['dpi'] = 100 print( ImageDraw.Draw(image).textsize('Loreum ipsum', font=font) ) image.info['dpi'] = 1000 print( ImageDraw.Draw(image).textsize('Loreum ipsum', font=font) ) ``` will print ``` (101, 18) (101, 18) ``` How do I get the size *in points* of the given text?
2019/03/12
[ "https://Stackoverflow.com/questions/55125763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10686733/" ]
**TL;DR** There is no implicit pixel density, because the Pillow documentation is incorrect. When you create the font, you are specifying the `size` in *pixels* even though the Pillow documentation says it's in points. It's actually doing all of these operations in pixels. **More detail** The Pillow documentation for `ImageFont.truetype` says that the `size` argument is in points. However, looking at the [source](https://github.com/python-pillow/Pillow/blob/44da2c3878c9def8a103b19b0915aa774985aee1/src/PIL/ImageFont.py#L193) for the `ImageFont` module, it passes the `size` argument to `core.getfont`. ``` self.font = core.getfont( font, size, index, encoding, layout_engine=layout_engine ) ``` That call [ultimately leads](https://github.com/python-pillow/Pillow/blob/44da2c3878c9def8a103b19b0915aa774985aee1/src/_imagingft.c#L313) to a call to `FT_Set_Pixel_Sizes`, which is provided by the FreeType library. This call forwards the given `size`, unmodified. ``` error = FT_Set_Pixel_Sizes(self->face, 0, size); ``` The [documentation](https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#ft_set_pixel_sizes) for `FT_Set_Pixel_Sizes` states > > > ``` > FT_EXPORT( FT_Error ) > FT_Set_Pixel_Sizes( FT_Face face, > FT_UInt pixel_width, > FT_UInt pixel_height ); > > ``` > > Call FT\_Request\_Size to request the nominal size (in **pixels**). > > > `face` A handle to the target face object. > > > `pixel_width` The nominal width, in **pixels**. > > > `pixel_height` The nominal height, in **pixels**. > > > So really there are no physical distances involved here at all, and there is no assumed DPI for either `ImageFont.truetype` or `ImageDraw.textsize`, despite the misleading Pillow documentation. Everything is in pixels, so no DPI is required. **Sidenote**: You may notice that the size you requested (16) is not exactly equal to the size you are getting back (18), but FreeType mentions that the size you ask for is not necessarily the size you get, and is at the discretion of the font itself.
Image don't have an "implicit" pixel density, they just have different number of pixels. The size of anything measured in pixels will depend on the display device's DPI or dots-per-inch. For example on a 100 DPI device, 12 pixels would appear to be 12/100 or 0.12 inches long. To convert inches to points, multiply them by 72. So 12 pixels β†’ 0.12 inches \* 72 β†’ 8.84 points.
39,980,658
I am starting to work with the [Django REST framework](http://www.django-rest-framework.org/) for a mini-reddit project I already developed. The problem is that I am stuck in this situation: A `Minisub` is like a subreddit. It has, among others, a field named `managers` which is `ManyToMany` with `User`. An `Ad` is an advertising which will be displayed on the minisub, and it has a field named `minisubs` which is `ManyToMany` with `Minisub`. It has also a `author` field, foreign key with `User`. I would like to allow these managers to add some ads on their minisubs through a DRF API. It is actually working. But I want to check that they put in `minisubs` only minisubs where they are managers. I found a way like that: ```python class AdSerializer(serializers.HyperlinkedModelSerializer): # ... def validate_minisubs(self, value): for m in value: if user not in m.managers.all(): raise serializers.ValidationError("...") return value ``` My question is: How to get `user` ? I can't find a way to get the value `Ad.author` (this field is set automatically in the serial data according to the user authentication). Maybe I don't find a way because there is no ways ? The place to do this is somewhere else ? Thanks in advance.
2016/10/11
[ "https://Stackoverflow.com/questions/39980658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595458/" ]
You may get it out of the serializer this way: ``` class YourModelSeializer(serializers.HyperlinkedModelSerializer): class Meta: model=YourModel def validate_myfield(self): instance = getattr(self, 'instance', None) ... ```
I believe that this is a job for the [permissions](http://www.django-rest-framework.org/api-guide/permissions/#permissions), if you are performing CRUD operations for inserting that into a database then u can have a permission class returns `True` if the user is a manager. a permissions instance has access to the request which u can use to get the user and check if he is a manager: <http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions>
33,722,333
It is very nice and easy to run Python from the command line. Especially for testing purposes. The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters. ``` $ python >>> from foo import bar >>> from package.file import Class >>> c = Class >>> c.name = "John" >>> c.age = 33 >>> c.function() >>> from datetime import timedelta, datetime >>> now = datetime.now().year() >>> next_year = now + timedelta(year=1) >>> etc... ``` Can someone tell me if there is an easier way then doing all the work over and over again every time I make a change in the Python code?
2015/11/15
[ "https://Stackoverflow.com/questions/33722333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039579/" ]
You could consider turning your testing into an actual python script. which can be run like this, and then checking the output ``` $ python my_tests.py ``` However, a much better way would be to write some unit tests which you can run in a similar way. <https://docs.python.org/2/library/unittest.html>. The unittest framework will run all the tests you've defined and gather the results into a report. If you need some steps to be done interactively, then you can achieve that by writing your setup into a script, and then executing the script before doing your interactive tests. See this other SO question: [Is there a possibility to execute a Python script while being in interactive mode](https://stackoverflow.com/questions/4624416/is-there-a-posibility-to-execute-a-python-script-while-being-in-interactive-mode)
Use IPython with a [notebook](http://jupyter.org/) instead. Much better for interactive computing.
33,722,333
It is very nice and easy to run Python from the command line. Especially for testing purposes. The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters. ``` $ python >>> from foo import bar >>> from package.file import Class >>> c = Class >>> c.name = "John" >>> c.age = 33 >>> c.function() >>> from datetime import timedelta, datetime >>> now = datetime.now().year() >>> next_year = now + timedelta(year=1) >>> etc... ``` Can someone tell me if there is an easier way then doing all the work over and over again every time I make a change in the Python code?
2015/11/15
[ "https://Stackoverflow.com/questions/33722333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039579/" ]
Use IPython with a [notebook](http://jupyter.org/) instead. Much better for interactive computing.
Going for IPython as well. You can write a script which will enter an interactive shell at any point in any frame, for example: ``` import IPython from foo import bar from package.file import Class c = Class c.name = "John" c.age = 33 c.function() from datetime import timedelta, datetime now = datetime.now().year() next_year = now + timedelta(year=1) IPython.embed() ``` Then simply run your script with python, and you'll get an interactive shell at the end.
33,722,333
It is very nice and easy to run Python from the command line. Especially for testing purposes. The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters. ``` $ python >>> from foo import bar >>> from package.file import Class >>> c = Class >>> c.name = "John" >>> c.age = 33 >>> c.function() >>> from datetime import timedelta, datetime >>> now = datetime.now().year() >>> next_year = now + timedelta(year=1) >>> etc... ``` Can someone tell me if there is an easier way then doing all the work over and over again every time I make a change in the Python code?
2015/11/15
[ "https://Stackoverflow.com/questions/33722333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039579/" ]
You could consider turning your testing into an actual python script. which can be run like this, and then checking the output ``` $ python my_tests.py ``` However, a much better way would be to write some unit tests which you can run in a similar way. <https://docs.python.org/2/library/unittest.html>. The unittest framework will run all the tests you've defined and gather the results into a report. If you need some steps to be done interactively, then you can achieve that by writing your setup into a script, and then executing the script before doing your interactive tests. See this other SO question: [Is there a possibility to execute a Python script while being in interactive mode](https://stackoverflow.com/questions/4624416/is-there-a-posibility-to-execute-a-python-script-while-being-in-interactive-mode)
Going for IPython as well. You can write a script which will enter an interactive shell at any point in any frame, for example: ``` import IPython from foo import bar from package.file import Class c = Class c.name = "John" c.age = 33 c.function() from datetime import timedelta, datetime now = datetime.now().year() next_year = now + timedelta(year=1) IPython.embed() ``` Then simply run your script with python, and you'll get an interactive shell at the end.
32,616,406
I'm writing a python application that allows users to write their own plugins and extend the core functionality I provide - ``` $ tree project_dir/ . β”œβ”€β”€ application.py β”œβ”€β”€ plugins β”‚Β Β  β”œβ”€β”€ __init__.py β”‚Β Β  β”œβ”€β”€ example_plugin.py β”‚Β Β  β”œβ”€β”€ plugin1.py β”‚Β Β  β”œβ”€β”€ plugin2.py β”‚Β Β  └── plugin3 β”‚Β Β  β”œβ”€β”€ sounds β”‚Β Β  β”‚Β Β  └── test.wav β”‚Β Β  └── player.py └── plugins_manager.py ``` plugins\_manager.py - ``` class Manager(object): def __init__(self): self.plugins = {} def register_plugin(self, name, plugin_func): self.plugins[name] = plugin_func ``` application.py initializes `Manager` instance globally - ``` manager = Manager() def main(): print manager.plugins main() ``` Each plugin is required to import the `Manager` instance from `application.py` and register itself like, plugin1.py - ``` from application import manager PLUGIN_NAME = "AAC_Player" def plugin_function(options): # do something manager.register_plugin(PLUGIN_NAME, plugin_function) ``` Now when I run application.py, obviously nothing gets printed. How do I make the plugins register themselves (call `.register_plugin()`) at program startup? So on that lines, a more generalised question would be - How can I make python execute a line of code that's global in a file without actually running the file? Suggestions on improving the plugin architecture welcome!
2015/09/16
[ "https://Stackoverflow.com/questions/32616406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2417277/" ]
You can use the `__import__()` builtin to import the plugins, and then include the `register_plugin()` call in either the plugin file `example_plugin.py` or in `__init__.py` if it's a directory. For example, let's say this is your project structure: ``` ./ application.py plugins_manager.py plugins/ __init__.py plugin1.py plugin2.py plugin3/ __init__.py ``` Plugins have these contents: ``` $ cat plugins/plugin1.py print 'Plugin 1' $ cat plugins/plugin2.py print 'Plugin 2' $ cat plugins/plugin3/__init__.py print 'Plugin 3' ``` In `plugins_manager.py`, identify the plugins and import them in: ```py from os import listdir from os.path import exists, isdir, basename, join, splitext def is_plugin(filename): filepath = join('plugins', filename) _, ext = splitext(filepath) # Ignore plugins/__init__.py if filename == '__init__.py': return False # Find single file plugins if ext == '.py': return True # Find plugins packaged in directories if isdir(filepath) and exists(join(filepath, '__init__.py')): return True return False plugin_names = [ splitext(p)[0] for p in listdir('plugins/') if is_plugin(p) ] plugins = [ __import__('plugins.' + p) for p in plugin_names ] ``` Should get output similar to: ``` Plugin 1 Plugin 2 Plugin 3 ``` Note that in this case the `plugins` variable contains a list of the module objects imported.
Strictly speaking I'd say there is no way to run code without it being invoked somehow. To do this, the running program can use ``` import importlib ``` so that once you've found the file you can import it with: ``` mod = importlib.import_module(import_name, pkg_name) ``` and if that file provides a known function (Run in this case) you can call it with: ``` mod.Run(your_args) ``` This works for Python 2.7. Version 3 might be different.
50,716,680
I have a file with contents like this (I don't wish to change the contents of the file in any way): ``` . . lines I don't need. . . abc # I know where it starts and the data can be anything, not just abc efg # I know where it ends. . . lines I don't need. . . ``` I know the line numbers (index) from where my useful data starts and ends. The useful lines can have any unpredictable data. Now I wish to make a list out of this data, like this: ``` [['a','b','c'],['e','f','g']] ``` Please note that there are no spaces in between a, b and so on in the input file so i guess the split() function won't work. What would be the best way to achieve this in python?
2018/06/06
[ "https://Stackoverflow.com/questions/50716680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6027453/" ]
I **guess** the compiler error that you see is referring to the fact that you are using `listener` into it's own defining context. Try this for a change: In UserManager: ``` func allUsers(completion:@escaping ([User])->Void) -> ListenerRegistration? { return db.collection("users").addSnapshotListener { querySnapshot, error in if let documents = querySnapshot?.documents { var users = [User]() for document in documents { let user = User(snapshot: document) users.append(user) } completion(users) } } } ``` In ViewController: ``` override func viewDidLoad() { super.viewDidLoad() self.listener = UserManager.shared.allUsers(completion: { (users) in self.users = users self.tableView.reloadData() }) } deinit { self.listener.remove() } ```
I think that *getDocument* instead of *addSnapshotListener* is what you are looking for. Using this method the listener is automatically detached at the end of the request... It will be something similar to ``` func allUsers(completion:@escaping ([User])->Void) { db.collection("users").getDocument { querySnapshot, error in if let documents = querySnapshot?.documents { var users = [User]() for document in documents { let user = User(snapshot: document) users.append(user) } completion(users) } } } ```
47,747,516
I hope i will get help here. I'm writing program who will read and export to txt 'devices live logging events' every two minutes. Everything works fine until i generate exe file. What is more interesting, program works on my enviroment(geckodriver and python libraries installed), but does not work on computers without python enviroment. Even if I generate exe with --onedir. Any ideas or tips? part of code is below(without tkinter): ``` browser = webdriver.Firefox() def logs(): global writing global browser logs_content = browser.find_element_by_css_selector(".content") if writing: curent_time = datetime.datetime.now() threading.Timer(120, logs).start() save_path = 'C:/Users/' + getpass.getuser() + '/Desktop/Logs ' + curent_time.strftime("%d-%B-%Y") + '.txt' with open(save_path, "w") as logs_txt: logs_txt.write(logs_content.text) def enter_to_IDE(): username = browser.find_element_by_id("username") username_input = login.get() username.send_keys(username_input) browser.find_element_by_id("next-step-btn").click() time.sleep(5) password_css = browser.find_element_by_id("password") password_input = password.get() password_css.send_keys(password_input) browser.find_element_by_id("login-user-btn").click() time.sleep(10) logs() def US_shard(): global browser browser.get('link') enter_to_IDE() def EU_shard(): global browser browser.get('link') enter_to_IDE() ```
2017/12/11
[ "https://Stackoverflow.com/questions/47747516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9082203/" ]
The problem is that the `deny from all` denies **everything** including the error documents. But hey, .htaccess files work in cascade, so you can 1. create a subfolder in your web root (assuming your webroot is `/www` - `/www/errordocs` 2. => in there put your ErrorDocuments like 403.html etc. 3. create another `.htaccess` **there** - `/www/errordocs/.htaccess` 4. => into this `/www/errordocs/.htaccess` put `allow from all` 5. In the main `.htaccess` in the webroot (`/www/.htaccess` ) put `ErrorDocument 403 /errordocs/403.html` etc.. If this is still not working for you, check there are public/others/everyone READ permissions on both the folder and the file `/www/errordocs` => `755` `/www/errordocs/.htaccess` => `640` `/www/errordocs/403.html` => `644` Don't be confused - Windows OS **also** has permissions, you will need at least Read permissions for `Everyone` on these, [more on the Windows permissions here](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/bb727008(v=technet.10)?redirectedfrom=MSDN). **Just remember, files in this folder will all be public!** (don't put there anything you don't want public :-)
yes I can help a Little bit to solve permission issue , I was encountered by same problem , You just need to give permission +777 to your /app if you have linux machine , go inside your web folder ``` sudo chmod -R +777 /app ``` and do the same to any other folders you write there and for 403 error I think you missed "l" If I am not wrong , ``` Order deny,allow Deny from all Allow from 192.168.1.0/24 ErrorDocument 403 /403.html ``` :) :)
23,006,023
I'm trying to install pyOpenSSL using pip, python version is 2.7, OS is linux. After pyOpenSSL installed, when I tried to import the module in python, I got the following error: ``` Python 2.7.5 (default, Jun 27 2013, 03:17:39) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import OpenSSL Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/OpenSSL/__init__.py", line 8, in <module> from OpenSSL import rand, crypto, SSL File "/usr/local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 84, in <module> OP_NO_TICKET = _lib.SSL_OP_NO_TICKET AttributeError: 'FFILibrary' object has no attribute 'SSL_OP_NO_TICKET' >>> ``` I tried to uninstall pyOpenSSL and install it again, but got the same error.
2014/04/11
[ "https://Stackoverflow.com/questions/23006023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/855643/" ]
This is because low version pyopenssl has not defined SSL\_OP\_NO\_TICKET。 clone the latest pyopenssl from <https://github.com/pyca/pyopenssl.git> and install it, then that'll be fine. no thks.
The fix is described here: <https://github.com/pyca/pyopenssl/issues/130> Indeed, you can apply it manually (not really recommended, but easy) Or download archive from github The link to the fix: <https://github.com/pyca/pyopenssl/commit/e7a6939a22a4290fff7aafe39dd0db85157d5e05> And the fix applied to SSL.py ``` -OP_NO_TICKET = _lib.SSL_OP_NO_TICKET +try: + OP_NO_TICKET = _lib.SSL_OP_NO_TICKET +except AttributeError: + pass ```
32,156,008
I am using Calendar and recieve list of lists of lists of tuples from it ``` calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1)) ``` Output is: ``` [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),... ``` I want to flat map it to simple tuples list saving their order. What is the best way to do map list of any deepness into plain list in python 2.7? Example of what I want: ``` [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6),(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1)... ``` Tryied code from other questions - didn't help. Sorry for silly questions, I'm new to python UPD I tried functions from here [python list comprehensions; compressing a list of lists?](https://stackoverflow.com/questions/1077015/python-list-comprehensions-compressing-a-list-of-lists) - didn't help
2015/08/22
[ "https://Stackoverflow.com/questions/32156008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386321/" ]
Python has a function to flatten one nesting level. It goes by the unfortunate name `itertools.chain.from_iterable()`. If you apply it three times, it will flatten three levels: ``` import itertools flatten1 = itertools.chain.from_iterable flattened_data = flatten1(flatten1(flatten1(your_data))) for a, b in flattened_data: # whatever ``` More generically, a function that flattens `n` levels would be ``` def flatten_n(n, iterable): for x in reduce(apply, [itertools.chain.from_iterable] * n, iterable): yield x ``` A function that recursively flattens all lists could look like this: ``` def flatten_lists(a): if isinstance(a, list): for b in a: for x in flatten_lists(b): yield x else: yield a ```
Try this: ``` def flatten(x): if isinstance(x, list): return [a for i in x for a in flatten(i)] else: return [x] ``` This answer is similar to this: <https://stackoverflow.com/a/2158522/1628832> but checking for the specific `list` type instead of an iterable. For optimization, memory efficiency, etc.. you can use `yield` operation too. Demo ``` >>> year = 2015 >>> x = calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1) >>> flatten(x) [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1), (14, 2), (15, 3), (16, 4), (17, 5), (18, 6), (19, 0), (20, 1), (21, 2), (22, 3), (23, 4), (24, 5), (25, 6), ...] ```
32,156,008
I am using Calendar and recieve list of lists of lists of tuples from it ``` calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1)) ``` Output is: ``` [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),... ``` I want to flat map it to simple tuples list saving their order. What is the best way to do map list of any deepness into plain list in python 2.7? Example of what I want: ``` [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6),(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1)... ``` Tryied code from other questions - didn't help. Sorry for silly questions, I'm new to python UPD I tried functions from here [python list comprehensions; compressing a list of lists?](https://stackoverflow.com/questions/1077015/python-list-comprehensions-compressing-a-list-of-lists) - didn't help
2015/08/22
[ "https://Stackoverflow.com/questions/32156008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386321/" ]
Python has a function to flatten one nesting level. It goes by the unfortunate name `itertools.chain.from_iterable()`. If you apply it three times, it will flatten three levels: ``` import itertools flatten1 = itertools.chain.from_iterable flattened_data = flatten1(flatten1(flatten1(your_data))) for a, b in flattened_data: # whatever ``` More generically, a function that flattens `n` levels would be ``` def flatten_n(n, iterable): for x in reduce(apply, [itertools.chain.from_iterable] * n, iterable): yield x ``` A function that recursively flattens all lists could look like this: ``` def flatten_lists(a): if isinstance(a, list): for b in a: for x in flatten_lists(b): yield x else: yield a ```
If you are using Python 2, the following one liner solution will currently work: ``` import compiler, itertools lpairs = [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1)]]]] print [(x,y) for x,y in itertools.izip(*[iter(compiler.ast.flatten(lpairs))]*2)] ``` Gives: ``` [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1)] ``` Note, the Python `compiler` module has been deprecated.
32,156,008
I am using Calendar and recieve list of lists of lists of tuples from it ``` calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1)) ``` Output is: ``` [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),... ``` I want to flat map it to simple tuples list saving their order. What is the best way to do map list of any deepness into plain list in python 2.7? Example of what I want: ``` [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6),(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1)... ``` Tryied code from other questions - didn't help. Sorry for silly questions, I'm new to python UPD I tried functions from here [python list comprehensions; compressing a list of lists?](https://stackoverflow.com/questions/1077015/python-list-comprehensions-compressing-a-list-of-lists) - didn't help
2015/08/22
[ "https://Stackoverflow.com/questions/32156008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386321/" ]
Try this: ``` def flatten(x): if isinstance(x, list): return [a for i in x for a in flatten(i)] else: return [x] ``` This answer is similar to this: <https://stackoverflow.com/a/2158522/1628832> but checking for the specific `list` type instead of an iterable. For optimization, memory efficiency, etc.. you can use `yield` operation too. Demo ``` >>> year = 2015 >>> x = calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1) >>> flatten(x) [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1), (14, 2), (15, 3), (16, 4), (17, 5), (18, 6), (19, 0), (20, 1), (21, 2), (22, 3), (23, 4), (24, 5), (25, 6), ...] ```
If you are using Python 2, the following one liner solution will currently work: ``` import compiler, itertools lpairs = [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1)]]]] print [(x,y) for x,y in itertools.izip(*[iter(compiler.ast.flatten(lpairs))]*2)] ``` Gives: ``` [(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6), (12, 0), (13, 1)] ``` Note, the Python `compiler` module has been deprecated.
56,721,424
I have two pandas columns, both converted to datetime format, and can't subtract one from the other. ``` df['date_listed'] = pd.to_datetime(df['date_listed'], errors='coerce').dt.floor('d') df['date_unconditional'] = pd.to_datetime(df['date_unconditional'], errors='coerce').dt.floor('d') print df['date_listed'][:5] print df['date_unconditional'][:5] 0 2013-01-01 1 2013-01-01 2 2015-04-08 3 2016-03-24 4 2016-04-27 Name: date_listed, dtype: datetime64[ns] 0 2018-10-15 1 2018-06-12 2 2018-08-28 3 2018-08-29 4 2018-10-29 Name: date_unconditional, dtype: datetime64[ns] ``` The formats seem to be correct to be able to do a subtraction, but then I get this mistake: ``` df['date_listed_to_sale'] = (df['date_sold'] - df['date_listed']).dt.days print df['date_listed_to_sale'][:5] TypeErrorTraceback (most recent call last) <ipython-input-139-85a5efbde0f1> in <module>() ----> 1 df['date_listed_to_sale'] = (df['date_sold'] - df['date_listed']).dt.days 2 print df['date_listed_to_sale'][:5] /Users/virt_env/virt1/lib/python2.7/site-packages/pandas/core/ops.pyc in wrapper(left, right) 1581 rvalues = rvalues.values 1582 -> 1583 result = safe_na_op(lvalues, rvalues) 1584 return construct_result(left, result, 1585 index=left.index, name=res_name, dtype=None) /Users/virt_env/virt1/lib/python2.7/site-packages/pandas/core/ops.pyc in safe_na_op(lvalues, rvalues) 1531 if is_object_dtype(lvalues): 1532 return libalgos.arrmap_object(lvalues, -> 1533 lambda x: op(x, rvalues)) 1534 raise 1535 pandas/_libs/algos.pyx in pandas._libs.algos.arrmap() /Users/virt_env/virt1/lib/python2.7/site-packages/pandas/core/ops.pyc in <lambda>(x) 1531 if is_object_dtype(lvalues): 1532 return libalgos.arrmap_object(lvalues, -> 1533 lambda x: op(x, rvalues)) 1534 raise 1535 TypeError: ufunc subtract cannot use operands with types dtype('S1') and dtype('<M8[ns]') ``` I added errors='coerce' thinking it may resolve the problem, it didn't. I would appreciate some help with this.
2019/06/23
[ "https://Stackoverflow.com/questions/56721424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718221/" ]
You could use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) operations and then map to recombine. ```js data = [ ['Jenny', 'id100', 'F', 'English', 'Science', 'Math', 'Physics'], ['Johnny', 'id101', 'M', 'Science', 'Sports', 'Gym', 'English'] ]; result = []; data.map(row => { var [name, id, gender, ...prefs] = row; prefs.map((x) => result.push([name, id, gender, x])); }) console.log(result); ``` As pointed out in the comments, since some of the features [might not be available](https://developers.google.com/apps-script/guides/services/#basic_javascript_features), here's a more conservative alternative. ```js data.forEach(function(row) { prefs = row.slice(3); prefs.map(function(x) { result.push([row[0], row[1], row[2], x]) }); }) ```
Try this: ``` function addingRows() { var ss=SpreadsheetApp.getActive(); var sh=ss.getSheetByName('Sheet1'); var rg=sh.getRange(2, 1, sh.getLastRow()-1,sh.getLastColumn()); var vA=rg.getValues(); var vB=[]; for(var i=0;i<vA.length;i++) { vt=vA[i].slice(3); for(var j=0;j<vt.length;j++) { vB.push([vA[i][0],vA[i][1],vA[i][2],vt[j]]) } } var osh=ss.getSheetByName('Sheet2'); osh.appendRow(['Name','ID','Gender','Course']); osh.getRange(2,1,vB.length,4).setValues(vB); } ``` My Sheet1: [![enter image description here](https://i.stack.imgur.com/nN6sZ.jpg)](https://i.stack.imgur.com/nN6sZ.jpg) My Sheet2: [![enter image description here](https://i.stack.imgur.com/EtTV2.jpg)](https://i.stack.imgur.com/EtTV2.jpg) * [Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
4,192,744
If I enter Baltic characters in textctrl and click button **test1** I have an error ``` "InicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)" ``` Button **test2** works fine. ``` #!/usr/bin/python # -*- coding: UTF-8 -*- import wx class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, (-1, -1), wx.Size(450, 300)) self.panel = wx.Panel(self) self.input_area = wx.TextCtrl(self.panel, -1, '',(5,5),(200,200), style=wx.TE_MULTILINE) self.output_list = wx.ListCtrl(self.panel, -1, (210,5), (200,200), style=wx.LC_REPORT) self.output_list.InsertColumn(0, 'column') self.output_list.SetColumnWidth(0, 100) self.btn1 = wx.Button(self.panel, -1, 'test1', (5,220)) self.btn1.Bind(wx.EVT_BUTTON, self.OnTest1) self.btn2 = wx.Button(self.panel, -1, 'test2', (100,220)) self.btn2.Bind(wx.EVT_BUTTON, self.OnTest2) self.Centre() def OnTest1(self, event): self.output_list.InsertStringItem(0,str(self.input_area.GetValue()).decode('utf-8')) def OnTest2(self, event): self.output_list.InsertStringItem(0,"ąčęėįő".decode('utf-8')) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, 'encoding') frame.Show(True) return True app = MyApp(0) app.MainLoop() ``` Update 1 -------- I have tried this code on two Windows 7 Ultimate x64 computers. Both have **python 2.7** and **wxPython2.8 win64 unicode** for python 2.7 In both machines I have the same error.
2010/11/16
[ "https://Stackoverflow.com/questions/4192744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509289/" ]
The [documentation](http://www.novell.com/documentation/suse91/suselinux-adminguide/html/ch12s03.html) for SUSE Linux provides a good explanation of why Linux is booted with a RAMDisk: > > As soon as the Linux kernel has been > booted and the root file system (/) > mounted, programs can be run and > further kernel modules can be > integrated to provide additional > functions. **To mount the root file > system, certain conditions must be > met. The kernel needs the > corresponding drivers to access the > device on which the root file system > is located** (especially SCSI > drivers). **The kernel must also contain > the code needed to read the file > system** (ext2, reiserfs, romfs, etc.). > It is also conceivable that the root > file system is already encrypted. In > this case, a password is needed to > mount the file system. > > > For the problem of SCSI drivers, a > number of different solutions are > possible. The kernel could contain all > imaginable drivers, but this might be > a problem because different drivers > could conflict with each other. Also, > the kernel would become very large > because of this. Another possibility > is to provide different kernels, each > one containing just one or a few SCSI > drivers. This method has the problem > that a large number of different > kernels are required, a problem then > increased by the differently optimized > kernels (Athlon optimization, SMP). > **The idea of loading the SCSI driver as > a module leads to the general problem > resolved by the concept of an initial > ramdisk: running user space programs > even before the root file system is > mounted.** > > > This prevents a potential chicken-or-egg situation where the root file system cannot be loaded until the device on which it is located can be accessed, but that device can't be accessed until the root file system has been loaded: > > **The initial ramdisk** (also called initdisk or initrd) **solves precisely the problems described above. The Linux kernel provides an option of having a small file system loaded to a RAM disk and running programs there before the actual root file system is mounted.** The loading of initrd is handled by the boot loader (GRUB, LILO, etc.). Boot loaders only need BIOS routines to load data from the boot medium. **If the boot loader is able to load the kernel, it can also load the initial ramdisk. Special drivers are not required.** > > > Of course, a RAMDisk is not *strictly necessary* for the boot process to take place. For example, you could compile a kernel that contained all necessary hardware drivers and modules to be loaded at startup. But apparently this is too much work for most people, and the RAMDisk proved to be a simpler, more scalable solution.
The reason that most Linux distributions use a ramfs (initramfs) when booting, is because its contents can be included in the kernel file, or provided by the bootloader. They are therefore available immediately at boot, without the kernel having to load them from somewhere. That allows the kernel to run userspace programs that e.g. configure devices, load modules, setup that nifty RAID array that contains all filesystems or even ask the user for the password to his encrypted root filesystem. When this configuration is done, the first script that is called just exec()s /sbin/init from the (now configured and available) root filesystem. I have seen quite a few systems where the drivers themselvess for the disk controllers and the rootfs are loaded via modules in an initramfs, rather than being included in the kernel image. You do not strictly *need* an initramfs to boot - if your kernel image contains all drivers necessary to access the rootfs and you don't need any special configuration or user input (like RAID arrays or encrypted filesystems) to mount it, it is often possible to directly start /sbin/init from the rootfs. See also: <http://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt> <http://www.kernel.org/doc/Documentation/initrd.txt> As a side note, some systems (rescue disks, embedded and such) may use a ramfs as the root filesystem when the actual root filesystem is in a medium that may be removed or is not writable (CD, Flash MTDs etc).
62,026,013
I have created a python script which do birthday wish to a person automatically when birthdate is arrive. I added this script on window start up but it run every time when i start my pc and do birthday wish to person also. I want to run that script only once a day. What should i do?
2020/05/26
[ "https://Stackoverflow.com/questions/62026013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12942284/" ]
Try this at the start of the file: ``` import datetime actualday = datetime.datetime.today().day # get the actual day actualmonth = datetime.datetime.today().month # get the actual month bday = 1 # day of birthday bmonth = 1 # month of birthday if actualday == bday and actualmonth == bmonth : # code ``` it should finish the process if the dates aren't equal
You can run this program when the system boot [How to start a python file while Windows starts?](https://stackoverflow.com/questions/4438020/how-to-start-a-python-file-while-windows-starts) And after that, you need check the time of when the system started like: ``` import datetime dayToday = datetime.datetime.today().day monthToday = datetime.datetime.today().month birthdayDay = 1 birthdayMonth = 10 if dayToday == birthdayDay and monthToday == birthdayMonth: print "HPBD" ```
50,225,903
I am trying a POC running a python script in a back-end implemented in PHP. The web server is Apache in a Docker container. This is the PHP code: ``` $command = escapeshellcmd('/usr/local/test/script.py'); $output = shell_exec($command); echo $output; ``` When I execute the python script using the back-end we are getting a permission denied error for creating the file. My python script: ``` #!/usr/bin/env python file = open("/tmp/testfile.txt","w+") file.write("Hello World") file.close() ``` This is the error I'm getting: > > IOError: [Errno 13] Permission denied: 'testfile.txt' > > > For the directory im working with the permissions are as follows, > > drwxrwsr-x 2 1001 www-data 4096 May 8 05:35 . > > > drwxrwxr-x 3 1001 1001 4096 May 3 08:49 .. > > > Any thoughts on this? How do I overcome this problem?
2018/05/08
[ "https://Stackoverflow.com/questions/50225903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4681701/" ]
To start is is incredibly bad practice to have relative paths in *any* scripting environment. Start by rewriting your code to use a full path such as `/usr/local/test/script.py` and `/tmp/testfile.txt`. My guess is your script is attempting to write to a different spot than you think it is. When you *know* exactly where the files are being written go to the directory and run `ls -la` and check the permissions on the directory. You want it to be writeable by the same user or group as the web server runs. Looking at the permissions you have shown you don't have the user able to write to the directory, just everyone and the group. You need to add user write permissions - `chmod u+w /tmp` will do the job.
I believe the problem is that you are trying to write to an existing file in the `/tmp/` directory. Typically `/tmp/` [will have the sticky permission bit set.](https://unix.stackexchange.com/questions/71622/what-are-correct-permissions-for-tmp-i-unintentionally-set-it-all-public-recu) That means that only the owner of a file has permission to write or delete it. Group write permissions on files do not matter if the sticky bit is set on the parent directory. So if this is the contents of your /tmp ``` $ ls -al /tmp drwxrwxrwt 5 root root 760 Apr 30 12:00 . drwxr-xr-x 21 root root 4096 Apr 30 12:00 .. -rw-rw---- 2 1001 www-data 80 May 8 12:00 testfile.txt ``` We might assume that users in the group `www-data` should be able to write to `testfile.txt`. But that is not the case, since `.` (the /tmp/ directory itself) has the sticky bit set (the `t` in the permissions section indicates this). The reason why the sticky bit is set here is that everyone should be able to write files there, but not have to worry that other users might modify our temporary files. To avoid permission errors, you can use the standard library [tempfile](https://docs.python.org/3/library/tempfile.html#tempfile-examples) module. This code will create a unique filename such as `testfile.JCDxK2.txt`, so it doesn't matter if `testfile.txt` already exists. ``` #!/usr/bin/env python import tempfile with tempfile.NamedTemporaryFile( mode='w', prefix='testfile.', suffix='.txt', delete=False, ) as file: file.write("Hello World") ```
73,523,116
i was wondering how i can get the product dimensions and weight from an amazon page. this is the page: [https://www.amazon.com/Vic-Firth-American-5B-Drumsticks/dp/B0002F73Z8/ref=psdc\_11966431\_t1\_B0064RNNP2?th=1](https://rads.stackoverflow.com/amzn/click/com/B0002F73Z8) there is a place where it says item weight: 3.2 ounces product dimensions: 16 x 0.6 x 0.6. I am new to webscraping and python so if you could please help me, that would be awesome!
2022/08/29
[ "https://Stackoverflow.com/questions/73523116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17215378/" ]
What you need to do is first install selenium in your computer. Then after setting it up you can go to the page and click on inspect.Then you search what you need to scrap after that copy the XPath . You can Follow [Selenium with Python](https://selenium-python.readthedocs.io/) Docs or watch any tutorial for more detail .
I would advise you look into requests, Beautiful Soup and Selenium. These are useful libraries/tools for web scraping. Also I believe Amazon specifically blocks a lot of scraping requests so you will need to mimic a regular users browser for it to work.
73,523,116
i was wondering how i can get the product dimensions and weight from an amazon page. this is the page: [https://www.amazon.com/Vic-Firth-American-5B-Drumsticks/dp/B0002F73Z8/ref=psdc\_11966431\_t1\_B0064RNNP2?th=1](https://rads.stackoverflow.com/amzn/click/com/B0002F73Z8) there is a place where it says item weight: 3.2 ounces product dimensions: 16 x 0.6 x 0.6. I am new to webscraping and python so if you could please help me, that would be awesome!
2022/08/29
[ "https://Stackoverflow.com/questions/73523116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17215378/" ]
This will get what you want done when it comes to scraping a webpage for specific content in the context of your question. From this point you'd want to loop over a list of desired URLs. Hope this helps :) ``` #!/bin/python3 from bs4 import BeautifulSoup import requests headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36', 'cookie': '<YOUR_COOKIE>'} req = requests.get("https://www.amazon.com/dp/B0002F73Z8?th=1", headers=headers) soup = BeautifulSoup(req.content.decode("utf-8"), 'html.parser') for res in soup.find_all('td'): try: if "prodDetAttrValue" in res['class']: print(res.get_text()) except KeyError: pass ``` output: ``` 3.2 ounces 16 x 0.6 x 0.6 inches USA B0002F73Z8 5B No April 13, 2004 Natural Hickory 5b ```
I would advise you look into requests, Beautiful Soup and Selenium. These are useful libraries/tools for web scraping. Also I believe Amazon specifically blocks a lot of scraping requests so you will need to mimic a regular users browser for it to work.
35,173,118
I am using httplib in my python code and have following mentioned. `import httplib httplib.HTTPConnection.debuglevel = 2` I do get all the info I need but httplib library is printing it on console. I do not know any way by which I can get all those logs in a log file and not on console.
2016/02/03
[ "https://Stackoverflow.com/questions/35173118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2606665/" ]
If you take a look at the httplib source (<https://hg.python.org/cpython/file/2.7/Lib/httplib.py>) you'll see the debugging is done via print statements, so you can't use logging configuration to intercept the logs, and because print is a statement, you can't monkeypatch it to do your bidding. You have a few options: 1. Use an alternative to httplib 2. Subclass HTTPConnection and do something ugly with `__getattribute__` (or just write pass-throughs for every method you want to log) and log when calls happen. 3. Depending on what you're doing, just redirect your program's stdout into a file.
Maybe try this: ``` f = open('output.txt','w') sys.stdout = f ``` Redirecting stdout to a file.
40,518,865
I am trying to figure out how to use a barely documented feature of a poorly documented API. I have distilled the chunk of code that is giving me trouble down to this for simplicity: ``` def build_custom_args(args): custom_args = {} for key in args: custom_args.update(key.get()) print(custom_args) ``` I can tell from the function that constructs `args` that it is a list. Problem is, a list of *what?* No matter what I put in the list, key.get() raises one exception of another. For example, if I execute that code like so: `build_custom_args(['foo'])` then I get an understandable error message: `AttributeError: 'str' object has no attribute 'get'`. Or, try a dictionary: `build_custom_args([{'foo': 'bar'}])`, but the error is raised: `TypeError: get expected at least 1 arguments, got 0`. As best I can tell `args` is a list of some standard python objects - there is no indication that these are special objects with a custom `get()` method. Am I missing something obvious? Is there some standard python object that has a `get()` method which takes no positional arguments? Is this a syntax of some older version of Python? Or have I found a bug in the API? **Edit** The accepted answer shows that I was mistaken believing that `args` had to be a python built-in. Jack's answer is worth a look because it actually does solve the problem "what Python built-in could `args` be that would cause this function to not throw an error?"
2016/11/10
[ "https://Stackoverflow.com/questions/40518865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197234/" ]
Well... I found this in the github link you have provided ``` class Email(object): # code... def get(self): ``` Matter of fact, a lot of those classes have get methods. Since Python is duck typed, there isn't really a way to determine what object is correct, but you're just building a dictionary, so shouldn't matter too much
AFAIK the only class with a `get` [method that can take zero arguments](https://docs.python.org/3/library/queue.html?highlight=get#queue.Queue.get) is a `Queue`. Which in your example is probably a `Queue` of `dict`s
8,159,414
I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 error but no other details. I've tried disabling the `DEBUG` mode to try and get it to send me emails but despite setting up the EMAIL\_HOST to something suitable, I'm not seeing any emails. I tried and verifying that the email system is working with a call to [send\_mail](https://docs.djangoproject.com/en/dev/topics/email/) ..but that succeeds and I still see no emails regarding internal server errors. What could I be missing? **edit** I'm running the dev server from PyCharm and the console output looks like this: ``` runnerw.exe C:\Python26\python.exe manage.py runserver 192.168.1.4:80 Validating models... 0 errors found Django version 1.4 pre-alpha, using settings 'settings' Development server is running at http://192.168.1.4:80/ Quit the server with CTRL-BREAK. Verifying... ...response: VERIFIED IpnEndPoint.on_process Valid: {u'last_name': u'Smith', u'txn_id': u'491116223', u'receiver_email': u'seller@paypalsandbox.com', u'payment_status': u'Completed', u'tax': u'2.02', u'payer_status': u'unverified', u'residence_country': u'US', u'invoice': u'abc1234', u'address_state': u'CA', u'item_name1': u'something', u'txn_type': u'cart', u'item_number1': u'AK-1234', u'quantity1': u'1', u'payment_date': u'14:03:49 Nov 16, 2011 PST', u'first_name': u'John', u'mc_shipping': u'3.02', u'address_street': u'123, any street', u'charset': u'windows-1252', u'custom': u'xyz123', u'notify_version': u'2.4', u'address_name': u'John Smith', u'address_zip': u'95131', u'test_ipn': u'1', u'receiver_id': u'TESTSELLERID1', u'payer_id': u'TESTBUYERID01', u'mc_handling1': u'1.67', u'verify_sign': u'A8SIYWSxkrwNPfuNewSuxsIAatvMAi2mxYjlYvaiWh3Z4BuIQojK3KBO', u'mc_handling': u'2.06', u'mc_gross_1': u'9.34', u'address_country_code': u'US', u'address_city': u'San Jose', u'address_status': u'confirmed', u'address_country': u'United States', u'mc_fee': u'0.44', u'mc_currency': u'USD', u'payer_email': u'buyer@paypalsandbox.com', u'payment_type': u'instant', u'mc_shipping1': u'1.02'} Logging Transaction.. [16/Nov/2011 22:20:49] "POST /IPN/ HTTP/1.0" 500 104946 ```
2011/11/16
[ "https://Stackoverflow.com/questions/8159414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
given that you are running a pre-alpha version of django, I would recomment asking this question on the django user list <https://groups.google.com/group/django-users>
have a look at [django-sentry](http://readthedocs.org/docs/sentry/en/latest/index.html) it logs 500 errors (also supports regular logging), making the dynamic "orange 500 pages" browsable after the fact. this is especially useful when you never get the original error page, e.g. when using ajax or remote apis like your case
8,159,414
I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 error but no other details. I've tried disabling the `DEBUG` mode to try and get it to send me emails but despite setting up the EMAIL\_HOST to something suitable, I'm not seeing any emails. I tried and verifying that the email system is working with a call to [send\_mail](https://docs.djangoproject.com/en/dev/topics/email/) ..but that succeeds and I still see no emails regarding internal server errors. What could I be missing? **edit** I'm running the dev server from PyCharm and the console output looks like this: ``` runnerw.exe C:\Python26\python.exe manage.py runserver 192.168.1.4:80 Validating models... 0 errors found Django version 1.4 pre-alpha, using settings 'settings' Development server is running at http://192.168.1.4:80/ Quit the server with CTRL-BREAK. Verifying... ...response: VERIFIED IpnEndPoint.on_process Valid: {u'last_name': u'Smith', u'txn_id': u'491116223', u'receiver_email': u'seller@paypalsandbox.com', u'payment_status': u'Completed', u'tax': u'2.02', u'payer_status': u'unverified', u'residence_country': u'US', u'invoice': u'abc1234', u'address_state': u'CA', u'item_name1': u'something', u'txn_type': u'cart', u'item_number1': u'AK-1234', u'quantity1': u'1', u'payment_date': u'14:03:49 Nov 16, 2011 PST', u'first_name': u'John', u'mc_shipping': u'3.02', u'address_street': u'123, any street', u'charset': u'windows-1252', u'custom': u'xyz123', u'notify_version': u'2.4', u'address_name': u'John Smith', u'address_zip': u'95131', u'test_ipn': u'1', u'receiver_id': u'TESTSELLERID1', u'payer_id': u'TESTBUYERID01', u'mc_handling1': u'1.67', u'verify_sign': u'A8SIYWSxkrwNPfuNewSuxsIAatvMAi2mxYjlYvaiWh3Z4BuIQojK3KBO', u'mc_handling': u'2.06', u'mc_gross_1': u'9.34', u'address_country_code': u'US', u'address_city': u'San Jose', u'address_status': u'confirmed', u'address_country': u'United States', u'mc_fee': u'0.44', u'mc_currency': u'USD', u'payer_email': u'buyer@paypalsandbox.com', u'payment_type': u'instant', u'mc_shipping1': u'1.02'} Logging Transaction.. [16/Nov/2011 22:20:49] "POST /IPN/ HTTP/1.0" 500 104946 ```
2011/11/16
[ "https://Stackoverflow.com/questions/8159414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
Another thing to try is to launch a simple SMTP server on your machine. ``` python -m smtpd -n -c DebuggingServer localhost:1025 ``` Which will output on your console all emails headers and body. Make sure localhost and the port 1025 correpond to what you have in your settings.py, respectively in EMAIL\_HOST and EMAIL\_PORT. Source: [Djangodocs Testing email sending](https://docs.djangoproject.com/en/dev/topics/email/#testing-email-sending "Djangodocs Testing email sending")
have a look at [django-sentry](http://readthedocs.org/docs/sentry/en/latest/index.html) it logs 500 errors (also supports regular logging), making the dynamic "orange 500 pages" browsable after the fact. this is especially useful when you never get the original error page, e.g. when using ajax or remote apis like your case
8,159,414
I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 error but no other details. I've tried disabling the `DEBUG` mode to try and get it to send me emails but despite setting up the EMAIL\_HOST to something suitable, I'm not seeing any emails. I tried and verifying that the email system is working with a call to [send\_mail](https://docs.djangoproject.com/en/dev/topics/email/) ..but that succeeds and I still see no emails regarding internal server errors. What could I be missing? **edit** I'm running the dev server from PyCharm and the console output looks like this: ``` runnerw.exe C:\Python26\python.exe manage.py runserver 192.168.1.4:80 Validating models... 0 errors found Django version 1.4 pre-alpha, using settings 'settings' Development server is running at http://192.168.1.4:80/ Quit the server with CTRL-BREAK. Verifying... ...response: VERIFIED IpnEndPoint.on_process Valid: {u'last_name': u'Smith', u'txn_id': u'491116223', u'receiver_email': u'seller@paypalsandbox.com', u'payment_status': u'Completed', u'tax': u'2.02', u'payer_status': u'unverified', u'residence_country': u'US', u'invoice': u'abc1234', u'address_state': u'CA', u'item_name1': u'something', u'txn_type': u'cart', u'item_number1': u'AK-1234', u'quantity1': u'1', u'payment_date': u'14:03:49 Nov 16, 2011 PST', u'first_name': u'John', u'mc_shipping': u'3.02', u'address_street': u'123, any street', u'charset': u'windows-1252', u'custom': u'xyz123', u'notify_version': u'2.4', u'address_name': u'John Smith', u'address_zip': u'95131', u'test_ipn': u'1', u'receiver_id': u'TESTSELLERID1', u'payer_id': u'TESTBUYERID01', u'mc_handling1': u'1.67', u'verify_sign': u'A8SIYWSxkrwNPfuNewSuxsIAatvMAi2mxYjlYvaiWh3Z4BuIQojK3KBO', u'mc_handling': u'2.06', u'mc_gross_1': u'9.34', u'address_country_code': u'US', u'address_city': u'San Jose', u'address_status': u'confirmed', u'address_country': u'United States', u'mc_fee': u'0.44', u'mc_currency': u'USD', u'payer_email': u'buyer@paypalsandbox.com', u'payment_type': u'instant', u'mc_shipping1': u'1.02'} Logging Transaction.. [16/Nov/2011 22:20:49] "POST /IPN/ HTTP/1.0" 500 104946 ```
2011/11/16
[ "https://Stackoverflow.com/questions/8159414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
Another thing to try is to launch a simple SMTP server on your machine. ``` python -m smtpd -n -c DebuggingServer localhost:1025 ``` Which will output on your console all emails headers and body. Make sure localhost and the port 1025 correpond to what you have in your settings.py, respectively in EMAIL\_HOST and EMAIL\_PORT. Source: [Djangodocs Testing email sending](https://docs.djangoproject.com/en/dev/topics/email/#testing-email-sending "Djangodocs Testing email sending")
given that you are running a pre-alpha version of django, I would recomment asking this question on the django user list <https://groups.google.com/group/django-users>
48,373,718
I have a spring boot web application without registration page or allowing users to register. I'm manually creating passwords using another web spring application which ones gives me encoded password on request. Using the below link to generate the encoded password: <http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt> But i was researching to find an alternate simple python equivalent,so i can use it on the cli easily.?
2018/01/22
[ "https://Stackoverflow.com/questions/48373718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1550594/" ]
I was facing the same problem, but the following worked for me: ``` bcrypt.gensalt(rounds = 10, prefix=b"2a") ``` This seems to be in sync with the bean `BCryptPasswordEncoder` in SpringBoot :)
BCrypt is a module in python which can be installed using `pip install bcrypt`. The equivalent to BCryptPasswordEncoder() would require importing bcrypt as `import bcrypt` and then executing `bcrypt.hashpw(password, bcrypt.gensalt())` to encrypt a password. Source: <https://pypi.python.org/pypi/bcrypt/3.1.0>
34,030,599
Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step, running the command `virtualenv venv`. I run that, then the next command, `pip install -r requirements.txt --allow-all-external`, and that's where I get this error: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_nickcode/psycopg2 Storing debug log for failure in /tmp/tmpb5tCeK ``` I don't understand why I'm getting this error. Can anyone help me make sense of it? My version of requirements.txt: ``` dj-database-url==0.3.0 Django==1.8.1 django-postgrespool==0.3.0 gunicorn==19.3.0 psycopg2==2.6 SQLAlchemy==1.0.4 whitenoise==1.0.6 ```
2015/12/01
[ "https://Stackoverflow.com/questions/34030599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266746/" ]
pg\_config is part of postgresql ( <http://www.postgresql.org/docs/8.1/static/app-pgconfig.html> ). So you need to install postgresql.
``` brew install postgresql ``` resolves this issue on macOS
34,030,599
Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step, running the command `virtualenv venv`. I run that, then the next command, `pip install -r requirements.txt --allow-all-external`, and that's where I get this error: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_nickcode/psycopg2 Storing debug log for failure in /tmp/tmpb5tCeK ``` I don't understand why I'm getting this error. Can anyone help me make sense of it? My version of requirements.txt: ``` dj-database-url==0.3.0 Django==1.8.1 django-postgrespool==0.3.0 gunicorn==19.3.0 psycopg2==2.6 SQLAlchemy==1.0.4 whitenoise==1.0.6 ```
2015/12/01
[ "https://Stackoverflow.com/questions/34030599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266746/" ]
pg\_config is part of postgresql ( <http://www.postgresql.org/docs/8.1/static/app-pgconfig.html> ). So you need to install postgresql.
I have overcame this issue defining a environment variable HEROKU and putting the following lines at the end of settings.py ``` if config('HEROKU', cast=bool, default=False): import django_heroku django_heroku.settings(locals()) ``` As Heroku use the buildpack: heroku/python, there is no additional configuration to perform
34,030,599
Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step, running the command `virtualenv venv`. I run that, then the next command, `pip install -r requirements.txt --allow-all-external`, and that's where I get this error: ``` Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip_build_nickcode/psycopg2 Storing debug log for failure in /tmp/tmpb5tCeK ``` I don't understand why I'm getting this error. Can anyone help me make sense of it? My version of requirements.txt: ``` dj-database-url==0.3.0 Django==1.8.1 django-postgrespool==0.3.0 gunicorn==19.3.0 psycopg2==2.6 SQLAlchemy==1.0.4 whitenoise==1.0.6 ```
2015/12/01
[ "https://Stackoverflow.com/questions/34030599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266746/" ]
``` brew install postgresql ``` resolves this issue on macOS
I have overcame this issue defining a environment variable HEROKU and putting the following lines at the end of settings.py ``` if config('HEROKU', cast=bool, default=False): import django_heroku django_heroku.settings(locals()) ``` As Heroku use the buildpack: heroku/python, there is no additional configuration to perform
68,565,656
I'm using Selenium to automate a report but when I download it the last number changes as if it were a sequence for example: 0001849191, 0001849192 and so on. I can't make it keep following the order because if someone else generates the report it can skip a number and python doesn't understand that it followed the sequence and ends up not renaming, so I'd like to make it possible for it to check what the last downloaded file and after that he renames the .xlsx file. Here's the code I made to try more without success: filepath = r'C:\Users\Luis.Serpa\Downloads' filename = max([filepath +'\'+ f for f in os.listdir(filepath)], key=os.path.getmtime)
2021/07/28
[ "https://Stackoverflow.com/questions/68565656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16541350/" ]
You can use the glob and os module to get the latest file.First import os, glob modules i.e: ``` import os import glob ``` Then you define path.My example gives path for any ones Download folder. ``` home = os.path.expanduser('~') path = os.path.join(home, 'Downloads') ``` "\*" is necessary. ``` path_a = path + "/*" list_of_files = glob.glob(path_a) # * means all if need specific format then *.csv latest_file = max(list_of_files, key=os.path.getctime) ``` This is name of new file ``` new_file = os.path.join(path, "b.kml") print(latest_file) #prints a.txt which was latest file i created os.rename(latest_file, new_file) ``` the file name becomes b.kml
First off, `'\'` is an invalid string, because `\` is used for escape sequences. `'\\'` would get you a string with a single backslash in it. But more than that, it's best not to construct paths this way; you should use [os.path.join](https://docs.python.org/3/library/os.path.html#os.path.join) to create paths out of components: ```py filename = max([os.path.join(filepath, f) for f in os.listdir(filepath)], key=os.path.getmtime) ``` This code works just fine to find the latest file on my OS, if I give a `filepath` to my own downloads folder. For a more modern python3 approach that has better cross-platform path support, you can also use [pathlib](https://docs.python.org/3/library/pathlib.html) Once you have the path of the file, you can rename it with [os.rename](https://docs.python.org/3/library/os.html#os.rename).
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple: * Find the current position within the file using `tell`. * Perform a `read` (or `write`) operation of some kind. * `seek` back to the previous file pointer. This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like: ``` def peek_line(f): pos = f.tell() line = f.readline() f.seek(pos) return line print peek_line(f) # cat1 print peek_line(f) # cat1 ``` --- You could implement the same thing for other `read` methods just as easily. For instance, implementing the same thing for `file.read`: ``` def peek(f, length=1): pos = f.tell() data = f.read(length) # Might try/except this line, and finally: f.seek(pos) f.seek(pos) return data print peek(f, 4) # cat1 print peek(f, 4) # cat1 ```
You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation For example ``` from itertools import tee import contextlib from StringIO import StringIO s = '''\ cat1 cat2 cat3 ''' with contextlib.closing(StringIO(s)) as f: handle1, handle2 = tee(f) print next(handle1) print next(handle2) cat1 cat1 ```
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation For example ``` from itertools import tee import contextlib from StringIO import StringIO s = '''\ cat1 cat2 cat3 ''' with contextlib.closing(StringIO(s)) as f: handle1, handle2 = tee(f) print next(handle1) print next(handle2) cat1 cat1 ```
Manually doing it is not that hard: ``` f = open('file.txt') line = f.readline() print line >>> cat1 # the calculation is: - (length of string + 1 because of the \n) # the second parameter is needed to move from the actual position of the buffer f.seek((len(line)+1)*-1, 1) line = f.readline() print line >>> cat1 ``` You can wrap this in a method like this: ``` def lookahead_line(file): line = file.readline() count = len(line) + 1 file.seek(-count, 1) return file, line ``` And use it like this: ``` f = open('file.txt') f, line = lookahead_line(f) print line ``` Hope this helps!
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation For example ``` from itertools import tee import contextlib from StringIO import StringIO s = '''\ cat1 cat2 cat3 ''' with contextlib.closing(StringIO(s)) as f: handle1, handle2 = tee(f) print next(handle1) print next(handle2) cat1 cat1 ```
The [`more_itertools`](https://github.com/erikrose/more-itertools) library offers a `peekable` class that allows you to `peek()` ahead without advancing an iterable. ``` with open("file.txt", "r") as f: p = mit.peekable(f.readlines()) p.peek() # 'cat1\n' next(p) # 'cat1\n' ``` We can view the next line before calling `next()` to advance the iterable `p`. We can now view the next line by calling `peek()` again. ``` p.peek() # 'cat2\n' ``` See also the [`more_itertools` docs](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.peekable), as `peekable` allows you to `prepend()` items to an iterable before advancing as well.
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation For example ``` from itertools import tee import contextlib from StringIO import StringIO s = '''\ cat1 cat2 cat3 ''' with contextlib.closing(StringIO(s)) as f: handle1, handle2 = tee(f) print next(handle1) print next(handle2) cat1 cat1 ```
Solutions with `tell()`/`seek()` will not work with `stdin` and other iterators. More generic implementation can be as simple as this: ``` class lookahead_iterator(object): __slots__ = ["_buffer", "_iterator", "_next"] def __init__(self, iterable): self._buffer = [] self._iterator = iter(iterable) self._next = self._iterator.next def __iter__(self): return self def _next_peeked(self): v = self._buffer.pop(0) if 0 == len(self._buffer): self._next = self._iterator.next return v def next(self): return self._next() def peek(self): v = next(self._iterator) self._buffer.append(v) self._next = self._next_peeked return v ``` Usage: ``` with open("source.txt", "r") as lines: lines = lookahead_iterator(lines) magic = lines.peek() if magic.startswith("#"): return parse_bash(lines) if magic.startswith("/*"): return parse_c(lines) if magic.startswith("//"): return parse_cpp(lines) raise ValueError("Unrecognized file") ```
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple: * Find the current position within the file using `tell`. * Perform a `read` (or `write`) operation of some kind. * `seek` back to the previous file pointer. This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like: ``` def peek_line(f): pos = f.tell() line = f.readline() f.seek(pos) return line print peek_line(f) # cat1 print peek_line(f) # cat1 ``` --- You could implement the same thing for other `read` methods just as easily. For instance, implementing the same thing for `file.read`: ``` def peek(f, length=1): pos = f.tell() data = f.read(length) # Might try/except this line, and finally: f.seek(pos) f.seek(pos) return data print peek(f, 4) # cat1 print peek(f, 4) # cat1 ```
Manually doing it is not that hard: ``` f = open('file.txt') line = f.readline() print line >>> cat1 # the calculation is: - (length of string + 1 because of the \n) # the second parameter is needed to move from the actual position of the buffer f.seek((len(line)+1)*-1, 1) line = f.readline() print line >>> cat1 ``` You can wrap this in a method like this: ``` def lookahead_line(file): line = file.readline() count = len(line) + 1 file.seek(-count, 1) return file, line ``` And use it like this: ``` f = open('file.txt') f, line = lookahead_line(f) print line ``` Hope this helps!
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple: * Find the current position within the file using `tell`. * Perform a `read` (or `write`) operation of some kind. * `seek` back to the previous file pointer. This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like: ``` def peek_line(f): pos = f.tell() line = f.readline() f.seek(pos) return line print peek_line(f) # cat1 print peek_line(f) # cat1 ``` --- You could implement the same thing for other `read` methods just as easily. For instance, implementing the same thing for `file.read`: ``` def peek(f, length=1): pos = f.tell() data = f.read(length) # Might try/except this line, and finally: f.seek(pos) f.seek(pos) return data print peek(f, 4) # cat1 print peek(f, 4) # cat1 ```
The [`more_itertools`](https://github.com/erikrose/more-itertools) library offers a `peekable` class that allows you to `peek()` ahead without advancing an iterable. ``` with open("file.txt", "r") as f: p = mit.peekable(f.readlines()) p.peek() # 'cat1\n' next(p) # 'cat1\n' ``` We can view the next line before calling `next()` to advance the iterable `p`. We can now view the next line by calling `peek()` again. ``` p.peek() # 'cat2\n' ``` See also the [`more_itertools` docs](https://more-itertools.readthedocs.io/en/latest/api.html#more_itertools.peekable), as `peekable` allows you to `prepend()` items to an iterable before advancing as well.
16,840,554
What's a pythonic approach for reading a line from a file but not advancing where you are in the file? For example, if you have a file of ``` cat1 cat2 cat3 ``` and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` . Is there some functionality like `file.some_function_here_nextline()` to get `cat1\n` then you can later do `file.readline()` and get back `cat1\n`?
2013/05/30
[ "https://Stackoverflow.com/questions/16840554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431282/" ]
As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple: * Find the current position within the file using `tell`. * Perform a `read` (or `write`) operation of some kind. * `seek` back to the previous file pointer. This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like: ``` def peek_line(f): pos = f.tell() line = f.readline() f.seek(pos) return line print peek_line(f) # cat1 print peek_line(f) # cat1 ``` --- You could implement the same thing for other `read` methods just as easily. For instance, implementing the same thing for `file.read`: ``` def peek(f, length=1): pos = f.tell() data = f.read(length) # Might try/except this line, and finally: f.seek(pos) f.seek(pos) return data print peek(f, 4) # cat1 print peek(f, 4) # cat1 ```
Solutions with `tell()`/`seek()` will not work with `stdin` and other iterators. More generic implementation can be as simple as this: ``` class lookahead_iterator(object): __slots__ = ["_buffer", "_iterator", "_next"] def __init__(self, iterable): self._buffer = [] self._iterator = iter(iterable) self._next = self._iterator.next def __iter__(self): return self def _next_peeked(self): v = self._buffer.pop(0) if 0 == len(self._buffer): self._next = self._iterator.next return v def next(self): return self._next() def peek(self): v = next(self._iterator) self._buffer.append(v) self._next = self._next_peeked return v ``` Usage: ``` with open("source.txt", "r") as lines: lines = lookahead_iterator(lines) magic = lines.peek() if magic.startswith("#"): return parse_bash(lines) if magic.startswith("/*"): return parse_c(lines) if magic.startswith("//"): return parse_cpp(lines) raise ValueError("Unrecognized file") ```
68,877,064
I'm pretty new in python and I'm having trouble doing this double summation. ![Summation](https://i.stack.imgur.com/C1TdQ.png) I already tried using ``` x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N)) ``` and using 2 for loops but nothing seens to work
2021/08/21
[ "https://Stackoverflow.com/questions/68877064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16722883/" ]
The solution is incredibly easy - Instead of using just the relevant part of the Alchemy key: 40Oo3XScVabXXXX8sePUEp9tb90gXXXX I used the whole URL: <https://eth-rinkeby.alchemyapi.io/v2/40Oo3XScVabXXXX8sePUEp9tb90gXXXX>
I had the same experience but when using hardhat not truffle.My internet connection was ok,try switching from Git bash to terminal(CMD).Use a completely new terminal avoid Gitbash and powershell.
68,877,064
I'm pretty new in python and I'm having trouble doing this double summation. ![Summation](https://i.stack.imgur.com/C1TdQ.png) I already tried using ``` x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N)) ``` and using 2 for loops but nothing seens to work
2021/08/21
[ "https://Stackoverflow.com/questions/68877064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16722883/" ]
The solution is incredibly easy - Instead of using just the relevant part of the Alchemy key: 40Oo3XScVabXXXX8sePUEp9tb90gXXXX I used the whole URL: <https://eth-rinkeby.alchemyapi.io/v2/40Oo3XScVabXXXX8sePUEp9tb90gXXXX>
Remove the function wrapper from provider inside the network configuration. ``` ropsten_infura: { provider: new HDWalletProvider({ mnemonic: { phrase: mnemonic }, providerOrUrl: `https://ropsten.infura.io/v3/${project_id}`, addressIndex }), network_id: 3 } ```
68,877,064
I'm pretty new in python and I'm having trouble doing this double summation. ![Summation](https://i.stack.imgur.com/C1TdQ.png) I already tried using ``` x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N)) ``` and using 2 for loops but nothing seens to work
2021/08/21
[ "https://Stackoverflow.com/questions/68877064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16722883/" ]
I also ran into this error when following the same tutorial. I use Alchemy (not Infura), and the issue was my API\_KEY. In other tutorials I've followed, the scripts require the full alchemy API Key (ex. "https://eth-rinkeby.alchemyapi.io/v2/<**random-key**>"). So, when I was following this tutorial, that is what I supplied. And, I ran into the error you reported. But when I reviewed the truffle.js script provided by the tutorial authors, I found this: ``` const rinkebyNodeUrl = isInfura ? "https://rinkeby.infura.io/v3/" + NODE_API_KEY : "https://eth-rinkeby.alchemyapi.io/v2/" + NODE_API_KEY; ``` Thus, the script was producing: ``` rinkebyNodeUrl = https://eth-rinkeby.alchemyapi.io/v2/https://eth-rinkeby.alchemyapi.io/v2/<**random-key**> ``` ...which is clearly wrong. Thus, ensuring I set my API\_KEY environment variable only to **random-key** and not <https://eth-rinkeby.alchemyapi.io/v2/https://eth-rinkeby.alchemyapi.io/v2/><**random-key**>, my contract deployed successfully. Also, make sure you have enough ETH in your wallet on the Rinkeby network. Faucets always seem to work for a little while then stop working, so do some Google searches to find one that is currently functional.
I had the same experience but when using hardhat not truffle.My internet connection was ok,try switching from Git bash to terminal(CMD).Use a completely new terminal avoid Gitbash and powershell.
68,877,064
I'm pretty new in python and I'm having trouble doing this double summation. ![Summation](https://i.stack.imgur.com/C1TdQ.png) I already tried using ``` x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N)) ``` and using 2 for loops but nothing seens to work
2021/08/21
[ "https://Stackoverflow.com/questions/68877064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16722883/" ]
I also ran into this error when following the same tutorial. I use Alchemy (not Infura), and the issue was my API\_KEY. In other tutorials I've followed, the scripts require the full alchemy API Key (ex. "https://eth-rinkeby.alchemyapi.io/v2/<**random-key**>"). So, when I was following this tutorial, that is what I supplied. And, I ran into the error you reported. But when I reviewed the truffle.js script provided by the tutorial authors, I found this: ``` const rinkebyNodeUrl = isInfura ? "https://rinkeby.infura.io/v3/" + NODE_API_KEY : "https://eth-rinkeby.alchemyapi.io/v2/" + NODE_API_KEY; ``` Thus, the script was producing: ``` rinkebyNodeUrl = https://eth-rinkeby.alchemyapi.io/v2/https://eth-rinkeby.alchemyapi.io/v2/<**random-key**> ``` ...which is clearly wrong. Thus, ensuring I set my API\_KEY environment variable only to **random-key** and not <https://eth-rinkeby.alchemyapi.io/v2/https://eth-rinkeby.alchemyapi.io/v2/><**random-key**>, my contract deployed successfully. Also, make sure you have enough ETH in your wallet on the Rinkeby network. Faucets always seem to work for a little while then stop working, so do some Google searches to find one that is currently functional.
Remove the function wrapper from provider inside the network configuration. ``` ropsten_infura: { provider: new HDWalletProvider({ mnemonic: { phrase: mnemonic }, providerOrUrl: `https://ropsten.infura.io/v3/${project_id}`, addressIndex }), network_id: 3 } ```
63,247,247
I downloaded pyttsx3 in command prompt I have a big error this the code: ``` import pyttsx3 engine = pyttsx3.init() engine.say("I will speak this text") engine.runAndWait() ``` output error: > > > > > > > > > > > > > > > > > > > > > ''' = RESTART: C:\Users\RAMS\AppData\Local\Programs\Python\Python38\text t speech.py Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\_*init*\_.py", line 20, in init eng = \_activeEngines[driverName] File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\weakref.py", line 131, in **getitem** o = self.datakey KeyError: None ``` During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module> from comtypes.gen import SpeechLib # comtypes ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\gen\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE return _win_functype_cache[(restype, argtypes, flags)] KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'ctypes.wintypes.LP_c_long'>), 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\text t speech.py", line 2, in <module> engine = pyttsx3.init() File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module> engine = comtypes.client.CreateObject("SAPI.SpVoice") File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject return _manage(obj, clsid, interface=interface) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage obj = GetBestInterface(obj) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface mod = GetModule(tlib) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule mod = _CreateWrapper(tlib, pathname) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper mod = _my_import(fullname) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import return __import__(fullname, globals(), locals(), ['DUMMY']) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 1467, in <module> ISpeechBaseStream._methods_ = [ File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__ self._make_methods(value) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods prototype = WINFUNCTYPE(restype, *argtypes) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 125, in WINFUNCTYPE class WinFunctionType(_CFuncPtr): TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported ``` ''' this is the error I don't know why In command prompt pip install pyttsx3: ``` Requirement already satisfied: pyttsx3 in c:\users\rams\appdata\local\programs\p ython\python38\lib\site-packages (2.90) Requirement already satisfied: comtypes; platform_system == "Windows" in c:\user s\rams\appdata\local\programs\python\python38\lib\site-packages (from pyttsx3) ( 1.1.7) Requirement already satisfied: pypiwin32; platform_system == "Windows" in c:\use rs\rams\appdata\local\programs\python\python38\lib\site-packages (from pyttsx3) (223) Requirement already satisfied: pywin32; platform_system == "Windows" in c:\users \rams\appdata\local\programs\python\python38\lib\site-packages (from pyttsx3) (2 28) ```
2020/08/04
[ "https://Stackoverflow.com/questions/63247247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14047733/" ]
Looks like the Vercel docs are currently outdated (AWS SDK V2 instead of V3). You can pass the credentials object to the AWS service when you instantiate it. Use an environment variable that is not reserved by adding the name of your app to it for example. *.env.local* ``` YOUR_APP_AWS_ACCESS_KEY_ID=[your key] YOUR_APP_AWS_SECRET_ACCESS_KEY=[your secret] ``` Add these env variables to your Vercel deployment settings (or Netlify, etc) and pass them in when you start up your AWS service client. ``` import { S3Client } from '@aws-sdk/client-s3' ... const s3 = new S3Client({ region: 'us-east-1', credentials: { accessKeyId: process.env.TRENDZY_AWS_ACCESS_KEY_ID ?? '', secretAccessKey: process.env.TRENDZY_AWS_SECRET_ACCESS_KEY ?? '', }, }) ``` (note: undefined check so Typescript stays happy)
If I'm not mistaken, you want to make `AWS_ACCESS_KEY_ID` into a runtime variable as well. Currently, it is a build time variable, which won't be accessible in your node application. ``` // replace this env: { //..others AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID }, // with this module.exports = { serverRuntimeConfig: { //..others AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID } } ``` Reference: <https://nextjs.org/docs/api-reference/next.config.js/environment-variables>
63,247,247
I downloaded pyttsx3 in command prompt I have a big error this the code: ``` import pyttsx3 engine = pyttsx3.init() engine.say("I will speak this text") engine.runAndWait() ``` output error: > > > > > > > > > > > > > > > > > > > > > ''' = RESTART: C:\Users\RAMS\AppData\Local\Programs\Python\Python38\text t speech.py Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\_*init*\_.py", line 20, in init eng = \_activeEngines[driverName] File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\weakref.py", line 131, in **getitem** o = self.datakey KeyError: None ``` During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\drivers\sapi5.py", line 3, in <module> from comtypes.gen import SpeechLib # comtypes ImportError: cannot import name 'SpeechLib' from 'comtypes.gen' (C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\gen\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 123, in WINFUNCTYPE return _win_functype_cache[(restype, argtypes, flags)] KeyError: (<class 'ctypes.HRESULT'>, (<class 'comtypes.automation.tagVARIANT'>, <class 'ctypes.wintypes.LP_c_long'>), 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\text t speech.py", line 2, in <module> engine = pyttsx3.init() File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\pyttsx3\drivers\sapi5.py", line 6, in <module> engine = comtypes.client.CreateObject("SAPI.SpVoice") File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\__init__.py", line 250, in CreateObject return _manage(obj, clsid, interface=interface) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\__init__.py", line 188, in _manage obj = GetBestInterface(obj) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\__init__.py", line 110, in GetBestInterface mod = GetModule(tlib) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\_generate.py", line 110, in GetModule mod = _CreateWrapper(tlib, pathname) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\_generate.py", line 184, in _CreateWrapper mod = _my_import(fullname) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\client\_generate.py", line 24, in _my_import return __import__(fullname, globals(), locals(), ['DUMMY']) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\gen\_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.py", line 1467, in <module> ISpeechBaseStream._methods_ = [ File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 329, in __setattr__ self._make_methods(value) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 698, in _make_methods prototype = WINFUNCTYPE(restype, *argtypes) File "C:\Users\RAMS\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 125, in WINFUNCTYPE class WinFunctionType(_CFuncPtr): TypeError: item 1 in _argtypes_ passes a union by value, which is unsupported ``` ''' this is the error I don't know why In command prompt pip install pyttsx3: ``` Requirement already satisfied: pyttsx3 in c:\users\rams\appdata\local\programs\p ython\python38\lib\site-packages (2.90) Requirement already satisfied: comtypes; platform_system == "Windows" in c:\user s\rams\appdata\local\programs\python\python38\lib\site-packages (from pyttsx3) ( 1.1.7) Requirement already satisfied: pypiwin32; platform_system == "Windows" in c:\use rs\rams\appdata\local\programs\python\python38\lib\site-packages (from pyttsx3) (223) Requirement already satisfied: pywin32; platform_system == "Windows" in c:\users \rams\appdata\local\programs\python\python38\lib\site-packages (from pyttsx3) (2 28) ```
2020/08/04
[ "https://Stackoverflow.com/questions/63247247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14047733/" ]
Looks like the Vercel docs are currently outdated (AWS SDK V2 instead of V3). You can pass the credentials object to the AWS service when you instantiate it. Use an environment variable that is not reserved by adding the name of your app to it for example. *.env.local* ``` YOUR_APP_AWS_ACCESS_KEY_ID=[your key] YOUR_APP_AWS_SECRET_ACCESS_KEY=[your secret] ``` Add these env variables to your Vercel deployment settings (or Netlify, etc) and pass them in when you start up your AWS service client. ``` import { S3Client } from '@aws-sdk/client-s3' ... const s3 = new S3Client({ region: 'us-east-1', credentials: { accessKeyId: process.env.TRENDZY_AWS_ACCESS_KEY_ID ?? '', secretAccessKey: process.env.TRENDZY_AWS_SECRET_ACCESS_KEY ?? '', }, }) ``` (note: undefined check so Typescript stays happy)
are you possibly hosting this app via vercel? As per vercel docs, some env variables are reserved by vercel. <https://vercel.com/docs/concepts/projects/environment-variables#reserved-environment-variables> AWS\_ACCESS\_KEY\_ID AWS\_SECRET\_ACCESS\_KEY Maybe that's the reason why it is not getting those env vars I was able to workaround this by adding my custom env variables into .env.local and then calling for those variables ``` AWS.config.update({ 'region': 'us-east-1', 'credentials': { 'accessKeyId': process.env.MY_AWS_ACCESS_KEY, 'secretAccessKey': process.env.MY_AWS_SECRET_KEY } }); ``` As last step would need to add these into vercel UI obviously not ideal solution and not recommended by AWS. <https://vercel.com/support/articles/how-can-i-use-aws-sdk-environment-variables-on-vercel>
31,264,522
I've made a simple combobox in python using Tkinter, I want to retrieve the value selected by the user. After searching, I think I can do this by binding an event of selection and call a function that will use something like box.get(), but this is not working. When the program starts the method is automatically called and it doesn't print the current selection. When I select any item from the combobox no method gets called. Here is a snippet of my code: ``` self.box_value = StringVar() self.locationBox = Combobox(self.master, textvariable=self.box_value) self.locationBox.bind("<<ComboboxSelected>>", self.justamethod()) self.locationBox['values'] = ('one', 'two', 'three') self.locationBox.current(0) ``` This is the method that is supposed to be called when I select an item from the box: ``` def justamethod (self): print("method is called") print (self.locationBox.get()) ``` Can anyone please tell me how to get the selected value? EDIT: I've corrected the call to justamethod by removing the brackets when binding the box to a function as suggested by James Kent. But now I'm getting this error: TypeError: justamethod() takes exactly 1 argument (2 given) EDIT 2: I've posted the solution to this problem. Thank You.
2015/07/07
[ "https://Stackoverflow.com/questions/31264522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018299/" ]
I've figured out what's wrong in the code. First, as James said the brackets should be removed when binding justamethod to the combobox. Second, regarding the type error, this is because justamethod is an event handler, so it should take two parameters, self and event, like this, ``` def justamethod (self, event): ``` After making these changes the code is working well.
``` from tkinter import ttk from tkinter import messagebox from tkinter import Tk root = Tk() root.geometry("400x400") #^ width - heghit window :D cmb = ttk.Combobox(root, width="10", values=("prova","ciao","come","stai")) #cmb = Combobox class TableDropDown(ttk.Combobox): def __init__(self, parent): self.current_table = tk.StringVar() # create variable for table ttk.Combobox.__init__(self, parent)# init widget self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices", "Prices"]) self.current(0) # index of values for current table self.place(x = 50, y = 50, anchor = "w") # place drop down box def checkcmbo(): if cmb.get() == "prova": messagebox.showinfo("What user choose", "you choose prova") elif cmb.get() == "ciao": messagebox.showinfo("What user choose", "you choose ciao") elif cmb.get() == "come": messagebox.showinfo("What user choose", "you choose come") elif cmb.get() == "stai": messagebox.showinfo("What user choose", "you choose stai") elif cmb.get() == "": messagebox.showinfo("nothing to show!", "you have to be choose something") cmb.place(relx="0.1",rely="0.1") btn = ttk.Button(root, text="Get Value",command=checkcmbo) btn.place(relx="0.5",rely="0.1") root.mainloop() ```
70,461,032
How do I get a user keyboard input with python and print the name of that key ? e.g: > > user clicked on "SPACE" and output is "SPACE" > user clicked on "CTRL" and output is "CTRL". > > > for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to use only keys on my dict. i dont know how to add the other keyboard keys. see example: ``` class KeyboardSettings(): def __init__(self,description,keyboard): self.keyboard = keyboard self.default = keyboard self.description = description self.active = False def activate_change(self,x,y): fixed_rect = self.rect.move(x_fix,y_fix) pos = pygame.mouse.get_pos() if fixed_rect.collidepoint((pos)): if pygame.mouse.get_pressed()[0]: self.active = True elif pygame.mouse.get_pressed()[0]: self.active = False ``` This is a part of my class. in my script i loading all related object to that class. the related object are the optional keys in the game. e.g ``` SHOOT1 = KeyboardSettings("SHOOT","q") move_right = KeyboardSettings("move_right","d") #and more keys key_obj_lst = [SHOOT1,move_right....] #also i built a dict a-z, 0,9 dict_key = { 'a' : pygame.K_a, 'b' : pygame.K_b, 'c' : pygame.K_c, ... 'z' : pygame.K_z, '0' : pygame.K_0, ... '1' : pygame.K_1, '9' : pygame.K_9, ``` then in game loop: ``` for event in pygame.event.get(): if event.type == pygame.KEYDOWN: for k in key_obj_lst: #define each key by user if k.active: k.keyboard = event.unicode default = False if k.keyboard in dict_key: if event.key == dict_key[k.keyboard]: if k.description == 'Moving Right': moving_right = True if k.description == 'SHOOT': SHOOT = True ``` The code worked perfectly but i trully dont know how to add keys that not letters and numbers such as "ENTER","SPACE" etc.
2021/12/23
[ "https://Stackoverflow.com/questions/70461032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17408857/" ]
`pygame` provides a function for getting the name of the key pressed: [`pygame.key.name`](https://www.pygame.org/docs/ref/key.html#pygame.key.name) And so you can use it to get the name of the key, there is no need to use a dictionary for this: ```py import pygame pygame.init() screen = pygame.display.set_mode((500, 400)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN: key_name = pygame.key.name(event.key) print(key_name) ```
``` pip install keyboard import keyboard #use keyboard module while True: if keyboard.is_pressed('SPACE'): print('You pressed SPACE!') break elif keyboard.is_pressed("ENTER"): print("You pressed ENTER.") break ```
70,461,032
How do I get a user keyboard input with python and print the name of that key ? e.g: > > user clicked on "SPACE" and output is "SPACE" > user clicked on "CTRL" and output is "CTRL". > > > for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to use only keys on my dict. i dont know how to add the other keyboard keys. see example: ``` class KeyboardSettings(): def __init__(self,description,keyboard): self.keyboard = keyboard self.default = keyboard self.description = description self.active = False def activate_change(self,x,y): fixed_rect = self.rect.move(x_fix,y_fix) pos = pygame.mouse.get_pos() if fixed_rect.collidepoint((pos)): if pygame.mouse.get_pressed()[0]: self.active = True elif pygame.mouse.get_pressed()[0]: self.active = False ``` This is a part of my class. in my script i loading all related object to that class. the related object are the optional keys in the game. e.g ``` SHOOT1 = KeyboardSettings("SHOOT","q") move_right = KeyboardSettings("move_right","d") #and more keys key_obj_lst = [SHOOT1,move_right....] #also i built a dict a-z, 0,9 dict_key = { 'a' : pygame.K_a, 'b' : pygame.K_b, 'c' : pygame.K_c, ... 'z' : pygame.K_z, '0' : pygame.K_0, ... '1' : pygame.K_1, '9' : pygame.K_9, ``` then in game loop: ``` for event in pygame.event.get(): if event.type == pygame.KEYDOWN: for k in key_obj_lst: #define each key by user if k.active: k.keyboard = event.unicode default = False if k.keyboard in dict_key: if event.key == dict_key[k.keyboard]: if k.description == 'Moving Right': moving_right = True if k.description == 'SHOOT': SHOOT = True ``` The code worked perfectly but i trully dont know how to add keys that not letters and numbers such as "ENTER","SPACE" etc.
2021/12/23
[ "https://Stackoverflow.com/questions/70461032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17408857/" ]
`pygame` provides a function for getting the name of the key pressed: [`pygame.key.name`](https://www.pygame.org/docs/ref/key.html#pygame.key.name) And so you can use it to get the name of the key, there is no need to use a dictionary for this: ```py import pygame pygame.init() screen = pygame.display.set_mode((500, 400)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.KEYDOWN: key_name = pygame.key.name(event.key) print(key_name) ```
Use `keyboard` module ```py import keyboard while True: print(f"You pressed {keyboard.get_hotkey_name()}) ```
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
Following mewahl's comment I've added to my .bashrc (I use bash): > > export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/** > > > and now basemap (and others work).
I faced same problem. I installed anaconda and install conda install -c anaconda basemap. I used Anaconda built in IDE named "Spyder". Spyder is better than pycharm. only problem with spyder is lack of intellisense. I solved problem of Proj4 by setting path. Other problem kernel restarting when loading of .json larger file dataset. I use notepad++ and 010 editor to re-save file in small chunks and at last I merged all outputs.
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
This seems to be a common issue. There are several bug reports about it * [basemap/issues/419](https://github.com/matplotlib/basemap/issues/419), * [https://github.com/matplotlib/basemap/issues/428](https://github.com/conda-forge/basemap-feedstock/issues/30) * [basemap/issues/428](https://github.com/matplotlib/basemap/issues/428) I had run into this error myself, and for me the solution was to uninstall basemap 1.2, then install basemap 1.1 from an old wheel file I still had lying around and then install basemap 1.2 again. I honestly have no idea why that worked though. Also from those issues above there are all kinds of other solutions that people have reported to work for them. Hopefully one of them fits here as well.
I faced same problem. I installed anaconda and install conda install -c anaconda basemap. I used Anaconda built in IDE named "Spyder". Spyder is better than pycharm. only problem with spyder is lack of intellisense. I solved problem of Proj4 by setting path. Other problem kernel restarting when loading of .json larger file dataset. I use notepad++ and 010 editor to re-save file in small chunks and at last I merged all outputs.
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
For Windows 10 with Anaconda + Python 3.71 (and I'm sure other Python 3 versions and Windows 7/8), you can tell Basemap where Proj4's "epsg" file is to succeed. I don't have an "environment" or whatever because it's too much work to figure out - so I didn't have an anaconda\share\proj area (as far as I could discern why I didn't have it). But, what Basemap wants is the file "epsg", search the Anaconda directory for it with Windows Explorer. If it doesn't find it, install Proj4 by opening the "Anaconda Prompt" and typing in: ``` conda install -c conda-forge proj4 ``` If it finds it, it should be in something like: **C:\Utilities\Python\Anaconda\Library\Share** (it's where mine was, as well as \pkgs\ places where I guess it puts the package itself - and those can work too if need be, I used them at first, but the library one should work through updates better (maybe)). Use the following code before importing Basemap and it'll work. Sets the environment variable PROJ\_LIB to wherever epsg is and then Basemap can be happy. ``` import os os.environ["PROJ_LIB"] = "C:\\Utilities\\Python\\Anaconda\\Library\\share"; #fixr from mpl_toolkits.basemap import Basemap ``` As a nice bonus, to get hi-res data of Basemap, which Anaconda doesn't include in the Basemap install to start, type into "Anaconda Prompt": ``` conda install -c conda-forge basemap-data-hires ```
Following mewahl's comment I've added to my .bashrc (I use bash): > > export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/** > > > and now basemap (and others work).
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
This worked for me: ``` import os os.environ["PROJ_LIB"] = os.path.join(os.environ["CONDA_PREFIX"], "share", "proj") ``` This extends @Yusuf Baktir 's answer by omitting hard-coding the path to the epsg file. This way the code works on any machine that has conda installed (and activated of course).
I was not able to solve this problem but I was able to find an alternate, use CartoPy. basemap is being maintained for python 2.7 users. CartoPy is a better alternative
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
This seems to be a common issue. There are several bug reports about it * [basemap/issues/419](https://github.com/matplotlib/basemap/issues/419), * [https://github.com/matplotlib/basemap/issues/428](https://github.com/conda-forge/basemap-feedstock/issues/30) * [basemap/issues/428](https://github.com/matplotlib/basemap/issues/428) I had run into this error myself, and for me the solution was to uninstall basemap 1.2, then install basemap 1.1 from an old wheel file I still had lying around and then install basemap 1.2 again. I honestly have no idea why that worked though. Also from those issues above there are all kinds of other solutions that people have reported to work for them. Hopefully one of them fits here as well.
I was not able to solve this problem but I was able to find an alternate, use CartoPy. basemap is being maintained for python 2.7 users. CartoPy is a better alternative
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
You have to set the path of Proj lib as in newer version , this path has been replaced. Write below two lines of code before importing matplot\_toolkits ``` ### For Window's Users import os os.environ['PROJ_LIB'] = r'C:\Users\XXXXX\Anaconda3\pkgs\proj4-5.2.0- ha925a31_1\Library\share' ``` To find the path of Proj\_lib , just search epsg and then copy this epsg file location and put in proj\_lib . Your Problem will be solved. ``` ### For Linux's Users import os os.environ['PROJ_LIB'] = r'/home/XXXXXX/anaconda3/pkgs/proj4-5.2.0- he6710b0_1/share/proj' ```
Proj4 easy solution to fix on pycharm is goto setting-> project interpreter -> + -> write proj4 in the search field and install.
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
The answer is from Github and it worked for me. ``` import os import conda conda_file_dir = conda.__file__ conda_dir = conda_file_dir.split('lib')[0] proj_lib = os.path.join(os.path.join(conda_dir, 'share'), 'proj') os.environ["PROJ_LIB"] = proj_lib from mpl_toolkits.basemap import Basemap ```
I faced same problem. I installed anaconda and install conda install -c anaconda basemap. I used Anaconda built in IDE named "Spyder". Spyder is better than pycharm. only problem with spyder is lack of intellisense. I solved problem of Proj4 by setting path. Other problem kernel restarting when loading of .json larger file dataset. I use notepad++ and 010 editor to re-save file in small chunks and at last I merged all outputs.
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
Following mewahl's comment I've added to my .bashrc (I use bash): > > export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/** > > > and now basemap (and others work).
Proj4 easy solution to fix on pycharm is goto setting-> project interpreter -> + -> write proj4 in the search field and install.
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
You have to set the path of Proj lib as in newer version , this path has been replaced. Write below two lines of code before importing matplot\_toolkits ``` ### For Window's Users import os os.environ['PROJ_LIB'] = r'C:\Users\XXXXX\Anaconda3\pkgs\proj4-5.2.0- ha925a31_1\Library\share' ``` To find the path of Proj\_lib , just search epsg and then copy this epsg file location and put in proj\_lib . Your Problem will be solved. ``` ### For Linux's Users import os os.environ['PROJ_LIB'] = r'/home/XXXXXX/anaconda3/pkgs/proj4-5.2.0- he6710b0_1/share/proj' ```
I was not able to solve this problem but I was able to find an alternate, use CartoPy. basemap is being maintained for python 2.7 users. CartoPy is a better alternative
52,295,117
I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with ``` from mpl_toolkits.basemap import Basemap` ``` And the Traceback as followed: ``` Traceback (most recent call last): File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-0a24a3a77efd>", line 7, in <module> from mpl_toolkits.basemap import Basemap File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/mpl_toolkits/basemap/__init__.py", line 146, in <module> pyproj_datadir = os.environ['PROJ_LIB'] File "/Users/yupeipei/anaconda3/lib/python3.6/os.py", line 669, in __ getitem__ raise KeyError(key) from None KeyError: 'PROJ_LIB' ``` I'm confused with this error on PyCharm, because the same script is running correctly on Jupyter or Spyder! The environment in PyCharm is ../anaconda3/lib/python3.6 where is same from anaconda. Has anyone met this error before? Could anyone can help me to solve this error?
2018/09/12
[ "https://Stackoverflow.com/questions/52295117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9101918/" ]
This worked for me: ``` import os os.environ["PROJ_LIB"] = os.path.join(os.environ["CONDA_PREFIX"], "share", "proj") ``` This extends @Yusuf Baktir 's answer by omitting hard-coding the path to the epsg file. This way the code works on any machine that has conda installed (and activated of course).
This seems to be a common issue. There are several bug reports about it * [basemap/issues/419](https://github.com/matplotlib/basemap/issues/419), * [https://github.com/matplotlib/basemap/issues/428](https://github.com/conda-forge/basemap-feedstock/issues/30) * [basemap/issues/428](https://github.com/matplotlib/basemap/issues/428) I had run into this error myself, and for me the solution was to uninstall basemap 1.2, then install basemap 1.1 from an old wheel file I still had lying around and then install basemap 1.2 again. I honestly have no idea why that worked though. Also from those issues above there are all kinds of other solutions that people have reported to work for them. Hopefully one of them fits here as well.
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
I got this problem while testing lambda function. What worked for me was formatting JSON.
For me, the issue was that I had set the wrong default region environment key.
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
I had this error simply because I had a typo in the role ARN. I really wish the error was more explicit and said something along the lines of "this role doesn't exist", but alas.
I was running into this error with terraform and needed to add an assume role policy and apply it to the role that lambda assumes. ``` data "aws_iam_policy_document" "lambda_assume_role_policy" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = [ "lambda.amazonaws.com" ] } } resource "aws_iam_role" "lambda_rotation_role" { name = "lambda-rotation-role" assume_role_policy = "${data.aws_iam_policy_document.lambda_assume_role_policy.json}" } ```
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
I got this problem while testing lambda function. What worked for me was formatting JSON.
I am just learning to use the AWS CLI and ran into this issue. I am using a series of PowerShell scripts to deploy an entire AWS architecture. My **createRole.ps1** script contains: ``` aws iam create-role ` --role-name $roleName ` --assume-role-policy-document file://myRoleTrustPolicy.json ``` The file **myRoleTrustPolicy.json** contains: ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "elasticmapreduce.amazonaws.com", "datapipeline.amazonaws.com", "lambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } ``` It is the **"lambda.amazonaws.com"** line that was missing from Service list that was causing the issue. Once I fixed that, the invocation of **aws lambda create-function** worked great. ``` aws lambda create-function ` --function-name $fn ` --runtime java8 ` --role $currentRoleARN ` --handler "handleRequest" ` --memory-size 128 ` --zip-file $jarFile ```
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
I'm also encountering this error. Have not got a definitive answer (yet) but figured I'd pass along a couple of hints that may help you and/or anyone else hitting this problem. A) If you build the Role ARN by putting together your account ID and role name, I think the account ID needs to be without any dashes B) If you just created the role, and possibly added policies to it, there seems to be a (small) window of time in which the role will trigger this error. Sleeping 5 or 6 seconds between the last operation on the role and the create-function call allowed me to bypass the issue (but of course, the timing may be variable so this is at best a work-around).
For me, the issue was that I had an incomplete name for the role. I set ``` --role arn:aws:iam::000000000000:role/MyRoleName ``` when it should have been ``` --role arn:aws:iam::000000000000:role/service-role/MyRoleName ``` *(of course my aws id isn't actually 000000000000)* I discovered this by running ``` aws iam get-role --role-name MyRoleName ``` and looking at the `"Arn"` property in the result set.
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
I am just learning to use the AWS CLI and ran into this issue. I am using a series of PowerShell scripts to deploy an entire AWS architecture. My **createRole.ps1** script contains: ``` aws iam create-role ` --role-name $roleName ` --assume-role-policy-document file://myRoleTrustPolicy.json ``` The file **myRoleTrustPolicy.json** contains: ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "elasticmapreduce.amazonaws.com", "datapipeline.amazonaws.com", "lambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } ``` It is the **"lambda.amazonaws.com"** line that was missing from Service list that was causing the issue. Once I fixed that, the invocation of **aws lambda create-function** worked great. ``` aws lambda create-function ` --function-name $fn ` --runtime java8 ` --role $currentRoleARN ` --handler "handleRequest" ` --memory-size 128 ` --zip-file $jarFile ```
It could be that the Lambda is missing an execution role. Or this role has been deleted. In console you can see the status at Lambda > Functions > YourFunction > Permissions. Even an IAM empty role with no policies is enough to make it work.
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
For me, the issue was that I had an incomplete name for the role. I set ``` --role arn:aws:iam::000000000000:role/MyRoleName ``` when it should have been ``` --role arn:aws:iam::000000000000:role/service-role/MyRoleName ``` *(of course my aws id isn't actually 000000000000)* I discovered this by running ``` aws iam get-role --role-name MyRoleName ``` and looking at the `"Arn"` property in the result set.
I was running into this error with terraform and needed to add an assume role policy and apply it to the role that lambda assumes. ``` data "aws_iam_policy_document" "lambda_assume_role_policy" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = [ "lambda.amazonaws.com" ] } } resource "aws_iam_role" "lambda_rotation_role" { name = "lambda-rotation-role" assume_role_policy = "${data.aws_iam_policy_document.lambda_assume_role_policy.json}" } ```
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
For me, the issue was that I had an incomplete name for the role. I set ``` --role arn:aws:iam::000000000000:role/MyRoleName ``` when it should have been ``` --role arn:aws:iam::000000000000:role/service-role/MyRoleName ``` *(of course my aws id isn't actually 000000000000)* I discovered this by running ``` aws iam get-role --role-name MyRoleName ``` and looking at the `"Arn"` property in the result set.
I got this problem while testing lambda function. What worked for me was formatting JSON.
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
I am just learning to use the AWS CLI and ran into this issue. I am using a series of PowerShell scripts to deploy an entire AWS architecture. My **createRole.ps1** script contains: ``` aws iam create-role ` --role-name $roleName ` --assume-role-policy-document file://myRoleTrustPolicy.json ``` The file **myRoleTrustPolicy.json** contains: ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "elasticmapreduce.amazonaws.com", "datapipeline.amazonaws.com", "lambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } ``` It is the **"lambda.amazonaws.com"** line that was missing from Service list that was causing the issue. Once I fixed that, the invocation of **aws lambda create-function** worked great. ``` aws lambda create-function ` --function-name $fn ` --runtime java8 ` --role $currentRoleARN ` --handler "handleRequest" ` --memory-size 128 ` --zip-file $jarFile ```
Most people end up in this error because of giving the wrong Role ARN in CloudFormation while creating the Lambda Function. Make sure the role is completed first by using "DependsOn" and use the intrinsic function """{ "Fn::GetAtt" : [ "your-role-logical-name", "Arn" ] }"""
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
For me, the issue was that I had set the wrong default region environment key.
Most people end up in this error because of giving the wrong Role ARN in CloudFormation while creating the Lambda Function. Make sure the role is completed first by using "DependsOn" and use the intrinsic function """{ "Fn::GetAtt" : [ "your-role-logical-name", "Arn" ] }"""
36,419,442
I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command. > > aws lambda create-function > > --region us-west-2 > > --function-name HelloPython > > --zip-file fileb://hello\_python.zip > > --role arn:aws:iam::my-acc-account-id:role/default > > --handler hello\_python.my\_handler > > --runtime python2.7 > > --timeout 15 > > --memory-size 512 > > >
2016/04/05
[ "https://Stackoverflow.com/questions/36419442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045354/" ]
Had the same issue although my IAM role did have the right policy and trust relationship. Lambda creation worked fine when done through CLI the problem was when using lambda module after just creating the IAM role. I also tried to "pause" for few seconds but it didn't help. Ended up adding retry and delay until registerdLambda.code was defined. Usually it works after 1-2 tries. example: ``` - name: creating lambda function lambda: state: present name: "{{ lambdaName }}" zip_file: "{{ lambdaZipFile }}" runtime: "{{ lambdaRuntime }}" role: "{{ lambdaRole }}" description: "{{ lambdaDescription }}" handler: "{{ lambdaHandler }}" register: lambdaFunc retries: 3 delay: 10 until: "{{ lambdaFunc.code is defined }}" ```
It could be that the Lambda is missing an execution role. Or this role has been deleted. In console you can see the status at Lambda > Functions > YourFunction > Permissions. Even an IAM empty role with no policies is enough to make it work.
65,751,105
I'm using python prometheus client and have troubles pushing metrics to VictoriaMetrics (VM). There is a function called `push_to_gateway` and I tried to replace prometheus URL with VM: `http://prometheus:9091 -> http://vm:8428/api/v1/write`. But VM responded with 400 status code.
2021/01/16
[ "https://Stackoverflow.com/questions/65751105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6689249/" ]
It possible to use `push_to_gateway` method with VictoriaMetrics, check examples at gist <https://gist.github.com/f41gh7/85b2eb895bb63b93ce46ef73448c62d0>
Also, pls take a look at the client I recently created: <https://github.com/gistart/prometheus-push-client> > > supports pushes directly to VictoriaMetrics via UDP and HTTP using InfluxDB line protocol > > > > > to StatsD or statsd-exporter in StatsD format via UDP > > > > > to pushgateway or prom-aggregation-gateway in OpenMetrics format via HTTP > > >
65,751,105
I'm using python prometheus client and have troubles pushing metrics to VictoriaMetrics (VM). There is a function called `push_to_gateway` and I tried to replace prometheus URL with VM: `http://prometheus:9091 -> http://vm:8428/api/v1/write`. But VM responded with 400 status code.
2021/01/16
[ "https://Stackoverflow.com/questions/65751105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6689249/" ]
I'm using CSV import at `/api/v1/import/csv` as described here: <https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/README.md#how-to-import-csv-data> Generating CSV directly from pandas dataframe. Something like: ``` df.rename(columns={'timestamp': 'ts_ns'}, inplace=True) data = df.to_csv(index=False, header=False) csv_format = f'1:time:unix_ns{metric_format}{label_format}' response = requests.post(url, params={'format': csv_format}, data=data) ```
Also, pls take a look at the client I recently created: <https://github.com/gistart/prometheus-push-client> > > supports pushes directly to VictoriaMetrics via UDP and HTTP using InfluxDB line protocol > > > > > to StatsD or statsd-exporter in StatsD format via UDP > > > > > to pushgateway or prom-aggregation-gateway in OpenMetrics format via HTTP > > >
21,202,434
I have to random choose names from a list in python **using random.randint.** I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names. please help me out. **I am not allowed to use any high functions.** I should do it with simple functions. here is my program. ``` import random names = [about 150 names] print([names[random.randint(0, len(names)-1)] for i in range(user_input)]) ```
2014/01/18
[ "https://Stackoverflow.com/questions/21202434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3209210/" ]
Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result ``` copy = names[:] for i in xrange( user_input-1, 1, -1 ): swap = random.randint(0, i) copy[i],copy[swap] = copy[swap],copy[i] print copy[ :user_input ] ```
Generate an array of random numbers of the same length as `names` ``` sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))] ``` and sort your `names` array based on this new array ``` names = [name for sa, name in sorted(zip(sortarr, names))] ``` What it does is assigns some random numbers to the `names`. They can be repeating, but it will not make repeating names because if two numbers are the same, they will be assigned to some arbitrary names.
21,202,434
I have to random choose names from a list in python **using random.randint.** I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names. please help me out. **I am not allowed to use any high functions.** I should do it with simple functions. here is my program. ``` import random names = [about 150 names] print([names[random.randint(0, len(names)-1)] for i in range(user_input)]) ```
2014/01/18
[ "https://Stackoverflow.com/questions/21202434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3209210/" ]
These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided [the function in your last question](https://stackoverflow.com/a/21202023/2980246), so perhaps function declarations aren't allowed? Still, you can do the same thing without a function. You just need to keep track of indices you've already used. Here's another go: ``` indices = [] for x in range(5): index = random.randint(0, len(population)-1) while index in indices: index = random.randint(0, len(population)-1) indices.append(index) names = [population[i] for i in indices] ```
Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result ``` copy = names[:] for i in xrange( user_input-1, 1, -1 ): swap = random.randint(0, i) copy[i],copy[swap] = copy[swap],copy[i] print copy[ :user_input ] ```
21,202,434
I have to random choose names from a list in python **using random.randint.** I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names. please help me out. **I am not allowed to use any high functions.** I should do it with simple functions. here is my program. ``` import random names = [about 150 names] print([names[random.randint(0, len(names)-1)] for i in range(user_input)]) ```
2014/01/18
[ "https://Stackoverflow.com/questions/21202434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3209210/" ]
If you can destructively modify `names`, just `pop` the values instead of copying them. Then they're not there anymore, so you won't be able to repeat. If you can't destructively modify `names`, just do the same to a copy: ``` tmp = names[:] result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)] ``` This does have quadratic performance, since each `pop` from the middle of the list has to shift half the list up one notch. But for 150 names, this is unlikely to be a problem. For example, on my laptop, picking 100 values out of 150 names takes 83 microseconds. If you really aren't allowed to use even randrange, you can write it yourself: ``` def randrange(x): return randint(0, x-1) ```
Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result ``` copy = names[:] for i in xrange( user_input-1, 1, -1 ): swap = random.randint(0, i) copy[i],copy[swap] = copy[swap],copy[i] print copy[ :user_input ] ```
21,202,434
I have to random choose names from a list in python **using random.randint.** I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names. please help me out. **I am not allowed to use any high functions.** I should do it with simple functions. here is my program. ``` import random names = [about 150 names] print([names[random.randint(0, len(names)-1)] for i in range(user_input)]) ```
2014/01/18
[ "https://Stackoverflow.com/questions/21202434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3209210/" ]
These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided [the function in your last question](https://stackoverflow.com/a/21202023/2980246), so perhaps function declarations aren't allowed? Still, you can do the same thing without a function. You just need to keep track of indices you've already used. Here's another go: ``` indices = [] for x in range(5): index = random.randint(0, len(population)-1) while index in indices: index = random.randint(0, len(population)-1) indices.append(index) names = [population[i] for i in indices] ```
Generate an array of random numbers of the same length as `names` ``` sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))] ``` and sort your `names` array based on this new array ``` names = [name for sa, name in sorted(zip(sortarr, names))] ``` What it does is assigns some random numbers to the `names`. They can be repeating, but it will not make repeating names because if two numbers are the same, they will be assigned to some arbitrary names.
21,202,434
I have to random choose names from a list in python **using random.randint.** I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names. please help me out. **I am not allowed to use any high functions.** I should do it with simple functions. here is my program. ``` import random names = [about 150 names] print([names[random.randint(0, len(names)-1)] for i in range(user_input)]) ```
2014/01/18
[ "https://Stackoverflow.com/questions/21202434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3209210/" ]
If you can destructively modify `names`, just `pop` the values instead of copying them. Then they're not there anymore, so you won't be able to repeat. If you can't destructively modify `names`, just do the same to a copy: ``` tmp = names[:] result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)] ``` This does have quadratic performance, since each `pop` from the middle of the list has to shift half the list up one notch. But for 150 names, this is unlikely to be a problem. For example, on my laptop, picking 100 values out of 150 names takes 83 microseconds. If you really aren't allowed to use even randrange, you can write it yourself: ``` def randrange(x): return randint(0, x-1) ```
Generate an array of random numbers of the same length as `names` ``` sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))] ``` and sort your `names` array based on this new array ``` names = [name for sa, name in sorted(zip(sortarr, names))] ``` What it does is assigns some random numbers to the `names`. They can be repeating, but it will not make repeating names because if two numbers are the same, they will be assigned to some arbitrary names.
21,202,434
I have to random choose names from a list in python **using random.randint.** I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names. please help me out. **I am not allowed to use any high functions.** I should do it with simple functions. here is my program. ``` import random names = [about 150 names] print([names[random.randint(0, len(names)-1)] for i in range(user_input)]) ```
2014/01/18
[ "https://Stackoverflow.com/questions/21202434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3209210/" ]
If you can destructively modify `names`, just `pop` the values instead of copying them. Then they're not there anymore, so you won't be able to repeat. If you can't destructively modify `names`, just do the same to a copy: ``` tmp = names[:] result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)] ``` This does have quadratic performance, since each `pop` from the middle of the list has to shift half the list up one notch. But for 150 names, this is unlikely to be a problem. For example, on my laptop, picking 100 values out of 150 names takes 83 microseconds. If you really aren't allowed to use even randrange, you can write it yourself: ``` def randrange(x): return randint(0, x-1) ```
These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided [the function in your last question](https://stackoverflow.com/a/21202023/2980246), so perhaps function declarations aren't allowed? Still, you can do the same thing without a function. You just need to keep track of indices you've already used. Here's another go: ``` indices = [] for x in range(5): index = random.randint(0, len(population)-1) while index in indices: index = random.randint(0, len(population)-1) indices.append(index) names = [population[i] for i in indices] ```
18,942,003
I have this Python skeleton, where main.py is fine and server.py is fine. But the moment chat() is launched i see the GUI, but the moment `gtk.main()` was executed it does not allow any activity under server.py module nor in chat.py itself. How can i have the chat.py flexible so that it does not interupt other class and run all like multi-task? Note: os.system('/var/tmp/chat.py') when i execute from server.py then i have no issue but i problem is i cant communicate in that way (so trying to avoid that method) Any idea, why and how can i make chat.py work independently without causing my whole application to be blocked until chat.py is exit? main.py: ``` #!/usr/bin/python from myglobal import bgcolors from myglobal import parsePresets from server import server from chat import chat t = server(58888) t.start() ``` server.py ``` class server(threading.Thread): def __init__(self, port): threading.Thread.__init__(self) self.port = port self.selfv = chat() self.selfv.run() def run(self): host = '' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, self.port)) #s.setblocking(0) # non-blocking s.listen(1) conn, addr = s.accept() serverFlag = True while serverFlag: try: data = conn.recv(1024) except socket.error: s.listen(1) conn, addr = s.accept() continue if not data: s.listen(1) conn, addr = s.accept() else: line = data conn.send('ok') conn.close() ``` chat.py ``` class chat(object): def listener(self, sock, *args): conn, addr = sock.accept() gobject.io_add_watch(conn, gobject.IO_IN, self.handler) return True def handler(self, conn, *args): line = conn.recv(4096) if not len(line): return False else: return True def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_size_request(800, 450) self.window.move(0,0) self.window.set_name("main window") self.window.connect("delete-event", gtk.main_quit) self.drawingarea = gtk.DrawingArea() self.window.add(self.drawingarea) def run(self): self.sock = socket.socket() self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', 58881)) self.sock.listen(1) gobject.io_add_watch(self.sock, gobject.IO_IN, self.listener) self.window.show_all() self.window.set_keep_above(True) if(self.window.get_window().get_state() == gtk.gdk.WINDOW_STATE_MAXIMIZED): self.window.unmaximize() gtk.main() def quit(self): gtk.main_quit() #if __name__=='__main__': # s=SelfView() # s.run() #gobject.MainLoop.run() ```
2013/09/22
[ "https://Stackoverflow.com/questions/18942003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Instead of the default `sent_tokenize`, what you'll need is the realignment feature that is already pre-coded pre-trained in the `punkt` sentence tokenizer. ``` >>> import nltk >>> st2 = nltk.data.load('tokenizers/punkt/english.pickle') >>> sent = 'A problem. She said: "I don\'t know about it."' >>> st2.tokenize(sent, realign_boundaries=True) ['A problem.', 'She said: "I don\'t know about it."'] ``` see `6 Punkt Tokenizer` section from <http://nltk.googlecode.com/svn/trunk/doc/howto/tokenize.html>
The default sentence tokenizer is `PunktSentenceTokenizer` that detects a new sentence each time it founds a period except, for example, the period belongs to an acronym like U.S.A. In nltk documentation there are examples of how to train a new sentence splitter with different corpus. You can find it [here.](http://nltk.googlecode.com/svn/trunk/doc/book/ch06.html#sec-further-examples-of-supervised-classification) So I guess that your problem can't be solved with the default sentence tokenizer and you have to train a new one and try.
23,386,290
I want to use the logging module instead of printing for debug information and documentation. The goal is to print on the console with DEBUG level and log to a file with INFO level. I read through a lot of documentation, the cookbook and other tutorials on the logging module but couldn't figure out, how I can use it the way I want it. (I'm on python25) I want to have the names of the modules in which the logs are written in my logfile. The documentation says I should use `logger = logging.getLogger(__name__)` but how do I declare the loggers used in classes in other modules / packages, so they use the same handlers like the main logger? To recognize the 'parent' I can use `logger = logging.getLogger(parent.child)` but where do I know, who has called the class/method?` The example below shows my problem, if I run this, the output will only have the `__main__` logs in and ignore the logs in `Class` This is my **Mainfile:** ``` # main.py import logging from module import Class logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create file handler which logs info messages fh = logging.FileHandler('foo.log', 'w', 'utf-8') fh.setLevel(logging.INFO) # create console handler with a debug log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # creating a formatter formatter = logging.Formatter('- %(name)s - %(levelname)-8s: %(message)s') # setting handler format fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) if __name__ == '__main__': logger.info('Script starts') logger.info('calling class Class') c = Class() logger.info('calling c.do_something()') c.do_something() logger.info('calling c.try_something()') c.try_something() ``` **Module:** ``` # module.py imnport logging class Class: def __init__(self): self.logger = logging.getLogger(__name__) # What do I have to enter here? self.logger.info('creating an instance of Class') self.dict = {'a':'A'} def do_something(self): self.logger.debug('doing something') a = 1 + 1 self.logger.debug('done doing something') def try_something(self): try: logging.debug(self.dict['b']) except KeyError, e: logging.exception(e) ``` Output in **console:** ``` - __main__ - INFO : Script starts - __main__ - INFO : calling class Class - __main__ - INFO : calling c.do_something() - __main__ - INFO : calling c.try_something() No handlers could be found for logger "module" ``` Besides: Is there a way to get the module names were the logs ocurred in my logfile, without declaring a new logger in each class like above? Also like this way I have to go for `self.logger.info()` each time I want to log something. I would prefer to use `logging.info()` or `logger.info()` in my whole code. Is a global logger perhaps the right answer for this? But then I won't get the modules where the errors occur in the logs... And my last question: Is this pythonic? Or is there a better recommendation to do such things right.
2014/04/30
[ "https://Stackoverflow.com/questions/23386290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2889642/" ]
In your main module, you're configuring the logger of name `'__main__'` (or whatever `__name__` equates to in your case) while in module.py you're using a different logger. You either need to configure loggers per module, or you can configure the root logger (by configuring `logging.getLogger()`) in your main module which will apply by default to all loggers in your project. I recommend using configuration files for configuring loggers. This link should give you a good idea of good practices: <http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python> EDIT: use %(module) in your formatter to include the module name in the log message.
The generally recommended logging setup is having at most 1 logger per module. If your project is [properly packaged](https://packaging.python.org/), `__name__` will have the value of `"mypackage.mymodule"`, except in your main file, where it has the value `"__main__"` If you want more context about the code that is logging messages, note that you can set your formatter with a [formatter string](https://docs.python.org/3/library/logging.html#logrecord-attributes) like `%(funcName)s`, which will add the function name to all messages. If you **really** want per-class loggers, you can do something like: ``` class MyClass: def __init__(self): self.logger = logging.getLogger(__name__+"."+self.__class__.__name__) ```
65,222,770
i am new to all this and im trying to make a shoot 'em up game. after i try to run the code, i encounter an error `TypeError: 'int' object is not subscriptable` at: line 269: `collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY)` line 118: `distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemyY[i] - knifeY,2)))` not just here but pretty much every where in the loop if i put an 'i' on it ``` import pygame from pygame import mixer mixer.init() import random import math #Define some colors BLACK = (0,0,0) WHITE = (255,255,255) #intialize the pygame pygame.init() #create the screen screen = pygame.display.set_mode((700,583)) #Caption and icon pygame.display.set_caption("Yoshi & the rise of mushroom ") icon = pygame.image.load("Yoshi_icon.png") pygame.display.set_icon(icon) #Player playerImg = pygame.image.load("YoshiMario.png") playerX = 370 playerY = 480 playerX_change = 0 playerY_change = 0 #Enemy enemyImg = [] enemyX = [] enemyY = [] enemyX_change = [] enemyY_change = [] num_of_enemies = 10 for i in range(num_of_enemies): enemyImg.append(pygame.image.load('msh1.png')) enemyImg.append(pygame.image.load('msh2.png')) enemyX.append(random.randint(0,583)) enemyY.append(random.randint(50,150)) enemyX_change.append(2) enemyY_change.append(20) #Knife # ready - you cant see the knife on the screen # fire - the knife is currently moving knifeImg = pygame.image.load('diamondsword3.png') knifeX = 0 knifeY = 480 knifeX_change = 0 knifeY_change = 10 knife_state = "ready" #Score score_value = 0 font = pygame.font.Font('freesansbold.ttf',28) testX = 10 testY = 10 #Game Over Text over_font = pygame.font.Font('freesansbold.ttf',64) def show_score(x,y): score = font.render("Score : "+ str(score_value),True,(255,255,255)) screen.blit(score, (x, y)) def game_over_text(): over_text = over_font.render("GAME OVER",True,(255,255,255)) screen.blit(over_text, (150, 250)) def player(x,y): screen.blit(playerImg, (x, y)) def enemy(x,y,i): screen.blit(enemyImg[i], (x, y)) def fire_knife( x, y ): """ Start a knife flying upwards from the player """ global knife_state, knifeX, knifeY knifeX = x + 16 knifeY = y + 10 knife_state = "fire" def knife_hits( enemyX, enemyY ): """ Return True if the knife hits the enemy at the given (x,y). If so, prepare the knife for firing again. """ global knife_state, knifeX, knifeY collision_result = False if ( knife_state == "fire" and isCollision( enemyX[i], enemyY[i], knifeX, knifeY ) ): knife_state = "ready" collision_result = True return collision_result def draw_knife( screen ): """ If the knife is flying, draw it to the screen """ global knife_state, knifeImg, knifeX, knifeY if ( knife_state == "fire" ): screen.blit( knifeImg, ( knifeX, knifeY ) ) def update_knife(): """ Make any knife fly up the screen, resetting at the top """ global knife_state, knifeX, knifeY, knifeY_change # if the knife is already flying, move it if ( knife_state == "fire" ): knifeY -= knifeY_change if ( knifeY <= 0 ): knife_state = "ready" # went off-screen def isCollision(enemyX,enemyY,knifeX,knifeY): distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemyY[i] - knifeY,2))) if distance < 27: return True else: return False #used to manage how fast the screen updates clock = pygame.time.Clock() font = pygame.font.Font(None,28) frame_count = 0 frame_rate = 60 start_time = 90 #game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #if keystroke is pressed check whether its right or left if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -2 if event.key == pygame.K_RIGHT: playerX_change = 2 if event.key == pygame.K_UP: playerY_change = -2 if event.key == pygame.K_DOWN: playerY_change = 2 if event.key == pygame.K_SPACE: if knife_state is "ready": knife_Sound = mixer.Sound("knife_hitwall1.wav") knife_Sound.play() # get the current x coordinate of yoshi knifeX = playerX fire_knife(playerX,playerY) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: playerY_change = 0 ## -- Timer going up -- #Calculate total seconds total_seconds = frame_count // frame_rate #divide by 60 to get total minures minutes = total_seconds // 60 #use modulus (remainder) to get seconds seconds = total_seconds % 60 #use python string formatting to format in leading zeros output_string = "Time : {0:02}:{1:02}".format(minutes, seconds) # Blit to the screen text = font.render(output_string, True, (255,255,255)) screen.blit(text, [10,40]) # --- Timer going down --- # --- Timer going up --- # Calculate total seconds total_seconds = start_time - (frame_count // frame_rate) if total_seconds < 0: total_seconds = 0 # Divide by 60 to get total minutes minutes = total_seconds // 60 # Use modulus (remainder) to get seconds seconds = total_seconds % 60 # Use python string formatting to format in leading zeros output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds) # Blit to the screen text = font.render(output_string, True,(255,255,255)) screen.blit(text, [10,70]) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT frame_count += 1 # Limit frames per second clock.tick(frame_rate) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # RGB - Red, Green, Blue screen.fill((0, 255, 0)) #add a wallpaper bgimage=pygame.image.load("Background.png") screen.blit(bgimage, (0, 0)) # 5 = 5 + -0.1 ->5 = 5 - 0.1 # 5 = 5 + 0.1 # checking for boundaries of yoshi/mushroom so it doesnt go out of bounds playerX += playerX_change if playerX < 0: playerX = 0 elif playerX > 645: playerX = 645 playerY += playerY_change if playerY < 0: playerY = 0 elif playerY > 500: playerY = 500 # enemy movement for i in range(num_of_enemies): #Game Over if enemyY[i]> 440: for j in range(num_of_enemies): enemyY[j] = 2000 game_over_text() break enemyX[i] += enemyX_change[i] if enemyX[i] <= 0: enemyX_change[i] = 2 enemyY[i] += enemyY_change[i] elif enemyX[i] > 645: enemyX_change[i] = -2 enemyY[i] += enemyY_change[i] update_knife() # move the flying knife (if any) if ( knife_hits( enemyX[i], enemyY[i] ) ): score_value += 1 print(score_value) enemyX[i] = random.randint(0,735) enemyY[i] = random.randint(50,150) else: draw_knife( screen ) # paint the flying knife (if any) player(playerX,playerY) enemy(enemyX[i],enemyY[i],i) pygame.display.update() # collision collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY) if collision: pop_Sound = mixer.Sound('pop.wav') pop_Sound.play() knifeY = 480 knife_state = "ready" score_value += 1 enemyX[i] = random.randint(0,735) enemyY[i] = random.randint(50,150) enemy(enemyX[i],enemyY[i],i) # knife movement if knifeY <= 0: knifeY = 480 knife_state = "ready" if knife_state == "fire": fire_knife(knifeX,knifeY) knifeY -= knifeY_change playerX += playerX_change playerY += playerY_change player(playerX,playerY) show_score(testX,testY) pygame.display.update() ```
2020/12/09
[ "https://Stackoverflow.com/questions/65222770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11592606/" ]
You call `isCollision()` with `enemyX[i]`, but then in `isCollision`, you try to access `enemyX[i]`. So you're trying to do `enemyX[i][i]`. But since `enemyX[i]` is an integer, trying to get a subscript of it, `[i]`, is invalid so that's why you get that error.
You're already sending the specific number with e.g. `enemyX[i]` when you call `isCollision(enemyX[i], ...)`. Once in that function, you can just use the passed argument (which you also happen to call `enemyX` - it's just a different one from the caller's `enemyX`) by itself, e.g. `math.pow(enemyX -...`. I recommend reconsidering those variable names.
65,222,770
i am new to all this and im trying to make a shoot 'em up game. after i try to run the code, i encounter an error `TypeError: 'int' object is not subscriptable` at: line 269: `collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY)` line 118: `distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemyY[i] - knifeY,2)))` not just here but pretty much every where in the loop if i put an 'i' on it ``` import pygame from pygame import mixer mixer.init() import random import math #Define some colors BLACK = (0,0,0) WHITE = (255,255,255) #intialize the pygame pygame.init() #create the screen screen = pygame.display.set_mode((700,583)) #Caption and icon pygame.display.set_caption("Yoshi & the rise of mushroom ") icon = pygame.image.load("Yoshi_icon.png") pygame.display.set_icon(icon) #Player playerImg = pygame.image.load("YoshiMario.png") playerX = 370 playerY = 480 playerX_change = 0 playerY_change = 0 #Enemy enemyImg = [] enemyX = [] enemyY = [] enemyX_change = [] enemyY_change = [] num_of_enemies = 10 for i in range(num_of_enemies): enemyImg.append(pygame.image.load('msh1.png')) enemyImg.append(pygame.image.load('msh2.png')) enemyX.append(random.randint(0,583)) enemyY.append(random.randint(50,150)) enemyX_change.append(2) enemyY_change.append(20) #Knife # ready - you cant see the knife on the screen # fire - the knife is currently moving knifeImg = pygame.image.load('diamondsword3.png') knifeX = 0 knifeY = 480 knifeX_change = 0 knifeY_change = 10 knife_state = "ready" #Score score_value = 0 font = pygame.font.Font('freesansbold.ttf',28) testX = 10 testY = 10 #Game Over Text over_font = pygame.font.Font('freesansbold.ttf',64) def show_score(x,y): score = font.render("Score : "+ str(score_value),True,(255,255,255)) screen.blit(score, (x, y)) def game_over_text(): over_text = over_font.render("GAME OVER",True,(255,255,255)) screen.blit(over_text, (150, 250)) def player(x,y): screen.blit(playerImg, (x, y)) def enemy(x,y,i): screen.blit(enemyImg[i], (x, y)) def fire_knife( x, y ): """ Start a knife flying upwards from the player """ global knife_state, knifeX, knifeY knifeX = x + 16 knifeY = y + 10 knife_state = "fire" def knife_hits( enemyX, enemyY ): """ Return True if the knife hits the enemy at the given (x,y). If so, prepare the knife for firing again. """ global knife_state, knifeX, knifeY collision_result = False if ( knife_state == "fire" and isCollision( enemyX[i], enemyY[i], knifeX, knifeY ) ): knife_state = "ready" collision_result = True return collision_result def draw_knife( screen ): """ If the knife is flying, draw it to the screen """ global knife_state, knifeImg, knifeX, knifeY if ( knife_state == "fire" ): screen.blit( knifeImg, ( knifeX, knifeY ) ) def update_knife(): """ Make any knife fly up the screen, resetting at the top """ global knife_state, knifeX, knifeY, knifeY_change # if the knife is already flying, move it if ( knife_state == "fire" ): knifeY -= knifeY_change if ( knifeY <= 0 ): knife_state = "ready" # went off-screen def isCollision(enemyX,enemyY,knifeX,knifeY): distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemyY[i] - knifeY,2))) if distance < 27: return True else: return False #used to manage how fast the screen updates clock = pygame.time.Clock() font = pygame.font.Font(None,28) frame_count = 0 frame_rate = 60 start_time = 90 #game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #if keystroke is pressed check whether its right or left if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -2 if event.key == pygame.K_RIGHT: playerX_change = 2 if event.key == pygame.K_UP: playerY_change = -2 if event.key == pygame.K_DOWN: playerY_change = 2 if event.key == pygame.K_SPACE: if knife_state is "ready": knife_Sound = mixer.Sound("knife_hitwall1.wav") knife_Sound.play() # get the current x coordinate of yoshi knifeX = playerX fire_knife(playerX,playerY) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: playerY_change = 0 ## -- Timer going up -- #Calculate total seconds total_seconds = frame_count // frame_rate #divide by 60 to get total minures minutes = total_seconds // 60 #use modulus (remainder) to get seconds seconds = total_seconds % 60 #use python string formatting to format in leading zeros output_string = "Time : {0:02}:{1:02}".format(minutes, seconds) # Blit to the screen text = font.render(output_string, True, (255,255,255)) screen.blit(text, [10,40]) # --- Timer going down --- # --- Timer going up --- # Calculate total seconds total_seconds = start_time - (frame_count // frame_rate) if total_seconds < 0: total_seconds = 0 # Divide by 60 to get total minutes minutes = total_seconds // 60 # Use modulus (remainder) to get seconds seconds = total_seconds % 60 # Use python string formatting to format in leading zeros output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds) # Blit to the screen text = font.render(output_string, True,(255,255,255)) screen.blit(text, [10,70]) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT frame_count += 1 # Limit frames per second clock.tick(frame_rate) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # RGB - Red, Green, Blue screen.fill((0, 255, 0)) #add a wallpaper bgimage=pygame.image.load("Background.png") screen.blit(bgimage, (0, 0)) # 5 = 5 + -0.1 ->5 = 5 - 0.1 # 5 = 5 + 0.1 # checking for boundaries of yoshi/mushroom so it doesnt go out of bounds playerX += playerX_change if playerX < 0: playerX = 0 elif playerX > 645: playerX = 645 playerY += playerY_change if playerY < 0: playerY = 0 elif playerY > 500: playerY = 500 # enemy movement for i in range(num_of_enemies): #Game Over if enemyY[i]> 440: for j in range(num_of_enemies): enemyY[j] = 2000 game_over_text() break enemyX[i] += enemyX_change[i] if enemyX[i] <= 0: enemyX_change[i] = 2 enemyY[i] += enemyY_change[i] elif enemyX[i] > 645: enemyX_change[i] = -2 enemyY[i] += enemyY_change[i] update_knife() # move the flying knife (if any) if ( knife_hits( enemyX[i], enemyY[i] ) ): score_value += 1 print(score_value) enemyX[i] = random.randint(0,735) enemyY[i] = random.randint(50,150) else: draw_knife( screen ) # paint the flying knife (if any) player(playerX,playerY) enemy(enemyX[i],enemyY[i],i) pygame.display.update() # collision collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY) if collision: pop_Sound = mixer.Sound('pop.wav') pop_Sound.play() knifeY = 480 knife_state = "ready" score_value += 1 enemyX[i] = random.randint(0,735) enemyY[i] = random.randint(50,150) enemy(enemyX[i],enemyY[i],i) # knife movement if knifeY <= 0: knifeY = 480 knife_state = "ready" if knife_state == "fire": fire_knife(knifeX,knifeY) knifeY -= knifeY_change playerX += playerX_change playerY += playerY_change player(playerX,playerY) show_score(testX,testY) pygame.display.update() ```
2020/12/09
[ "https://Stackoverflow.com/questions/65222770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11592606/" ]
You do the subscription when you call the function `isCollision`: ```py if ( knife_state == "fire" and isCollision( enemyX[i], enemyY[i], knifeX, knifeY ) ): ``` Hence you must remove the subscription in the function: ~~`distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemyY[i] - knifeY,2)))`~~ ```py def isCollision(enemyX,enemyY,knifeX,knifeY): distance = math.sqrt((math.pow(enemyX - knifeX,2)) + (math.pow(enemyY - knifeY,2))) if distance < 27: return True else: return False ```
You're already sending the specific number with e.g. `enemyX[i]` when you call `isCollision(enemyX[i], ...)`. Once in that function, you can just use the passed argument (which you also happen to call `enemyX` - it's just a different one from the caller's `enemyX`) by itself, e.g. `math.pow(enemyX -...`. I recommend reconsidering those variable names.
38,218,609
I started to learn Scrapy but I stuck up at weird point where I couldn't set default shell to ipython. The operating system of my laptop is Ubuntu 15.10. I also installed ipython and scrapy. They run well without causing any errors. According to Scrapy's [official tutorial](http://doc.scrapy.org/en/latest/topics/shell.html), I can change my default scrapy shell by entering this in the global configuration file ``` [settings] shell = ipython ``` The problem is I couldn't locate the configuration file. I tried following instructions from [another page](http://doc.scrapy.org/en/latest/topics/commands.html#topics-config-settings). I made these three config files in 1. `/etc/scrapy.cfg` (system-wide), 2. `~/.config/scrapy.cfg` ($XDG\_CONFIG\_HOME) and `~/.scrapy.cfg` ($HOME) for global (user-wide) settings. but It didn't help at all. what should I do? --- I followed the instruction in the first answer by paul trmbrth. There still seems to be a problem though. [![enter image description here](https://i.stack.imgur.com/MqEpr.png)](https://i.stack.imgur.com/MqEpr.png) seems like I do have a right configuration file in the right place. But I still cannot open scrapy shell with ipython, as you can see in the screenshot. Have any idea?
2016/07/06
[ "https://Stackoverflow.com/questions/38218609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5538922/" ]
Another way to configure (or test) the shell used by `scrapy shell` is the [`SCRAPY_PYTHON_SHELL` environment variable](http://doc.scrapy.org/en/latest/topics/shell.html#configuring-the-shell). So running: ``` paul@paul:~$ SCRAPY_PYTHON_SHELL=ipython scrapy shell ``` would use `ipython` as first choice, whatever setting in `*scrapy.cfg` you may have. To check where scrapy is looking for config files, and what it finds, you can start the `python` interpreter and run [what `scrapy shell` does](https://github.com/scrapy/scrapy/blob/ebef6d7c6dd8922210db8a4a44f48fe27ee0cd16/scrapy/shell.py#L67): ``` $ python Python 3.5.1+ (default, Mar 30 2016, 22:46:26) [GCC 5.3.1 20160330] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from scrapy.utils.conf import get_config, get_sources >>> get_sources() ['/etc/scrapy.cfg', 'c:\\scrapy\\scrapy.cfg', '/home/paul/.config/scrapy.cfg', '/home/paul/.scrapy.cfg', ''] >>> cfg = get_config() >>> cfg.sections() ['deploy', 'settings'] >>> cfg.options('settings') ['shell'] >>> cfg.get('settings', 'shell') 'bpython' ```
If you are inside of the project you can use this: ``` from scrapy.utils.project import get_project_settings settings = get_project_settings() settings.get('IMPORT_API_URL') ``` If you are outside of the project, you can use this: ``` from scrapy.settings import Settings settings = Settings() settings_module_path = os.environ.get('SCRAPY_ENV', 'project.settings.dev') settings.setmodule(settings_module_path, priority='project') settings.get('BASE_URL') ```
41,780,388
Please refrain from calling this a duplicate, I am completely new to idea of accessing USB devices via Python. The other questions and answers were often too high level for me to comprehend. I have a qr code scanner that is USB plug and play. I can't find it on the command line for whatever reason and it has me stumped. When the scanner scans a QR code I want its data to be sent to my python script so I can set it to a variable for comparison against a database. I don't understand how to access a USB device and retrieve the information with Python. I have read quite a bit about it and still nothing. Is there a some-what simple way of doing this?
2017/01/21
[ "https://Stackoverflow.com/questions/41780388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4562973/" ]
With this (second) call: ``` name_array = realloc(name_array, sizeof(char *)); ``` You are still allocating just one char pointer. So, you can't store two pointers; you need to increase the size: ``` name_array = realloc(name_array, 2 * sizeof *name_array); ``` Now, you'd be fine. Note that `p = realloc(p, ..);` style of realloc() could lead to memory leaks if `realloc()` fails. Also, you'd be better off using a format string to avoid pontential format string attack (if it's going to be user inputted): ``` /* Print the names */ printf ("%s\n", name_array[0]); printf ("%s\n", name_array[1]); ```
The error is better reported by address sanitizer than valgrind. If you compile your code like: ``` gcc test.c -fsanitize=address -g ``` and then run it, it will report heap-buffer-overflow error in line 19 of your code. This is the line where you assign second element of name\_array having allocated memory for only one element.
16,223,412
I have a relatively big project that has many dependencies, and I would like to distribute this project around, but installing these dependencies where a bit of a pain, and takes a very long time (pip install takes quite some time). So I was wondering if it was possible to migrate a whole virtualenv to another machine and have it running. I tried copying the whole virtualenv, but whenever I try running something, this virtualenv still uses the path of my old machine. For instance when I run ``` source activate pserve development.ini ``` I get ``` bash: ../bin/pserve: /home/sshum/backend/bin/python: bad interpreter: No such file or directory ``` This is my old directory. So is there a way to have virtualenv reconfigure this path with a new path? I tried `sed -i 's/sshum/dev1/g' *` in the bin directory and it solved that issue. However, I'm getting a different issue now, my guess is that this sed changed something. I've confirmed that I have `libssl-dev` installed but when I run `python` I get: ``` E: Unable to locate package libssl.so.1.0.0 E: Couldn't find any package by regex 'libssl.so.1.0.0' ``` But when I run `aptitude search libssl` and I see: ``` i A libssl-dev - SSL development libraries, header files and documentation ``` I also tried `virtualenv --relocatable backend` but no go.
2013/04/25
[ "https://Stackoverflow.com/questions/16223412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515864/" ]
Export virtualenvironment *from within the virtual environment:* ``` pip freeze > requirements.txt ``` as example, here is for myproject virtual environment: [![enter image description here](https://i.stack.imgur.com/EJUEk.png)](https://i.stack.imgur.com/EJUEk.png) once in the new machine & environment, copy the requirements.txt into the *new project folder in the new machine* and run the terminal command: ``` sudo pip install -r requirements.txt ``` then you should have all the packages previously available in the old virtual environment.
When you create a new virtualenv it is configured for the computer it is running on. I even think that it is configured for that specific directory it is created in. So I think you should always create a fresh virtualenv when you move you code. What might work is copying the lib/Pythonx.x/site-packages in your virtualenv directory, but I don't think that is a particularly good solution. What may be a better solution is using the pip download cache. This will at least speed up the download part of pip install. Have a look at this thread: [How do I install from a local cache with pip?](https://stackoverflow.com/questions/4806448/how-do-i-install-from-a-local-cache-with-pip)
16,223,412
I have a relatively big project that has many dependencies, and I would like to distribute this project around, but installing these dependencies where a bit of a pain, and takes a very long time (pip install takes quite some time). So I was wondering if it was possible to migrate a whole virtualenv to another machine and have it running. I tried copying the whole virtualenv, but whenever I try running something, this virtualenv still uses the path of my old machine. For instance when I run ``` source activate pserve development.ini ``` I get ``` bash: ../bin/pserve: /home/sshum/backend/bin/python: bad interpreter: No such file or directory ``` This is my old directory. So is there a way to have virtualenv reconfigure this path with a new path? I tried `sed -i 's/sshum/dev1/g' *` in the bin directory and it solved that issue. However, I'm getting a different issue now, my guess is that this sed changed something. I've confirmed that I have `libssl-dev` installed but when I run `python` I get: ``` E: Unable to locate package libssl.so.1.0.0 E: Couldn't find any package by regex 'libssl.so.1.0.0' ``` But when I run `aptitude search libssl` and I see: ``` i A libssl-dev - SSL development libraries, header files and documentation ``` I also tried `virtualenv --relocatable backend` but no go.
2013/04/25
[ "https://Stackoverflow.com/questions/16223412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515864/" ]
Export virtualenvironment *from within the virtual environment:* ``` pip freeze > requirements.txt ``` as example, here is for myproject virtual environment: [![enter image description here](https://i.stack.imgur.com/EJUEk.png)](https://i.stack.imgur.com/EJUEk.png) once in the new machine & environment, copy the requirements.txt into the *new project folder in the new machine* and run the terminal command: ``` sudo pip install -r requirements.txt ``` then you should have all the packages previously available in the old virtual environment.
The clean way seems to be with `virtualenv --relocatable`. Alternatively, you can do it manually by editing the `VIRTUAL_ENV` path in `bin/activate` to reflect the changes. If you choose to do so, you must also edit the first line (#) of `bin/pserve` which indicates the interpreter path.
24,209,181
I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>. When working on my application locally I simply go to `http://127.0.0.1:8000/surveythree/` Based on my urls.py (below) I thought that I would simply have to go to <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> to see my Survey application online. However I cant seem to find it... My question: **What URL should I be using to locate my Survey Application based on my below settings?** Or have I missed some other step in the process? The project has been uploaded, I have restarted the server, I have set it running with `python manage.py runserver` Some of the urls I have tried * <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> * <http://phaedrus.scss.tcd.ie/bias_experiment/src/surveythree/> * <http://phaedrus.scss.tcd.ie/bias_experiment/src/bias_experiment/surveythree/> Below is my setup and what I have tried so far. NOTE: I have a Bias\_Experiment Django Project created in Pydev. It has three applications contained within an src folder. * survey (my working project) * polls (a tutorial i was following) * bias\_experiment (the root application with my settings file etc) **My URL patterns** from bias\_experiment/src/bias\_experiment/urls.py ``` urlpatterns = patterns('', url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), url(r'^surveythree/$', SurveyWizard.as_view([SurveyForm1, SurveyForm2, SurveyForm3, SurveyForm4, SurveyForm5])), ) ``` **My virtual host** located at /etc/apache2/sites-available/bias\_experiment ``` <VirtualHost *:80> ServerAdmin myemail@gmail.com ServerName phaedrus.scss.tcd.ie/bias_experiment ServerAlias phaedrus.scss.tcd.ie WSGIScriptAlias /bias_experiment /var/www/bias_experiment/src/bias_experiment/index.wsgi Alias /static/ /var/www/bias_experiment/src/bias_experiment/static/ <Location "/static/"> Options -Indexes </Location > </VirtualHost > ``` **My WSGI file** located at /var/www/bias\_experiment/src/bias\_experiment/index.wsgi ``` import os import sys import site # This is to add the src folder sys.path.append('/var/www/bias_experiment/src/bias_experiment') os.environ['DJANGO_SETTINGS_MODULE'] = 'bias_experiment.settings' # Activate your virtual env activate_env=os.path.expanduser("/var/www/bias_experiment/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ``` **This is the project structure** ![enter image description here](https://i.stack.imgur.com/4lSyZ.png) I had a [previous question related to this](https://stackoverflow.com/questions/24188604/django-application-not-visable) which had multiple issues pointed out to me which I have since fixed so I am re-posting this here. I have been following several tutorials as details in that question. Any help with this would be massively appreciated. Thanks Deepend EDIT: My Apache Error Log: `tail /var/log/apache2/error.log` ``` (bias_experiment)spillab@kdeg-vm-18:/var/www/bias_experiment/src$ sudo su root@kdeg-vm-18:/var/www/bias_experiment/src# tail /var/log/apache2/error.log [Fri Jun 13 16:21:04 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/surveythree, referer: https://stackoverflow.com/questions/24209181/what-should-be-the-url-of-my-django-application/24209864?noredirect=1 [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Use of undefined constant PHP_SELF - assumed 'PHP_SELF' in /var/www/bias_experiment/brendy.php on line 24, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Undefined index: brendy in /var/www/bias_experiment/brendy.php on line 27, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Use of undefined constant action - assumed 'action' in /var/www/bias_experiment/brendy.php on line 72, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Undefined index: action in /var/www/bias_experiment/brendy.php on line 72, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Warning: include(footer.php): failed to open stream: No such file or directory in /var/www/bias_experiment/brendy.php on line 118, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Warning: include(): Failed opening 'footer.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/bias_experiment/brendy.php on line 118, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/special.css, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/images, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/images, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php root@kdeg-vm-18:/var/www/bias_experiment/src# ```
2014/06/13
[ "https://Stackoverflow.com/questions/24209181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214163/" ]
The URL should be <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> I think there is one tiny error in the Apache configuration, which might be my fault (sorry): you need a trailing slash, so: ``` WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi ``` Also note that you don't need to run manage.py runserver, that's pointless as Apache is serving your app.
Try with this changes: Apache conf: ``` WSGIApplicationGroup %{GLOBAL} ServerName phaedrus.scss.tcd.ie WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi WSGIDaemonProcess bias_experiment processes=4 threads=25 display-name=%{GROUP} WSGIProcessGroup bias_experiment WSGIPassAuthorization On ``` And you need to restart the Apache server.
24,209,181
I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>. When working on my application locally I simply go to `http://127.0.0.1:8000/surveythree/` Based on my urls.py (below) I thought that I would simply have to go to <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> to see my Survey application online. However I cant seem to find it... My question: **What URL should I be using to locate my Survey Application based on my below settings?** Or have I missed some other step in the process? The project has been uploaded, I have restarted the server, I have set it running with `python manage.py runserver` Some of the urls I have tried * <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> * <http://phaedrus.scss.tcd.ie/bias_experiment/src/surveythree/> * <http://phaedrus.scss.tcd.ie/bias_experiment/src/bias_experiment/surveythree/> Below is my setup and what I have tried so far. NOTE: I have a Bias\_Experiment Django Project created in Pydev. It has three applications contained within an src folder. * survey (my working project) * polls (a tutorial i was following) * bias\_experiment (the root application with my settings file etc) **My URL patterns** from bias\_experiment/src/bias\_experiment/urls.py ``` urlpatterns = patterns('', url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), url(r'^surveythree/$', SurveyWizard.as_view([SurveyForm1, SurveyForm2, SurveyForm3, SurveyForm4, SurveyForm5])), ) ``` **My virtual host** located at /etc/apache2/sites-available/bias\_experiment ``` <VirtualHost *:80> ServerAdmin myemail@gmail.com ServerName phaedrus.scss.tcd.ie/bias_experiment ServerAlias phaedrus.scss.tcd.ie WSGIScriptAlias /bias_experiment /var/www/bias_experiment/src/bias_experiment/index.wsgi Alias /static/ /var/www/bias_experiment/src/bias_experiment/static/ <Location "/static/"> Options -Indexes </Location > </VirtualHost > ``` **My WSGI file** located at /var/www/bias\_experiment/src/bias\_experiment/index.wsgi ``` import os import sys import site # This is to add the src folder sys.path.append('/var/www/bias_experiment/src/bias_experiment') os.environ['DJANGO_SETTINGS_MODULE'] = 'bias_experiment.settings' # Activate your virtual env activate_env=os.path.expanduser("/var/www/bias_experiment/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ``` **This is the project structure** ![enter image description here](https://i.stack.imgur.com/4lSyZ.png) I had a [previous question related to this](https://stackoverflow.com/questions/24188604/django-application-not-visable) which had multiple issues pointed out to me which I have since fixed so I am re-posting this here. I have been following several tutorials as details in that question. Any help with this would be massively appreciated. Thanks Deepend EDIT: My Apache Error Log: `tail /var/log/apache2/error.log` ``` (bias_experiment)spillab@kdeg-vm-18:/var/www/bias_experiment/src$ sudo su root@kdeg-vm-18:/var/www/bias_experiment/src# tail /var/log/apache2/error.log [Fri Jun 13 16:21:04 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/surveythree, referer: https://stackoverflow.com/questions/24209181/what-should-be-the-url-of-my-django-application/24209864?noredirect=1 [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Use of undefined constant PHP_SELF - assumed 'PHP_SELF' in /var/www/bias_experiment/brendy.php on line 24, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Undefined index: brendy in /var/www/bias_experiment/brendy.php on line 27, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Use of undefined constant action - assumed 'action' in /var/www/bias_experiment/brendy.php on line 72, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Undefined index: action in /var/www/bias_experiment/brendy.php on line 72, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Warning: include(footer.php): failed to open stream: No such file or directory in /var/www/bias_experiment/brendy.php on line 118, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Warning: include(): Failed opening 'footer.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/bias_experiment/brendy.php on line 118, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/special.css, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/images, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/images, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php root@kdeg-vm-18:/var/www/bias_experiment/src# ```
2014/06/13
[ "https://Stackoverflow.com/questions/24209181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214163/" ]
Is this it in your /static/ folder? <http://phaedrus.scss.tcd.ie/bias_experiment/static/>
Try with this changes: Apache conf: ``` WSGIApplicationGroup %{GLOBAL} ServerName phaedrus.scss.tcd.ie WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi WSGIDaemonProcess bias_experiment processes=4 threads=25 display-name=%{GROUP} WSGIProcessGroup bias_experiment WSGIPassAuthorization On ``` And you need to restart the Apache server.
24,209,181
I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>. When working on my application locally I simply go to `http://127.0.0.1:8000/surveythree/` Based on my urls.py (below) I thought that I would simply have to go to <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> to see my Survey application online. However I cant seem to find it... My question: **What URL should I be using to locate my Survey Application based on my below settings?** Or have I missed some other step in the process? The project has been uploaded, I have restarted the server, I have set it running with `python manage.py runserver` Some of the urls I have tried * <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> * <http://phaedrus.scss.tcd.ie/bias_experiment/src/surveythree/> * <http://phaedrus.scss.tcd.ie/bias_experiment/src/bias_experiment/surveythree/> Below is my setup and what I have tried so far. NOTE: I have a Bias\_Experiment Django Project created in Pydev. It has three applications contained within an src folder. * survey (my working project) * polls (a tutorial i was following) * bias\_experiment (the root application with my settings file etc) **My URL patterns** from bias\_experiment/src/bias\_experiment/urls.py ``` urlpatterns = patterns('', url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), url(r'^surveythree/$', SurveyWizard.as_view([SurveyForm1, SurveyForm2, SurveyForm3, SurveyForm4, SurveyForm5])), ) ``` **My virtual host** located at /etc/apache2/sites-available/bias\_experiment ``` <VirtualHost *:80> ServerAdmin myemail@gmail.com ServerName phaedrus.scss.tcd.ie/bias_experiment ServerAlias phaedrus.scss.tcd.ie WSGIScriptAlias /bias_experiment /var/www/bias_experiment/src/bias_experiment/index.wsgi Alias /static/ /var/www/bias_experiment/src/bias_experiment/static/ <Location "/static/"> Options -Indexes </Location > </VirtualHost > ``` **My WSGI file** located at /var/www/bias\_experiment/src/bias\_experiment/index.wsgi ``` import os import sys import site # This is to add the src folder sys.path.append('/var/www/bias_experiment/src/bias_experiment') os.environ['DJANGO_SETTINGS_MODULE'] = 'bias_experiment.settings' # Activate your virtual env activate_env=os.path.expanduser("/var/www/bias_experiment/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ``` **This is the project structure** ![enter image description here](https://i.stack.imgur.com/4lSyZ.png) I had a [previous question related to this](https://stackoverflow.com/questions/24188604/django-application-not-visable) which had multiple issues pointed out to me which I have since fixed so I am re-posting this here. I have been following several tutorials as details in that question. Any help with this would be massively appreciated. Thanks Deepend EDIT: My Apache Error Log: `tail /var/log/apache2/error.log` ``` (bias_experiment)spillab@kdeg-vm-18:/var/www/bias_experiment/src$ sudo su root@kdeg-vm-18:/var/www/bias_experiment/src# tail /var/log/apache2/error.log [Fri Jun 13 16:21:04 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/surveythree, referer: https://stackoverflow.com/questions/24209181/what-should-be-the-url-of-my-django-application/24209864?noredirect=1 [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Use of undefined constant PHP_SELF - assumed 'PHP_SELF' in /var/www/bias_experiment/brendy.php on line 24, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Undefined index: brendy in /var/www/bias_experiment/brendy.php on line 27, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Use of undefined constant action - assumed 'action' in /var/www/bias_experiment/brendy.php on line 72, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Notice: Undefined index: action in /var/www/bias_experiment/brendy.php on line 72, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Warning: include(footer.php): failed to open stream: No such file or directory in /var/www/bias_experiment/brendy.php on line 118, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:36 2014] [error] [client 134.226.38.233] PHP Warning: include(): Failed opening 'footer.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/bias_experiment/brendy.php on line 118, referer: http://phaedrus.scss.tcd.ie/bias_experiment/ [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/special.css, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/images, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php [Fri Jun 13 16:22:37 2014] [error] [client 134.226.38.233] File does not exist: /var/www/bias_experiment/images, referer: http://phaedrus.scss.tcd.ie/bias_experiment/brendy.php root@kdeg-vm-18:/var/www/bias_experiment/src# ```
2014/06/13
[ "https://Stackoverflow.com/questions/24209181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214163/" ]
The URL should be <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/> I think there is one tiny error in the Apache configuration, which might be my fault (sorry): you need a trailing slash, so: ``` WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi ``` Also note that you don't need to run manage.py runserver, that's pointless as Apache is serving your app.
Is this it in your /static/ folder? <http://phaedrus.scss.tcd.ie/bias_experiment/static/>
24,618,832
I wonder if anyone has an elegant solution to being able to pass a python list, a numpy vector (shape(n,)) or a numpy vector (shape(n,1)) to a function. The idea would be to generalize a function such that any of the three would be valid without adding complexity. Initial thoughts: ``` 1) Use a type checking decorator function and cast to a standard representation. 2) Add type checking logic inline (significantly less ideal than #1). 3) ? ``` I do not generally use python builtin array types, but suspect a solution to this question would also support those.
2014/07/07
[ "https://Stackoverflow.com/questions/24618832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839375/" ]
You can convert the three types to a "canonical" type, which is a 1dim array, using: ``` arr = np.asarray(arr).ravel() ``` Put in a decorator: ``` import numpy as np import functools def takes_1dim_array(func): @functools.wraps(func) def f(arr, *a, **kw): arr = np.asarray(arr).ravel() return func(arr, *a, **kw) return f ``` Then: ``` @takes_1dim_arr def func(arr): print arr.shape ```
I think the simplest thing to do is to start off your function with [`numpy.atleast_2d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html). Then, all 3 of your possibilities will be converted to the `x.shape == (n, 1)` case, and you can use that to simplify your function. For example, ``` def sum(x): x = np.atleast_2d(x) return np.dot(x, np.ones((x.shape[0], 1))) ``` `atleast_2d` returns a view on that array, so there won't be much overhead if you pass in something that's already an `ndarray`. However, if you plan to modify `x` and therefore want to make a copy instead, you can do `x = np.atleast_2d(np.array(x))`.
20,714,517
**Hi, I ran into an encoding error with Python Django. In my views.py, I have the following:** ``` from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template from django.template import Context # Create your views here. def hello(request): name = 'Mike' html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name return HttpResponse(html) def hello2(request): name = 'Andrew' html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name return HttpResponse(html) # -*- coding: utf-8 -*- def hello3_template(request): name = u'ε“ˆε“ˆ' t = get_template('hello3.html') html = t.render(Context({'name' : name})) return HttpResponse(html) ``` **I got the following error:** SyntaxError at /hello3\_template/ ================================= Non-ASCII character '\xe5' in file D:\WinPython-32bit-2.7.5.3\django\_test\article\views.py on line 19, but no encoding declared; see <http://www.python.org/peps/pep-0263.html> for details (views.py, line 19) I look up that link, but I am still puzzled on how to resolve it. Could you help? Thanks, smallbee **As lalo points out, the following line has to be on the top** ``` # -*- coding: utf-8 -*- ``` **Thank you, all.**
2013/12/21
[ "https://Stackoverflow.com/questions/20714517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139783/" ]
Well, here you are: Put `# -*- coding: utf-8 -*-` at top of file, it define de encoding. The [docs](http://www.python.org/dev/peps/pep-0263/) says: > > Python will default to ASCII as standard encoding if no other > encoding hints are given. > > > > ``` > To define a source code encoding, a magic comment must > be placed into the source files either as first or second > line in the file, such as: > > ``` > > So, you code must begin: ``` # -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.template.loader import get_template ... ``` Hope helps
If you read [PEP 263](http://www.python.org/dev/peps/pep-0263/), it clearly says: > > To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file… > > > (The original proposal said that it had to be the first line after the #!, if any, but presumably it turned out to be easier to implement with the "first or second line" rule.) The actual reference docs describe the same thing, in a less friendly but more rigorous way, for [3.3](http://docs.python.org/3/reference/lexical_analysis.html#encoding-declarations) and [2.7](http://docs.python.org/2.7/reference/lexical_analysis.html#encoding-declaration). A "magic comment" that appears later in the file is not magic, it's just a comment to mislead your readers without affecting the Python compiler. UTF-8 for `u'ε“ˆε“ˆ'` is `'\xe5\x93\x88\xe5\x93\x88'`, so those are the bytes in the file. In recent Python versions (including 2.7 and all 3.x), the default encoding is always ASCII unless the file starts with a UTF BOM (as some Microsoft editors like to do); even in 2.3-2.6 it's usually ASCII; in earlier versions it's Latin-1. Trying to interpret `'\xe5\x93\x88\xe5\x93\x88'` will fail with the exact exception you saw.
49,510,289
I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information. I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Python and openpyxl. I thought that applying an AutoFilter and then copying the results would solve the problem. But it seems that openpyxl can only apply the AutoFilter and [not do the actual filtering?](https://openpyxl.readthedocs.io/en/2.5/filters.html) I tried to follow the answer to [this question](https://stackoverflow.com/questions/47918217/python3-openpyxl-copying-data-from-row-that-contains-certain-value-to-new-sheet), but it won't do anything. I want to filter the number in column D (4). ``` import openpyxl, os from openpyxl.utils import range_boundaries #Intitializes workbooks print('Opening data file...') min_col, min_row, max_col, max_row = range_boundaries("A:AG") wb = openpyxl.load_workbook('Data.xlsx') ws = wb.active template = openpyxl.load_workbook('Template.xlsx') templatews = template.active #Asks for numeric identifier print('Done! Now introduce identifier:') filterNumber = input() #Does the actual thing for row in ws.iter_rows(): if row[3].value == str(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) #Saves the results template.save('templatesave.xlsx') print('All done! Have fun!') ``` Any insight on this will be appreciated. Thanks! EDIT: corrected column number according to @alexis suggestion, although it has not solved the issue. SOLVED: it turns out that the IF statement asks for an integer, not a string. Using **int()** solved the problem. ``` for row in ws.iter_rows(): if row[3].value == int(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) ```
2018/03/27
[ "https://Stackoverflow.com/questions/49510289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9553462/" ]
Yes, all of your answers are correct. `int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte. The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text files you write bytes, but if you want to write human-readable "8" into a text file, you must write this in some encoding, such as ASCII where bytes correspond to human-readable characters. So, to write "8" you would need to write the byte `0x38` (ASCII value of `8`). So, in files you have *data*, not *int* or *chars*.
When we consider the memory location for an `int` or for a `char` we think as a whole. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored in an `int` variable. As we need total 32 bits (32/8 = 4) hence we need 4 bytes for an `int` variable. But to store a ascii character we need 7 bits. The ASCII table has 128 characters, with values from 0 through 127. Thus, 7 bits are sufficient to represent a character in ASCII; (However, most computers typically reserve 1 bits more, (i.e. 8 bits), for an ASCII character And about your question:- > > and if I create an int variable as the number 12345 and a character array of "12345" the character array will have consumed more memory? > > > Yes from the above definition it is true. In the first case(int value) it just need 4 bytes and for the second case it need total 5 bytes. The reason is in the first case `12345` is a single integer value and in the second case `"12345"` are total 5 ascii characters. Even in the second case, you actually need one more byte to hold the `'\0'` character as a part of a string (marks end of string).
49,510,289
I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information. I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Python and openpyxl. I thought that applying an AutoFilter and then copying the results would solve the problem. But it seems that openpyxl can only apply the AutoFilter and [not do the actual filtering?](https://openpyxl.readthedocs.io/en/2.5/filters.html) I tried to follow the answer to [this question](https://stackoverflow.com/questions/47918217/python3-openpyxl-copying-data-from-row-that-contains-certain-value-to-new-sheet), but it won't do anything. I want to filter the number in column D (4). ``` import openpyxl, os from openpyxl.utils import range_boundaries #Intitializes workbooks print('Opening data file...') min_col, min_row, max_col, max_row = range_boundaries("A:AG") wb = openpyxl.load_workbook('Data.xlsx') ws = wb.active template = openpyxl.load_workbook('Template.xlsx') templatews = template.active #Asks for numeric identifier print('Done! Now introduce identifier:') filterNumber = input() #Does the actual thing for row in ws.iter_rows(): if row[3].value == str(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) #Saves the results template.save('templatesave.xlsx') print('All done! Have fun!') ``` Any insight on this will be appreciated. Thanks! EDIT: corrected column number according to @alexis suggestion, although it has not solved the issue. SOLVED: it turns out that the IF statement asks for an integer, not a string. Using **int()** solved the problem. ``` for row in ws.iter_rows(): if row[3].value == int(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) ```
2018/03/27
[ "https://Stackoverflow.com/questions/49510289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9553462/" ]
Yes, all of your answers are correct. `int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte. The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text files you write bytes, but if you want to write human-readable "8" into a text file, you must write this in some encoding, such as ASCII where bytes correspond to human-readable characters. So, to write "8" you would need to write the byte `0x38` (ASCII value of `8`). So, in files you have *data*, not *int* or *chars*.
> > if a number is stored as a character it will contain 1 byte per character of the number(not 4 bytes)? for example if I make an int variable of the number 8 and a char variable of '8' the int variable will have consumed more memory? > > > Yes, since it is guaranteed that (assuming 8-bit bytes): ``` sizeof(char) == 1 sizeof(int) >= 2 ``` --- > > if I create an int variable as the number 12345 and a character array of "12345" the character array will have consumed more memory? > > > Correct. See the different between: ``` strlen("12345") == 5 sizeof(12345) >= 2 ``` Of course, for small numbers like `7`, it is not true: ``` strlen("7") == 1 sizeof(7) >= 2 ``` --- > > in text files if numbers are stored are they considered as integers or characters? > > > To read any data (be it in a file or in a clay tablet!) you need to know its [encoding](https://en.wikipedia.org/wiki/Code). If it is a *text* file, then *typically* the numbers will be encoded using characters, possibly in their decimal representation. If it is a *binary* file, then you *may* find them written as they are stored in memory for a particular computer. In short, it depends.
49,510,289
I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information. I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Python and openpyxl. I thought that applying an AutoFilter and then copying the results would solve the problem. But it seems that openpyxl can only apply the AutoFilter and [not do the actual filtering?](https://openpyxl.readthedocs.io/en/2.5/filters.html) I tried to follow the answer to [this question](https://stackoverflow.com/questions/47918217/python3-openpyxl-copying-data-from-row-that-contains-certain-value-to-new-sheet), but it won't do anything. I want to filter the number in column D (4). ``` import openpyxl, os from openpyxl.utils import range_boundaries #Intitializes workbooks print('Opening data file...') min_col, min_row, max_col, max_row = range_boundaries("A:AG") wb = openpyxl.load_workbook('Data.xlsx') ws = wb.active template = openpyxl.load_workbook('Template.xlsx') templatews = template.active #Asks for numeric identifier print('Done! Now introduce identifier:') filterNumber = input() #Does the actual thing for row in ws.iter_rows(): if row[3].value == str(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) #Saves the results template.save('templatesave.xlsx') print('All done! Have fun!') ``` Any insight on this will be appreciated. Thanks! EDIT: corrected column number according to @alexis suggestion, although it has not solved the issue. SOLVED: it turns out that the IF statement asks for an integer, not a string. Using **int()** solved the problem. ``` for row in ws.iter_rows(): if row[3].value == int(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) ```
2018/03/27
[ "https://Stackoverflow.com/questions/49510289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9553462/" ]
Yes, all of your answers are correct. `int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte. The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text files you write bytes, but if you want to write human-readable "8" into a text file, you must write this in some encoding, such as ASCII where bytes correspond to human-readable characters. So, to write "8" you would need to write the byte `0x38` (ASCII value of `8`). So, in files you have *data*, not *int* or *chars*.
When int is defined the memory would be allocated based on compiler option ( it can be 4 to 8 bytes). The number assigned to int is stored as is. e.g int a = 86; The number 86 would be stored at memory allocated for a. When char is defined , there are numbers assigned to each character. When these character needs to be printed the same would print but when its stored in memory it would stored as number. These are called ASCII character, there are some more. The allocation to store is 1Byte because with 1Byte you can represent 2^8 symbols.
49,510,289
I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information. I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Python and openpyxl. I thought that applying an AutoFilter and then copying the results would solve the problem. But it seems that openpyxl can only apply the AutoFilter and [not do the actual filtering?](https://openpyxl.readthedocs.io/en/2.5/filters.html) I tried to follow the answer to [this question](https://stackoverflow.com/questions/47918217/python3-openpyxl-copying-data-from-row-that-contains-certain-value-to-new-sheet), but it won't do anything. I want to filter the number in column D (4). ``` import openpyxl, os from openpyxl.utils import range_boundaries #Intitializes workbooks print('Opening data file...') min_col, min_row, max_col, max_row = range_boundaries("A:AG") wb = openpyxl.load_workbook('Data.xlsx') ws = wb.active template = openpyxl.load_workbook('Template.xlsx') templatews = template.active #Asks for numeric identifier print('Done! Now introduce identifier:') filterNumber = input() #Does the actual thing for row in ws.iter_rows(): if row[3].value == str(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) #Saves the results template.save('templatesave.xlsx') print('All done! Have fun!') ``` Any insight on this will be appreciated. Thanks! EDIT: corrected column number according to @alexis suggestion, although it has not solved the issue. SOLVED: it turns out that the IF statement asks for an integer, not a string. Using **int()** solved the problem. ``` for row in ws.iter_rows(): if row[3].value == int(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) ```
2018/03/27
[ "https://Stackoverflow.com/questions/49510289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9553462/" ]
When we consider the memory location for an `int` or for a `char` we think as a whole. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored in an `int` variable. As we need total 32 bits (32/8 = 4) hence we need 4 bytes for an `int` variable. But to store a ascii character we need 7 bits. The ASCII table has 128 characters, with values from 0 through 127. Thus, 7 bits are sufficient to represent a character in ASCII; (However, most computers typically reserve 1 bits more, (i.e. 8 bits), for an ASCII character And about your question:- > > and if I create an int variable as the number 12345 and a character array of "12345" the character array will have consumed more memory? > > > Yes from the above definition it is true. In the first case(int value) it just need 4 bytes and for the second case it need total 5 bytes. The reason is in the first case `12345` is a single integer value and in the second case `"12345"` are total 5 ascii characters. Even in the second case, you actually need one more byte to hold the `'\0'` character as a part of a string (marks end of string).
> > if a number is stored as a character it will contain 1 byte per character of the number(not 4 bytes)? for example if I make an int variable of the number 8 and a char variable of '8' the int variable will have consumed more memory? > > > Yes, since it is guaranteed that (assuming 8-bit bytes): ``` sizeof(char) == 1 sizeof(int) >= 2 ``` --- > > if I create an int variable as the number 12345 and a character array of "12345" the character array will have consumed more memory? > > > Correct. See the different between: ``` strlen("12345") == 5 sizeof(12345) >= 2 ``` Of course, for small numbers like `7`, it is not true: ``` strlen("7") == 1 sizeof(7) >= 2 ``` --- > > in text files if numbers are stored are they considered as integers or characters? > > > To read any data (be it in a file or in a clay tablet!) you need to know its [encoding](https://en.wikipedia.org/wiki/Code). If it is a *text* file, then *typically* the numbers will be encoded using characters, possibly in their decimal representation. If it is a *binary* file, then you *may* find them written as they are stored in memory for a particular computer. In short, it depends.