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
62,446,911
I have this dataset ``` age 24 32 29 23 23 31 25 26 34 ``` I want to categorize using python and save the result to a new column "agegroup" such that age between; 23 to 26 to return 1 in the agegroup column, 27-30 to return value 2 in the agegroup column and 31-34 to return 3 in the agegroup column
2020/06/18
[ "https://Stackoverflow.com/questions/62446911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12360445/" ]
You can use [`pandas.cut`](https://pandas.pydata.org/docs/reference/api/pandas.cut.html). Given: ``` >>> df age 0 24 1 32 2 29 3 23 4 23 5 31 6 25 7 26 8 34 ``` Solution: ``` >>> df.assign(agegroup=pd.cut(df['age'], bins=[23, 27, 31, 35], right=False, labels=[1, 2, 3])) age agegroup 0 24 ...
You can use dictionaries to do this as well. Key-value pairs. The keys would be the different age ranges and the value for a particular key would be the count for that particular age group. groupDict={'23-26':0,'27-30':0,'31-34':0} ``` for i in ages: if i>=23 and i<=26: groupDict['23-26']+=1 elif i>=27 and i<=30...
8,891
40,744,392
I use Anonymous Python Functions in BitBake recipes to set variables during parsing. Now I wonder if I can check if a specific variable is set or not. If not, then I want to generate a BitBake Error, which stops the build process. Pseudo code, that I want to create: ``` python __anonymous () { if d.getVar('MY_VAR...
2016/11/22
[ "https://Stackoverflow.com/questions/40744392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5316879/" ]
You can call `bb.fatal("MY_VARIABLE not set")` which will print that error and abort the build by throwing an exception. Beware that d.getVar() returns `None` when the variable is unset. You only get the empty string if that's your default value.
Outputs are possible on different loglevels and with python as well as shell script code For usage in python there are: * **bb.fatal** * bb.error * bb.warn * bb.note * bb.plain * bb.debug For usage in shell script there are: * **bbfatal** * bberror * bbwarn * bbnote * bbplain * bbdebug for example if you want to th...
8,892
37,228,607
In C, as well as in C++, one can in a for-loop change the index (for example `i`). This can be useful to, for example, compare a current element and based on that comparison compare the next element: ``` for(int i = 0; i < end; i++) if(array[i] == ':') if(array[++i] == ')') smileyDetected = true; ``` Now...
2016/05/14
[ "https://Stackoverflow.com/questions/37228607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762311/" ]
Perhaps: ``` smileyDetected = ':)' in "".join(array) ``` or per @jonrsharpe: ``` from itertools import tee # pairwise() from "Itertools Recipes" def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) for a, b in pairwise(array): if a...
In this special case, you could do: ``` for i, char in enumerate(array[:-1]): if char == ":" and array[i+1] == ")": smiley_detected = True ``` However, in the more general case, if you need to skip elements, you could modify the raw iterator: ``` iterator = iter(array) for char in iterator: if char ...
8,893
68,026,549
I'm using TFX to build an AI Pipeline on Vertex AI. I've followed [this tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/gcp/vertex_pipelines_simple) to get started, then I adapted the pipeline to my own data which has over 100M rows of time series data. A couple of my components get killed midway because of memo...
2021/06/17
[ "https://Stackoverflow.com/questions/68026549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2005440/" ]
Turns out you can't at the moment but according to this [issue](https://github.com/tensorflow/tfx/issues/3194#issuecomment-802598448), this feature is coming. An alternative solution is to convert your TFX pipeline to a Kubeflow pipeline. Vertex AI pipelines support kubeflow and with these you can set memory and cpu c...
An alternate option to this solution would be using the dataflow beam runner which allows components to be run dataflow cluster via Vertex. I am still to find a way for specifying machine types for custom components Sample beam input: ``` BIG_QUERY_WITH_DIRECT_RUNNER_BEAM_PIPELINE_ARGS = [ --project= GOOGLE_CLOUD_PR...
8,896
24,862,912
**Solution:** My fault: The file where adding the icon to the button is used via the "placeholder" function from QtDesigner. The Main-programm located in a different folder searches in its own folder for the icon, not in the folder from the "imported" file. So you just have to add the path to the icon: ``` dirpath ...
2014/07/21
[ "https://Stackoverflow.com/questions/24862912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3027322/" ]
This works for me and is auto generated by pyqt when you convert a .ui file to .py with the [pyuic4](http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#the-uic-module) tool. ``` Icon = QtGui.QIcon() Icon.addPixmap(QtGui.QPixmap(_fromUtf8("SOME FILE")), QtGui.QIcon.Normal, QtGui.QIcon.Off) button.setIcon(...
Do you have text rendered on that button? Try playing with the icon size setIconSize(), to begin with you can try setting it to the rect of the pixmap.
8,897
2,823,907
I am looking for a graphics library for 3D reconstruction research to develop my specific viewer based on some library. OpenGL seems in a low level and I have to remake the wheel everywhere. And I also tried VTK(visualization toolkit). However, it seems too abstract that I need to master many conceptions before I start...
2010/05/13
[ "https://Stackoverflow.com/questions/2823907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166482/" ]
Have you tried [Pyglet](http://www.pyglet.org/) with [PyOpenGL](http://pyopengl.sourceforge.net/)? The two goes very well together. Wheaties' suggest is quite good as well, although [PyOgre](http://www.ogre3d.org/wiki/index.php/PyOgre) also has a steep learning curve, as it is indeed higher-level. On another thought, t...
I have no personal experience with this, but I have heard some decent things about [Pyglet](http://www.pyglet.org/index.html)
8,900
21,327,768
Note: I was using the wrong source file for my data - once that was fixed, my issue was resolved. It turns out, there is no simple way to use `int(..)` on a string that is not an integer literal. This is an example from the book "Machine Learning In Action", and I cannot quite figure out what is wrong. Here's some bac...
2014/01/24
[ "https://Stackoverflow.com/questions/21327768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1884158/" ]
strings like "largeDoses" could not be converted to integers. In folder `Ch02` of [that code project](https://github.com/pbharrin/machinelearninginaction), you have two data files, use the second one `datingTestSet2.txt` instead of loading the first
You can use [ast.literal\_eval](http://docs.python.org/2/library/ast.html#ast.literal_eval) and catch the exception ValueError the malformed string (by the way int('9.4') will raise an exception)
8,908
60,490,195
I am trying to write a small program using the AzureML Python SDK (v1.0.85) to register an Environment in AMLS and use that definition to construct a local Conda environment when experiments are being run (for a pre-trained model). The code works fine for simple scenarios where all dependencies are loaded from Conda/ p...
2020/03/02
[ "https://Stackoverflow.com/questions/60490195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9821873/" ]
The issue was with out firewall blocking the required requests between AMLS and the storage container (I presume to get the environment definitions/ private wheels). We resolved this by updating the firewall with appropriate ALLOW rules for the AMLS service to contact and read from the attached storage container.
Assuming that you'd like to run in the script on a remote compute, then my suggestion would be to pass the environment you just "got". to a `RunConfiguration`, then pass that to an `ScriptRunConfig`, `Estimator`, or a `PythonScriptStep` ```py from azureml.core import ScriptRunConfig from azureml.core.runconfig import ...
8,909
1,419,416
please, could someone explain to me a few basic things about working with languages like C? Especially on Windows? 1. If I want to use some other library, what do I need from the library? Header files .h and ..? 2. What is the difference between .dll and .dll.a.? .dll and .lib? .dll and .exe? What is .def? 3. Does it ...
2009/09/14
[ "https://Stackoverflow.com/questions/1419416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166939/" ]
> > 1: If I want to use some other library, what do I need from the library? Header files .h and ..? > > > ... and, usually a `*.lib` file which you pass as an argument to your linker. > > 2: What is the difference between .dll and .dll.a.? .dll and .lib? .dll and .exe? What is .def? > > > This might be usef...
In all seriousness, the place to go to learn how to run your local environment is the documentation for your local environment. After all we on not even know exactly what your environment *is*, much less have it in front of us. But here are some answers: `1.` You need the headers, and a linkable object of some kind. ...
8,910
20,303,558
Coming from this link: [Splitlines in Python a table with empty spaces](https://stackoverflow.com/questions/20252728/splitlines-in-python-a-table-with-empty-spaces) It works well but there is a problem when the size of the columns change: ``` COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME init...
2013/11/30
[ "https://Stackoverflow.com/questions/20303558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2898827/" ]
I did a bit of reading on `lsof -F` after checking out the other thread and found that it does produce easily parsed output. Here's a quick demonstration of the general idea. It parses that and prints a small subset of the parsed output to show format. Are you able to use `-F` for your use case? ``` import subprocess ...
As [@Tim Wilder said](https://stackoverflow.com/a/20304501/4279), you could use `lsof -F` to get machine-readable output. Here's a script that converts `lsof` output into json. One json object per line. It produces output as soon as pipe buffers are full without waiting for the whole `lsof` process to end (it takes a w...
8,913
35,196,449
I am writing script supporting my Django project development. First I thought of using bash for this purpose but due to lack of enough knowledge and total lack of time I decided to write something using argparse and running system commands using subprocess. Everything went ok until I had to run ``` ./manage.py migrat...
2016/02/04
[ "https://Stackoverflow.com/questions/35196449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1844201/" ]
This is not impossible, but it is a bad idea - it's very tricky to get right. Instead, you want to separate the business logic from the UI, so that you can do the logic in the background, while the UI is still on the UI thread. The key is that you must not modify the UI controls from the background thread - instead, y...
WPF does not allow you to change UI from the background thread. Only ONE SINGLE thread can handle UI thread. Instead, you should calculate your data in the background thread, and then call `Application.Current.Dispatcher.Invoke(...)` method to update the UI. For example: ``` Application.Current.Dispatcher.Invoke(() =>...
8,914
36,811,332
I'm having some trouble create a table using values from a text file. My text file looks like this: ``` e432,6/5/3,6962,c8429,A,4324 e340,2/3/5,566623,c1210,A,3201 e4202,6/5/3,4232,c8419,E,4232 e3230,2/3/5,66632,c1120,A,53204 e4202,6/5/3,61962,c8429,A,4322 ``` I would like to generate a table containing arrays where...
2016/04/23
[ "https://Stackoverflow.com/questions/36811332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5854201/" ]
AFAIK, neither JavaScript nor TypeScript provide a generic hashing function. You have to import a third-party lib, like [ts-md5](https://www.npmjs.com/package/ts-md5) for instance, and give it a string representation of your object: `Md5.hashStr(JSON.stringify(yourObject))`. Obviously, depending on your precise use ...
If you want to compare the objects and not the data, then the @Valery solution is not for you, as it will compare the data and not the two objects. If you want to compare the data and not the objects, then JSON.stringify(obj1) === JSON.stringify(obj2) is enough, which is simple string comparison.
8,915
25,960,754
``` ImportError at / cannot import name views Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.7 Exception Type: ImportError Exception Value: cannot import name views Exception Location: /Users/adam/Desktop/qblog/qblog/urls.py in <module>, line 1 Python Executable: /...
2014/09/21
[ "https://Stackoverflow.com/questions/25960754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1779600/" ]
There is no need to import the views in your project-level file. You are not using them there, so no reason to import them. If you *did* need to, you would just to `from blog import views`, because the views are in the blog directory and manage.py puts the top-level directory into the Python path.
You can just use `import views`.This works for me
8,917
41,155,985
Frustratingly having a lot of difficult installing the TA-Lib package in python. <https://pypi.python.org/pypi/TA-Lib> I have read through all the forum posts I can find on this but no such luck for my particular problem.. Windows 10 Python 3.5.2 Anaconda 4.2.0 Cython 0.24.1 Microsoft Visual Studio 14.0 I have d...
2016/12/15
[ "https://Stackoverflow.com/questions/41155985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7273219/" ]
In order to use the python package you need the dependencies first. For mac you can just use `brew install ta-lib` and then `pip install TA-Lib` will work just fine.
I faced the same problems trying with Anaconda 5.1.0 and Python 3.6 via Visual Studio. The solution was to get a wheel from <https://www.lfd.uci.edu/~gohlke/pythonlibs>, then install it via pip. You need to make sure the wheel matches your python version (in my case, 3.6). In Anaconda, I just opened a prompt, naviga...
8,918
31,091,104
I am using a PHP server at the back end and a basic web page which asks the user to upload an image. This image is used as an input to a MATLAB script to be executed on the server side. What I need is something like a MATLAB session(not clear on that word) that is already running on the server side which runs the MATL...
2015/06/27
[ "https://Stackoverflow.com/questions/31091104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3159395/" ]
There exist multiple interfaces to control matlab. Probably best choice for this case is [matlabcontrol](https://code.google.com/p/matlabcontrol/) or the matlab engine for python (which you can't use for some reason). On windows a third alternative would be com. Besides controlling the matlab process, you could implem...
There is an API for C++ where you call the Matlab engine using engOpen. This will open Matlab and leave it running until you close it. Then your C++ program can wait and listen for the image to process. <http://www.mathworks.com/help/matlab/calling-matlab-engine-from-c-c-and-fortran-programs.html> Another option is t...
8,928
24,518,868
I am looking at the bencode specification and I am writing a C++ port of the deluge bit-torrent client's bencode implementation (written in python). The Python implementation includes a dictionary of { data\_types : callback\_functions } by which a function wrapper easily selects which encoding function to use by a dic...
2014/07/01
[ "https://Stackoverflow.com/questions/24518868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3795241/" ]
A primer on templates --------------------- C++, in contrast to the dynamic Python, is a **statically typed language**. What this means is that the types of objects are known at compile time (more on the differences [here](https://stackoverflow.com/a/1517670/2567683)). A way to generalize code in C++ is templates, w...
What you're seeing here is not a parent-child relationship as in normal inheritance, it's a [specialization](http://en.cppreference.com/w/cpp/language/template_specialization). The template defines the default implementation, and the specializations replace that implementation for parameters that match the specific typ...
8,930
49,342,652
I have a Django Web-Application that uses celery in the background for periodic tasks. Right now I have three docker images * one for the django application * one for celery workers * one for the celery scheduler whose `Dockerfile`s all look like this: ``` FROM alpine:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code W...
2018/03/17
[ "https://Stackoverflow.com/questions/49342652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376172/" ]
I will suggest to use one Dockerfile and just update your CMD during runtime. Litle bit modification will work for both local and Heroku as well. As far Heroku is concern they provide environment variable to start container with the environment variable. [heroku set-up-your-local-environment-variables](https://devcent...
I would recommend looking at [docker-compose](https://docs.docker.com/compose/) to simplify management of multiple containers. Use a single Dockerfile like the one you posted above, then create a `docker-compose.yml` that might look something like this: ``` version: '3' services: # a django service serving an appli...
8,931
61,882,562
I'm trying to access to my Api rest that I released in Heroku with docker and see that Dynos is running the gunicorn command that I put in the Dockerfile. The Dockerfile that I used is: ``` FROM ubuntu:18.04 RUN apt update RUN apt install -y python3 python3-pip RUN mkdir /opt/app ENV PYTHONUNBUFFERED 1 ENV LANG C.UT...
2020/05/19
[ "https://Stackoverflow.com/questions/61882562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13039952/" ]
@jhaos mentioned gunicorn was running in the root path Change the following in `Dockerfile` ``` RUN mkdir /opt/app to WORKDIR /opt/app COPY Ski4All/ /opt/app/ to COPY Ski4All . ```
The problem was that the gunicorn command was running in the / root path and not in the correct workdir. In the comments @HariHaraSuhan solved the error.
8,932
12,183,763
I am following the tutorial for deploying a django project on AWS elastic beanstalk here: <http://docs.amazonwebservices.com/elasticbeanstalk/latest/dg/create_deploy_Python_django.html> My app works when I test locally but when I deploy, I'm getting a 404 error. Looking at the event logs, I see this message: `Error r...
2012/08/29
[ "https://Stackoverflow.com/questions/12183763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/656707/" ]
I believe you don't need to put container\_commands in .config because there is no database or table at this moment.
I followed the same tutorial recently and had a similar result. At step 6, upon seeing the default django 'congrats' page render locally, I deployed to EB as instructed and got a 404 instead of the default 'congrats' page. I decided to use the code up to that point as a foundation for following the '[getting starte...
8,933
730,573
I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available? A few google searches have not turned up very promising results. Though I did find this: [Receive and send emails in python](https://stac...
2009/04/08
[ "https://Stackoverflow.com/questions/730573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
There's an app called [jutda-helpdesk](http://code.google.com/p/jutda-helpdesk/) that uses Python's `poplib` and `imaplib` to process incoming emails. You just have to have an account somewhere with POP3 or IMAP access. This is adapted from their [get\_email.py](http://code.google.com/p/jutda-helpdesk/source/browse/tr...
Django is really intended as a web server (well, as a framework that fits into a web server), not as an email server. I suppose you could put some code into a Django web application that starts up an email server, using the kind of code shown in that question you linked to, but I really wouldn't recommend it; it's an a...
8,937
39,840,323
I'm using tensorflow 0.10 and I was benchmarking the examples found in the [official HowTo on reading data](https://www.tensorflow.org/versions/r0.10/how_tos/reading_data/index.html#reading-data). This HowTo illustrates different methods to move data to tensorflow, using the same MNIST example. I was surprised by the ...
2016/10/03
[ "https://Stackoverflow.com/questions/39840323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765009/" ]
**Update Oct 9** the slowness comes because the computation runs too fast for Python to pre-empt the computation thread and to schedule the pre-fetching threads. Computation in main thread takes 2ms and apparently that's too little for the pre-fetching thread to grab the GIL. Pre-fetching thread has larger delay and he...
Yaroslav nails the problem well. With small models you'll need to speed up the data import. One way to do this is with the Tensorflow function, [tf.TFRecordReader.read\_up\_to](https://www.tensorflow.org/api_docs/python/io_ops/readers#TFRecordReader.read_up_to), that reads multiple records in each `session.run()` call,...
8,940
52,407,452
When I run the following piece of code, only the print statements in the method, which I have dynamically assigned to the class "Test" only return "my\_unique\_method\_name". **How to print the method name I have given it?** (Which is "wizardry" in the method—see "Expected Output" below.) ``` #!/usr/bin/python3 impo...
2018/09/19
[ "https://Stackoverflow.com/questions/52407452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039582/" ]
As you have already made the step to use template matching with the `template match="Class/Student"` I would suggest to stick with that approach and simply write two templates, one for the `Class` elements, the other for the `Student` elements ``` <xsl:template match="Class"> <ul> <xsl:apply-template...
You want one `ul` per `Class`, not per `Student`, so change ``` <xsl:template match="Class/Student"> ``` to ``` <xsl:template match="Class"> ``` Then change ``` <xsl:for-each select="../Student"> ``` to ``` <xsl:for-each select="Student"> ``` to get one `li` per `Student` child element of the `Class...
8,943
39,745,460
I am working on some piece of python code that calls various linux tools (like ssh) for automation purposes. Right now I am looking into "return code" handling. Thus: I am looking for a simple way to run *some* command that gives me a specific non-zero return code; something like ``` echo "this is a testcommand, tha...
2016/09/28
[ "https://Stackoverflow.com/questions/39745460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1531124/" ]
Run `exit` in a subshell. ``` $ (exit 5) ; echo $? 5 ```
This is not exactly what you are asking but custom `rc` can be achieved through exit command. ``` echo "this is a test command, that should return with " ;exit 5 echo $? 5 ```
8,944
4,377,260
As an exercise I built a little script that query Google Suggest JSON API. The code is quite simple: ``` query = 'a' url = "http://clients1.google.co.jp/complete/search?hl=ja&q=%s&json=t" %query response = urllib.urlopen(url) result = json.load(response) UnicodeDecodeError: 'utf8' codec can't decode byte 0x83 in posit...
2010/12/07
[ "https://Stackoverflow.com/questions/4377260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246242/" ]
The response header (`print response.header`) contains the following information: ``` Content-Type: text/javascript; charset=Shift_JIS ``` Note the charset. If you specify this encoding in `json.load` it will work: ``` result = json.load(response, encoding='shift_jis') ```
Regardless of what the spec says, the string "\x83A\x83}\x83]\x83\x93" is not UTF-8. At a guess, it is one of [ "cp932", "shift\_jis", "shift\_jis\_2004", "shift\_jisx0213" ]; try decoding as one of these.
8,946
32,566,625
Say I generated a `dots = psychopy.visual.DotStim`. Is it possible to change the number of dots later? `dots.nDots = 5` leads to an error on the next `dots.draw()` because the underlying matrices don't match: ``` Traceback (most recent call last): File "/home/jonas/Documents/projects/work pggcs/experiment/dots.py", ...
2015/09/14
[ "https://Stackoverflow.com/questions/32566625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297830/" ]
It can be fixed for the `DotStim`: ``` dots.nDots = 5 dots._dotsDir = [0]*dots.nDots dots. _verticesBase = dots._newDotsXY(dots.nDots) ``` This set movement of all dots to 0 but you can change that value to whatever you like or specify for individual dots. This is a hack which will likely break if you modify other a...
Yes, it would be nice to be able to do this but I haven't gotten around to it. The code that has to be run when the nDots/nElements changes is pretty close to starting from scratch with a new stimulus.**init** so adding this in 'correctly' probably means some refactoring (move a lot of the **init** code into setNDots()...
8,947
48,279,419
How does the quality of my code gets affected if I don't use `__init__` method in python? A simple example would be appreciated.
2018/01/16
[ "https://Stackoverflow.com/questions/48279419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735772/" ]
*Short answer*; nothing happens. *Long answer*; if you have a class `B`, which inherits from a class `A`, and if `B` has no `__init__` method defined, then the parent's (in this case, `A`) `__init__` is invoked. ``` In [137]: class A: ...: def __init__(self): ...: print("In A") ...: ...
Its not a matter of quality here, in `Object-oriented-design` which python supports, `__init__` is way to supply data when an object is created first. In `OOPS`, this is called a `constructor`. In other words **A constructor is a method which prepares a valid object**. There are design patters on large projects are bu...
8,948
11,577,619
I got two files each containing a column with "time" and one with "id" like this: File 1: ``` time id 11.24 1 11.26 2 11.27 3 11.29 5 11.30 6 ``` File 2: ``` time id 11.25 1 11.26 3 11.27 4 11.31 6 11.32 7 11.33 8 ``` Im trying to do a python script which can subtract the...
2012/07/20
[ "https://Stackoverflow.com/questions/11577619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1540477/" ]
Python Set do not support ordering for the elements. I would store the data as a dictionary ``` file1 = {1:'11:24', 2:'11:26', ... etc} file2 = {1:'11:25', 3:'11:26', ... etc} ``` The loop over the intersection of the keys (or union based on your needs) to do the subtraction (time based or math based).
This is a bit old school. Look at using a default dict from the `collections` module for a more elegant approach. This will work for any number of files, I've named mine `f1`, `f2` etc. The general idea is to process each file and build up a list of time values for each id. After file processing, iterate over the dict...
8,949
23,221,577
I'm following [this tutorial on Embedding Python on C](https://docs.python.org/2.7/extending/embedding.html), but their [Pure Embedding](https://docs.python.org/2.7/extending/embedding.html#pure-embedding) example is not working for me. I have on the same folder (taken from the example): **call.c** ``` #include <Pyt...
2014/04/22
[ "https://Stackoverflow.com/questions/23221577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1970845/" ]
Try setting `PYTHONPATH`: ``` export PYTHONPATH=`pwd` ```
Really, the example should have `PySys_SetPath(".");` after initialization.
8,953
71,363,142
how do you call a php function with html I have this: ``` <input class="myButton" type="button" name="woonkameruit" value="UIT" onclick="kameroff('woonkamer');<?php woonkameruit()?>"> ``` and ``` function woonkameruit() { exec("sudo pkill python"); exec("sudo python3/home/pi/Documents/Programmas/WOONKAMERUit...
2022/03/05
[ "https://Stackoverflow.com/questions/71363142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17288855/" ]
You have to send the function name via Javascript, and create some controller like logic. It is a similar to what Laravel Livewire does. For Example: frontend.php: ``` <!-- Frontend Logic --> <input id="myButton" class="myButton" type="button" name="woonkameruit" value="UIT"> <!-- Put Before </body> --> <script typ...
You cannot directly call PHP functions with HTML as it is in the backend. However you can send a request to the backend with JS or HTML and make the PHP handle it so it executes a function. To do this there are multiple ways: HTML: Form JS: Ajax If you do not know how to implement this I suggest going to websites ...
8,954
3,636,928
I have some code that pulls data from a com-port and I want to make sure that what I got really is a printable string (i.e. ASCII, maybe UTF-8) before printing it. Is there a function for doing this? The first half dozen places I looked, didn't have anything that looks like what I want. ([string has printable](http://d...
2010/09/03
[ "https://Stackoverflow.com/questions/3636928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
``` >>> # Printable >>> s = 'test' >>> len(s)+2 == len(repr(s)) True >>> # Unprintable >>> s = 'test\x00' >>> len(s)+2 == len(repr(s)) False ```
``` ctrlchar = "\n\r| " # ------------------------------------------------------------------------ # This will let you control what you deem 'printable' # Clean enough to display any binary def isprint(chh): if ord(chh) > 127: return False if ord(chh) < 32: return False if chh in ctrlchar...
8,955
53,727,275
I am trying to ammend a group of files in a folder, by adding F to the 4th line (which is number 3 in python, if I'm correct). With the following code below, the code is just continuously running and not making the amendments, anyone got any ideas? ``` import os from glob import glob list_of_files = glob('*.gjf') ...
2018/12/11
[ "https://Stackoverflow.com/questions/53727275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750169/" ]
The error is expected. Function runtime is based on C#, when the response tries to add the `Allow` header, underlying C# code checks its name. It's by design that `Allow` is a read-only header in [HttpContentHeaders](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.headers.httpcontentheaders?view=netframewo...
Have you tried adding the allowed methods to the **function.json** files as noted in the [documentation](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook#trigger---configuration)? Example below: ``` "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", ...
8,965
71,044,523
For Example I have enabled the mTLS in my istio service in STRICT mode. and I have authorization policy that have kind of source.principals rule check. Now I want to access these rules details like source.principals and source.namespace after request is authenticated and authorized so that I can do more business login...
2022/02/09
[ "https://Stackoverflow.com/questions/71044523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2090808/" ]
Have a look at the [AuthConfig class](https://github.com/manfredsteyer/angular-oauth2-oidc/blob/master/projects/lib/src/auth.config.ts) and try setting `loginUrl` to the authorize endpoint and also set the token endpoint explicitly. See if this gives you a different error. A good library should allow you to set endpoi...
Extending **auth.config** about additional loginUrl and tokenUrl solved the issue. This is finall version of my config file: ``` export const OAUTH_CONFIG: AuthConfig = { issuer: environment.identityProviderBaseUrl, loginUrl: environment.identityProviderLoginUrl, logoutUrl: environment.identityProviderLogoutUrl...
8,968
14,386,536
I have an existing, functional Django application that has been running in DEBUG mode for the last several months. When I change the site to run in production mode, I begin getting the following Exception emails sent to me when I hit a specific view that tries to create a new Referral model object. ``` Traceback (most...
2013/01/17
[ "https://Stackoverflow.com/questions/14386536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1988262/" ]
**UPDATE** (with solution below) I've been digging into the Django model code and it seems like there is a bug that creates a race condition when using "app.model"-based identifiers for the related field in a ForeignKey. When the application is running in production mode as opposed to DEBUG, the ForeignKey.get\_defaul...
Another cause: Make sure that all Foreign Keys are in the same reference models in the same application (app label). I was banging my head against the wall for a while on this one. ``` class Meta: db_table = 'reservation' app_label = 'admin' ```
8,969
50,866,111
I'm working with retrain.python file from this demo. I'm getting different types of files: [![enter image description here](https://i.stack.imgur.com/WLY0Y.png)](https://i.stack.imgur.com/WLY0Y.png) [![enter image description here](https://i.stack.imgur.com/htD6r.png)](https://i.stack.imgur.com/htD6r.png) [![enter i...
2018/06/14
[ "https://Stackoverflow.com/questions/50866111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4024038/" ]
Here is a nice script to freeze a graph ``` import os import argparse import tensorflow as tf from tensorflow.python.framework import graph_util from tensorflow.python.platform import gfile def load_graph_def(model_path, sess=None): if os.path.isfile(model_path): with gfile.FastGFile(model_path, 'rb') as ...
Given that you have a `meta graph` saved, try using the `input_meta_graph` argument: ``` python freeze_graph.py \ --input_meta_graph=/home/automator/Desktop/retrain/code/tmp/model.meta \ --input_checkpoint=/home/automator/Desktop/retrain/code/tmp/model.ckpt \ --input_binary=true \ --output_graph=/home/automator/Des...
8,976
60,763,948
These are my two models, when I try to open City page on Django I get an error: "column city.country\_id\_id does not exist". I don't know why python adds extra `_id` there. ``` class Country(models.Model): country_id = models.CharField(primary_key=True,max_length=3) country_name = models.CharField(max_length=...
2020/03/19
[ "https://Stackoverflow.com/questions/60763948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13090788/" ]
as the comments have begun to mention, and in reference to your final statement, this code absolutely *should not* work, for multiple reasons. 1) you open the file three times, for no apparent reason. 2) `outfile` isn't declared, doesn't do anything. 3) when you open a file with `w` it clears the contents of afforme...
This will work. ``` f_name = input("Input file name: ") with open(f_name, "r+") as f: lines = f.read().splitlines() # get string, split lines lines = [l.capitalize() for l in lines] # capitalize each line f.seek(0) # move the cursor to the beginning f.write('\n'.join(lines)) # join the lines and w...
8,977
3,939,482
I have a stats app written in python that on a timer refreshes the ssh screen with stats. Right now it uses os.system('clear') to clear the screen and then outputs a multi line data with the stats. I'd like to do just do a \r instead of executing the clear but that only works with one line, is it possible to do this w...
2010/10/15
[ "https://Stackoverflow.com/questions/3939482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388538/" ]
It doesn't really answer your question, but there isn't really anything wrong with calling os.system to clear out the terminal (other than the system running on different operating systems) in which case you could use: `os.system('cls' if os.name=='nt' else 'clear')`
For simple applications you can use: ``` print('\n' * number_of_lines) ``` For more advanced there is [curses](http://docs.python.org/library/curses.html) module in standard library.
8,978
40,119,361
I have a dictionary which has the following structure in a python program `{'John':{'age': '12', 'height':'152', 'weight':'45}}`, this is the result returned from a function. My question is how may I extract the sub-dictionary please? so that I can have the data in this form only `{'age': '12', 'height':'152', 'weight...
2016/10/18
[ "https://Stackoverflow.com/questions/40119361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6797800/" ]
To get a value from a dictionary, use dict[key]: ``` >>> d = {'John':{'age': '12', 'height':'152', 'weight':'45'}} >>> d['John'] {'age': '12', 'height': '152', 'weight': '45'} >>> ```
``` >>> d = {'John':{'age': '12', 'height':'152', 'weight':'45'}, 'Kim':{'age': '13', 'height': '113', 'weight': '30'}} >>> for key in d: ... print(key, d[key]) ... John {'height': '152', 'weight': '45', 'age': '12'} Kim {'height': '113', 'weight': '30', 'age': '13'} ``` Just access the subdictionary with `d[key...
8,980
45,103,348
I try to make to load the content from mysqldb using an animation and a limit of content taken and it takes content is displaying when it gets at the end of content the animation of loading is continue loading a I get this error My script: ``` <script> $(document).ready(function(){ var limit = 7; var...
2017/07/14
[ "https://Stackoverflow.com/questions/45103348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7906290/" ]
You are returning an empty string from your python code: ``` if json_fetch=="<Response 3 bytes [200 OK]>": return "" ``` When you use `JSON.parse("")`, you are returned with the `Uncaught SyntaxError: Unexpected end of JSON input`
i change but now is returning an empty array "[]" and the animation did't stop to place on the screen the text("did't stop") script: ``` <script> $(document).ready(function(){ var limit = 7; var start = 0; var action = 'inactive'; function load_country_data(limit, start) { $.ajax({ url:"/select_index", ...
8,981
29,037,501
I created an SSH-Agent to provide my key to the ssh/scp cmd when connecting to my server. I also scripted a SSH-Add with the command 'expect' to write my paraphrase when it's needed. This works perfectly with my user "user". But I'm executing a python script that uses /dev/mem that need to be run as root through sudo...
2015/03/13
[ "https://Stackoverflow.com/questions/29037501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4542774/" ]
There's no general way to get this behavior. You can create an ImmutablePerson class with a constructor that would accept a Person and construct an immutable version of that Person .
Sure, just have a boolean flag in the Person object which says if the object is locked for modifications. If it is locked just have all setters do nothing or have them throw exceptions. When invoking `immutableObject(person)` just set the flag to true. Setting the flag will also lock/deny the ability to set/change th...
8,982
45,309,118
Trying to create a game called `hangman` in Python. I've come a long way, but the 'core' functionality is failing me. I've edited out all the parts which are irrelevant for this question. Here it comes: ``` picked = ['yaaayyy'] length = len(picked) dashed = "-" * length guessed = picked.replace(pick...
2017/07/25
[ "https://Stackoverflow.com/questions/45309118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4834431/" ]
This code seems to be slightly wrong: ``` found = [i for i, x in enumerate(picked) if x == input] for item in found: guessed = guessed[:item] + input + guessed[i+1:] ``` That last line should probably be: ``` guessed = guessed[:item] + input + guessed[item+1:] ``` **EDIT** This seems simpler to me: ``` for ...
Assuming you're using python3 you can solve it by simply doing: ``` user_input = input() guessed = ''.join(letter if user_input == letter else guessed[i] for i, letter in enumerate(picked)) ```
8,985
51,954,369
``` [{"answerInfo":{"extraData":{"am_answer_type":"NN"}},"content":"MP3:not support.","messageId":"c4d6a2f4649d483a811fcce4b26ae9a1"}] ``` How to extract "MP3: not support" from this String using regular expression or python code? But an error was generated per the suggestion: ``` Traceback (most recent call last):...
2018/08/21
[ "https://Stackoverflow.com/questions/51954369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697911/" ]
In my code below, I create a dataframe then output it to a .csv file using `pandas.DataFrame.to_csv()` ([link to docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html)). In this example, I also add try and except clauses to raise an exception if the user enters an invalid Series ID (...
``` import requests import json import csv headers = {'Content-type': 'application/json'} data = json.dumps({"seriesid": ['LAUMT421090000000005'],"startyear":"2011", "endyear":"2014"}) p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers) json_data = json.loads(p.text) ``` ...
8,986
30,532,431
My program consists in mouse drawing: Simultaneous reproduction of the drawn curves are done on a toplevel window. My aim is to set the vertical and horizontal scroll bars to the toplevel window. The drawing works as I expected except I am not seeing the scrollbars as well as I am getting this error (which does not st...
2015/05/29
[ "https://Stackoverflow.com/questions/30532431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4949239/" ]
These lines are incorrect: ``` self.canvas.config(yscrollcommand=self.canvas.yview) self.canvas.config(xscrollcommand=self.canvas.xview) ``` You're telling the canvas to scroll the canvas when the canvas scrolls. The `yscrollcommand` and `xscrollcommand` options typically need to call the `set` method of a scrollbar...
I want to share the solution I found in case someone in the future encounters this problem: I only had encrust the two scrollbars into the same parent widget as the canvas itself. I mean: ``` self.sbarv=Scrollbar(self.top,orient=VERTICAL) self.sbarh=Scrollbar(self.top,orient=HORIZONTAL) ```
8,987
29,583,102
I've been working locally on an AngularJS front-end, Django REST backend project and I want to deploy it to Heroku. It keeps giving me errors when I try to push, however, I've followed the steps on [here](https://devcenter.heroku.com/articles/getting-started-with-django), which has helped me deploy Django-only apps be...
2015/04/11
[ "https://Stackoverflow.com/questions/29583102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2883245/" ]
I don't understand why you need Node at all in a Django project - it's not required for Angular or DRF - but the instructions in the linked project mention setting the buildpack to a custom "multi" one: ``` heroku config:set BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git ```
it seems like you have not installed Django in you virtualenv Have you forgot to run `pip install django-toolbelt`
8,988
8,949,454
I have a pygtk Table with 16 squares, each of them containing a label. Label names are: label1, label2, label3, ..., label16. I also have a timer that fires every *n* seconds. When the timer is fired one of the squares is highlighted (just set the font size of it to 18 and the font size of the rest to 12). If there w...
2012/01/21
[ "https://Stackoverflow.com/questions/8949454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090788/" ]
You *could* use the built-in function, [`getattr()`](http://docs.python.org/library/functions.html#getattr) as others have suggested: ``` label = getattr(self, 'label%d' % i) label.modify_font(self.__font_small) ``` But in reality, you'd be better off storing your 16 `label`s in a [`list`](http://docs.python.org/tut...
You should look into the `getattr` function.
8,989
5,333,509
What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it? For example I have the numbers 1,2,5,15 and I want to reverse the bits like so: ``` original reversed 1 - 0001 - 1000 - 8 2 - 0010 - 0100 - 4 5 - 0101 - 1010 - 10 15 - 1111 - 1111...
2011/03/17
[ "https://Stackoverflow.com/questions/5333509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
Numpy indexing arrays provide concise notation for application of bit reversal permutations. ``` import numpy as np def bitrev_map(nbits): """create bit reversal mapping >>> bitrev_map(3) array([0, 4, 2, 6, 1, 5, 3, 7], dtype=uint16) >>> import numpy as np >>> np.arange(8)[bitrev_map(3)] array([0, 4, 2, ...
You can do something like this where you can define how many bits in the argument l. ``` def reverse(x, l): r = x & 1 for i in range (1, l): r = r << 1 | (x >> i) & 1 print(bin(r)) return r ```
8,994
28,055,565
I have an python `dict` whose keys and values are strings, integers and other dicts and tuples ([json does not support those](https://stackoverflow.com/q/7001606/850781)). I want to save it to a text file and then read it from the file. **Basically, I want a [`read`](http://www.lispworks.com/documentation/HyperSpec/Bod...
2015/01/20
[ "https://Stackoverflow.com/questions/28055565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/850781/" ]
You could use `repr()` on the `dict`, then read it back in and parse it with `ast.literal_eval()`. It's as human readable as Python itself is. Example: ``` In [1]: import ast In [2]: x = {} In [3]: x['string key'] = 'string value' In [4]: x[(42, 56)] = {'dict': 'value'} In [5]: x[13] = ('tuple', 'value') In [6]:...
Honestly, json is your answer [EDIT: so long as the keys are strings, didn't see the part about dicts as keys], and that's why it's taken over in the least 5 years. What legibility issues does json have? There are tons of json indenter, pretty-printer utilities, browser plug-ins [1][2] - use them and it certainly is hu...
9,004
73,067,801
I'm using databricks, and I have a repo in which I have a basic python module within which I define a class. I'm able to import and access the class and its methods from the databricks notebook. One of the methods within the class within the module looks like this (simplified) ```py def read_raw_json(self): ...
2022/07/21
[ "https://Stackoverflow.com/questions/73067801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9485834/" ]
The INFILE statement is for reading a file as raw TEXT. If you have a SAS dataset then you can just SET the dataset to read it into a data step. So the equivalent for your attempted method would be something like: ``` data _null_; set "C:\myfiles\sample.sas7bdat" end=eof; if eof then put "Observations read=====...
One cool thing about sas7bdat files is the amount of metadata stored with them. The row count of that file is already known by SAS as an attribute. You can use `proc contents` to read it. `Observations` is the number of rows in the table. ``` libname files "C:\myfiles"; proc contents data=files.sample; run; ``` A m...
9,005
57,009,331
I'm currently coding a text based game in python in which the narrative will start differently depending on answers to certain questions. The first question is simple, a name. I can't seem to get the input to display in the correct text option after the prompt. I tried using "if name is True" and "if name is str" ...
2019/07/12
[ "https://Stackoverflow.com/questions/57009331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11389547/" ]
use `isinstance` instead of `is`. And, You do not need to use `str(input())` because `input` returns `str`. ``` while True: try: # This will query for first user input, Name. name = input("Please enter your name: ") except ValueError: print("Sorry, I didn't understand that.") # ...
The exception handling around `input` is not required as the `input` function always returns a string. If the user does not enter a value an empty string is returned. Therefore your code can be simplified to ``` name = input("Please enter your name: ") # In python an empty string is considered `False` allowing # yo...
9,006
55,327,900
I'm currently developing my first python program, a booking system using tkinter. I have a customer account creation screen that uses a number of Entry boxes. When the Entry box is clicked the following key bind is called to clear the entry box of its instruction (ie. "enter name") ``` def entry_click(event): if "en...
2019/03/24
[ "https://Stackoverflow.com/questions/55327900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11240330/" ]
Just add an arg to your `entry_focusout` event and bind to the `Entry` widgets with a lambda function. ``` from tkinter import * root = Tk() def entry_click(event): if event.widget["foreground"] == "grey": event.widget.delete(0, "end") event.widget.insert(0, "") event.widget.configure(fg="black") d...
> > **Question**: Return empty `tk.Entry` box to previous state when clicked away > > > The following is a `OOP` **universal** solution. Thanks to @Henry Yik, for the `if event.widget["foreground"] == "grey":` part. ``` class EntryInstruction(tk.Entry): def __init__(self, parent, instruction=None): ...
9,008
6,003,932
``` import cgi def fill(): s = """\ <html><body> <form method="get" action="./show"> <p>Type a word: <input type="text" name="word"> <input type="submit" value="Submit"</p> </form></body></html> """ return s # Receive the Request object def show(req): # The getfirst() method returns the value of the first fi...
2011/05/14
[ "https://Stackoverflow.com/questions/6003932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/640666/" ]
``` while flag!=1: x=1 ``` This loop won't ever finish. When is `flag` ever going to change so that `flag != 1` is False? Remember, `flag` is a *local* variable so changing it anywhere else isn't going to have an effect -- especially since no other code is going to have the opportunity to run while that l...
it is not the most elegant way to do this, but if you need to change the value of flag outside your method, you should use it as a `global` variable. ``` def test(): global flag # use this everywhere you're using flag. print flag while flag!=1: x=1 return ``` but to make a waiting meth...
9,009
59,282,950
We use python with pyspark api in order to run simple code on spark cluster. ``` from pyspark import SparkContext, SparkConf conf = SparkConf().setAppName('appName').setMaster('spark://clusterip:7077') sc = SparkContext(conf=conf) rdd = sc.parallelize([1, 2, 3, 4]) rdd.map(lambda x: x**2).collect() ``` It works wh...
2019/12/11
[ "https://Stackoverflow.com/questions/59282950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406595/" ]
You try to run pyspark (which calls spark-submit) form a remote computer outside the spark cluster. This is technically possible but it is not the intended way of deploying applications. In yarn mode, it will make your computer participate in the spark protocol as a client. Thus it would require opening several ports a...
According to this [Amazon Doc](https://aws.amazon.com/premiumsupport/knowledge-center/emr-submit-spark-job-remote-cluster/?nc1=h_ls), you can't do that: > > *Common errors* > > > **Standalone mode** > > > Amazon EMR doesn't support standalone mode for Spark. It's not > possible to submit a Spark application to a...
9,010
1,247,133
Working in python I want to extract a dataset with the following structure: Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the poten...
2009/08/07
[ "https://Stackoverflow.com/questions/1247133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408134/" ]
you should probably use a defaultdictionary for this: ``` from collections import defaultdict itemdict = defaultdict(list) for id, parent_id in itemlist: itemdict[parent_id].append(id) ``` then you can recursively print it (with indentation) like ``` def printitem(id, depth=0): print ' '*depth, id ...
Are you saying that each item only maintains a reference to its parents? If so, then how about ``` def getChildren(item) : children = [] for possibleChild in allItems : if (possibleChild.parent == item) : children.extend(getChildren(possibleChild)) return children ``` This returns a l...
9,011
7,394,301
i have a class "karte" i want to know is there a way of dynamic name creation of my new objects normal object creation would be > > karta=karte() > > > but i am curious in something like this > > karta[i]=karte() > > > or something like that where i would be the number of for loop. and at the end i would ca...
2011/09/12
[ "https://Stackoverflow.com/questions/7394301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666160/" ]
You can create a list of objects like this: ``` karta = [] for i in range(10): karta.append(karte()) ``` Or using a list comprehension: ``` karta = [karte() for i in range(10)] ``` Now you can access the objects like this: `karta[i]`. To accomplish your last example, you have to modify the `globals()` dictio...
Unless you have a real need to keep the objects out of a list and have names like karta1, karta2, etc. I would do as you suggest and use a list with a loop to initialize: ``` for i in some_range: karta[i]=karte() ```
9,016
69,238,333
I'm trying to fit a curve to a differential equation. For the sake of simplicity, I'm just doing the logistic equation here. I wrote the code below but I get an error shown below it. I'm not quite sure what I'm doing wrong. ``` import numpy as np import pandas as pd import scipy.optimize as optim from scipy.integrate ...
2021/09/18
[ "https://Stackoverflow.com/questions/69238333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10796158/" ]
@hpaulj has pointed out the problem with the shape of the return value from `logistic_solution` and shown that fixing that eliminates the error that you reported. There is, however, another problem in the code. The problem does not generate an error, but it does result in an incorrect solution to your test problem (th...
A sample run of `logistic_solution` produces a (18,1) result: ``` In [268]: logistic_solution(df_yeast['td'], *parsic) Out[268]: array([[ 1.00000000e+00], [ 2.66666671e+00], [ 4.33333337e+00], [ 1.00000004e+00], [-1.23333333e+01], [-4.06666666e+01], [-8.90000000e+01], ...
9,017
35,930,924
I am new to Python(I am using Python2.7) and Pycharm, but I need to use MySQLdb module to complete my task. I spent time to search for some guides or tips and finally I go to here but does not found MySQLdb to install. [MySQL-python](http://i.stack.imgur.com/EhTaq.png) But there is error: [Error](http://i.stack.imgur...
2016/03/11
[ "https://Stackoverflow.com/questions/35930924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5886173/" ]
I have a suggestion,if you have install MySQL database,you follow this,open pycharm and click File->Settings->Project->Project Interpreter,then select your Python interpreter and click install button (the little green plus sign),input "MySQL-Python" and click the button "install package",you will install MySQL-Python s...
From Windows Command Prompt / Linux Shell install using wheel ``` pip install wheel ``` Download 32 or 64 Bit version from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python> **64-Bit** ``` pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl ``` **32-Bit** ``` pip install MySQL_python-1.2.5-cp27-none-...
9,018
12,609,728
I need to change to reference of a function in a mach-o binary to a custom function defined in my own dylib. The process I am now following is, 1. Replacing references to older functions to the new one. e.g `_fopen` to `_mopen` using sed. 2. I open the mach-o binary in [MachOView](http://sourceforge.net/projects/mach...
2012/09/26
[ "https://Stackoverflow.com/questions/12609728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390984/" ]
Just a guess and atm I am not able to test it, but try following code: ``` <Button.Template> <ControlTemplate> <Border Background="{StaticResource BlueGradient}" CornerRadius="5"> <DockPanel> <Image x:Name="imgIcon" DockPanel.Dock="Left" Height="32" Margin="4"/> ...
Just tried your code and it works fine, with a couple of caveats. In order to get it to work I needed to drop the resouceDictionary link, as I don't have that file. Is there any chance that some content is being defined, rather than just a style/template etc? Also I note that your code has an x:Class="ShinyButton", i...
9,021
22,960,956
The python package 'isbntools' (<https://github.com/xlcnd/isbntools>) allows to retrieve bibliography information about books from online resources. In particular the script `isbn_meta [number]` retrieves information about the book with given isbn-number `[number]`. Among other it uses data from google using googleapis...
2014/04/09
[ "https://Stackoverflow.com/questions/22960956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429540/" ]
you made me some good challenge with this, but here you go: Method that return image with bottom half coloured with some colour ``` - (UIImage *)image:(UIImage *)image withBottomHalfOverlayColor:(UIColor *)color { CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height); if (UIGraphicsBeginIm...
You can use some tricks: * Use 2 different images and change the whole background. * Use one background color (light blue) and 2 images, one with the bottom half transparent
9,022
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
> > `TypeError: can't use a string pattern` > `on a bytes-like object` > > > what did i do wrong?? > > > You used a string pattern on a bytes object. Use a bytes pattern instead: ``` linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>') ^ Add the b there, it makes it into ...
That worked for me in python3. Hope this helps ``` import urllib.request import re urls = ["https://google.com","https://nytimes.com","http://CNN.com"] i = 0 regex = '<title>(.+?)</title>' pattern = re.compile(regex) while i < len(urls) : htmlfile = urllib.request.urlopen(urls[i]) htmltext = htmlfile.read() ...
9,027
55,937,156
I am trying to read glove.6B.300d.txt file into a Pandas dataframe. (The file can be downloaded from here: <https://github.com/stanfordnlp/GloVe>) Here are the exceptions I am getting: ``` glove = pd.read_csv(filename, sep = ' ') ParserError: Error tokenizing data. C error: EOF inside string starting at line 8 glove...
2019/05/01
[ "https://Stackoverflow.com/questions/55937156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8270077/" ]
You can do it in two steps. 1. Get all record which satisfy criteria like `dimension === 2` `let resultArr = jsObjects.filter(data => { return data.dimension === 2 })` 2. Get random object from result. `var randomElement = resultArr[Math.floor(Math.random() * resultArr.length)];` ```js var arr = [{ dimension: 2, x...
You could use `Math.random()` and in the range of `0` to `length` of array. ``` let result = jsObjects.filter(data => { return data.dimension === 2 }) let randomObj = result[Math.floor(Math.random() * result.length)] ```
9,037
26,193,193
How can I change the priority of the path in sys.path in python 2.7? I know that I can use `PYTHONPATH` environment variable, but it is what I will get: ``` $ PYTHONPATH=/tmp python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more informatio...
2014/10/04
[ "https://Stackoverflow.com/questions/26193193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470911/" ]
As you may know, [`sys.path` is initialized from](https://docs.python.org/2/tutorial/modules.html#the-module-search-path): * the current directory * your `PYTHONPATH` * an installation-dependent default However unfortunately that is only part of the story: `setuptools` creates [`easy-install.pth`](https://pythonhoste...
We encountered an almost identical situation and wanted to expand upon @kynan's response which is spot-on. In the case where you have such an `easy-install.pth` that you want to overcome, but which you cannot modify it (say you are a user with no root/admin access), you can do the following: * Set up an [alternate pyt...
9,038
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
You can use a [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) to create the inner dicts automatically when needed: ``` from collections import defaultdict data = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4),...
Yes, with something like this. ```py my_query = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) ) dict_query = {} for key1, key2, value in my_query: if key1 not in dict_query: dict_query[key1] = {} dict_query[key1][key2] = va...
9,039
66,912,406
Been following a tutorial on udemy for python, and atm im suppose to get a django app deployed. Since I already had a vps, I didnt go with the solution on the tutorial using google cloud, so tried to configure the app on my vps, which is also running plesk. Followed the tutorial at <https://www.plesk.com/blog/tag/djan...
2021/04/01
[ "https://Stackoverflow.com/questions/66912406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6291059/" ]
The '.no-content' has display: none which instantly removes the element and the animation does not take place I just removed that and it worked just fine. I added the other CSS to fix the position of the div 'I assumed you want it like this' ```js const App = () => { const [opened, setOpened] = React.useState(fal...
You dont need animation for that transition is much cleaner ```js const App = () => { const [opened, setOpened] = React.useState(false) return ( < div > < button className = 'btn' onClick = { () => setOpened(!opened) } > { opened ? 'Close' : 'Open' } < /button> < div style =...
9,047
63,510,765
I am following with Datacamp's tutorial on using convolutional autoencoders for classification [here](https://www.datacamp.com/community/tutorials/autoencoder-classifier-python). I understand in the tutorial that we only need the autoencoder's head (i.e. the encoder part) stacked to a fully-connected layer to do the cl...
2020/08/20
[ "https://Stackoverflow.com/questions/63510765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You are trying to render an object, and when you convert Javascript objects to string it will convert to "`[object Object]`". I think you are misunderstanding what the "name" prop of the input field should do in this context, you don't actually need that. A better way of writing your handleChange function would be: ...
You're using invalid html: ``` <input type="text-area" /> ``` [Textarea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element is to be: ``` <textarea /> ``` --- Okay, I found the issue with the userReview state. You should use: ``` <textarea onChange...> {userReview.userReview} /* name ...
9,048
2,893,193
I'd like to tell you what I've tried and then I'd really welcome any comments you can provide on how I can get PortAudio and PyAudio setup correctly! I've tried installing the stable and svn releases of PortAudio from [their website](http://www.portaudio.com/download.html) for my Core 2 Duo MacBook Pro running Snow L...
2010/05/23
[ "https://Stackoverflow.com/questions/2893193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51532/" ]
Thanks to PyAudio's author's speedy response to my inquiries, I now have a nicely installed copy. His directions are posted below for anyone who has similar issues. > > Hi Michael, > > > Try this: > > > 1) Make sure your directory layout is > like: > > > ./foo/pyaudio/portaudio-v19/ ./foo/pyaudio/ > > > 2) B...
I'm on Mac 10.5.8 Intel Core 2 duo and hitting the same issue. The directory layout you need is ``` ./foo/pyaudio/portaudio-v19/ ./foo/pyaudio ``` The reason is setup.py has the following: portaudio\_path = os.environ.get("PORTAUDIO\_PATH", "./portaudio-v19") alternatively, you should be able to set PORTAUDIO\_PATH...
9,049
70,872,795
i am new to c++ and i know so much more python than c++ and i have to change a code from c++ to python, in the code to change i found this sentence: ``` p->arity = std::stoi(x, nullptr, 10); ``` i think for sake of simplicity we can use ``` p->arity = x; /* or some whit pointers im really noob on c++ but i think ...
2022/01/27
[ "https://Stackoverflow.com/questions/70872795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11579387/" ]
The API keys are only available in the deployed function, not in the react app. You can call a function from your react app which then calls the MailChimp API. This keeps you API key out of the client side code which keeps it secure. As the documentation says, you set the API keys with the CLI in the terminal ``` fir...
Firebase can use Google Cloud Platform Services, you can integrate [GCP Secret Manager](https://cloud.google.com/secret-manager) on your functions. Google Secret Manager is a fully-managed, secure, and convenient storage system for such secrets. Developers have historically leveraged environment variables or the files...
9,050
45,224,882
As I understand, the current java.net.URL handshake (for a GSS/Kerberos authentication mode) always entails a 401 as a first leg operation, which is kind of inefficient if we know the client and server are going to use GSS/Kerberos, right? Does anyone know if preemptive authentication (where you can present the token u...
2017/07/20
[ "https://Stackoverflow.com/questions/45224882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874076/" ]
I have faced the same issue and came to the same conclusion as you - preemptive SPNEGO authentication is not supported neither in Oracle JRE HttpUrlConnection nor in Apache HTTP Components. I haven't checked other HTTP clients but almost sure that it should be the same. I started working on an alternative Spnego clien...
After much investigation, it looks like preemptive kerberos authentication is not available in the default Hotspot java implementation. The http-components from Apache is also not able to help with this. However, the default implementation does have the ability to only send headers when the payload is potentially larg...
9,051
52,216,312
Data: ``` {"Survived":{"0":0,"1":1,"2":1,"3":1,"4":0,"5":0,"6":0,"7":0,"8":1,"9":1,"10":1,"11":1,"12":0,"13":0,"14":0,"15":1,"16":0,"17":1,"18":0,"19":1,"20":0,"21":1,"22":1,"23":1,"24":0,"25":1,"26":0,"27":0,"28":1,"29":0,"30":0,"31":1,"32":1,"33":0,"34":0,"35":0,"36":1,"37":0,"38":0,"39":1,"40":0,"41":0,"42":0,"43":...
2018/09/07
[ "https://Stackoverflow.com/questions/52216312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7170271/" ]
Try this ``` @Override public void onValidationFailed(View failedView, Rule<?> failedRule) { String message = failedRule.getFailureMessage(); if (failedView instanceof EditText) { failedView.requestFocus(); if(!TextUtils.isEmpty(message){ ((EditText) failedView).setError(message); ...
> > I found the problem : > > > ``` android:theme="@style/TextLabel" ``` > > Had to create a theme first and than a style and use it like : > > > ``` <style name="TextLabel" parent="BellicTheme"> ``` > > Thanks everyone > > >
9,054
44,550,192
Suppose I have the following dict... ``` sample = { 'a' : 100, 'b' : 3, 'e' : 42, 'c' : 250, 'f' : 42, 'd' : 42, } ``` I want to sort this dict with the highest order sort being by value and the lower order sort being by key. The key-value pairs of the result would be this ... ``` ( ('b', 3), ('d', 42)...
2017/06/14
[ "https://Stackoverflow.com/questions/44550192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1800838/" ]
You can define a lambda that uses both the value and key. ``` sorted(sample.items(), key=lambda x: (x[1], x[0])) ```
You can use the operator module: ``` import operator sample = { 'a' : 100, 'b' : 3, 'e' : 42, 'c' : 250, 'f' : 42, 'd' : 42, } sorted_by_value = tuple(sorted(sample.items(), key=operator.itemgetter(1))) sorted_by_key = tuple(sorted(sample.items(), key=operator.itemgetter(0))) ``` sorted\_by\_value: ``` (('b...
9,055
37,000,231
I have a Pandas DataFrame as follow: ```python In [28]: df = pd.DataFrame({'A':['CA', 'FO', 'CAP', 'CP'], 'B':['Name1', 'Name2', 'Name3', 'Name4'], 'C':['One', 'Two', 'Other', 'Some']}) In [29]: df Out[29]: A B C 0 CA Name1 One 1 FO Name2 ...
2016/05/03
[ "https://Stackoverflow.com/questions/37000231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3908401/" ]
You explicitly set the input's ID as "TextBox" but you're trying to retrieve it as `<%= TextBox.ClientID %>`, use "TextBox" as the ID (and better, give a more meaningful name to the ID). ClientId is used for ASP .net controls which have it's ID autogenerated by the ASP runtime.
Turns out I was referencing the wrong control. Referencing the correct control in the script solved my problem. The rest of the code is totally usable. Referencing a control with `#` in the call to the ID is required for jQuery functions but not plain Javascript. `<%= TextBox.ClientID %>` will work even for HTML input...
9,056
10,414,210
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
2012/05/02
[ "https://Stackoverflow.com/questions/10414210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552671/" ]
> > [`next(iterator[, default])`](http://docs.python.org/2/library/functions.html#next) > > > Retrieve the next item from the *iterator* by calling its `next()``(__next__()` in python 3) method. If *default* is given, it is returned if the iterator is exhausted, otherwise `StopIteration` is raised. > > > You get...
Apart from the obvious additional functionality, it also looks better when used together with generator expressions. Compare ``` (x for x in lst if x > 2).next() ``` to ``` next(x for x in lst if x > 2) ``` The latter is a lot more consistent with the rest of Python's style, IMHO.
9,057
28,242,398
I am trying to create an algorithm in Python 2.7.9 which can be viewed below: ![enter image description here](https://i.stack.imgur.com/4qsGy.gif) This equates to: `10/3 (-510 + sqrt(15) * sqrt(-44879 + 1000 * y))` When I try to solve it in python with the following code: ``` from __future__ import division import...
2015/01/30
[ "https://Stackoverflow.com/questions/28242398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241308/" ]
You are missing the multiplication operator below: ``` x = "%0.2f" % (10/3 (-510 + sqrt(15) * sqrt(-44879 + 1000 * y))) ^ Need to add '*' ```
Where is the multiplication operator? ``` x = "%0.2f" % (10/3 * (-510 + sqrt(15) * sqrt(-44879 + 1000 * y))) ``` Tip Whenever you get `TypeError: 'int' object is not callable`, it means that you have something like an integer followed immediately by a brace. Check out for that, Debugging will be a piece of cake.
9,060
28,064,563
I am using distutils (setup.py) to create rpm-packages from my python projects. Now, one of my projects which had a very specific task (say png-creation) is moved to a more general project (image-toolkit). 1. Is there a way to tell the user that the old package (png-creation) is obsolete when he/she installs the new p...
2015/01/21
[ "https://Stackoverflow.com/questions/28064563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4034527/" ]
ARI uses a subscription based model for events. Quoting from the documentation on the [wiki](https://wiki.asterisk.org/wiki/display/AST/Introduction+to+ARI+and+Channels): > > Resources in Asterisk do not, by default, send events about themselves to a connected ARI application. In order to get events about resources, ...
For more clarity regarding what Matt Jordan has already provided, here's an example of doing what he suggests with [ari-py](https://github.com/asterisk/ari-py): ``` import ari import logging logging.basicConfig(level=logging.ERROR) client = ari.connect('http://localhost:8088', 'username', 'password') postRequest=clie...
9,061
40,282,812
I have a data in mongoDB, I want to retrieve all the values of a key `"category"` using python code. I have tried several ways but in every case I have to give the "value" to retrieve. Any suggestions would be appreciated. ``` { id = "my_id1" tags: [tag1, tag2, tag3], category: "movie", }, { id = "my_id2" ...
2016/10/27
[ "https://Stackoverflow.com/questions/40282812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6858122/" ]
This Should Work ``` db.test.find({},{"category":1}); ```
Pymongo's `distinct()` method returns a list of all values associated with a key across all documents in a collection. The following code: ``` db.collection.distinct('category') ``` should return the following list: ``` ['movie', 'tv', 'movie'] ```
9,066
62,657,673
alright so I've been working on some program and I need to send emails from my gmail account.. so I wrote a code (irrelevent, it works) however the mails not send until I approve the captcha.. [captcha url](https://accounts.google.com/b/0/DisplayUnlockCaptcha) and then this solution only work once, What should I do ...
2020/06/30
[ "https://Stackoverflow.com/questions/62657673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13046336/" ]
``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoroutineController : MonoBehaviour { static CoroutineController _singleton; static Dictionary<string,IEnumerator> _routines = new Dictionary<string,IEnumerator>(100); [RuntimeInitializeOnLoadMethod( RuntimeIni...
My solution to starting the Coroutines from places that can't do this is making a Singleton CoroutineManager. I then use this CoroutineManager to invoke these Coroutines from places like ScriptableObjects. You can also use it to cache WaitForEndOfFrame or WaitForFixedUpdate so you don't need to create new ones every ti...
9,067
53,058,052
I am trying to create executable python file using pyinstaller, but while loading hooks, it shows error like this, ``` 24021 INFO: Removing import of PySide from module PIL.ImageQt 24021 INFO: Loading module hook "hook-pytz.py"... 24506 INFO: Loading module hook "hook-encodings.py"... 24600 INFO: Loading module hook...
2018/10/30
[ "https://Stackoverflow.com/questions/53058052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9921123/" ]
I have been working on this issue for a few days not and don't have hair left. For some reason nltk and pyinstaller do not work well together. So my first solution to this issue is to use something other than nltk if it is possible to code the solution without nltk. If you must use NLTK, I solved this by forcing the...
I solved the problems editing the pyinstaller nltk-hook. After much research, I decided to go it alone in the code structure. I solved my problem by commenting on the lines: `datas=[]` `'''for p in nltk.data.path: datas.append((p, "nltk_data"))'''` `hiddenimports = ["nltk.chunk.named_entity"]` What's more, you need...
9,070
28,616,942
I am trying to upload video files to a Bucket in S3 server from android app using a signed URLs which is generated from server side (coded in python) application. We are making a PUT request to the signed URL but we are getting > > `connection reset by peer exception`. > > > But when I try the same URL on the PO...
2015/02/19
[ "https://Stackoverflow.com/questions/28616942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2562861/" ]
Done this using [Retrofit](http://square.github.io/retrofit/) HTTP client library,it successfully uploaded file to Amazon s3 server. code: ``` public interface UploadService { String BASE_URL = "https://bucket.s3.amazonaws.com/folder"; /** * @param url :signed s3 url string after 'BASE_URL'. * @...
Use dynamic URL instead of providing the base URL, use @Url instead of @Path and pass a complete URI, encode= false is by default Eg: `@Multipart @PUT @Headers("x-amz-acl:public-read") Call<Void> uploadFile(@Url String url, @Header("Content-Type") String contentType, @Part MultipartBody.Part part);`
9,073
41,363,888
I could send mail using the following code ``` E:\Python\django-test\LYYDownloaderServer>python manage.py shell Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.c...
2016/12/28
[ "https://Stackoverflow.com/questions/41363888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485853/" ]
First, it doesn't matter if you were able to send the mail using the console, but if you received the mail. I assume you did. Second, it's best to try with exactly the same email address in the console as the one set in the `ADMINS`, just to be sure. Finally, the sender address might also matter. The default is "root...
Djano sends admin emails on error using logging system. As I can see from your `views.py` you are changing logging settings. This can be the cause of the problem as you cleared that django admin handler `mail_admins`. For more information check [django documentation](https://docs.djangoproject.com/en/1.10/topics/logg...
9,074
70,453,702
I am a trader, I want to use the XTB API to access the account,T try to learn Python I found XTBApi I install it Windows (python3 -m venv env) but when I enter the command (. \ venv \ Scripts \ activate) it doesn't work: The specified path could not be found. What do I have to do? Thanks How can i convert linux script...
2021/12/22
[ "https://Stackoverflow.com/questions/70453702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17330089/" ]
`stringr` is fine, but here a very good solution exists in base R. ``` x <- head(state.name) x # [1] "Alabama" "Alaska" "Arizona" "Arkansas" "California" "Colorado" substring(x, 5) # [1] "ama" "ka" "ona" "nsas" "fornia" "rado" ```
You may find this useful to rename columns. ```r library(dplyr) library(stringr) df %>% rename_with(str_sub, start = 5L) ``` If you don't want to do it for all of the columns, you can use the `.cols` argument. ```r # like this iris %>% rename_with(str_sub, start = 5L, .cols = starts_with("Sepal")) # or this...
9,076
36,730,812
I'm newbie for raspberry pi and python coding. I'm working on a school project. I've already looked for some tutorials and examples but maybe I'm missing something. I want to build a web server based gpio controller. I'm using flask for this. For going into this, I've started with this example. Just turning on and off ...
2016/04/19
[ "https://Stackoverflow.com/questions/36730812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6227347/" ]
Firstly it helps to run it in debug mode: `app.run(debug=True)` This will help you track down any errors which are being suppressed. Next have a look at the line where you are building the title string: `'title' : 'Status of Pin' + status` If you enable the debug mode, then you should see something saying that an ...
Your server was probably throwing an exception when trying to create your dictionary, therefore the templateData value was being sent as an empty value. Notice in this example, the TypeError which is thrown when trying to concatenate 2 variables of different type. Hence, wrapping your variable in the str(status) will...
9,079
53,480,646
I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do; Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the curre...
2018/11/26
[ "https://Stackoverflow.com/questions/53480646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8118659/" ]
Using jquery method as follows: ``` $("button[name^=t]").click(function(){ //process } ``` The above method will be invoked whenever a `button` whose name starts with `'t'` is clicked.
Run this snippet. You can read text using prev(). ```js $('.btn').on('click', function(){ alert($( this ).prev().val()); }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="post-comment"> <textarea class="comment-box" name="" id="" cols="8...
9,080
50,397,060
I have dataframe like this: ``` >>df L1 L0 desc_L0 4956 10 Hi 1509 nan I am 1510 20 Here 1511 nan where r u ? ``` I want to insert a new column `desc_L1` when value for `L0` is null and same time move respective `desc_L0` value to `desc_L1`. Desired output:...
2018/05/17
[ "https://Stackoverflow.com/questions/50397060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7566673/" ]
First copy your series: ``` df['desc_L1'] = df['desc_L0'] ``` Then use a mask to update the two series: ``` mask = df['L1'].isnull() df.loc[~mask, 'desc_L1'] = np.nan df.loc[mask, 'desc_L0'] = np.nan ```
You can try so: ``` df['desc_L1'] = df['desc_L0'] df['desc_L1'] = np.where(df['L0'].isna(), df['desc_L0'], np.NaN) df['desc_L0'] = np.where(df['L0'].isna(), np.NaN, df['desc_L0']) ``` Input: ``` L0 desc_L0 0 10.0 hi 1 NaN I am 2 20.0 Here 3 NaN where are u? ``` Outpu...
9,083
49,172,957
I'm learning python, I want to check if the second largest number is duplicated in a list. I've tried several ways, but I couldn't. Also, I have searched on google for this issue, I have got several answers to get/print 2nd largest number from a list but I couldn't find any answer to check if the 2nd largest number is ...
2018/03/08
[ "https://Stackoverflow.com/questions/49172957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6544266/" ]
Here is a *1-liner*: ``` >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(sorted(list1)[-2]) > 1 True ``` or using [heapq](https://docs.python.org/3/library/heapq.html#heapq.nlargest) ``` >>> import heapq >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(heapq.nlargest(2, list1)[1]) > 1 True ```
This is a simple algorithm: 1. Makes values unique 2. Sort your list by max value 3. Takes the second element 4. Check how many occurences of this elemnt exists in list Code: ``` list1 = [5, 6, 9, 9, 11] list2 = [8, 9, 13, 14, 14] def check(data): # 1. Make data unique unique = list(set(data)) # 2. Sort...
9,084
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
You can play with some slicing through lists to gather elements from original list based on content in another list, sum it up and append to final list: ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] i = 0 for x in color: total.append(sum(vp[i:i+x])) i += x print(total) # [60, 90, 60] ```
``` total = [] index = 0 for c in color: inside = 0 for i in range(c): inside += vp[index + i] index += 1 total.append(inside) print(total) ```
9,087
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
Don't use to much reflection.
For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI: ``` protected override System.Windows.Forms.CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle = cp.ExStyle...
9,094
11,070,920
I try to understand the regex in python. How can i split the following sentence with regular expression? ``` "familyname, Givenname A.15.10" ``` this is like the phonebook in python regex <http://docs.python.org/library/re.html>. The person maybe have 2 or more familynames and 2 or more givennames. After the familyn...
2012/06/17
[ "https://Stackoverflow.com/questions/11070920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364181/" ]
What you want to do is first split the family name by , `familyname, rest = text.split(',', 1)` Then you want to split the office with the first space from the right. `givenname, office = rest.rsplit(' ', 1)`
Assuming that family names don't have a comma, you can take them easily. Given names are sensible to dots. For example: ``` Harney, PJ A.15.10 Harvey, P.J. A.15.10 ``` This means that you should probably trim the rest of the record (family names are out) by a mask at the end (regex "maskpattern$").
9,104
6,947,210
how would I add set elements to a string in python? I tried: ``` sett = set(['1', '0']) elements = '' for i in sett: elements.join(i) ``` but no dice. when I print elements the string is empty. help
2011/08/04
[ "https://Stackoverflow.com/questions/6947210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/879311/" ]
This should work: ``` sett = set(['1', '0']) elements = '' for i in sett: elements += i # elements = '10' ``` However, if you're just looking to get a string representation of each element, you can simply do this: ``` elements = ''.join(sett) # elements = '10' ```
Don't know what you mean with "add set elements" to a string. But anyway: Strings are immutable in Python, so you cannot add anything to them.
9,107
70,148,408
I am new to learning python but I can't seem to find out how to make the first part of the while loop run in the background while the second part is running. Putting in the input I set allows the first part to run twice but then pauses it. Here is the code ``` import time def money(): coins = 0 multiplyer =...
2021/11/28
[ "https://Stackoverflow.com/questions/70148408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16408072/" ]
I think you need to refactor your `onSubmit` function to make it `async` so `isSubmitting` will stay `true` during your `signIn` call. ```js const onSubmit = async (data) => { await signIn(data.email, data.password) .then((response) => console.log(response)) .catch((error) => { let message = nu...
`onSubmit` needs to return a `Promise` for `formState` to update correctly. ``` const onSubmit = (payload) => { // You need to return a promise. return new Promise((resolve) => { setTimeout(() => resolve(), 1000); }); }; ``` References: * <https://react-hook-form.com/api/useform/formstate/> * <https://git...
9,116
17,099,808
I want to implement the following code in more of a pythonic way: ``` odd_rows = table.findAll('tr', attrs = {'class':'odd'}) #contain all tr tags even_rows = table.findAll('tr', attrs = {'class':'even'}) for rows in odd_rows: #rows equal 1 <tr> tag rows.findAll('td') #find all the <td> ...
2013/06/14
[ "https://Stackoverflow.com/questions/17099808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407162/" ]
Perhaps: ``` for row in table.findAll('tr', attrs = {'class':'odd'}) + table.findAll('tr', attrs = {'class':'even'}): for cell in row.findAll('td'): print cell ``` From a performance standpoint, your original code is better. Combining two lists does use resources. However, unless you are writing code fo...
``` for cls in ("odd", "even"): for rows in table.findAll('tr', class_=cls): for row in rows.findAll('td'): print row ```
9,117
40,785,453
I have a huge file of data: **datatable.txt** ``` id1 england male id2 germany female ... ... ... ``` I have another list of data: **indexes.txt** ``` id1 id3 id6 id10 id11 ``` I want to extract all rows from **datatable.txt** where the id is included in **indexes.txt**. Is it possible to do this with awk/sed/...
2016/11/24
[ "https://Stackoverflow.com/questions/40785453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2662639/" ]
You just need a simple `awk` as ``` awk 'FNR==NR {a[$1]; next}; $1 in a' indexes.csv datatable.csv id1 england male ``` 1. `FNR==NR{a[$1];next}` will process on `indexes.csv` storing the entries of the array as the content of the first column till the end of the file. 2. Now on `datatable.csv`, I can match those row...
maybe i overlook something, but i build two test files: ``` a1: id1 id2 id3 id6 id9 id10 ``` and ``` a2: id1 a 1 id2 b 2 id3 c 3 id4 c 4 id5 e 5 id6 f 6 id7 g 7 id8 h 8 id9 i 9 id10 j 10 ``` with `join a1 a2 2> /dev/null` I get all lines matched by column one.
9,118
49,760,858
I need to get data from this API <https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434> (sample node) This is my code (python): ``` import requests f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434') print f.text ``` I want to save only protocol, responseTim...
2018/04/10
[ "https://Stackoverflow.com/questions/49760858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9590393/" ]
``` import requests f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434') # Store content as json answer = f.json() # List of element you want to keep items = ['protocol', 'responseTime', 'reputation'] # Display for item in items: print(item + ':' + str(answer[item])) # If y...
This is a very unrefined way to do what you want that you could build off of. You'd need to sub in a path/filename for text.txt. ``` import requests import json f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434') t = json.loads(f.text) with open('text.txt', 'a') as mfile: mfi...
9,119
20,467,107
as we know, python has two built-in url lib: * `urllib` * `urllib2` and a third-party lib: * `urllib3` if my requirement is only to request a API by GET method, assume it return a JSON string. which lib I should use? do they have some duplicated functions? if the `urllib` can implement my require, but after...
2013/12/09
[ "https://Stackoverflow.com/questions/20467107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122265/" ]
As Alexander says in the comments, use `requests`. That's all you need.
I don't really know what you want to do, but you should try with [`requests`](http://requests.readthedocs.org/en/latest/). It's simple and intuitive.
9,121
60,388,686
Can someone please tell me how to downgrade Python 3.6.9 to 3.6.6 on Ubuntu ? I tried the below commands but didnot work 1) pip install python3.6==3.6.6 2) pip install python3.6.6
2020/02/25
[ "https://Stackoverflow.com/questions/60388686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12651893/" ]
First, verify that 3.6.6 is available: ```sh apt-cache policy python3.6 ``` If available: ```sh apt-get install python3.6=3.6.6 ``` If not available, you'll need to find a repo which has the version you desire and add it to your apt sources list, update, and install: ```sh echo "<repo url>" >> /etc/apt/sources.l...
One option is to use Anaconda, which allows you to easily use different Python versions on the same computer. [Here are the installation instructions for Anaconda on Linux](https://docs.anaconda.com/anaconda/install/linux/). Then create a Conda environment by running this command: ``` conda create --name myenv python=...
9,124
45,340,587
How do I use python, mss, and opencv to capture my computer screen and save it as an array of images to form a movie? I am converting to gray-scale so it can be a 3 dimensional array. I would like to store each 2d screen shot in a 3d array for viewing and processing. I am having a hard time constructing an array that s...
2017/07/27
[ "https://Stackoverflow.com/questions/45340587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8298595/" ]
A clue perhaps, save screenshots into a list and replay them later (you will have to adapt the sleep time): ``` import time import cv2 import mss import numpy with mss.mss() as sct: monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 640} img_matrix = [] for _ in range(100): # Get raw pizels...
use `collections.OrderedDict()` to saves the sequence ``` import collections .... fps_list= collections.OrderedDict() ... fps_list[timer] = fps ```
9,125
16,438,259
I've just learned how to use `virtualenv` and I installed Django 1.4.5. I'm assuming that the `virtualenv` created a clean slate for me to work on so with the Django 1.4.5 installed, I copied all my previous files into the `virtualenv` environment. I tried to run the server but I get an error saying `"no module named ...
2013/05/08
[ "https://Stackoverflow.com/questions/16438259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
When doing in a virtualenv : ``` pip install MySQL-python ``` I got ``` EnvironmentError: mysql_config not found ``` To install mysql\_config, as Artem Fedosov said, first install ``` sudo apt-get install libmysqlclient-dev ``` then everything works fine in virtualenv
The suggested solutions didn't work out for me, because I still got compilation errors after running ``` `$ sudo apt-get install libmysqlclient-dev` ``` so I had to run ``` apt-get install python-dev ``` Then everything worked fine for me with ``` apt-get install python-dev ```
9,126
65,990,047
I've been trying to make a keylogger but got this error in python while running the script. > > File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\pynput\_util\_*init*\_.py", line 211, in inner > return f(self, \*args, \*\*kwargs) > File "C:\Users\David\AppData\Roaming\Python\Python39\site-packages\py...
2021/02/01
[ "https://Stackoverflow.com/questions/65990047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14644110/" ]
Because keys is literally not defined anywhere **I think you made a spelling mistake.** You need to replace `key = []` with `keys = []`
I think you have a typo during initialization of the `keys` list. You have declared it as `key` but you need `keys`. You need: ``` keys = [] ``` instead of: ``` key = [] ```
9,136
4,522,733
Okay, so I'm admittedly a newbie to programming, but I can't determine how to get python v3.2 to generate a random positive integer between parameters I've given it. Just so you can understand the context, I'm trying to create a guessing-game where the user inputs parameters (say 1 to 50), and the computer generates a ...
2010/12/23
[ "https://Stackoverflow.com/questions/4522733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552834/" ]
Use [random.randrange](http://docs.python.org/dev/py3k/library/random.html#random.randrange) or [random.randint](http://docs.python.org/dev/py3k/library/random.html#random.randint) (Note the links are to the Python 3k docs). ``` In [67]: import random In [69]: random.randrange(1,10) Out[69]: 8 ```
You can use `random` module: ``` import random # Random integer >= 5 and < 10 random.randrange(5, 10) ```
9,138
50,182,828
I've installed pillow for python 3 on my macbook successfully. But I still can't use PIL library. I tried uninstalling and installing it again. I've also tried `import Image` without `from PIL` as well. I do not have PIL installed, though. It says > > Could not find a version that satisfies the requirement PIL (from...
2018/05/04
[ "https://Stackoverflow.com/questions/50182828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5991761/" ]
If you use `Anaconda`, you may try: ``` conda install Pillow ``` because this works for me.
Pil is depricated and replaced by pillow. Pillow is the official fork of PIL Install using pip or how you usually do it. <https://pillow.readthedocs.io/en/5.1.x/index.html>
9,139
28,233,090
I want to get the width % shown. So that i can monitor the progress.How to get the value using selenium in python. I don't know how to achieve this.
2015/01/30
[ "https://Stackoverflow.com/questions/28233090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4472647/" ]
A `CSS3`-only (actually moved into `CSS4` specs) solution would be the `pointer-events` property, e.g. ``` .media__body:hover:after, .media__body:hover:before { ... pointer-events: none; } ``` supported on [all modern browser](https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events) but only from `IE11` ...
``` .media__body p { margin-bottom: 1.5em; position: relative; z-index:999; ``` } try this !
9,140
33,116,636
I am very new to REGEX and HTML in particular. I know that BeautifulSoup is a way to deal with HTML but would like to try regex I need to search the text for HTML tags (I use findall). I tried multiple scenarios and examples in Stackoverflow but only got [] (empty string). Here is what I tried: ``` #reHTML = r'(?:<([...
2015/10/14
[ "https://Stackoverflow.com/questions/33116636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287011/" ]
You misunderstood [regex.findall(string[, pos[, endpos]])](https://docs.python.org/3.5/library/re.html?highlight=findall#re.regex.findall) `HTMLpara = rHTML.findall('http://pythonprogramming.net/parse-website-using- regular-expressions-urllib/', re.IGNORECASE)` means you will match the `rHTML` pattern with the string(...
This will read in a webpage and find any instances of `<html>` or `</html>`. Is this the solution you are looking for? ``` import re import urllib2 url = "http://stackoverflow.com" f = urllib2.urlopen(url) file = f.read() p = re.compile("<html>|</html>") instances = p.findall(file) print instances ``` Output: ``` ...
9,141
15,279,942
Coming from python I could do something like this. ``` values = (1, 'ab', 2.7) s = struct.Struct('I 2s f') packet = s.pack(*values) ``` I can pack together arbitrary types together very simply with python. What is the standard way to do it in Objective C?
2013/03/07
[ "https://Stackoverflow.com/questions/15279942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299648/" ]
Try using something like this: ``` window.addEventListener('load', function() { document.getElementById("demo").innerHTML="Works"; }, false); ```
Where did you get `document.onready` from? That would **never work**. To ensure the page is loaded, you could use `window.onload`; ``` window.onload = function () { document.getElementById("demo").innerHTML="Works"; } ```
9,142