qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
61,889,217
I have this list of dictionaries. ``` [{'value': '299021.000000', 'abbrev': 'AAA'}, {'value': '299021.000000', 'abbrev': 'BBB'}, {'value': '8.597310', 'abbrev': 'CCC'}] ``` I want to transform this list to look like this; ``` [{'AAA': '299021.000000'}, {'BBB': '299021.000000'}, {'CCC': '8.597310'}] ``` Any hi...
2020/05/19
[ "https://Stackoverflow.com/questions/61889217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7518091/" ]
With [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) you can do the following: ``` data = [ {'value': '299021.000000', 'abbrev': 'AAA'}, {'value': '299021.000000', 'abbrev': 'BBB'}, {'value': '8.597310', 'abbrev': 'CCC'} ] data_2 = [{elem["abbrev"]: elem["v...
Using for loop; ``` original_list = [ {'value': '299021.000000', 'abbrev': 'AAA'}, {'value': '299021.000000', 'abbrev': 'BBB'}, {'value': '8.597310', 'abbrev': 'CCC'} ] transformed_list = [ ] for i in original_list: key = i['abbrev'] value = i[...
16,778
30,070,300
**I want to bind two event to one ListCtrl weight in wxpython.** **Such as, left click and right click.** The former will refresh the content of somewhere, and the later will create a PopupMenu, which contains something about rename, setting... How should I do? I tried `wx.EVT_LIST_ITEM_SELECTED`, `wx.EVT_LIST_COL_...
2015/05/06
[ "https://Stackoverflow.com/questions/30070300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4827183/" ]
I got my Answer, it was quit simple. Open Terminal, Type command: ``` keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android ``` Press Enter: You will get the following info, and SHA1 can be seen there. ..... Certificate fingerprints: ``` MD5: 79:F5:59:...
**Very easy and simply finding the SHA1 key for certificate in only android studio.** You can use below steps: ``` A.Open Android Studio B.Open Your Project C.Click on Gradle (From Right Side Panel, you will see Gradle Bar) D.Click on Refresh (Click on Refresh from Gradle Bar, you will see List Gradle scripts of yo...
16,779
72,304,877
super new to python and having an error on one of my codecademy projects that i cant seem to understand, even referencing the walkthrough and altering line 17 multiple times i cant quiet understand why this is returning an error. could somebody help me understand the error so i can learn from it? this is my code thats ...
2022/05/19
[ "https://Stackoverflow.com/questions/72304877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19153697/" ]
If there is only one non empty value per groups use: ``` df = df.replace('',np.nan).groupby('ID', as_index=False).first().fillna('') ``` If possible multiple values and need unique values in original order use lambda function: ``` print (df) ID LU MA ME JE VE SA DI 0 201 B C B 1 201 C C C B...
This could be treated as a pivot. You'd need to melt the df first then pivot: ``` (df.melt(id_vars='ID') .dropna() .pivot(index='ID',columns='variable',values='value') .fillna('') .rename_axis(None, axis=1) .reset_index() ) ```
16,789
2,166,818
How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)?
2010/01/30
[ "https://Stackoverflow.com/questions/2166818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55246/" ]
Calling the *function* `collections.namedtuple` gives you a new type that's a subclass of `tuple` (and no other classes) with a member named `_fields` that's a tuple whose items are all strings. So you could check for each and every one of these things: ``` def isnamedtupleinstance(x): t = type(x) b = t.__base...
IMO this might be the best solution for *Python 3.6* and later. You can set a custom `__module__` when you instantiate your namedtuple, and check for it later ```py from collections import namedtuple # module parameter added in python 3.6 namespace = namedtuple("namespace", "foo bar", module=__name__ + ".namespace")...
16,790
48,835,934
Installing Google Cloud SDK I get the response below: Note - I checked, and `C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython` does indeed lead to a python `2.7` that runs fine. ``` Output folder: C:\Users\jonat\AppData\Local\Google\Cloud SDK Downloading Google Cloud SDK core. Ext...
2018/02/16
[ "https://Stackoverflow.com/questions/48835934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9371800/" ]
Here is a piece of code that may help: ``` mat = cbind(1:3, 4:6, 7) layout(mat, width = c(1,1,.25)) pal = colorRampPalette(c("white", "black"))(100) # empty plots for (i in 1:6) image(matrix(runif(100), 10), col = pal) # color scale par(las=1, mar = c(4, 1, 4, 5)) image(t(1:100), col = pal, axes = F, ann = F) axis(4)...
Okay, figured it out with the help of [this post](https://stackoverflow.com/questions/9314658/colorbar-from-custom-colorramppalette) that uses a customised function to plot scales. I just had to remove the `dev.new()` call to avoid plotting the colour scale in a new device. The function is flexible but you still need t...
16,800
4,250,939
I started programming in january of this year and have covered a lot of ground. I have learnt javascript, ruby on rails, html, css, jquery and every now and then i like to try out some clojure but i will really get into that in the middle of next yr. I really didnt like rails and prefer using netbeans with pure javaScr...
2010/11/22
[ "https://Stackoverflow.com/questions/4250939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390129/" ]
Not sure why you don't like rails, but you might want to try the newly released "Rails for Zombies" tutorials by Envy Labs: <http://railsforzombies.org/>. Or if you like books instead of online stuff, check out [Agile Web Development with Rails](http://pragprog.com/titles/rails4/agile-web-development-with-rails) As b...
If you like ruby as programming language, but find rails to be just too much to take in it once, I'd recommend trying [Sinatra](http://www.sinatrarb.com/). It's also a ruby-based web framework, but it's a lot simpler than rails, and offers you a lot more control over how you want to set things up. For smaller projects,...
16,801
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally...
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars ``` <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_add_size" android:title="@string/menu_add_item" android:orderInCategory="10" ...
in your **menu/main.xml:** ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/settings" android:title="@string/settings" android:orderInCategory="0" android:showAsAction="always" /> <item android:id="@+id/action_compose" android:title="hello" ...
16,803
33,679,414
Suppose I have two types of axis aligned rectangles: a) Defined by left-up and right-bottom points: (x1, y1), (x2, y2) b) Defined by (x1, y1) and (width, height) The aim is to create pythonic-way code, that allows for conversion between these types. E.g. if there is a function, that performs calculations only in o...
2015/11/12
[ "https://Stackoverflow.com/questions/33679414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2864143/" ]
Create one class, and give it two constructors. One the default `__init__` method, the other a classmethod accepting the other form to specify a rectangle: ``` class Rectangle(Shape): def __init__(self, x1, y1, x2, y2): # .... @classmethod def fromSize(cls, x1, y1, width, height): return c...
I recommend creating one class and handling the inputs during your init to determine what is present/not present. Then add all the missing parameters based on a calculation. Here is a working example for your situation: ``` class RectangleClass: def __init__(self, x1, y1, x2=None, y2=None, width=None, height=None)...
16,809
18,269,672
I mean the situation when lua is run not as embedded in another app but as standalone scripting language. I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ?
2013/08/16
[ "https://Stackoverflow.com/questions/18269672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393087/" ]
Note that the the solution given by lhf is not the most general. If the interpreter has been called with additional command line parameters (if this may be your case) you will have to search `arg`. In general the interpreter name is stored at the most negative integer index defined for `arg`. See this test script: ``...
Try `arg[-1]`. But note that `arg` is not defined when Lua is executed interactively.
16,810
29,321,077
I am trying to write a function to mix strings in python but I am getting stuck at the end. So for this example, I have 2 words, mix and pod. I would like to create a function that returns: pox mid My code only returns pox mix Code: ``` def mix_up(a, b): if len(a and b)>1: b=str.replace(b,b[2],a[2:3]) ...
2015/03/28
[ "https://Stackoverflow.com/questions/29321077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120266/" ]
Little play on [string slicing](https://docs.python.org/2/tutorial/introduction.html#strings) ``` def mix_up(first, second): new_first = second[:2] + first[2:] new_second = first[:2] + second[2:] return " ".join((new_first, new_second)) assert mix_up('mix','pod') == 'pox mid' assert mix_up('dog','dinner')...
If you simply wanted to put the 2nd word before the first word all the time: ``` def mix_up(a,b): return " ".join([b,a]) # Should return pod mix ``` Give that you aimed for `pox mix` suggests that you probably wanted to: 1) Replace the last character of word `b` with x 2) Place b before a. In that case, the ...
16,813
5,385,238
I've got a timestamp in a log file with the format like: ``` 2010-01-01 18:48:14.631829 ``` I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. `("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")` I've even tried splitting the value by "." so I ...
2011/03/22
[ "https://Stackoverflow.com/questions/5385238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669983/" ]
You can use `strptime` like so (Python 2.6+ only): ``` >>> import datetime >>> s = "2010-01-01 18:48:14.631829" >>> datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f") datetime.datetime(2010, 1, 1, 18, 48, 14, 631829) ``` Docs: <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior> > > ......
Of course, splitting the string *does* work: ``` >>> print s 2010-01-01 18:48:14.631829 >>> time.strptime(s.split('.')[0], "%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2010, tm_mon=1, tm_mday=1, tm_hour=18, tm_min=48, tm_sec=14, tm_wday=4, tm_yday=1, tm_isdst=-1) >>> ```
16,815
27,929,400
I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color This is what I have: ``` color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']; ``` I want to be able to have a program that can let me...
2015/01/13
[ "https://Stackoverflow.com/questions/27929400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450564/" ]
This works for me: ``` from random import choice color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] l = len(color) str = "Hit Here" html = '' for x in str: html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x print(html) ``` Sample o...
try like this: ``` import random #console color W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green O = '\033[33m' # orange B = '\033[34m' # blue P = '\033[35m' # purple my_color = [W, R, G, O, B, P] a = raw_input("Enter your text to be colourful: ") new_text ="" for x in a: new_te...
16,817
12,135,555
I am trying to build my first Django project from scratch and am having difficulty setting the background image. I am new to programming in general so forgive me if this is a stupid question. I have read the documentation [here](https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles) on static file implementati...
2012/08/27
[ "https://Stackoverflow.com/questions/12135555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1611337/" ]
Your css file is not rendered by Django template engine and so {{ STATIC\_URL }} is not being replaced. You'll have to use /static/img/IMG\_0002.jpg in the CSS file or move that bit of CSS in your html file's style tag.
Try this settings.py ``` MEDIA_URL = '/static_media/' ``` urly.py ``` if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'^static_media/(?P<path>.*)$', 'serve', { 'document_root': '/path/to/static_media', 'show_indexes': True }),) ``` your css and jquery on te...
16,820
39,675,898
I am reading [The Hitchhiker’s Guide to Python](http://docs.python-guide.org/en/latest/writing/structure/#mutable-and-immutable-types) and there is a short code snippet ``` foo = 'foo' bar = 'bar' foobar = foo + bar # This is good foo += 'ooo' # This is bad, instead you should do: foo = ''.join([foo, 'ooo']) ``` ...
2016/09/24
[ "https://Stackoverflow.com/questions/39675898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534298/" ]
Is it bad practice? ------------------- It's reasonable to assume that it isn't bad practice for this example because: * The author doesn't give any reason. Maybe it's just disliked by him/her. * Python documentation doesn't mention it's bad practice (from what I've seen). * `foo += 'ooo'` is just as readable (accord...
If the number of string is small and strings are known in advance, I would go : ``` foo = f"{foo}ooo" ``` Using [f-strings](https://docs.python.org/fr/3/tutorial/inputoutput.html#formatted-string-literals). However, this is valid only since python 3.6.
16,821
73,453,875
Few days ago I uninstalled and then reinstalled python due to some error related to pip . Since then whenever I start my pc it shows python modify setup window 2 or 3 times [you can see popup here](https://i.stack.imgur.com/nrsLv.png) Though I can close these windows ; Whenever I open vs code it can be upwards of 10 p...
2022/08/23
[ "https://Stackoverflow.com/questions/73453875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825726/" ]
If there's code I'm likely to use repeatedly (like checking whether a radio button is selected or not), I like to put it in a method so it's easily reusable. This method takes the parent DIV of the radio button and counts the number of SVG circles inside. If there's more than one, the radio button is selected. This way...
Most important thing a circle tag represents the one circle, not the svg tag. So svg tag which looks like selected radiobutton contains two circle tags. You can measure number of circle tags in svg tag and based on that consider the svg as un/selected. **Code:** ``` List<WebElement> svgTags = driver.findElements...
16,822
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do...
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this: ``` <div style="padding:25px; width:400px;"> <div style="background-color:#bf5b5b;"> <span>Yes</span> <span>No</span></div> <div...
use width with float in div ``` <div id="rdiv" style="float:right; background-color: #74d4dd; /* margin-left: 151px; */ padding-left: 20px; width: 210px;padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> ``` [plz check](http://jsfiddle.net/akash4pj...
16,823
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_h...
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
The last time I saw a similar error it was because I was using the wrong version of `npm` and/or `node` for one of my dependencies. Try upgrading these and try again. Before trying again remove your `node_modules` directory. You may need to investigate what versions of `npm` and `node` your dependencies need. You c...
Install python2 and try running `npm install` again. This approach worked for me.
16,830
16,007,094
I'm having problems with this method in python called findall. I'm accessing a web pages HTML and trying to return the name of a product in this case `'bread'` and print it out to the console.
2013/04/15
[ "https://Stackoverflow.com/questions/16007094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051382/" ]
Don't use regex for HTML parsing. There are a few solutions. I suggest BeautifulSoup (<http://www.crummy.com/software/BeautifulSoup/>) Having said so, however, in this particular case, RE will suffice. Just relax it a notch. There might be more or less spaces or maybe those are tabs. So instead of literal spaces use t...
In case you still want to use regexps, here's a working one for your case: ``` product = re.findall(r'<br>\s*Item:\s+is\s+in\s+lane 12\s+(\w*)[^<]*<br>', content) ``` It takes into account DSM's space flexibility suggestion and non-letters after `(\w*)` that might appear before `<br>`.
16,840
21,790,203
I want to remove double open quotes and double close quotes from the text. By Double opening quotes i mean **“** not **"** I am trying to do it with python. But is unable to read **“**
2014/02/14
[ "https://Stackoverflow.com/questions/21790203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3288929/" ]
how about... ``` >>> s = "“hello“" >>> s.replace('“','') 'hello' >>> ```
Well, since you didn't want to say how you initially did it in excel, here's how you remove those: * Option 1: Use the Find/Replace with find `“` and replace with nothing then find `”` and replace with nothing. * Option 2: In excel, use `CHAR(147)` to have `“` and `CHAR(148)` to have `”`. Then `SUBSTITUTE` to remov...
16,841
60,229,299
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay more attention to comments): ``` # Drink some water...
2020/02/14
[ "https://Stackoverflow.com/questions/60229299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7643771/" ]
I think what you will find, is if you run your application, it will log an error like `requried a single bean but 2 were found`. What you can do however is remove the ambiguity using the @Qualifier where you need it injected and naming your bean definitions, i.e. for your example. ``` @Configuration public class Con...
Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name: ``` @Bean @Qualifier("restTemplateB") public RestTemplate restTemplateB() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties...
16,842
72,587,334
In .Net c# there is a function Task.WhenAll that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this: ``` tasks = ... #list of coroutines for task in tasks: await task ```
2022/06/11
[ "https://Stackoverflow.com/questions/72587334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11660685/" ]
After adding tasks to a list, you should use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) that gives coroutines as an argument list and executes them asynchronously. Also, you could use [`asyncio.create_task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_t...
Use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) if you're on Python 3.7 or above. From the docs: > > Run awaitable objects in the aws sequence concurrently. > If any awaitable in aws is a coroutine, it is automatically scheduled as a Task. > If all awaitables are completed s...
16,844
16,808,349
I've installed following packages <https://github.com/zacharyvoase/django-postgres> via pip and virtualenv.: ``` pip install git+https://github.com/zacharyvoase/django-postgres.git ``` It was installed succesfully. I used it in my model(As described in its documentaion) ``` from django.db import models import djang...
2013/05/29
[ "https://Stackoverflow.com/questions/16808349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089202/" ]
In order for management commands to work, the app has to be added to `INSTALLED_APPS`. However, a basic problem that you have is that the module doesn't support [`ENUM`](http://www.postgresql.org/docs/9.1/static/datatype-enum.html) yet. Its still a work in progress.
After adding new app: 1. add app to INSTALLED\_APPS in settings.py 2. run python manage.py syncdb 3. add urls to urls.py Perhaps you should go through this (again?) <https://docs.djangoproject.com/en/dev/intro/tutorial01/>
16,845
32,533,820
``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list. example\_List = [1,2,2,3,4] It should return True. So far I have this ``` def checkList(List1): for i in range(len(List1 - 1)): if ...
2015/09/12
[ "https://Stackoverflow.com/questions/32533820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The issue is with this part: ``` len(List1 - 1) ``` You should change it into ``` len(List1) - 1 ``` And you should use the same case for variable List1. Change ``` if list1[i] == 2 and list1[i+1] == 2: ``` to: ``` if List1[i] == 2 and List1[i+1] == 2: ```
Replace ``` len(List1 - 1) ``` for ``` len(List1) - 1 ```
16,846
50,205,683
I'm using Ubuntu 14.04 with Django 2.0.5 with Django Cookiecutter. I am trying to start a Django server on DigitalOcean and trying to bind gunicorn to 0.0.0.0:8000. python manage.py runserver works fine, but the issue is that it says it can't import environ. Any tips are greatly appreciated, Thanks. I've ran > > pip...
2018/05/07
[ "https://Stackoverflow.com/questions/50205683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6907366/" ]
You need to run your manage.py file with the local settings ``` python manage.py runserver --settings=config.settings.production ```
you need to set environment variables for you database : if you are on linux machine : ``` $ export DATABASE_URL=postgres://postgres:<password>@127.0.0.1:5432/<DB name given to createdb> ``` cookiecutter doc can help you more for all this : link : <https://cookiecutter-django.readthedocs.io/en/latest/developing-loc...
16,851
22,882,125
I updated my system to Mavericks and I have a python code using pgdb. How can I install pgdb on my new mac? I tried ``` sudo pip install git+git://github.com/cancerhermit/pgdb.py.git ``` And ``` sudo pip install pgdb ``` And ``` brew install pgdb ``` And I have even tried to install it from PyCharm directly (...
2014/04/05
[ "https://Stackoverflow.com/questions/22882125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/762435/" ]
**Assuming that you want to:** * Replace lower-case letters with lower-case letters * Replace upper-case letters with upper-case letters * Leave spaces and any other non-alphabetic characters as is --- ``` void encrypt (std::string &e) { int size = e.size(); for (int i=0; i<size; i++) { char c = ...
You could do something like this: ``` char _character='X'; int _value=static_cast<int>(_character); if(_value!=32)//not space { int _newValue=((_value+11)%90); (_newValue<65)?_newValue+=65:_newValue+=0; char _newCharacter=static_cast<char>(_newValue); } ```
16,852
38,958,697
I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements: ``` <li class="spacer"> <span>Location:</span> <br>Some Sample Street<br> Abbeville, AL 00000 </li> ``` ...
2016/08/15
[ "https://Stackoverflow.com/questions/38958697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6285753/" ]
You can choose names for the nodes in your model by passing the optional `name="myname"` argument to pretty much any Tensorflow operator that builds a node. Tensorflow will pick names for graph nodes automatically if you don't specify them, but if you want to identify those nodes to a tool like freeze\_graph.py, then i...
You can get all of the node names in your model with something like: ```py node_names = [node.name for node in tf.get_default_graph().as_graph_def().node] ``` Or with restoring the graph: ```py saver = tf.train.import_meta_graph(/path/to/meta/graph) sess = tf.Session() saver.restore(sess, /path/to/checkpoints) grap...
16,853
45,489,388
I am working on a Python/Django project, and we need to use two databases. Following the documentation I added a second database like this: ``` DATABASE_URL = os.getenv('DATABASE_URL', 'postgres://*******:********@aws-us-***********:*****/*****') CURRENCIES_URL = os.getenv('CURRENCIES_URL', 'postgres://*******:*******...
2017/08/03
[ "https://Stackoverflow.com/questions/45489388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7776359/" ]
There is a small but fatal typo in your code. It should be `django.db.connections` instead of your `connection` (you have not specified where that comes from). Quoting from <https://docs.djangoproject.com/en/1.11/topics/db/sql/#executing-custom-sql-directly> > > If you are using more than one database, you can use >...
You can't access `connection` using bracket notation. Perhaps this will work: ``` currencies = DATABASES['currencies'].cursor() ```
16,854
52,306,134
I am pretty new to Django. I think I cannot run django application as sudo since all pip related modules are installed for the user and not for the sudo user. So, it's a kind of basic question like how do I run django app that can listen for port 80 as well as port 443. So, far I have tried following option - i.e pre-...
2018/09/13
[ "https://Stackoverflow.com/questions/52306134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10318265/" ]
Ideally module should go into your site packages. Do you see it there? If its there then check your package path. You package may be steplib, but have you checked if you are importing right package and module there. For example within your steplib folder you might have additional package and module within it. Say pack...
Did you install the package in the python directory under Lib?
16,855
23,909,292
I am new to mqtt and still discovering this interesting protocol. I want to create a client in python that publishes every 10 seconds a message. Until now I succeed to publish only one message and keep the client connected to the broker. How can I make the publishing part a loop ? Below is my client: ``` import mosq...
2014/05/28
[ "https://Stackoverflow.com/questions/23909292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3683176/" ]
You can sleep between calls: ``` import mosquitto import time # import time module mqttc=mosquitto.Mosquitto("ioana") mqttc.connect("127.0.0.1",8000,60,True) mqttc.subscribe("test/", 2) while mqttc.loop() == 0: mqttc.publish("test","Hello") time.sleep(10)# sleep for 10 seconds before next call ```
I would suggest: ``` import paho.mqtt.client as mqtt # mosquitto.py is deprecated import time mqttc = mqtt.Client("ioana") mqttc.connect("127.0.0.1", 1883, 60) #mqttc.subscribe("test/", 2) # <- pointless unless you include a subscribe callback mqttc.loop_start() while True: mqttc.publish("test","Hello") time....
16,856
62,287,967
I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?` If there is a way to scra...
2020/06/09
[ "https://Stackoverflow.com/questions/62287967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Instead of using `scrapy` you can use `urllib`. Instead of `beautifulsoup` you can use `regex`. But `scrapy` and `beautifulsoup` do your life easier. `Scrapy`, not easy library so you can use `requests` or `urllib`.
i think the best, popular and easy to learn and use libraries in python web scraping are requests, lxml and BeautifulSoup which has the latest version is bs4 in summary ‘Requests’ lets us make HTML requests to the website’s server for retrieving the data on its page. Getting the HTML content of a web page is the first ...
16,857
73,071,481
**edit** using utf-16 seems to get me closer in the right direction, but I have csv values that include commas such as "one example value is a description, which is long and can include commas, and quotes" So with my current code: ``` filepath="csv_input/frups.csv" rows = [] with open(filepath, encoding='utf-16') as...
2022/07/21
[ "https://Stackoverflow.com/questions/73071481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18283635/" ]
No token expiration date is there for security reasons. If someone steals a token which has no expiration date that token will be able to be used forever. This can be extremely dangerous. Especially if the token is valuable. If a token has expired, the token should be refreshed and then you can request again.
I would say your frontend should manage valid token state properly. Good auth libs have config where you can define when before token expiration is token refreshed. So it should be configured in that way that token won't be never expired on the backend side.
16,860
11,203,167
I'm building a site in django that interfaces with a large program written in R, and I would like to have a button on the site that runs the R program. I have that working, using `subprocess.call()`, but, as expected, the server does not continue rendering the view until `subprocess.call()` returns. As this program cou...
2012/06/26
[ "https://Stackoverflow.com/questions/11203167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134853/" ]
``` subprocess.Popen(['R', 'CMD', 'BATCH', '/path/to/script.R']) ``` The process will be started asynchronously. Example: ``` $ cat 1.py import time import subprocess print time.time() subprocess.Popen(['sleep', '1000']) print time.time() $ python 1.py 1340698384.08 1340698384.08 ``` You must note that the chil...
You may use a wrapper for subprocess.call(), that wrapper would have its own thread within which it will call subprocess.call() method.
16,861
58,455,611
Currently I’m working on a corpus/dataset. It’s in xml format as you can see the picture below. I’m facing a problem. I want to access all **‘ne’** elements one by one as shown in below picture. Then I want to access the **text of the ‘W’ elements** which are inside the ‘ne’ elements. Then I want to **concatenate** thy...
2019/10/18
[ "https://Stackoverflow.com/questions/58455611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5067040/" ]
The expression `let rec c_write = "printf(\" %d \");\n"` is not a function. It is a value of type `string` which is bound to a variable named `c_write`. So you're not using any I/O functions in your code. When entered in the interactive toplevel, this value is printed by the interpreter evaluation loop for user conven...
Since you are somehow using the toplevel printer for printing, and that you somehow needs a very specific format, you need to install a custom printer. The following would work: ``` # #install_printer Format.pp_print_string;; # " This \" is not escaped " ;; - : string = This " is not escaped ``` However, it seems ...
16,862
1,460,559
I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this?
2009/09/22
[ "https://Stackoverflow.com/questions/1460559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72106/" ]
Convert it to JSON and include, in your template.html, inside a `<script>` tag, something like ``` var my_associative_array = {{ json_data }} ``` after having JSON-encoded your Python dict into a string and put it in the context using key `json_data`.
What does that mean exactly? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django. But, you...
16,863
20,658,451
I've opened Aptana Studio 3 (Ubuntu 10.04) just like I did it hundreds times before (last time was yesterday). But this time I see EMPTY workspace. No projects. No error messages. Nothing. Screen attached. I have not changed anything since the last time I used Aptana Studio (yesterday). I have not switched workspace ...
2013/12/18
[ "https://Stackoverflow.com/questions/20658451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367181/" ]
I had this problem and after freaking out I looked around and found File -> Switch Workspace and choosing my workspace loaded everything as normal.
I solved the problem by manually adding the projects back to workspace. Wasn't that bad. I still don't know why they disappeared.
16,866
63,442,415
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. Ho...
2020/08/16
[ "https://Stackoverflow.com/questions/63442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12946401/" ]
Qt Stylesheets -------------- This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors. So in your case, to apply to...
Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button. ```py my_font = QFont("Times New Roman", 12) my_button.setFont(my_font) ``` Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html> Yeah, documentation for C++ is okay t...
16,867
18,048,232
I get satchmo to try, but I have a great problem at first try, and I don't understand whats wrong. When I making `$ python clonesatchmo.py` into clear django project, it trows an error: ``` $ python clonesatchmo.py Creating the Satchmo Application Customizing the files Performing initial data synching Traceback (most ...
2013/08/04
[ "https://Stackoverflow.com/questions/18048232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768419/" ]
Replace the contents of manage.py with the following (from a new django 1.6 project). ``` #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<app>.settings") from django.core.management import execute_from_command_line execute_from_comm...
`execute_manager` was put on the deprecation path as part of the project layout refactor in Django 1.4 <https://docs.djangoproject.com/en/1.4/releases/1.4/#django-core-management-execute-manager>. Per the deprecation policy that means that the code for `execute_manager` has been completely removed in 1.6. If you are se...
16,872
58,176,203
In python, I have gotten quite used to container objects having truthy behavior when they are populated, and falsey behavior when they are not: ```py # list a = [] not a True a.append(1) not a False # deque from collections import deque d = deque() not d True d.append(1) not d False # and so on ``` However, [que...
2019/09/30
[ "https://Stackoverflow.com/questions/58176203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867968/" ]
According to the definition of the [truth value testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) procedure, the behavior is expected: > > Any object can be tested for truth value, for use in an if or while > condition or as operand of the Boolean operations below. > > > By default, an ...
I'm going to leave the accepted answer as is, but as far as I can tell, the reason is that `if _queue: # do something` *would* be a race condition, since `Queue` is designed to be passed between threads and therefore possesses dubious state as far as tasks go. From the source: ```py class Queue: ~snip~ def q...
16,873
39,367,963
I did python script: ``` from string import punctuation from collections import Counter import urllib from stripogram import html2text myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7") html_string = myurl.read() text = html2text( html_stri...
2016/09/07
[ "https://Stackoverflow.com/questions/39367963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6708233/" ]
What do you mean with "webpage text"? It seems you don't want the full HTML-File. If you just want the text you see in your browser, that is not so easily solvable, as the parsing of a HTML-document can be very complex, especially with JavaScript-rich pages. That starts with assessing if a String between "<" and ">" i...
``` import urllib urllib.urlretrieve("http://www.example.com/test.html", "test.txt") ```
16,874
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
While `.get()` is a nice idiom, it's slower than `if/else` (and slower than `try/except` if presence of the key in the dictionary can be expected most of the time): ``` >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10") 0.07691968797894333 >>> timeit.timeit(setup...
(this is a late answer) An alternative is to subclass the `dict` class and implement the [`__missing__()`](https://docs.python.org/3/reference/datamodel.html?highlight=__missing__#object.__missing__) method, like this: ``` class ConnectionDetails(dict): def __missing__(self, key): if key == 'host': ...
16,876
15,728,081
I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database. The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; tha...
2013/03/31
[ "https://Stackoverflow.com/questions/15728081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929999/" ]
In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet.
I suggest you to use Celery which works with Django and has support for long running tasks among other features. <http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html> <http://docs.celeryproject.org/en/latest/getting-started/introduction.html>
16,886
61,256,730
I'm writing a python code that converts a binary to decimal. ``` def bin_dec (binary): binary_list = list(str(binary)) **for bit in binary_list: if int(bit) > 1 or int(bit) < 0: print('Invalid Binary') print('') exit()** total = 0 argument = 0 binary_...
2020/04/16
[ "https://Stackoverflow.com/questions/61256730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13332906/" ]
``` $agent = $this->request->getUserAgent(); if ($agent->isBrowser()) { if($this->input->cookie('country')) { $countryId = $this->input->cookie('country'); }else{ redirect(base_url()); } } ```
HTTP 302 response code means that the URL of requested resource has been changed temporarily. Further changes in the URL might be made in the future. Therefore, this same URI should be used by the client in future requests.[You can check this out to learn more](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/3...
16,891
25,844,794
While executing below code, I am getting error as mentioned. I downloaded the required package from <http://www.cs.unm.edu/~mccune/prover9/download/> and configure. But still same issue. I am getting this error: ``` >>> import nltk >>> dt = nltk.DiscourseTester(['A student dances', 'Every student is a person']) >>...
2014/09/15
[ "https://Stackoverflow.com/questions/25844794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2518644/" ]
Try following code: ``` .mini1 { width: 100%; height: 6.7%; margin-top: -2%; background-image: url('../images/footer1.jpg'); z-index: 10; background-size: 100% 100%; } ``` Please see to it that, image path is correct. Go in console to check for any errors.
Well here is a working JSfiddle: <http://jsfiddle.net/knftvt6v/4/> I believe it is your file path that's causing the error, can you make a JS fiddle ``` .mini1 { width: 100%; height: 2em; margin-top: -2%; background: url('http://www.serenitybaumer.com/main_images/footer.jpg'); z-index: 10; co...
16,892
62,221,721
I have created GuI in Visual Studio 2019. [![enter image description here](https://i.stack.imgur.com/g21cN.png)](https://i.stack.imgur.com/g21cN.png) There user will enter username and password and that i have to pass to python script. That when user will click on login button, python script will be triggered and out...
2020/06/05
[ "https://Stackoverflow.com/questions/62221721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11699581/" ]
You could use arguments to call your Python Script. Change the python script: ``` import paramiko import time import sys # Used to get arguments ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: hostname = sys.argv[1] # Skip 0th arg, since it is just the filename usern...
There are multiple approaches to incorporating a Python script with .NET C# code ================================================================================ I will try and give a basic overview, along with my suggestion, but ultimately, it will be up to you to figure out what works best. IronPython ---------- I...
16,893
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ tes...
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
Adjacent strings are concatenated at compile time: ``` if True: print ("this is the first line of a very long string" " this is the second line") ``` Output: ``` this is the first line of a very long string this is the second line ```
You can use a trailing backslash to join separate strings like this: ``` if True: print "long test long test long test long test long " \ "test long test long test long test long test long test" ```
16,894
56,680,581
If there's a function `f(x)`, and x's type may be Int or String, if it's Int, then this f will return `x+1` if it's String, then f will reverse x and return it. This is easy in dynamic typed languages like python and javascript which just uses `isinstance(x, Int)`. We can know its type and do something with if-else,...
2019/06/20
[ "https://Stackoverflow.com/questions/56680581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11674346/" ]
In kotlin you have [Arrow](https://arrow-kt.io/) that provides a lot of functional capabilities to the language. Between them you have [`EitherT`](https://arrow-kt.io/docs/arrow/data/eithert/). That lets you define: ``` fun f(x: Either<Int, String>): Either<Int, String> = x.bimap({ it+1 }, { it.reversed() }) ```
You could do something like: ``` fun getValue(id: Int): Any { ... } fun process(value: Int) { ... } fun process(value: String) { ... } val value = getValue(valueId) when (value) { is Int -> process(value) is String -> process(value) else -> ... } ``` This way, you can use method overloading to do the job for yo...
16,904
34,894,096
What is the best way to read in a line of numbers from a file when they are presented in a format like this: ``` [1, 2, 3 , -4, 5] [10, 11, -12, 13, 14 ] ``` Annoyingly, as I depicted, sometimes there are extra spaces between the numbers, sometimes not. I've attempted to use `CSV` to work around the commas, but the ...
2016/01/20
[ "https://Stackoverflow.com/questions/34894096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5814412/" ]
Use regular expression to remove any unwanted characters from strings ``` import re text_ = re.sub("[0-9]+", " ", text); ``` Second Method: ``` str = "h3110 23 cat 444.4 rabbit 11 2 dog" >>> [int(s) for s in str.split() if s.isdigit()] [23, 11, 2] ```
Use the [`json`](https://docs.python.org/3/library/json.html#json.loads) module to parse each line as a [JSON](http://json.org/) array. ``` import json list_of_ints = [] for line in open("/tmp/so.txt").readlines(): a = json.loads(line) list_of_ints.extend(a) print(list_of_ints) ``` This collects all integer...
16,906
30,798,447
I tried the following code, but I ran into problems. I think .values is the problem but how do I encode this as a Theano object? The following is my data source ``` home_team,away_team,home_score,away_score Wales,Italy,23,15 France,England,26,24 Ireland,Scotland,28,6 Ireland,Wales,26,3 Scotland,England,0,20 France,I...
2015/06/12
[ "https://Stackoverflow.com/questions/30798447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2610971/" ]
Here is my translation of your PyMC2 model: ``` model = pm.Model() with pm.Model() as model: # global model parameters home = pm.Normal('home', 0, .0001) tau_att = pm.Gamma('tau_att', .1, .1) tau_def = pm.Gamma('tau_def', .1, .1) intercept = pm.Normal('intercept', 0, .0001...
Your model is failing because you can't use NumPy functions on theano tensors. Thus ``` np.mean(atts_star3) ``` Will give you an error. You can remove `atts_star3 = pm3.Normal("atts_star",...)` and just use the NumPy array directly `atts_star3 = x`. I don't think you need to explicitly model `tau_att3`, `tau_def3`...
16,912
61,195,729
I have been working with binance websocket. Worked well if the start/stop command is in the main programm. Now I wanted to start and stop the socket through a GUI. So I placed the start/stop command in a function each. But it doesn't work. Just no reaction while calling the function. Any idea what's the problem? Here ...
2020/04/13
[ "https://Stackoverflow.com/questions/61195729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13305068/" ]
Whatever user is executing that code, does not have permission to write to that file path. If you go to C:\Users\chris\Source\Repos\inventory2.0\PIC\_Program\_1.0\Content\images\Components, right click, properties, Security tab, you will see the users that have permissions and what those permissions are. You can add or...
I think the problem is your application user don't have permission to access your the folder. If you are testing this in VS IIS express, then you should grant permission for your current user. However, if you are receiving this error message from IIS Server. Then you should grant permission for application pool ident...
16,914
52,436,084
I have a word list and I need to find the count of words that are present in the string. eg: ``` text_string = 'I came, I saw, I conquered!' word_list=['I','saw','Britain'] ``` I require a python script that prints ``` {‘i’:3,’saw’:1,’britain':0} ```
2018/09/21
[ "https://Stackoverflow.com/questions/52436084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9635284/" ]
You can use a [property accessor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) to reference `mutableValue` from accessing the property `a` like this: ```js let mutableValue = 3 const obj = { get a() { return mutableValue } } console.log(obj.a) mutableValue = 4 co...
object -> reference values try ``` let mutableValue = {aa: 3} const getText = () => mutableValue const obj = {a: getText()} ``` run ``` obj.a// {aa: 3} mutableValue.aa = 4 obj.a// {aa: 4} ```
16,915
58,901,682
First of all i tried command from their main page, that they gave me: ``` pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html ``` Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No ...
2019/11/17
[ "https://Stackoverflow.com/questions/58901682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8037832/" ]
There is no any wheels for Python 3.8 at <https://download.pytorch.org/whl/torch_stable.html>. > > not supported wheel on my platform > > > This is because the wheel is for Python 3.7. Advice: downgrade to Python 3.7.
Adding to @phd's answer, you could consider [installing from source](https://github.com/pytorch/pytorch#from-source). Note that I have built PyTorch from the source in the past (and it was a mostly straightforward process) but I have not done this on windows or for Python 3.8.
16,917
12,938,786
Im trying to pass a sql ( wich works perfectly if i run it on the client ) inside my python script, but i receive the error "not enough arguments for format string" Following, the code: ``` sql = """ SELECT rr.iserver, foo.*, rr.queue_capacity, rr.queue_refill_level, rr.is_concurrent, rr.max_executi...
2012/10/17
[ "https://Stackoverflow.com/questions/12938786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1323826/" ]
``` WHERE TRIGGER LIKE '%(package)s%' ``` you have an EXTRA '%' if you want the actual character '%', you need to escape with a double '%'. so it should be ``` WHERE TRIGGER LIKE '%(package)s%%' ``` if you want to display a '%' and ``` WHERE TRIGGER LIKE '%(pac...
Don't build SQL like this using `%`: ``` "SELECT %(foo)s FROM bar WHERE %(baz)s" % {"foo": "FOO", "baz": "1=1;-- DROP TABLE bar;"} ``` This opens the door for nasty SQL injection attacks. Use the proper form of your [Python Database API Specification v2.0](http://www.python.org/dev/peps/pep-0249/) adapter. For Ps...
16,924
54,311,678
I have a UDP socket application where I am working on the server side. To test the server side I put together a simple python client program that sends the message "hello world how are you". The server, should then receive the message, convert to uppercase and send back to the client. The problem lies here: I can obser...
2019/01/22
[ "https://Stackoverflow.com/questions/54311678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970879/" ]
**Quick and dirty:** Remove this line from your C code: ``` claddr.sin_port = htons(PORT_NUM); ``` **Now why:** When you send a message in your python script, your operating system will fill a [UDP packet](https://en.wikipedia.org/wiki/User_Datagram_Protocol) with the destination IP address and port you specified,...
N. Dijkhoffz, Would love to hear how you fixed it and perhaps post the correct code.
16,925
36,965,951
I'm begineer in python. I'm bit confused about this basic python program and its output ``` for num in range(2,10): for i in range(2,num): if (num % i) == 0: break else: print(num) ``` output ``` Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (In...
2016/05/01
[ "https://Stackoverflow.com/questions/36965951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5483135/" ]
You can use `ajax`. **timestamp.php** ``` <?php date_default_timezone_set('YOUR TIMEZONE'); echo $timestamp = date('H:i:s'); ``` **jQuery** ``` $(document).ready(function() { setInterval(timestamp, 1000); }); function timestamp() { $.ajax({ url: 'http://localhost/timestamp.php', su...
PHP is a server-side programming language, Javascript is a client-side programming language. The PHP code that fills the variables will only update when the webpage is loaded, after that you are left with Javascript code and nothing more. I recommend you to search a basic programming book which mentions concepts such...
16,926
58,543,054
I am trying to use pyspark to preprocess data for the prediction model. I get an error when I try spark.createDataFrame out of my preprocessing.Is there a way to check how processedRDD look like before making it to dataframe? ``` import findspark findspark.init('/usr/local/spark') import pyspark from p...
2019/10/24
[ "https://Stackoverflow.com/questions/58543054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9240223/" ]
I don't know what this script has to do with Django exactly, but adding the following lines at the top of the script will probably fix this issue: ``` import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') import django django.setup() ```
Basically, you need to load your settings and populate Django’s application registry before doing anything else. You have all the information required in the Django docs. <https://docs.djangoproject.com/en/2.2/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage>
16,928
149,474
This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files. ``` big_story_export.xml ``` turns into ``` lifestyles.xml food.xml nascar.xml ``` ...and so on. I got the job done using a one-off python script, *however*, **I origi...
2008/09/29
[ "https://Stackoverflow.com/questions/149474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22491/" ]
This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file. 1. Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like [xmlstarlet](http://xmlstar.sourceforge.net/), can tell you that. 2. Does ...
What language/parser were you using? For large files I try to use Unix command line tools. They are usually much, much more efficient than other solutions and don't "crap out" on large files. Try using `xsltproc`
16,930
56,921,192
I have created a text file using file operations in python. I want the file to be pushed to my existed GITLAB repository. I have tried the below code where i get the created file in my local folders. ``` file_path = 'E:\My material\output.txt' k= 'Fail/Pass' with open (file_path, 'w+') as text: text.write('Test ...
2019/07/07
[ "https://Stackoverflow.com/questions/56921192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7547718/" ]
You can use `.loc` and column names in the following way: ``` import pandas as pd import numpy as np np.random.seed(12) df = pd.DataFrame( { "df0" : np.random.choice(["a", "b"], 100), "df1" : np.random.randint(0, 15, 100), "df2" : np.random.randint(0, 15, 100), "df3" : np.random....
I think you were doing correct you need to define all columns you need to multiply ``` df.iloc[:,1:] = df.iloc[:,1:]*l ```
16,938
31,745,613
I have the below mysql table. I need to pull out the first two rows as a dictionary using python. I am using python 2.7. ``` C1 C2 C3 C4 C5 C6 C7 25 33 76 87 56 76 47 67 94 90 56 77 32 84 53 66 24 93 33 88 99 73 34 52 85 67 ...
2015/07/31
[ "https://Stackoverflow.com/questions/31745613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5070767/" ]
[`dict` keys have no easily predictable order](https://stackoverflow.com/q/4458169/190597). To obtain the database table fields in the order in which they appear in the database, use the cursor's [description attribute](https://www.python.org/dev/peps/pep-0249/#description): ``` fields = [item[0] for item in cursor.de...
Instead of ``` data_keys = data.keys() ``` Try: ``` data_keys = exp_cur.column_names ``` Source: [10.5.11 Property MySQLCursor.column\_names](http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html)
16,941
67,384,831
Using this option in python it is possible to calculate the mean from multiple csv file If file1.csv through file100.csv are all in the same directory, you can use this Python script: ``` #!/usr/bin/env python3 N = 100 mean_sum = 0 std_sum = 0 for i in range(1, N + 1): with open(f"file{i}.csv") as f: mea...
2021/05/04
[ "https://Stackoverflow.com/questions/67384831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14961922/" ]
Try the following **Solution 1, create a new axios instance in your plugins folder:** ``` export default function ({ $axios }, inject) { // Create a custom axios instance const api = $axios.create({ headers: { // headers you need } }) // Inject to context as $api inject...
You can pass the below configuration to `nuxt-auth`. Beware, those `plugins` are not related to the root configuration, but related to the `nuxt-auth` package. `nuxt.config.js` ```js auth: { redirect: { login: '/login', home: '/', logout: '/login', callback: false, }, strategies: { ... }, ...
16,944
35,387,277
Is there a way in python with selenium that instead of selecting an option using a value or name from a drop down menu, that I can select an option via count? Like select option 1 and another example select option 2. This is because it's a possibility that a value or text of a drop down menu option can change so to ens...
2016/02/14
[ "https://Stackoverflow.com/questions/35387277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1096892/" ]
If this represents the way you have been trying to match output, it's your problem: ``` while(reader.readLine() != "\u001B") {} ``` Except in special cases, you have to use the `equals()` method on `String` instances: ``` while (true) { String line = reader.readLine(); if ((line == null) || "\u001B".equals(line...
I believe you need to call the Process.waitFor() method. So you need something like: ``` Process p = build.start(); p.waitFor() ``` If you are trying to simulate a bash shell, allowing input of a command, executing, and processing output without terminating. There is an open source project that may be a good referen...
16,945
60,959,688
I have a python2 script I want to run with the [pwntools python module](https://github.com/Gallopsled/pwntools) and I tried running it using: > > python test.py > > > But then I get: > > File "test.py", line 3, in > from pwn import \* > ImportError: No module named pwn > > > But when I try it with python...
2020/03/31
[ "https://Stackoverflow.com/questions/60959688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12941653/" ]
**Yes**, It's absolutely possible to include a `JavaScript` object into `makeStyles`. Thanks to the `spread` operator. > > Advice is to spread over the object first, so that you can easily override any styles. > > Therefore it's preferred to do as follows. > > > ```js const useStyles = makeStyles(theme =...
For the benefit of future posters, the code in my original post worked perfectly, I just had something overriding it later! (Without the callback function it was undefined) – H Capello just
16,946
65,370,140
Thanks for looking into this, I have a python program for which I need to have `process_tweet` and `build_freqs` for some NLP task, `nltk` is installed already and `utils` **wasn't** so I installed it via `pip install utils` but the above mentioned two modules apparently weren't installed, the error I got is standard o...
2020/12/19
[ "https://Stackoverflow.com/questions/65370140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11779635/" ]
You can easily access any source code with ??, for example in this case: process\_tweet?? (the code above from deeplearning.ai NLP course custome utils library): ``` def process_tweet(tweet): """Process tweet function. Input: tweet: a string containing a tweet Output: tweets_clean: a list of words containing t...
Try this code, It should work: ``` def process_tweet(tweet): stemmer = PorterStemmer() stopwords_english = stopwords.words('english') tweet = re.sub(r'\$\w*', '', tweet) tweet = re.sub(r'^RT[\s]+', '', tweet) tweet = re.sub(r'https?:\/\/.*[\r\n]*', '', tweet) tweet = re.sub(r'#', '', tweet) tokenizer = TweetTokenizer(...
16,947
25,916,444
I would like to test, using unittest, a method which reads from a file using a context manager: ``` with open(k_file, 'r') as content_file: content = content_file.read() ``` I don't want to have to create a file on my system so I wanted to mock it, but I'm not suceeding much at the moment. I've found [mock\_open...
2014/09/18
[ "https://Stackoverflow.com/questions/25916444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914086/" ]
`mock_open()` is the way to go; you patch `open` in your code-under-test with the result of a `mock_open()` call: ``` mocked_open = unittest.mock.mock_open(read_data='file contents\nas needed\n') with unittest.mock.patch('yourmodule.open', mocked_open, create=True): # tests calling your code; the open function wil...
An alternative is [pyfakefs](http://github.com/jmcgeheeiv/pyfakefs). It allows you to create a fake file system, write and read files, set permissions and more without ever touching your real disk. It also contains a practical example and tutorial showing how to apply pyfakefs to both unittest and doctest.
16,956
26,679,011
I am trying to use mpl\_toolkits.basemap on python and everytime I use a function for plotting like drawcoastlines() or any other, the program automatically shows the plot on the screen. My problem is that I am trying to use those programs later on an external server and it returns 'SystemExit: Unable to access the X...
2014/10/31
[ "https://Stackoverflow.com/questions/26679011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510686/" ]
Use the `Agg` backend, it doesn't require a graphical environment: Do this at the very beginning of your script: ``` import matplotlib as mpl mpl.use('Agg') ``` See also the FAQ on [Generate images without having a window appear](http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appea...
The easiest way is to put off the interactive mode of matplotlib. ``` from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np #NOT SHOW plt.ioff() m = Basemap(projection='robin',lon_0=0) m.drawcoastlines() #m.fillcontinents(color='coral',lake_color='aqua') # draw parallels and me...
16,957
32,567,357
Since today i've been using [remote\_api](https://cloud.google.com/appengine/articles/remote_api) (python) to access the datastore on GAE. I usually do `remote_api_shell.py -s <mydomain>`. Today I tried and it fails, the error is: > > oauth2client.client.ApplicationDefaultCredentialsError: The > Application Defaul...
2015/09/14
[ "https://Stackoverflow.com/questions/32567357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1257185/" ]
You could try implementing [SignalR](http://www.asp.net/signalr/overview/deployment/tutorial-signalr-self-host). It is a great library that uses web sockets to push data to clients. Edit: SignalR can help you solve your problem by allowing you to set up Hubs on your console app (server) that WPF application (clients)...
You need to create some kind of subscription model for the clients to the server to handle a Publish-Subscribe channel (see <http://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html>). The basic architecture is this: 1. Client sends a request to the messaging channel to register its...
16,958
11,866,944
I would like to be able to pickle a function or class from within \_\_main\_\_, with the obvious problem (mentioned in other posts) that the pickled function/class is in the \_\_main\_\_ namespace and unpickling in another script/module will fail. I have the following solution which works, is there a reason this shoul...
2012/08/08
[ "https://Stackoverflow.com/questions/11866944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1068490/" ]
You can get a better handle on global objects by importing `__main__`, and using the methods available in that module. This is what [dill](http://pythonhosted.org/dill) does in order to serialize almost anything in python. Basically, when dill serializes an interactively defined function, it uses some name mangling on ...
If you are trying to pickle something so that you can use it somewhere else, separate from `test_script`, that's not going to work, because pickle (apparently) just tries to load the function from the module. Here's an example: test\_script.py ``` def my_awesome_function(x, y, z): return x + y + z ``` picklescr...
16,963
50,005,229
So the assignment is: take 2 lists and write a program that returns a list that contains only the elements that are common to the lists without duplicates, and it must work on lists of different sizes. My code is: ``` a = [1, 2, 4] b = [3, 1, 5, 2] for j < len(a): for i < len(b): if a(elem) == b(i): ...
2018/04/24
[ "https://Stackoverflow.com/questions/50005229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9691751/" ]
The value is a regular JavaScript expression. This way, if you want to pass a string, say `'test'`, use: ``` v-my-directive="'test'" ``` Demo: ```js Vue.directive('my-directive', function (el, binding) { console.log('directive expression:', binding.value) // => "test" }) new Vue({ el: '#app', data: { ...
You have to quote the string, otherwise it will look for the `test` variable in your component context (its `props` or `data`): ``` v-my-directive="'test'" ``` Inside your custom directive, you can access the passed value as in the `binding.value`: ``` Vue.directive('demo', { bind: function (el, binding, vnode) {...
16,966
37,490,609
i'm working on site for renting rooms. User picks 2 dates(UserStartDate & UserEndDate). with this python code i gonna get number of days in his date range: ``` user_date_range = [endUser - timedelta(i) for i in range((endUser - startUser).days+1)] user_range_num_days = len(user_date_range) ``` and i have a day pri...
2016/05/27
[ "https://Stackoverflow.com/questions/37490609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6361942/" ]
It doesn't have anything to do with django but rather python. I assume `user_start_date` and `user_end_date` are both python `datetime.date` or `datetime.datetime` objects, then you could do: ``` num_days = (user_end_date - user_start_date).days total_price = num_days * 20 ```
<https://docs.python.org/2/library/calendar.html> A calendar is necessary as you should be aware that not all months have the same amount of days in them. itermonthdates(year, month) returns an iterator for all days in the month. Run through that iterator and increment a count for every date match within the range. Of...
16,967
6,831,685
I am learning python via dive into python. Got few questions and unable to understand, even through the documentation. 1) ***BaseClass*** 2) ***InheritClass*** What exactly happens when we assign a *InheritClass* instance to a variable, when the *InheritClass* doesn't contain an `__init__` method and *BaseClass* doe...
2011/07/26
[ "https://Stackoverflow.com/questions/6831685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570928/" ]
Yes, `BaseClass.__init__` will be called automatically. Same goes for any other methods defined in the parent class but not the child class. Observe: ``` >>> class Parent(object): ... def __init__(self): ... print 'Parent.__init__' ... def func(self, x): ... print x ... >>> class Child(Parent): ... pass ...
@FogleBird has already answered your question, but I wanted to add something and can't comment on his post: You may also want to look at the [`super` function](http://docs.python.org/library/functions.html#super). It's a way to call a parent's method from inside a child. It's helpful when you want to extend a method, ...
16,968
23,969,296
I wanted to get number of indexes in two string which are not same. Things that are fixed: String data will only have 0 or 1 on any index. i.e strings are binary representation of a number. Both the string will be of same length. For the above problem I wrote the below function in python ``` def foo(a,b): resu...
2014/05/31
[ "https://Stackoverflow.com/questions/23969296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3694018/" ]
I'll walk through the options here, but basically you are calculating the hamming distance between two numbers. There are dedicated libraries that can make this really, really fast, but lets focus on the pure Python options first. Your approach, zipping ---------------------- `zip()` produces one big list *first*, th...
Not tested, but how would this perform: ``` sum(x!=y for x,y in zip(a,b)) ```
16,969
24,502,360
I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon. In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]]. Here is th...
2014/07/01
[ "https://Stackoverflow.com/questions/24502360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3792245/" ]
It is not very necessary to write your `array` into a special format. Write it into a normal `csv` and use [`dlmread`](http://www.mathworks.com/help/matlab/ref/dlmread.html) to open it in `matlab`. In `numpy` side, write your `array` using `np.savetxt('some_name.txt', aar, delimiter=' ')`
If you have scipy than you can do: ``` import scipy.io scipy.io.savemat('/tmp/test.mat', dict(SPOT=SPOT)) ``` And in matlab: ``` a=load('/tmp/test.mat'); a.SPOT % should have your data ```
16,972
65,753,830
I'm trying to train Mask-R CNN model from cocoapi(<https://github.com/cocodataset/cocoapi>), and this error code keep come out. ``` ModuleNotFoundError Traceback (most recent call last) <ipython-input-8-83356bb9cf95> in <module> 19 sys.path.append(os.path.join(ROOT_DIR, "samples/...
2021/01/16
[ "https://Stackoverflow.com/questions/65753830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14258016/" ]
The answer is summarise from [these](https://github.com/cocodataset/cocoapi/issues/172) [three](https://github.com/cocodataset/cocoapi/issues/168) [GitHub issues](https://github.com/cocodataset/cocoapi/issues/141#issuecomment-386606299) 1.whether you have installed cython in the correct version. Namely, you should ins...
Try cloning official repo and run below commands ``` python setup.py install make ```
16,977
53,469,976
I am using the osmnx library (python) to extract the road network of a city. I also have a separate data source that corresponds to GPS coordinates being sent by vehicles as they traverse the aforementioned road network. My issue is that I only have the GPS coordinates but I wish to also know which road they correspond...
2018/11/25
[ "https://Stackoverflow.com/questions/53469976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10702801/" ]
You can do map matching with OSMnx. See the nearest\_nodes and nearest\_edges functions in the OSMnx documentation: <https://osmnx.readthedocs.io/>
My suggestion woud be to use the leuvenmapmatching package. You will get the details in the documentation of the package itself. <https://github.com/wannesm/LeuvenMapMatching>
16,978
13,793,973
I have a string in python 3 that has several unicode representations in it, for example: ``` t = 'R\\u00f3is\\u00edn' ``` and I want to convert t so that it has the proper representation when I print it, ie: ``` >>> print(t) Róisín ``` However I just get the original string back. I've tried re.sub and some others...
2012/12/10
[ "https://Stackoverflow.com/questions/13793973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205923/" ]
You want to use the built-in codec `unicode_escape`. If `t` is already a `bytes` (an 8-bit string), it's as simple as this: ``` >>> print(t.decode('unicode_escape')) Róisín ``` If `t` has already been decoded to Unicode, you can to encode it back to a `bytes` and then `decode` it this way. If you're sure that all o...
First of all, it is rather confused what you what to convert to. Just imagine that you may want to convert to 'o' and 'i'. In this case you can just make a map: ``` mp = {u'\u00f3':'o', u'\u00ed':'i'} ``` Than you may apply the replacement like: ``` t = u'R\u00f3is\u00edn' for i in range(len(t)): if t[i] in mp...
16,979
62,502,606
I have the following python code which should be able to read a .csv file with cities and their coordinates. The .csv file is in the form of: ``` name,x,y name,x,y name,x,y ``` However, I am getting the error '**list index out of range**' at line 764: ``` 758 """function to calculate the route for files in data f...
2020/06/21
[ "https://Stackoverflow.com/questions/62502606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13722495/" ]
Change DateCutting to **DateTime** and adjust your criteria: ```vb Dim strCriteria As String strCriteria = "[DateCutting] >= #" & Format(Me.txtfrom, "yyyy\/mm\/dd") & "# And [DateCutting] <= #" & Format(Me.txtto, "yyyy\/mm\/dd") & "#" DoCmd.ApplyFilter strCriteria ``` To find a number: ``` strCriteria = "[Number]...
Try `Dim strCriteria as String` `dim task As String`
16,981
36,706,131
I am having trouble getting one of my functions in python to work. The code for my function is below: ``` def checkBlackjack(value, pot, player, wager): if (value == 21): print("Congratulations!! Blackjack!!") pot -= wager player += wager print ("The pot value is $", pot) pr...
2016/04/18
[ "https://Stackoverflow.com/questions/36706131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4832091/" ]
You're only returning something if the condition in your function is met, otherwise the function returns `None` by default and it is then trying to unpack `None` into two values (your variables)
Here is an [MCVE](https://stackoverflow.com/help/mcve) for this question: ``` >>> a, b = None Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> a, b = None TypeError: 'NoneType' object is not iterable ``` At this point, the problem should be clear. If not, one could look up multiple as...
16,982
59,952,898
I am trying to install `python3-psycopg2` as a part of `postgresql` installation, but I get: ``` The following packages have unmet dependencies: python3-psycopg2 : Depends: python3 (>= 3.7~) but 3.6.7-1~18.04 is to be installed E: Unable to correct problems, you have held broken packages. ``` I installed `python3.8...
2020/01/28
[ "https://Stackoverflow.com/questions/59952898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1626977/" ]
The `Psycopg2` library is built as a wrapper around `libpq` and mostly written in C. It is distributed as a `sdist` and is built during installation. For this reason it requires some `PostgreSQL` binaries and headers to be present during installation. Consider running these 2 commands: ``` sudo apt install python3-de...
While the explanation of Gitau is very good. You can simply install the psycopg2 binary instead as mentioned by Maurice: `python3 -m pip install psycopg2-binary` or just `pip install psycopg2-binary`
16,983
60,140,174
I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment. requirements.txt given below, ``` aniso8601==6.0.0 Click==7.0 Flask==1.0.3 Flask-Cors==3.0.7 Flask-RESTful==0.3.7 Flask-SQLAlchemy==2.4.0 itsdangerous==1.1.0 Jinja2==2...
2020/02/09
[ "https://Stackoverflow.com/questions/60140174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727390/" ]
The bug was fixed in [werkzeug 0.15.5](https://werkzeug.palletsprojects.com/en/1.0.x/changes/#version-0-15-5). Upgrade from 0.15.4 to to a later version.
I had the error in django shell, it seems there is a bug in ipython. finally, I decided to remove ipython temporary until bug fix ``` pip uninstall ipython ``` [more info](https://bugs.python.org/issue35894)
16,985
6,377,535
I have trouble setting up funkload to work well with cookies. I turn on `fl-record` and perform a series of requests of which each is sending a cookie. If I use the command without supplying a folder path, the output is stored in TCPWatch-Proxy format and I can see the contents of all the cookies, so I know that they a...
2011/06/16
[ "https://Stackoverflow.com/questions/6377535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475763/" ]
I see this old post not answered, so I thought I could post: In Python: Identify the name of cookie you are sending. mine is 'csrftoken' in header and same one in post as 'csrfmiddlewaretoken'> intially I get the value of cookie then pass the same in post for authentication. Example: ``` res = self.get ( server_...
I've found a bug in Funkload. Funkload isn't handling correctly the cookies with a leading '.' in the domain. At the moment all that cookies are being silently ignored. Check this branch: <https://github.com/sbook/FunkLoad> I've already send a pull request: <https://github.com/nuxeo/FunkLoad/pull/32>
16,995
913,396
I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application! The class PyMonitor.cc describes the swig interface to the desired class, Moni...
2009/05/27
[ "https://Stackoverflow.com/questions/913396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75827/" ]
You have to forward the exceptions to Python if you want to parse them there. See the [SWIG Documentation](http://www.swig.org/Doc1.3/Customization.html#exception). In order to forward exceptions, you only have to add some code in the SWIG interface (.i) file. Basically, this can be anywhere in the .i file. All types ...
I'm not familiar with swig, or with using C++ and Python together, but if this is under a recent version of Microsoft Visual C++, then the `Monitor` class is probably throwing a C structured exception, rather than a C++ typed exception. C structured exceptions aren't caught by C++ exception handlers, even the `catch(.....
16,996
3,856,314
After using C# for long time I finally decided to switch to Python. The question I am facing for the moment has to do about auto-complete. I guess I am spoiled by C# and especially from resharper and I was expecting something similar to exist for Python. My editor of choice is emacs and after doing some research I fou...
2010/10/04
[ "https://Stackoverflow.com/questions/3856314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404984/" ]
I found this post > > [My Emacs Python environment](http://www.saltycrane.com/blog/2010/05/my-emacs-python-environment/) > > > to be the most useful and comprehensive list of instructions and references on how to setup a decent Python development environment in Emacs regardless of OS platform. It is still a bit ...
I find that [PyDev](http://pydev.org/) + Eclipse can meet most of my needs. There is also [PyCharm](http://www.jetbrains.com/pycharm/) from the Intellij team. PyCharm has the added advantage of smooth integration with git.
16,998
55,062,944
I have seen multiple posts on passing the string but not able to find good solution on reading the string passed to python script from batch file. Here is my problem. I am calling python script from batch file and passing the argument. ``` string_var = "123_Asdf" bat 'testscript.py %string_var%' ``` I have follow...
2019/03/08
[ "https://Stackoverflow.com/questions/55062944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442477/" ]
You can order by a field created with annotate: ``` from django.db.models import IntegerField, Value as V from django.db.models.functions import Cast, StrIndex, Substr last = ( Machine.objects.annotate( part=Cast(Substr("deviceSerialNo", StrIndex("deviceSerialNo", V("-"))), IntegerField()) ) .orde...
If number have multiple - and want to extract out number from reverse then try following. AB-12-12344 Output: 12344 ``` qs.annotate( r_part=Reverse('number') ).annotate( part=Reverse( Cast( Substr("r_part", 1, StrIndex("r_part", V("-"))) ), IntegerField() ) ``` ) tha...
17,008
18,401,287
I am trying to build documentation for my flask project, and I am experiencing issues with the path My project structure is like: ``` myproject config all.py __init__.py logger.py logger.conf myproject models.py __init__.py en (english language docs folder) ...
2013/08/23
[ "https://Stackoverflow.com/questions/18401287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2080641/" ]
It is the behaviour of `open()` that is the problem. Commands like `open()` and `chdir()` and so work from the directory you're now in, which is probably the directory where the makefile is. To test it, add an `print(os.listdir('.')` above your call to `open('logger.conf')`, that'll show you the problem. The solution...
I had a similar problem when generating sphinx documentation for some python code that was not written to be run in my computer, but in an embedded system instead. In that case, the existing code attempted to open a file that did not exist in my computer, and that made sphinx fail. In this case, I decided to change the...
17,010
54,681,449
I upgraded from pandas 0.20.3 to pandas 0.24.1. While running the command `ts.sort_index(inplace=True)`, I am getting a `FutureWarning` in my test output, which is shown below. Can I change the method call to suppress the following warning? I am happy to keep the old behavior. ``` /lib/python3.6/site-packages/pandas/c...
2019/02/14
[ "https://Stackoverflow.com/questions/54681449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4808588/" ]
I rewrote your question [here](https://stackoverflow.com/questions/54854900/workaround-for-pandas-futurewarning-when-sorting-a-datetimeindex), to include an MCVE. After it went a while with no responses, I posted an issue against Pandas. Here's my workaround: ``` with warnings.catch_warnings(): # Bug in Pandas em...
If I were you, I would do a downgrade using pip and setting the previous version. It's the lazier answer. But if you really want to keep it upgraded, then there is a parameter call deprecated warning inside pandas data frame. Just adjust it accordingly what you need. You can check it using the documentation of pandas. ...
17,011
29,585,296
I have the following code (test.cgi): ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgitb cgitb.enable() print "Content-Type: text/plain;charset=utf-8" print print "Hello World!" ``` The file is CHMOD 777 and so is the directory it is in. I am getting the following error log ``` [S...
2015/04/12
[ "https://Stackoverflow.com/questions/29585296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103669/" ]
Flatten the list by using `itertools.chain`, then find the minimum as you would otherwise: ``` from itertools import chain listA = [[10,20,30],[40,50,60],[70,80,90]] min(chain.from_iterable(listA)) # 10 ```
Set `result` to `float("inf")`. Iterate over every number in every list and call each number `i`. If `i` is less than `result`, `result = i`. Once you're done, `result` will contain the lowest value.
17,012
16,505,259
I am new in django and python.I am using windows 7 and Eclipse IDE.I have installed python 2.7,django and pip.I have created a system variable called PYTHONPATH with values `C:\Python27;C:\Python27\Scripts`.I am unable to set path for django and pip.When i type django-admin.py and pip in powershell,it shows `commandnot...
2013/05/12
[ "https://Stackoverflow.com/questions/16505259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1770199/" ]
You need to set the Powershell specific path variable. It does not know to look for an environment variable called `pythonpath`. That is helpful only for python aware applications (such as installers for Python modules). You need to add the Python directories to the `$env:Path` environment variable in Powershell. See...
Also, if you're just getting started with Django and Eclipse, make sure you configure your PyDev interpreter settings to include the site-packages directory. This will ensure Eclipse can find your Django packages. You can find more details about setting up your PYTHONPATH inside Eclipse here: [PyDev Interpreter Conf...
17,017
2,767,013
I think in the past python scripts would run off CGI, which would create a new thread for each process. I am a newbie so I'm not really sure, what options do we have? Is the web server pipeline that python works under any more/less effecient than say php?
2010/05/04
[ "https://Stackoverflow.com/questions/2767013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
You can still use CGI if you want, but the normal approach these days is using WSGI on the Python side, e.g. through `mod_wsgi` on Apache or via bridges to `FastCGI` on other web servers. At least with `mod_wsgi`, I know of no inefficiencies with this approach. BTW, your description of CGI ("create a new thread for ea...
I suggest cherrypy (<http://www.cherrypy.org/>). It is very convenient to use, has everything you need for making web services, but still quite simple (no mega-framework). The most efficient way to use it is to run it as self-contained server on localhost and put it behind Apache via a Proxy statement, and make apache ...
17,018
21,102,790
I am using RHEL 6.3 and have 2.6.6. I need to use the Python 2.7.6. I compiled python from source, installed pip and virtual env. Now I am trying in different ways: ``` virtualenv-2.7 testvirtualenv virtualenv --python=/usr/local/bin/python2.7 myenv ``` However I am getting AssertionError. Full trace: ``` New ...
2014/01/13
[ "https://Stackoverflow.com/questions/21102790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2195440/" ]
You need type composition: ``` trait Composition[F[_], G[_]] { type T[A] = F[G[A]] } class Later extends Do[Composition[Future, Seq]#T] { def do[A](f: Int => A): Future[Seq[A]] } ``` Or if you just need it in this one place ``` class Later extends Do[({ type T[A] = Future[Seq[A]] })#T] { def do[A](f: Int => A)...
**I** believe you want this: ``` import scala.language.higherKinds import scala.concurrent.Future object Main { type Id[A] = A trait Do[F[_]] { // Notice the return type now contains `Seq`. def `do`[A](f: Int => A): F[Seq[A]] } class Now extends Do[Id] { override def `do`[A](f: Int => A): Seq[A]...
17,021
20,986,255
In our application we allow users to write specific conditions and we allow them express the conditions using such notation: ``` (1 and 2 and 3 or 4) ``` Where each numeric number correspond to one specific rule/condition. Now the problem is, how should I convert it, such that the end result is something like this: ...
2014/01/08
[ "https://Stackoverflow.com/questions/20986255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534862/" ]
This is most easily done using a two step process. 1) Convert to syntax tree. 2) Convert syntax tree to prefix notation. A syntax tree is basically the same as your prefix notation, just built using the data structures of your programming language. The standard method to create a syntax tree is to use a LALR parser g...
First define semantics. In your first example you gave `(1 and 2 and 3) or 4` interpretation but it can also be `1 and 2 and (3 or 4)` so: ``` { "$and": [ {"$or": [3,4] }, [1,2] ] } ``` Let's assume that `and` has higher priority. Then just go through list join all terms with `and`. Next, joi...
17,023
43,005,480
Let's say that I have three lists and want to add all elements that are integers to a list named `int_list`: ``` test1 = [1, 2, 3, "b", 6] test2 = [1, "foo", "bar", 7] test3 = ["more stuff", 1, 4, 99] int_list = [] ``` I know that I can do the following code to append all integers to a new list: ``` for elem1, ele...
2017/03/24
[ "https://Stackoverflow.com/questions/43005480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6779980/" ]
When you import the data into Excel, tell the **Import Wizard** that the field is *Text*. [![enter image description here](https://i.stack.imgur.com/tqMFm.png)](https://i.stack.imgur.com/tqMFm.png)
My preference is to deal with the inputs, when possible, and in this case if you have control over the python script, it may be preferable to simply modify *that*, so that Excel's default behavior interprets the file in the desired way. Borrowing from [this similar question with a million upvotes](https://stackoverflo...
17,026
60,286,051
I have a python script and want to call a subprocess from it. The following example works completely fine: Script1: ``` from subprocess import Popen p = Popen('python Script2.py', shell=True) ``` Script2: ``` def execute(): print('works!') execute() ``` However as soon as I want to pass a variable to the f...
2020/02/18
[ "https://Stackoverflow.com/questions/60286051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12920312/" ]
There is file called extensions.json in the bin folder. Your startup calls register in that file. Whichever function app deployed latest, that function's startup call will be replaced with earlier function's startup call. So, you need to take an action that all the functions' startup calls will be registered in this fi...
Seems like you haven't [injected](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1) `IAzureTableStorageService` properly in your Startup class hence the DI can't find it. Reference the project where `IAzureTableStorageService` is located, add something like this in you...
17,027
1,083,391
Please, help me in: how to put a double command in the *cmd*, like this in the Linux: `apt-get install firefox && cp test.py /home/python/`, but how to do this in Windows?, more specific in Windows CE, but it´s the same in Windows and in Windows CE, because the *cmd* is the same. Thanks!
2009/07/05
[ "https://Stackoverflow.com/questions/1083391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126353/" ]
If CE is the same as XP Pro (and I'm not sure you're right about that), you can use the same method: ``` dir && echo hello ``` Here it is running on my Windows VM (XP SP3): ``` C:\Documents and Settings\Pax>dir && echo hello Volume in drive C is Primary Volume Serial Number is 04F7-0E7B Directory of C:\Document...
This <http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true> might be of some help. cheers
17,028
17,620,875
I'm python developer and most frequently I use [buildout](http://www.buildout.org/en/latest/) for managing my projects. In this case I dont ever need to run any command to activate my dependencies environment. However, sometime I use virtualenv when buildout is to complicated for this particular case. Recently I st...
2013/07/12
[ "https://Stackoverflow.com/questions/17620875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/375373/" ]
One feature of Unix shells is that they let you create *shell functions*, which are much like functions in other languages; they are essentially named groups of commands. For example, you can write a function named `mycd` that first runs `cd`, and then runs other commands: ``` function mycd () { cd "$@" if ......
I think you're looking for one of two things. [`autoenv`](https://github.com/kennethreitz/autoenv) is a relatively simple tool that creates the relevant bash functions for you. It's essentially doing what ruakh suggested, but you can use it without having to know how the shell works. [`virtualenvwrapper`](https://pyp...
17,029
62,389,496
I wanted to write a Python Script that lists all files in the current working directory, if the **length** of a file's name is between 3 - 6 characters long. Also, it should only list files with the extension `.py` I was not able to find any specific function that would return the legnth of a files name, only the siz...
2020/06/15
[ "https://Stackoverflow.com/questions/62389496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12781947/" ]
Maybe rewording `file` to `filename` might make things clearer... ``` import os for filename in os.listdir(os.getcwd()): if filename.endswith(".py"): print(filename, len(filename)) ``` Now since you know how `if` statements work, you can probably do something with `len(filename)`? :)
your variable `file` is a string so, you can use a function for retrive a lenght of a string ``` for file in os.listdir(os.getcwd()): if file.endswith(".py"): print(file, len(file)) ```
17,032
21,957,231
I'm very new to d3 and in order to learn I'm trying to manipulate the [d3.js line example](http://bl.ocks.org/mbostock/3883245), the code is below. I'm trying to modify this to use model data that I already have on hand. This data is passed down as a json object. The problem is that I don't know how to manipulate the d...
2014/02/22
[ "https://Stackoverflow.com/questions/21957231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870013/" ]
``` for (String hashTagged : hashTags) { if (tweet.equalsIgnoreCase(hashTagged) != true) { hashTags.add(hashTagged); -----------------------------^ } } ``` The issue is while iterating the hashTags list you cant upda...
You are getting `java.util.ConcurrentModificationException` because you are modifying the `List` `hashTags` while you are iterating over it. ``` for (String hashTagged : hashTags) { if (tweet.equalsIgnoreCase(hashTagged) != true) { hashTags.add(hashTagged); } } ``` You can create a temporary list of ...
17,034
65,736,625
In python, I have a datetime object in python with that format. ``` datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') ``` In other classes, I'm using this object. When i reach this object,i want to extract time from it and compare string time. Like below; ``` if "01:15:13" == time_from_dateti...
2021/01/15
[ "https://Stackoverflow.com/questions/65736625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14697436/" ]
You need to use the strftime method: ``` from datetime import datetime date_time_str = '2021-01-15 01:15:13' datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') if "01:15:13" == datetime_object.strftime('%H:%M:%S'): print("match") ```
If you want to compare it as string: ``` if "01:15:13" == datetime_object.strftime('%H:%M:%S'): ```
17,035
7,172,585
> > **Possible Duplicate:** > > [Should Python import statements always be at the top of a module?](https://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module) > > > In a very simple one-file python program like ``` # ------------------------ # place 1 # impor...
2011/08/24
[ "https://Stackoverflow.com/questions/7172585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909210/" ]
[PEP 8](http://www.python.org/dev/peps/pep-0008/) specifies that: * Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. Imports should be grouped in the following order: 1. standard library imports 2. related third party imports 3...
I'd principally agree with Robert S. answer, but sometimes it makes sense to put it into a function. Especially if you want to control the importing mechanism. This is useful if you cannot be sure if you actually have access to a specific module. Consider this example: ``` def foo(): try: import somespecia...
17,037
19,328,381
I am confused about classes in python. I don't want anyone to write down raw code but suggest methods of doing it. Right now I have the following code... ``` def main(): lst = [] filename = 'yob' + input('Enter year: ') + '.txt' for line in open(filename): line = line.strip() lst.append(lin...
2013/10/11
[ "https://Stackoverflow.com/questions/19328381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2835743/" ]
You can use reflection ``` item.GetType().GetProperty(field).GetValue(item).ToString(); ``` (or `GetField()` instead of `GetProperty()` if... that's a field)
This is not trivial like it might be, say, in ecmascript. The simplest option is reflection, for example: ``` data = item.GetType().GetProperty(field).GetValue(item).ToString(); ``` however: depending on the API involved, there may be other options available involving indexers, etc. Note that reflection is slower th...
17,038
53,327,826
Many open-source projects use a "Fork me on Github" banner at the top-right corner of the pages in the documentation. To name just one, let's take the example of Python [requests](http://docs.python-requests.org/en/master/): [![Fork me on Github ribbon](https://i.stack.imgur.com/CHfGm.png)](https://i.stack.imgur.com/...
2018/11/15
[ "https://Stackoverflow.com/questions/53327826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291710/" ]
The easiest way is to use an alternative theme like [`alabaster`](https://pypi.org/project/alabaster/) as it comes with preconfigured option like `github_banner` (see [Joran's answer](https://stackoverflow.com/a/53328720/2291710)). For other themes like `sphinx-rtd-theme` which do not provide such setting, the solutio...
the great thing about python (especially python on github) is that you can simply look at the source I can go to <https://github.com/requests/requests/blob/master/docs/conf.py> and look at their conf.py where we can see this entry ``` # Theme options are theme-specific and customize the look and feel of a theme # f...
17,039
44,922,108
The objective is to parse the output of an ill-behaving program which concatenates a list of numbers, e.g., 3, 4, 5, into a string "345", without any non-number separating the numbers. I also know that the list is sorted in ascending order. I came up with the following solution which reconstructs the list from a strin...
2017/07/05
[ "https://Stackoverflow.com/questions/44922108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2618889/" ]
This finds solutions for all possible initial number lengths: ``` a = '3456781015203040' def numbers(a,n): current_num, i = 0, 0 while True: while i+n <= len(a) and int(a[i:i+n]) <= current_num: n += 1 if i+n <= len(a): current_num = int(a[i:i+n]) yield curr...
little modification which allows to parse "7000000000001" data and give the best output (max list size) ``` a = 30000001 def numbers(a,n): current_num, i = 0, 0 while True: while i+n <= len(a) and int(a[i:i+n]) <= current_num:n += 1 if i+2*n>len(a):current_num = int(a[i:]);yield current_num; re...
17,040