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
18,485,044
It's not under the supported libraries here: <https://developers.google.com/api-client-library/python/reference/supported_apis> Is it just not available with Python? If not, what language is it available for?
2013/08/28
[ "https://Stackoverflow.com/questions/18485044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721465/" ]
Andre's answer points you at a correct place to reference the API. Since your question was python specific, allow me to show you a basic approach to building your submitted search URL in python. This example will get you all the way to search content in just a few minutes after you sign up for Google's free API key. `...
Somebody has written a wrapper for the API: <https://github.com/slimkrazy/python-google-places> Basically it's just HTTP with JSON responses. It's easier to access through JavaScript but it's just as easy to use `urllib` and the `json` library to connect to the API.
17,315
37,659,072
I'm new with python and I have to sort by date a voluminous file text with lot of line like these: ``` CCC!LL!EEEE!EW050034!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!GH676589!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!IJ6758004!2016-04-01T04:39:54.000Z!7!1!1!1 ``` Can someone help me please ? Thank y...
2016/06/06
[ "https://Stackoverflow.com/questions/37659072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4989650/" ]
Have you considered using the \*nix [`sort`](http://linux.die.net/man/1/sort) program? in raw terms, it'll probably be faster than most Python scripts. Use `-t \!` to specify that columns are separated by a `!` char, `-k n` to specify the field, where `n` is the field number, and `-o outputfile` if you want to output...
I would like to convert the time to timestamp then sort. first convert the date to list. ``` rawData = '''CCC!LL!EEEE!EW050034!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!GH676589!2016-04-01T04:39:54.000Z!7!1!1!1 CCC!LL!EEEE!IJ6758004!2016-04-01T04:39:54.000Z!7!1!1!1''' a = rawData.split('\n') >>> import dateu...
17,318
42,620,323
I am trying to parse many files found in a directory, however using multiprocessing slows my program. ``` # Calling my parsing function from Client. L = getParsedFiles('/home/tony/Lab/slicedFiles') <--- 1000 .txt files found here. combined ~100MB ``` Following ...
2017/03/06
[ "https://Stackoverflow.com/questions/42620323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6530695/" ]
Looks like you're [I/O bound](https://en.wikipedia.org/wiki/I/O_bound): > > In computer science, I/O bound refers to a condition in which the time it takes to complete a computation is determined principally by the period spent waiting for input/output operations to be completed. This is the opposite of a task being ...
In general it is never a good idea to read from the same physical (spinning) hard disk from different threads simultaneously, because every switch causes an extra delay of around 10ms to position the read head of the hard disk (would be different on SSD). As @peter-wood already said, it is better to have one thread re...
17,320
56,465,109
I am looking for an example of using python multiprocessing (i.e. a process-pool/threadpool, job queue etc.) with hylang.
2019/06/05
[ "https://Stackoverflow.com/questions/56465109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7740698/" ]
The first example from the [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html) documentation can be literally translated to Hy like so: ``` (import multiprocessing [Pool]) (defn f [x] (* x x)) (when (= __name__ "__main__") (with [p (Pool 5)] (print (.map p f [1 2 3])))) ```
Note that a straightforward translation runs into a problem on macOS (which is not officially supported, but mostly works anyway): Hy sets `sys.executable` to the Hy interpreter, and `multiprocessing` relies on that value to start up new processes. You can work around that particular problem by calling `(multiprocessin...
17,323
38,217,594
[Distinguishable objects into distinguishable boxes](https://math.stackexchange.com/questions/468824/distinguishable-objects-into-distinguishable-boxes?rq=1) It is very similar to this question posted. I'm trying to get python code for this question. Note although it is similar there is a key difference. i.e. A bucke...
2016/07/06
[ "https://Stackoverflow.com/questions/38217594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6055596/" ]
I think there is no way to combine more than one language in one editor. Please refer to this link. <https://www.tinymce.com/docs/configure/localization/#language> TinyMce is made for simplicity and easyness. If you want to have more than one language that points to one ID please play around with your Database Desi...
Actually now you can add languages in Tinymce by downloading different languages packages and integrating it with your editor. <https://www.tiny.cloud/docs/configure/localization/> here you will find the list of Available Language Packages and how to use them
17,324
50,311,713
Hello I'm trying to make a python script to loop text and toggle through it. I'm able to get python to toggle through the text once but what I cant get it to do is to keep toggling through the text. After it toggles through the text once I get a message that says Traceback (most recent call last): File "test.py", lin...
2018/05/13
[ "https://Stackoverflow.com/questions/50311713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9394080/" ]
> > Is this not redundant?? > > > Maybe it is redundant for instance methods and constructors. It isn't redundant for static methods or class initialization pseudo-methods. --- It is also possible that the (supposedly) redundant reference gets optimized away by the JIT compiler. (Or maybe it isn't optimized aw...
> > The stack frame will contain the "current class constant pool reference" and also it will have the reference to the object in heap which in turn will also point to the class data. Is this not redundant?? > > > You missed the precondition of that statement, or you misquoted it, or it was just plainly wrong wher...
17,325
69,416,562
I have this simple csv: ``` date,count 2020-07-09,144.0 2020-07-10,143.5 2020-07-12,145.5 2020-07-13,144.5 2020-07-14,146.0 2020-07-20,145.5 2020-07-21,146.0 2020-07-24,145.5 2020-07-28,143.0 2020-08-05,146.0 2020-08-10,147.0 2020-08-11,147.5 2020-08-14,146.5 2020-09-01,143.5 2020-09-02,143.0 2020-09-09,144.5 2020-09-...
2021/10/02
[ "https://Stackoverflow.com/questions/69416562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7503046/" ]
I made some research and found this: [how to close server on ctrl+c when in no-daemon](https://github.com/Unitech/pm2/issues/2833#issuecomment-298560152) ```sh pm2 kill && pm2 start ecosystem.json --only dev --no-daemon ``` It works if you run pm2 alone but you are running 2 programs together, so give it a try below...
I've created `dev.sh` script: ``` #!/bin/bash yarn pm2:del yarn pm2:dev yarn wp:dev yarn pm2:del ``` And run it using `yarn dev`: ``` "scripts": { "dev": "sh ./scripts/dev.sh", "pm2:dev": "pm2 start ecosystem.config.js --only dev", "pm2:del": "pm2 delete all || exit 0", "wp:dev": "webpack --mode=de...
17,328
61,819,993
I'm trying to run a Python script from a (windows/c#) background process. I'm successfully getting python.exe to run with the script file, but it's erroring out on the first line, "import pandas as pd". The exact error I'm getting from stderr is... Traceback (most recent call last): File "predictX.py", line 1, in i...
2020/05/15
[ "https://Stackoverflow.com/questions/61819993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13507069/" ]
You should install it in your desktop before using it. ``` $ pip install pandas ``` Then it should work fine. If not, try un-install and re-install it. [EDIT] Anaconda is a package for python which includes more module that wasn't included in the original python installer. So the script can run in Anaconda, but not...
Pilot error... Apparently there are at least two python.exe files on my computer. I changed the path to reflect the one under the Anaconda folder and everything came right up.
17,329
14,974,659
Please bear with me as I'm new to Python/Django/Unix in general. I'm learning how to use different `settings.py` files for local and production environments. The following is from the section on the `--settings` option in [the official Django docs page on `django-admin.py`](https://docs.djangoproject.com/en/1.5/ref/...
2013/02/20
[ "https://Stackoverflow.com/questions/14974659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312462/" ]
the `--settings` flag takes a dotted Python path, not a relative path on your filesystem. Meaning `--settings=mysite/local` should actually be `--settings=mysite.local`. If your current working directory is your project root when you run `django-admin`, then you shouldn't have to touch your `PYTHONPATH`.
You have to replace `/` with `.` ``` $ django-admin.py runserver --settings=mysite.local ``` You can update PYTHONPATH in the `manage.py` too. Inside `if __name__ == "__main__":` add the following. ``` import sys sys.path.append(additional_path) ```
17,330
22,429,004
I have multiple forms in a html file, which all call the same python cgi script. For example: ``` <html> <body> <form method="POST" name="form1" action="script.cgi" enctype="multipart/data-form"> .... </form> ... <form method="POST" name="form2" action="script.cgi" enctype="multipart/data-form"> ... </form> ... </body...
2014/03/15
[ "https://Stackoverflow.com/questions/22429004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2415118/" ]
You cannot. The browser submits one form, or the other, but not both. If you need data from both forms, merge the forms into one `<form>` tag instead.
First, `FieldStorage()` consumes standard input, so it should only be instantiated once. Second, only the data in the submitted form is sent to the server. The other forms may as well not exist. So while you can use the same cgi script to process both forms, if you need process both forms at the same time, as Martij...
17,331
46,511,011
The question has racked my brains There are 26 underscores presenting English alphabet in-sequence. means that letter a,b and g should be substituted by the letter k, j and r respectively, while all the other letters are not substituted. how do I do like this? How can python detect each underscore = each English alp...
2017/10/01
[ "https://Stackoverflow.com/questions/46511011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use `str.translate`: ``` In [8]: from string import ascii_lowercase In [9]: text.translate({ord(l): l if g == '_' else g for g, l in zip(guess, ascii_lowercase)}) Out[9]: 'i km jen .' ``` This maps elements of `string.ascii_lowercase` to elements of `guess` (by position). If an element of `guess` is the u...
If you had a list of the alphabet, then the list of underscores, enter a for loop and then just compare the two values, appending to a list if it does or doesn’t
17,332
73,646,972
I am using the following function to estimate the Gaussian window rolling average of my timeseries. Though it works great from small size averaging windows, it crushes (or gets extremely slow) for larger averaging windows. ``` def norm_factor_Gauss_window(s, dt): numer = np.arange(-3*s, 3*s+dt, dt) mu...
2022/09/08
[ "https://Stackoverflow.com/questions/73646972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15353940/" ]
Using [numba njit decorator](https://numba.pydata.org/numba-doc/latest/user/parallel.html?highlight=njit) on `norm_factor_Gauss_window` function on my pc I get a **10x** speed up (from 10µs to 1µs) on the execution time of this function. ``` import numba as nb @nb.njit(nogil=True) def norm_factor_Gauss_window(s, dt):...
I was able to drastically improve the speed of this code using the following: ``` from scipy import signal def norm_factor_Gauss_window(s, dt): numer = np.arange(-3*s, 3*s+dt, dt) multiplic_fac = np.exp(-(numer)**2/(2*s**2)) norm_factor = np.sum(multiplic_fac) window = len(multiplic_f...
17,336
8,765,568
I am trying to make a windows executable from a python script that uses matplotlib and it seems that I am getting a common error. > > File "run.py", line 29, in > import matplotlib.pyplot as plt File "matplotlib\pyplot.pyc", line 95, in File "matplotlib\backends\_\_init\_\_.pyc", line > 25, in pylab\_setup ImportE...
2012/01/06
[ "https://Stackoverflow.com/questions/8765568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842785/" ]
First, the easy question, is that backend installed? On my Fedora system I had to install it separately from the base matplotlib. At a Python console can you: ``` >>> import matplotlib.backends.backend_tkagg ``` If that works, then force py2exe to include it. In your config: ``` opts = { 'py2exe': { "includes" ...
If you are using py2exe it doesn't handle .egg formatted Python modules. If you used easy\_install to install the trouble module then you might only have the .egg version. See the py2exe site for more info on how to fix it. <http://www.py2exe.org/index.cgi/ExeWithEggs>
17,337
46,006,513
I'm trying to evaluate the accuracy of an algorithm that segments regions in 3D MRI Volumes (Brain). I've been using Dice, Jaccard, FPR, TNR, Precision... etc but I've only done this pixelwise (I.E. FNs= number of false neg pixels). Is there a python package (or pseudo code) out there to do this at the lesion level? Fo...
2017/09/01
[ "https://Stackoverflow.com/questions/46006513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7914014/" ]
You could use scipy's [`label`](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.measurements.label.html) to find connected components in an image: ``` from scipy.ndimage.measurements import label label_pred, numobj_pred = label(my_predictions) label_true, numobj_true = label(my_groundtruth) ...
Here is the code I ended up writing to do this task. Please let me know if anyone sees any errors. ``` def distance(p1, p2,dim): if dim==2: return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) elif dim==3: return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2+ (p2[2] - p1[2])**2) else: print 'error...
17,342
67,959,301
I want to print the code exactly after one min ``` import time from datetime import datetime while True: time.sleep(1) now = datetime.now() current_datetime = now.strftime("%d-%m-%Y %H:%M:%S") if current_datetime==today.strftime("%d-%m-%Y") + "09:15:00": sec = 60 time.sleep(sec) ...
2021/06/13
[ "https://Stackoverflow.com/questions/67959301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
No. They are different things. Auto-incremented columns in MySQL are not guaranteed to be gapless. Gaps can occur for multiple reasons. The most common are: * Concurrent transactions. * Deletion. It sounds like you have a unique identifier in Java which is either redundant or an item of data. If the latter, then add ...
It isn't compulsory to create and unique id field in the database . You can instead change the table like--> ``` CREATE TABLE companies ( 'COMPANYID' int NOT NULL, `NAME` varchar(200) DEFAULT NULL, `EMAIL` varchar(200) DEFAULT NULL, `PASSWORD` varchar(200) DEFAULT NULL, PRIMARY KEY (`ID`) ``` since you are...
17,343
39,852,963
I have the following list of tuples already sorted, with "sorted" in python: ``` L = [("1","blaabal"), ("1.2","bbalab"), ("10","ejej"), ("11.1","aaua"), ("12.1","ehjej"), ("12.2 (c)", "ekeke"), ("12.2 (d)", "qwerty"), ("2.1","baala"), ("3","yuio"), ("4","poku"), ("5....
2016/10/04
[ "https://Stackoverflow.com/questions/39852963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6726377/" ]
Since the first element in each tuple is a string, Python is performing lexographic sorting in which all strings that start with `'1'` come before strings that start with a `'2'`. To get the sorting you desire, you'll want to treat the first entry *as a `float`* instead of a string. We can use `sorted` along with a c...
The first value of your tuples are strings, and are being sorted in lexicographic order. If you want them to remain strings, sort with ``` sorted(l, key = lambda x: float(x[0])) ```
17,344
21,699,251
I got a function to call an exec in **node.js** server. I'm really lost about getting the stdout back. This is function: ``` function callPythonFile(args) { out = null var exec = require('child_process').exec, child; child = exec("../Prácticas/python/Taylor.py 'sin(w)' -10 10 0 10", function (er...
2014/02/11
[ "https://Stackoverflow.com/questions/21699251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742560/" ]
Because you return from the function before the exec is finished and the callback is executed. Exec in this case is asynchronous and unfortunately there is no synchronous exec in node.js in the last version (0.10.x). There are two ways to do what you are trying to do. Wait until the exec is done -------------------...
Have a look here about the `exec`: [nodejs doc](http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback). The callback function does not really return anything. So if you want to "return" the output, why don't you just read the stream and return the resulting string ([nodejs ...
17,346
3,289,330
I have 5 python cgi pages. I can navigate from one page to another. All pages get their data from the same database table just that they use different queries. The problem is that the application as a whole is slow. Though they connect to the same database, each page creates a new handle every time I visit it and hand...
2010/07/20
[ "https://Stackoverflow.com/questions/3289330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343409/" ]
cgi requires a new interpreter to start up for each request, and then all the resources such as db connections to be acquired and released. [fastcgi](http://en.wikipedia.org/wiki/FastCGI) or [wsgi](http://en.wikipedia.org/wiki/Wsgi) improve performance by allowing you to keep running the same process between requests
Django and Pylons are both frameworks that solve this problem quite nicely, namely by abstracting the DB-frontend integration. They are worth considering.
17,347
24,863,576
I have a python script that have \_\_main\_\_ statement and took all values parametric. I want to import and use it in my own script. Actually I can import but don't know how to use it. As you see below, \_\_main\_\_ is a bit complicated and rewriting it will take time because I even don't know what does most of code...
2014/07/21
[ "https://Stackoverflow.com/questions/24863576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681662/" ]
No, there is no clean way to do so. When the module is being imported, it's code is executed and all global variables are set as attributes to the module object. So if part of the code is not executed at all (is guarded by `__main__` condition) there is no clean way to get access to that code. You can however run code ...
by what your saying you want to call a function in the script that is importing the module so try: ``` import __main__ __main__.myfunc() ```
17,348
43,754,065
I want to get the shade value of each circles from an image. 1. I try to detect circles using `HoughCircle`. 2. I get the center of each circle. 3. I put the text (the circle numbers) in a circle. 4. I set the pixel subset to obtain the shading values and calculate the averaged shading values. 5. I want to get the re...
2017/05/03
[ "https://Stackoverflow.com/questions/43754065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7955795/" ]
I can't answer completely, because it depends entirely on what's in `$HashVariable`. The easiest way to tell what's in there is: ``` use Data::Dumper; print Dumper $HashVariable; ``` Assuming this is a hash *reference* - which it would be, if `print $HashVariable` gives `HASH(0xdeadbeef)` as an output. So this *...
There's an obvious problem here, but it wouldn't cause the behaviour that you are seeing. You think that you have a hash reference in `$HashVariable` and that sounds correct given the `HASH(0xd1007d0)` output that you see when you print it. But setting up a hash reference and running your code, gives slightly strange...
17,351
37,096,806
I have landed into quite a unique problem. I created the model **1.**'message', used it for a while, then i changed it to **2.** 'messages' and after that again changed it back to **3.** 'message' but this time with many changes in the model fields. As i got to know afterwards, django migrations gets into some problem...
2016/05/08
[ "https://Stackoverflow.com/questions/37096806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4510252/" ]
Normally, You should not edit them manually. Once you start editing them, you will land into cyclic dependencies problems and if you do not remember what changes you made, your entire migrations will be messed up. What you can do is revert back migrations if you do not have any data to lose. If you are deleting migra...
No, I don't think so, you are better off deleting the migration files after the last successful migrations and running it again.
17,352
57,060,964
I am using `sklearn` modules to find the best fitting models and model parameters. However, I have an unexpected Index error down below: ``` > IndexError Traceback (most recent call > last) <ipython-input-38-ea3f99e30226> in <module> > 22 s = mean_squared_error(y[ts], be...
2019/07/16
[ "https://Stackoverflow.com/questions/57060964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7302169/" ]
The root cause of your issue is that, while you ask for the evaluation of 6 models in `GridSearchCV`, you provide parameters only for the first 2 ones: ``` models = [SVR(), RandomForestRegressor(), LinearRegression(), Ridge(), Lasso(), XGBRegressor()] params = [{'C': [0.01, 1]}, {'n_estimators': [10, 20]}] ``` The r...
When you define ``` cv = [[] for _ in range(len(models))] ``` it has an empty list for each model. In the loop, however, you go over `enumerate(zip(models, params))` which has only **two** elements, since your `params` list has two elements (because `list(zip(x,y))` [has length](https://docs.python.org/3.3/library...
17,354
31,387,660
How I can use the Kivy framework in Qpython3 (Python 3.2 for android) app? I know that Qpython (Python 2.7 for android) app support this framework. pip\_console don't install kivy. I have an error, when I try to install it. Please help me.
2015/07/13
[ "https://Stackoverflow.com/questions/31387660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111676/" ]
``` Session["email"] = email; ``` This will store the value between response and postback. Let me know if this is what you were looking for.
**TempData** can work for you. Another option is to store it in hidden field and receive it back on POST but you should be aware that "bad users" can modify that (via browser developer tools for example).
17,355
7,391,689
Here is what I can read in the python subprocess module documentation: ``` Replacing shell pipeline output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output ...
2011/09/12
[ "https://Stackoverflow.com/questions/7391689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From [Wikipedia](http://en.wikipedia.org/wiki/SIGPIPE), **SIGPIPE** is the signal sent to a process when it attempts to write to a pipe without a process connected to the other end. When you first create `p1` using `stdout=PIPE`, there is one process connected to the pipe, which is your Python process, and you can rea...
OK I see. p1.stdout is closed from my python script but remains open in p2, and then p1 and p2 communicate together. Except if p2 is already closed, then p1 receives a SIGPIPE. Am I correct?
17,357
46,517,814
sudo python yantest.py 255,255,0 ``` who = sys.argv[1] print sys.argv[1] print who print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) yanon(strip, Color(who)) ``` output from above is ``` 255,255,0 255,255,0 Number of arguments: 2 arguments. Argument List: ['yantes...
2017/10/01
[ "https://Stackoverflow.com/questions/46517814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7509061/" ]
The problem with your implementation is that it does not distinguish original numbers from the squares that you have previously added. First, since you are doing this recursively, you don't need a `for` loop. Each invocation needs to take care of the initial value of the list alone. Next, `add(n)` adds the number at ...
There are two ways to safely add (or remove) elements to a list while iterating it: 1. Iterate backwards over the list, so that the indexes of the upcoming elements don't shift. 2. Use an [`Iterator`](https://docs.oracle.com/javase/9/docs/api/java/util/Iterator.html) or [`ListIterator`](https://docs.oracle.com/javase/...
17,358
45,765,946
I'm using some objects in python with dynamic properties, all with numbers and strings. Also I created a simple method to make a copy of an object. One of the property is a list, but I don't need it to be deep copied. This method seems to work fine, but I found an odd problem. This piece of code shows it: ``` #!/usr/b...
2017/08/18
[ "https://Stackoverflow.com/questions/45765946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1502508/" ]
Your `copy()` method copied the `copy` method (*not* the function from the class) from `test1`, which means that `self` in `test2.copy()` is still `test1`.
If you take a look at `dir(test1)`, you'll see that one of the elements is `'copy'`. In other words, you're not just copying the `type` attribute. **You're copying the `copy` method.** `test2` gets `test2.copy` set to `test1.copy`, a bound method that will copy `test1`. Don't use `dir` for this. Look at the instance...
17,359
4,834,538
``` import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = "trade.settings" from trade.turkey.models import * d = DemoRecs.objects.all() d.delete() ``` When I run this, it imports fine if I leave out the `d.delete()` line. It's erroring on that line. Why? If I comment that out, everything is cool. I can insert...
2011/01/29
[ "https://Stackoverflow.com/questions/4834538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
The directory for the `trade` project is missing from `sys.path`.
Try adding "trade" to the pythonpath... ``` import os.path _pypath = os.path.realpath(os.path.dirname(__file__) + '/trade') sys.path.append(_pypath) ```
17,360
50,809,052
So in python, if I want to make an if statement I need to do something like this (where a,b,c are conditions): ``` if(a) x=1 elsif(b) x=1 elseif(c) x=1 ``` is there a way to simply do something like: ``` if(a or b or c) x=1 ``` this would save a huge amount of time, but it doesn't evaluate.
2018/06/12
[ "https://Stackoverflow.com/questions/50809052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9928114/" ]
Turns out, whatever the issue was internally, it was actually triggered by this library in my `build.gradle` file: ``` implementation "com.github.bigfishcat.android:svg-android:2.0.8" ``` How a library cause this, I do not know. Everything builds fine now though.
apply plugin: 'com.android.application' **apply plugin: 'kotlin-android'** **apply plugin: 'kotlin-android-extensions'** android { ``` compileSdkVersion 26 defaultConfig { applicationId "com.example.admin.myapplication" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" te...
17,361
12,173,856
I'm trying to reimplement python [slice notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is, given a list and a triple `(start, stop, step)` or a part th...
2012/08/29
[ "https://Stackoverflow.com/questions/12173856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989121/" ]
I've written a PHP port based on the C code, optimized for step sizes -1 and 1: ``` function get_indices($length, $step, &$start, &$end, &$size) { if (is_null($start)) { $start = $step < 0 ? $length - 1 : 0; } else { if ($start < 0) { $start += $l...
I can't say there's no bug in the codes, but it had past your test program :) ``` def mySlice(L, start=None, stop=None, step=None): ret = [] le = len(L) if step is None: step = 1 if step > 0: #this situation might be easier if start is None: start = 0 else: if ...
17,362
1,376,016
I was playing around with Python's subprocess module, trying a few examples but I can't seem to get heredoc statements to work. Here is the trivial example I was playing with: ``` import subprocess a = "A String of Text" p = subprocess.Popen(["cat", "<<DATA\n" + a + "\nDATA"]) ``` I get the following error when I r...
2009/09/03
[ "https://Stackoverflow.com/questions/1376016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124861/" ]
The shell "heredoc" support is a shell feature. `subprocess.Popen` does not run your command through the shell by default, so this syntax certainly won't work. However, since you're using pipes anyway, there isn't any need to use the heredoc support of the shell. Just write your string `a` to the stdin pipe of the pro...
You're passing shell syntax as an arguments to `cat` program. You can try to do it like that: ``` p = subprocess.Popen(["sh", "-c", "cat <<DATA\n" + a + "\nDATA"]) ``` But the concept itself is wrong. You should use Python features instead of calling shell scripts inside your python scripts. And in this particular ...
17,372
30,438,227
I am building an application in python that uses a wrap to a library that performs hardware communication I would like to create some test units and I am pretty new to unit tests, so I would like to mock the communications but I really don't know how to do it quick example: this is the application code using the co...
2015/05/25
[ "https://Stackoverflow.com/questions/30438227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180699/" ]
You can use [`mock`](https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock) framework to this kind of jobs. First of all you use `comm = Comm()` in `MyClass` and that means you have something like `from comm_module import Comm` in `MyClass`'s module. In these cases you need to patch `Comm` referenc...
The trick is not to use global objects like `comm`. If you can, make it so that `comm` gets injected to your class or method by the caller. Then what you do is pass a mocked `comm` when testing and then real one when in production. So either you make a `comm` reference a field in your class (and inject it via a const...
17,377
247,301
Besides the syntactic sugar and expressiveness power what are the differences in runtime efficiency. I mean, plpgsql can be faster than, lets say plpythonu or pljava? Or are they all approximately equals? We are using stored procedures for the task of detecting nearly-duplicates records of people in a moderately sized...
2008/10/29
[ "https://Stackoverflow.com/questions/247301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
plpgsql provides greater type safety I believe, you have to perform explicit casts if you want to perform operations using two different columns of similar type, like varchar and text or int4 and int8. This is important because if you need to have your stored proc use indexes, postgres requires that the types match exa...
Without doing actual testing, I would expect plpgsql to be somewhat more efficient than other languages, because it's small. Having said that, remember that SQL functions are likely to be even faster than plpgsql, if a function is simple enough that you can write it in just SQL.
17,378
14,053,552
I am writing a webapp and I would like to start charging my users. What are the recommended billing platforms for a python/Django webapp? I would like something that keeps track of my users' purchase history, can elegantly handle subscription purchases, a la carte items, coupon codes, and refunds, makes it straightfo...
2012/12/27
[ "https://Stackoverflow.com/questions/14053552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234270/" ]
The **[koalixcrm](https://github.com/scaphilo/koalixcrm)** is perhaps something you could start with. It offers some of your required functionality. Still it is in a prealpha stage but it already provides PDF export for Invoices and Quotes, there is already one included plugin for subscriptions. also try the **[demo]...
It's not really clear why Django Community hasn't come up a with complete billing system or at least a generic one to start working on. There's many packages that can be used for getting an idea how to implement such platform: <https://www.djangopackages.com/grids/g/payment-processing/>
17,381
67,996,181
So in python to call a parent classes function in a child class we use the `super()` method but why do we use the `super()` when we can just call the Parent class function suppose i have a `Class Employee:` and i have another class which inherites from the Employee class `class Programmer(Employee):` to call any functi...
2021/06/16
[ "https://Stackoverflow.com/questions/67996181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15895348/" ]
With `super()` you don't need to define `takeBreath()` in each class inherited from the `Person()` class.
`super()` is a far more general method. Suppose you decide to change your superclass. Maybe you name it `Tom` instead of `Employee`. Now you have to go about and change every mention of your `Employee` call. You can think of `super()` as a "proxy" to get the superclass regardless of what it is. It enables you to write...
17,382
59,475,157
I'm a beginner in python. I'm not able to understand what the problem is? ``` the runtime process for the instance running on port 43421 has unexpectedly quit ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine...
2019/12/25
[ "https://Stackoverflow.com/questions/59475157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277769/" ]
Since the column in the first table is an identity field, you should use [`scope_idenity()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15) immediately after the first INSERT statement to get the result. Then use that result in the subsequent INSERT statements. ...
You can use MAX: ``` DECLARE @id int = (select max(BusinessEntityId) From Person.BusinessEntity) ```
17,384
23,382,499
I'm running a python script that makes modifications in a specific database. I want to run a second script once there is a modification in my database (local server). Is there anyway to do that? Any help would be very appreciated. Thanks!
2014/04/30
[ "https://Stackoverflow.com/questions/23382499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343621/" ]
Thanks for your answers, i found a solution here: <http://crazytechthoughts.blogspot.fr/2011/12/call-external-program-from-mysql.html> A Trigger must be defined to call an external function once the DB Table is modified: ``` DELIMITER $ CREATE TRIGGER Test_Trigger AFTER INSERT ON SFCRoutingTable FOR EACH ROW BEGIN D...
You can use 'Stored Procedures' in your database a lot of RDBMS engines support one or multiple programming languages to do so. AFAIK postgresql support signals to call external process to. Google something like 'Stored Procedures in Python for PostgreSQL' or 'postgresql trigger call external program'
17,387
37,355,375
There is a dict (say `d`). `dict.get(key, None)` returns `None` if `key` doesn't exist in `d`. **How do I get the first value (i.e., `d[key]` is not `None`) from a list of keys (some of them might not exist in `d`)?** This post, [Pythonic way to avoid “if x: return x” statements](https://stackoverflow.com/questions/...
2016/05/20
[ "https://Stackoverflow.com/questions/37355375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3067748/" ]
There's no convenient builtin, but you could implement it easily enough: ``` def getfirst(d, keys): for key in keys: if key in d: return d[key] return None ```
I would use `next` with a comprehension: ``` # build list of keys levels = [ 'level' + str(i) for i in range(3) ] for d in list_dicts: level_key = next(k for k in levels if d.get(k)) level = d[level_key] ```
17,390
828,139
I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python The C code ``` double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; ``` Python so far ``` import ctypes null_ptr = ctypes.c_void_p() pa_stream_pee...
2009/05/06
[ "https://Stackoverflow.com/questions/828139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102018/" ]
My ctypes is rusty, but I believe you want POINTER(c\_float) instead of c\_void\_p. So try this: ``` null_ptr = POINTER(c_float)() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) null_ptr[0] null_ptr[5] # etc ```
You'll also probably want to be passing the null\_ptr using byref, e.g. ``` pa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length)) ```
17,397
4,960,777
The following Python code tries to create an SQLite database and a table, using the command line in Linux: ``` #!/usr/bin/python2.6 import subprocess args = ["sqlite3", "db.sqlite", "'CREATE TABLE my_table(my_column TEXT)'"] print(" ".join(args)) subprocess.call(args) ``` When I ran the code, it created a database...
2011/02/10
[ "https://Stackoverflow.com/questions/4960777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249487/" ]
Drop the `'` in the second argument to `sqlite` (third element of the `args` list). The `subprocess` module does the quoting on its own and ensures, that the arguments gets passed to the executable as one string. It works on the command line, because there, the `'` are necessary to tell the shell, that it should treat ...
Besides the extra quoting that @Dirk mentions before, you can also create the database without spawning a subprocess: ``` import sqlite3 cnx = sqlite3.connect("e:/temp/db.sqlite") cnx.execute("CREATE TABLE my_table(my_column TEXT)") cnx.commit() cnx.close() ```
17,402
51,576,837
I have dataset where one of the column holds total sq.ft value. ``` 1151 1025 2100 - 2850 1075 1760 ``` I would like to split the 2100 - 2850 if the dataframe contains '-' and take its average(mean) as the new value. I am trying achieve this using apply method but running into error when statement containing contai...
2018/07/29
[ "https://Stackoverflow.com/questions/51576837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10148648/" ]
IIUC ``` df.col.str.split('-',expand=True).apply(pd.to_numeric).mean(1) Out[630]: 0 1151.0 1 1025.0 2 2475.0 3 1075.0 4 1760.0 dtype: float64 ```
IIUC, you can `split` by `-` anyway and just `transform` using `np.mean`, once the mean of a single number is just the number itself ``` df.col.str.split('-').transform(lambda s: np.mean([int(x.strip()) for x in s])) 0 1151.0 1 1025.0 2 2475.0 3 1075.0 4 1760.0 ``` Alternatively, you can `sum` and di...
17,403
74,057,953
browser build and python (flask) backend. As far as I understand everything should work, the DOM is identical in both and doesn't change after that, but vue ignores the server-side rendered DOM and generates it from scratch. What surprises me even more is the fact that it does not delete the server's initial rendered D...
2022/10/13
[ "https://Stackoverflow.com/questions/74057953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15810660/" ]
It turned out that the issue for me was formating... It was working: ``` <div id="app">{{ server rendered html }}</div> ``` It was not: ``` <div id="app"> {{ server rendered html}} </div> ```
[This answer](https://stackoverflow.com/a/67978474/8816585) is explaining the use case with a Nuxt configuration but is totally valid for your code too. The issue here being that you probably have: * some hardcoded HTML string * SSR content generated by Vue * client-side hydrated content by Vue All of them can have ...
17,404
48,033,519
``` import pygame as pg, sys from pygame.locals import * import os pg.mixer.pre_init(44100, 16, 2, 4096) pg.init() a = pg.mixer.music.load("./Sounds/ChessDrop2.wav") a.play() ``` The code above is what I have written to test whether sound can be played through pygame. My 'ChessDrop2.wav' file is a 16 bit wav-PCM f...
2017/12/30
[ "https://Stackoverflow.com/questions/48033519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8965922/" ]
this functions doesn't return any object to be used, check the documentation: <https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load> after loading the file you should use ``` pg.mixer.music.play() ```
As @CaMMelo stated `pygame.mixer.music.load(filename)` method doesn't return an object. However, if you are looking for an return object after the load, you may want to try [pygame.mixer.Sound](https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound) . > > pygame.mixer.Sound > > Create a new Sound object ...
17,405
60,754,120
Does anyone know a solution to this? EDIT: This question was closed, because the problem didn't seem clear. So the problem was the error "AttributeError: module 'wx' has no attribute 'adv'", although everything seemed right. And actually, everything was right, the problem was individual to another PC, where "import ...
2020/03/19
[ "https://Stackoverflow.com/questions/60754120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1647509/" ]
try importing this and run this again ``` import wx.adv ```
As @arvind8 points out it is a separate import. At its simplest: ``` import wx import wx.adv app = wx.App() frame = wx.Frame(parent=None, title="Hello, world!") frame.Show() m=wx.adv.NotificationMessage("My message","The text I wish to show") #m.Show(timeout = m.Timeout_Never) m.Show(timeout = m.Timeout_Auto) #m.Sho...
17,406
54,683,892
I have a python project with multiple files and a cmd.py which uses argparse to parse the arguments, in the other files there are critical functions. What I want to do is: I want to make it so that if in the command line I were to put `cmd -p hello.txt` it runs that python file. I was thinking that I could just simpl...
2019/02/14
[ "https://Stackoverflow.com/questions/54683892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585864/" ]
The usual way to do this is to define a set of entry points in `setup.py` and let the packaging infrastructure do the heavy lifting for you. ``` setup( # ... entry_points = { 'console_scripts': ['cmd = cmd:main'], } ) ``` This requires `setuptools`. Here is some documentation for this facility: ...
For one thing I don't recommend installation in `/usr/bin` as that's where system programs go. `/usr/local/bin` or another custom directory added to `$PATH` could be appropriate. As for getting it to run like a typical program, name it `cmd`, wherever you put it, as the extension is not necessary, and add this line to...
17,407
23,021,864
I've added Python's logging module to my code to get away from a galloping mess of print statements and I'm stymied by configuration errors. The error messages aren't very informative. ``` Traceback (most recent call last): File "HDAudioSync.py", line 19, in <module> logging.config.fileConfig('../conf/logging.co...
2014/04/11
[ "https://Stackoverflow.com/questions/23021864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811299/" ]
You can dig into the Python source code to investigate these sorts of problems. Much of the library is implemented in Python and is pretty readable without needing to know the inner details of the interpreter. [hg.python.org](http://hg.python.org/cpython/file/a8f3ca72f703/Lib/logging/config.py) provides a web interface...
### Look for keywords The last two lines of the traceback contain the word `handler` (`handler = ...` and `_install_handlers`). That gives you a starting point to look at the handler definitions in your config file. ### Look for matching values *everywhere* If a function takes 5 arguments, but you've somehow given o...
17,409
65,367,490
I have a python data frame like this ``` ID ID_1 ID_2 ID_3 ID_4 ID_5 ID_1 1.0 20.1 31.0 23.1 31.5 ID_2 3.0 1.0 23.0 90.0 21.5 ID_3. 7.0 70.1 1.0 23.0 31.5 ID_4. 9.0 90.1 43.0 1.0 61.5 ID_5 11.0 10.1 11.0 23.0 1.0 ``` I need to updat...
2020/12/19
[ "https://Stackoverflow.com/questions/65367490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4726029/" ]
Consider `df`: ``` In [1479]: df Out[1479]: ID ID_1 ID_2 ID_3 ID_4 ID_5 ID_6 0 ID_1 1.0 20.1 31.0 23.0 31.5 24.6 1 ID_2 3.0 1.0 23.0 90.0 21.5 24.6 2 ID_3 7.0 70.1 1.0 23.0 31.5 24.6 3 ID_4 9.0 90.1 43.0 1.0 61.5 24.6 4 ID_5 11.0 10.1 11.0 23.0 1.0 24.6 5 ID_6 ...
Let's try broadcasting: ``` df[:] = np.where(df['ID'].values[:,None] == df.columns.values,0, df) ``` Output: ``` ID ID_1 ID_2 ID_3 ID_4 ID_5 0 ID_1 0.0 20.1 31.0 23.1 31.5 1 ID_2 3.0 0.0 23.0 90.0 21.5 2 ID_3 7.0 70.1 0.0 23.0 31.5 3 ID_4 9.0 90.1 43.0 0.0 61.5 4 ID_5 11.0...
17,410
30,982,532
I'm trying to connect to JIRA using a Python wrapper for the Rest interface and I can't get it to work at all. I've read everything I could find so this is my last resort. I've tried a lot of stuff including > > verify=False > > > but nothing has worked so far. The strange thing is that with urllib.request it ...
2015/06/22
[ "https://Stackoverflow.com/questions/30982532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2314427/" ]
The actual enum behavior of instatiating the instance [doesn't have an issue with thread safety](https://stackoverflow.com/a/2531881/1424875). However, you will need to make sure that the instance state itself is thread-safe. The interactions with the fields and methods of `Application` are the risk--using either care...
Singleton ensures you only have one instance of a class per class loader. You only have to take care about concurrency if your singleton has a mutable state. I mean if singleton persist some kind of mutable data. In this case you should use some kind of synchronization-locking mechanishm to prevent concurrent modific...
17,411
45,425,026
--- *tldr:* How is Python set up on a Mac? Is there a ton of senseless copying going on even before I start wrecking it? -------------------------------------------------------------------------------------------------------------------- I am hoping to get some guidance regarding Python system architecture on Mac (pe...
2017/07/31
[ "https://Stackoverflow.com/questions/45425026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619510/" ]
Sadly that's not how Bootstrap works; you get a single row that you can place columns within and you can't float another column underneath others and have it all automatically adjust like your diagram. I would suggest checking out the jQuery plugin called [Masonry](https://masonry.desandro.com/) which does help with ...
[Bootstrap4](https://v4-alpha.getbootstrap.com/) might help with [flexbox](https://v4-alpha.getbootstrap.com/utilities/flexbox/) inbricated. Not too sure this is the best example, it still does require some extra CSS to have it run properly: ```css .container>.d-flex>.col { box-shadow: 0 0 0 3px turquoise; min-...
17,412
23,449,320
How to write something like `!(str.endswith())` in python I mean I want to check if string IS NOT ending with something. My code is ``` if text == text. upper(): and text.endswith("."): ``` But I want to put IS NOT after and writing ``` if text == text. upper(): and not text.endswith("."): ``` or ``` if te...
2014/05/03
[ "https://Stackoverflow.com/questions/23449320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/678855/" ]
You can use `not` ``` if not str.endswith(): ``` your code can be modified to: ``` if text == text.upper() and not text.endswith("."): ```
You can just use the `not()` oporator: ``` not(str.endswith()) ``` EDIT: Like so: ``` if text == text. upper() and not(text.endswith(".")): do stuff ``` or ``` if text == text. upper() and not(text.endswith(".")): do studff ```
17,414
43,148,235
I want python with selenium webdriver to do the following:- 1. Open Facebook 2. Login 3. Click and open the user pane which has the "Logout" option A small arrow opens the user pane I wrote the following script ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdrive...
2017/03/31
[ "https://Stackoverflow.com/questions/43148235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7236897/" ]
How about using macros only instead of using variables and enumerations. ``` //libnameConf.h #define LIBNAME_A // #define LIBNAME_B // Uncomment this line and both comment the above line while changing libs. ``` Then we use several conditional compilation statements like this. ``` //libname.c double coef_arr_a[100]...
Sounds like you need [conditional compilaiton](https://en.wikipedia.org/wiki/Conditional_compilation) in C but the way you're doing it is not correct. Conditional compilation is a concept of the [preprocessor](https://en.wikipedia.org/wiki/Preprocessor) which is run before the compiler. The point of preprocessor is to ...
17,417
3,093,352
Is there a method to pass a [variable number of arguments](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) to a function and have it change those arguments using the `( *args, **keywords )` style of argument passing? I've tried a few things but either see no change or have an error raised by ...
2010/06/22
[ "https://Stackoverflow.com/questions/3093352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178060/" ]
No - Python uses [call by object-sharing](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing), also known as call-by-value. To clarify the terminology: you are not receiving a deep copy of the object, but a copy of the object **reference**. Note: this is not the same as [call-by-reference](http://en.wiki...
The reason ``` args[0] = 4 ``` doesn't work is because, as the error message says, `args` a tuple, which is immutable. So, you'll need it convert it to the mutable object first, for example like this: ``` >>> def foo( *args ): print(args) args = list(args) args[0] = 42 print(args) >>> foo(23) (23,...
17,418
10,621,021
I am a newbie to python,everywhere I read about list methods I see one thing **The slice method returns a "new" list** What is here meant by "new" list,and why is it faster then changing the original list? Does it really matter if python manipulates the original list,I mean I cant use it anyway.
2012/05/16
[ "https://Stackoverflow.com/questions/10621021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1251851/" ]
I hope that this helps explain what it means by making a new list: ``` >>> lista = [1, 2, 3, 4] >>> listb = lista >>> print lista [1, 2, 3, 4] >>> print listb [1, 2, 3, 4] >>> lista[0] = 3 >>> print listb [3, 2, 3, 4] >>> listc = lista[:] >>> print listc [3, 2, 3, 4] >>> lista[0] = 1 >>> print listc [3, 2, 3,...
With lists, you can do both: 1) create a new list (the original is left intact): ``` In [1]: l = [1, 2, 3, 4, 5] In [2]: l[:3] Out[2]: [1, 2, 3] In [3]: l Out[3]: [1, 2, 3, 4, 5] ``` 2) modify the list in-place: ``` In [6]: del l[3:] In [7]: l Out[7]: [1, 2, 3] In [8]: l.append(15) In [9]: l Out[9]: [1, 2, 3,...
17,421
62,833,614
I am working on a project with OpenCV and python but stuck on this small problem. I have end-points' coordinates on many lines stored in a list. Sometimes a case is appearing that from a single point, more than one line is detected. From among these lines, I want to keep the line of shortest length and eliminate all t...
2020/07/10
[ "https://Stackoverflow.com/questions/62833614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11651779/" ]
I still having the same problems ``` @EnableIntegration @Configuration @TestPropertySource(locations="classpath:/msc-test.properties") @Slf4j @RunWith(SpringRunner.class) @ActiveProfiles("test") @ContextConfiguration(classes = MessagingListenerTestConfig.class) @Import(TestChannelBinderConfiguration.class) @SpringBoot...
I think the problem is that you are calling `outputDestination.receive()` two times. First time you are getting the message and when trying to reach it second time it's not there. For me was working this approach: ``` String messagePayload = new String(outputDestination.receive().getPayload()); assertThat(messagePaylo...
17,426
25,572,574
Hello I've installed a local version of pip using ``` python get-pip.py --user ``` After that I can't find the path of pip, so I run: ``` python -m pip install --user Cython ``` Finally I can't import Cython ``` import Cython Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No...
2014/08/29
[ "https://Stackoverflow.com/questions/25572574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486641/" ]
You need to filter each date field individually within the range, like so: ``` WHERE (Date1 >= ISNULL(@DateFrom,'17531231') AND Date1 <= ISNULL(@dateTo,'20991231')) OR (Date2 >= ISNULL(@DateFrom,'1753-12-31') AND Date2 <= ISNULL(@dateTo,'20991231')) OR (Date3 >= ISNULL(@DateFrom,'1753-12-31') AND Dat...
Just for another way to look at it. This solution would also work. It makes the where clause simpler at the expense of an additional block of code and a join. ``` CREATE TABLE #dates (id INT, date1 DATE, date2 DATE, date3 DATE) INSERT INTO #dates VALUES ('1','12/13/1945','11/4/1930',NULL), ('2','9/12/1970','9/13/197...
17,427
26,569,498
I am new to python. I want to store each HTML tag into item of list. ``` from bs4 import BeautifulSoup text = """ <body> <div class="product"> <div class="x">orange</div> <div class="x">apple</div> <p> This is text </p> </div> </body>""" soup = BeautifulSoup(text) y=[] for i in (soup.find_all("di...
2014/10/26
[ "https://Stackoverflow.com/questions/26569498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291434/" ]
Assuming your HTML code looks something like this: ``` <ul class="ulComprar"> <li>Milk</li> <li class="liEspecial">Eggs</li> <li>Bread</li> </ul> ``` Then you could use the following query snippet to show and hide element li.liEspecial: ``` $('.ulComprar').hover( function() { $('.liEspecial', this).hide...
we don't have `display: normal;`. the default `display` for [li](http://www.w3schools.com/tags/tag_li.asp) is `list-item`. try this code: ``` $('.ulComprar').on('mouseenter', function () { $('.liEspecial').css("display", "list-item"); }).on('mouseleave', function () { $('.liEspecial').css("display", "none"); }...
17,430
36,306,938
I want to generate colors that go well with a given `UIColor` (Triadic, Analogues, Complement etc). I have read a lot of posts like [this](https://stackoverflow.com/questions/14095849/calculating-the-analogous-color-with-python/14116553#14116553) and [this](https://stackoverflow.com/questions/180/function-for-creating...
2016/03/30
[ "https://Stackoverflow.com/questions/36306938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133585/" ]
The hue component ranges from 0.0 to 1.0, which corresponds to the angle from 0º to 360º in a color wheel (compare [Wikipedia: HSL and HSV](http://en.wikipedia.org/wiki/HSL_and_HSV)). To "rotate" the hue component by `n` degrees, use: ``` let n = 120 // 120 degrees as an example hue = fmod(hue + CGFloat(n)/360.0, 1.0...
> > **In SwiftUI you can do by using apple documentation code** > > > ``` struct HueRotation: View { var body: some View { HStack { ForEach(0..<6) { Rectangle() .fill(.linearGradient( colors: [.blue, .red, .green], startPoint: .top, en...
17,431
70,298,164
I have this python coded statement: ``` is_headless = ["--headless"] if sys.argv[0].find('console.py') != -1 else [""] ``` 1. In what way does the blank between `["--headless"]` and `if` control the code line? 2. How and would `"--headless"` ever be an element in the `is_headless` variable? 3. Using the variable nam...
2021/12/09
[ "https://Stackoverflow.com/questions/70298164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17640238/" ]
There is not much to it. Just increment the pointer. → `p++` ``` void printArray(int *s_ptr, int *e_ptr) { for (int *p = s_ptr; p <= e_ptr; p++) { printf("%d\n", *p); } } ```
> > *How can I can print the whole array using only the addreses of the first element and the last element?* > > > To start with, couple of things about array that you should know (if not aware of): 1. An array is a collection of elements of the same type placed in **contiguous memory locations**. 2. An array nam...
17,432
12,193,803
On Windows 7, I am using the command line ``` python -m SimpleHTTPServer 8888 ``` to invoke a simple web server to serve files from a directory, for development. The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available. Is there a way to...
2012/08/30
[ "https://Stackoverflow.com/questions/12193803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/605337/" ]
I suggest that you press Ctrl+F5 when refreshing the browser. Just ran into [this](https://gist.github.com/3300372), it can just might be the thing you are looking for (it's in ruby, by the way)
Maybe it's the browser caching your files not the SimpleHTTPServer. Try deactivating the browser cache first.
17,433
10,361,714
I mostly spend time on Python/Django and Objective-C/CocoaTouch and js/jQuery in the course of my daily work. My editor of choice is `vim` for Python/Django and js/jQuery and `xcode` for Objective-C/CocoaTouch. One of the bottlenecks on my development speed is the pace at which I read existing code, particularly open...
2012/04/28
[ "https://Stackoverflow.com/questions/10361714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/482506/" ]
Tags are a very good start indeed. (There's too much stuff all over the place on it, so I'll just provide you with one extra keyword to search with: ctags.) In Vim, it ends up (in the basic case) with `Ctrl+]` to go to a class/function definition and `Ctrl+T` to return.
I've been using [exuberant ctags](http://ctags.sourceforge.net/) with [taglist](http://www.vim.org/scripts/script.php?script_id=273) for vim. Use `ctrl``]` to jump to class definition in the current window, `ctrl``w``]` to jump to the definition in a split window. You can install exuberant ctags via homebrew: ``` br...
17,442
31,846,508
I'm new in python and I'm trying to dynamically create new instances in a class. So let me give you an example, if I have a class like this: ``` class Person(object): def __init__(self, name, age, job): self.name = name self.age = age self.job = job ``` As far as I know, for each new inst...
2015/08/06
[ "https://Stackoverflow.com/questions/31846508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5196412/" ]
Just iterate over the dictionary using a for loop. ``` people = [] for id in persons_database: info = persons_database[id] people.append(Person(info[0], info[1], info[2])) ``` Then the List `people` will have `Person` objects with the data from your persons\_database dictionary If you need to get the Person...
Sure, a simple [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) should do the trick: ``` people = [Person(*persons_database[pid]) for pid in persons_database] ``` This just loops through each key (id) in the person database and creates a person instance by passing thro...
17,444
3,580,520
To add gtk-2.0 to my virtualenv I did the following: ``` $ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv $ cd myvirtualenv $ source bin/activate $ cd lib/python2.6/ $ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ ``` [Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/quest...
2010/08/27
[ "https://Stackoverflow.com/questions/3580520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145117/" ]
`sudo python` imports it just fine because that interpreter isn't using your virtual environment. So don't do that. You only linked in one of the necessary items. Do the others mentioned in the answer to the question you linked as well. (The pygtk.pth file is of particular importance, since it tells python to actuall...
This works for me (Ubuntu 11.10): once you activate your virtualenv directory make sure 'dist-packages' exists: ``` mkdir -p lib/python2.7/dist-packages/ ``` Then, make links: For GTK2: ``` ln -s /usr/lib/python2.7/dist-packages/glib/ lib/python2.7/dist-packages/ ln -s /usr/lib/python2.7/dist-packages/gobject/ li...
17,445
10,350,765
Here is my basic problem: I have a Python file with an import of ``` from math import sin,cos,sqrt ``` I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python. Now enter Cython. In my Python file, the trig functions get...
2012/04/27
[ "https://Stackoverflow.com/questions/10350765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360263/" ]
I'm not a Cython expert, but AFAIK, all you could do is write a Cython wrapper around `sin` and call that. I can't imagine that's really going to be faster than `math.sin`, though, since it's still using Python calling semantics -- the overhead is in all the Python stuff to call the function, not the actual trig calcul...
I may have misunderstood your problem, but the [Cython documentation on interfacing with external C code](http://docs.cython.org/src/userguide/external_C_code.html#resolving-naming-conflicts-c-name-specifications) seems to suggest the following syntax: ``` cdef extern from "math.h": double c_sin "sin" (double) ``...
17,454
2,844,365
im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window) ``` from qt import * from dialogselectkernelfile import * from formcopyextract import * import sys...
2010/05/16
[ "https://Stackoverflow.com/questions/2844365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995052/" ]
As Ryan Bigg suggested `simple_format` is the best tool for the job: it's 'l safe' and much neater than other solutions. so for @var: ``` <%= simple_format(@var) %> ``` If you need to sanitize the text to get rid of HTML tags, you should do this *before* passing it to `simple_format` <http://api.rubyonrails.org/cl...
The best way I can figure to go about this is using the sanitize method to strip all but the BR tag we want. Assume that we have `@var` with the content `"some\ntext"`: Trying `<%= @var.gsub(/\n/, '<br />') %>` doesn't work. Trying `<%= h @var.gsub(/\n/, '<br />').html_safe %>` doesn't work and is unsafe. Trying `<...
17,459
56,674,550
I want to split a text that contains numbers ``` text = "bla bla 1 bla bla bla 142 bla bla (234.22)" ``` and want to add a `'\n'` before and after each number. ``` > "bla bla \n1\n bla bla bla \n142\n bla bla (234.22)" ``` The following function gives me the sub strings, but it throws away the pattern, i.e. the...
2019/06/19
[ "https://Stackoverflow.com/questions/56674550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5452008/" ]
Use ``` s = re.sub(r' \d+ ', '\n\\g<0>\n', s) ``` See the [regex demo](https://regex101.com/r/081OkV/1). To replace only standalone numbers as whole words use ``` s = re.sub(r'\b\d+\b', '\n\\g<0>\n', s) ``` If you want to match the numbers enclosed with whitespaces only use either of ``` re.sub(r'(?<!\S)\d+(?!\...
Try this code!! This might help! ``` import re text = "bla bla 1 bla bla bla 142 bla bla" replaced = re.sub('([0-9]+)', r'\n\1\n',text) print(replaced) Output: 'bla bla \n1\n bla bla bla \n142\n bla bla' ```
17,462
63,610,350
I have int in python that I want to reverse `x = int(1234567899)` I want to result will be `3674379849` explain : = `1234567899` = `0x499602DB` and `3674379849` = `0xDB029649` How to do that in python ?
2020/08/27
[ "https://Stackoverflow.com/questions/63610350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13767076/" ]
``` >>> import struct >>> struct.unpack('>I', struct.pack('<I', 1234567899))[0] 3674379849 >>> ``` This converts the integer to a 4-byte array (`I`), then decodes it in reverse order (`>` vs `<`). Documentation: [`struct`](https://docs.python.org/3/library/struct.html)
If you just want the result, use [sabiks approach](https://stackoverflow.com/a/63610471/7505395) - if you want the intermediate steps for bragging rights, you would need to * create the hex of the number (#1) and maybe add a leading 0 for correctness * reverse it 2-byte-wise (#2) * create an integer again (#3) f.e. l...
17,463
71,632,619
I am new to Python. I have a XML file("topstocks.xml") with some elements and attributes which looks like as below. I was trying to pass an attribute "id" as a function parameter, so that I can dynamically fetch the data. ``` <properties> <property id="H01" cost="106000" state="NM" percentage="0.12">2925.6</proper...
2022/03/26
[ "https://Stackoverflow.com/questions/71632619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14810351/" ]
You cannot combine make constructs, like `ifeq`, with shell constructs, like setting a shell variable. Makefiles are not scripts, like a shell script or a python script or whatever. Make works in two distinct phases: first ALL the makefiles are parsed, all make variables are assigned, all `ifeq` statements are resolve...
Sigh - so the answer after MANY permutations is the tab mistake: ``` a = MISMATCH= all: ifeq ($(a),) MISMATCH=yes endif ifdef MISMATCH $(info fooz) else $(info bark) endif ``` (make files are so frustrating)
17,464
66,109,204
I have a file called `setup.sh` which basically has this ``` python3 -m venv env source ./env/bin/activate # other setup stuff ``` When I run `sh setup.sh`, the environment folder `env` is created, and it will run my `#other setup stuff`, but it will skip over `source ./env/bin/activate`, which puts me in my enviro...
2021/02/08
[ "https://Stackoverflow.com/questions/66109204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14745324/" ]
### global variable and change listener You can add an event listener listening for changes for the checkbox. You can use a global variable which gets track of the unchecked boxes. ``` let countUnchecked = 0; ``` Initially its *value is 0* when you add a new checkbox its value *increases by one*. When the box gets ...
You can add an event listener just for the `<ul>` element and not for each `type='checkbox'` element ex: ```js document.querySelector("#todo-list").onchange = function() { document.querySelector("#unchecked-count").textContent = this.querySelectorAll("[type=checkbox]:not(:checked)").length; } ``` so here on each c...
17,465
22,146,205
### Context: I have been playing around with python's wrapper for opencv2. I wanted to play with a few ideas and use a wide angle camera similar to 'rear view' cameras in cars. I got one from a scrapped crash car (its got 4 wires) I took an educated guess from the wires color codding, connect it up so that I power the...
2014/03/03
[ "https://Stackoverflow.com/questions/22146205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3380927/" ]
Ok , so after deeper investigation the initial suspicion was confirmed i.e. because the NTSC dongle is not handled as an imaging device (it's seen as a Video Controller , so similar to an emulation of a TV Tuner card ) it means that although we are able to call cv2.VideoCapture with cam\_index=0 the video channel itsel...
It's a few months late, but might be useful. I was working on a Windows computer and had installed the drivers that came with the device, I tried the same code as your question with an Ezcap from Somagic and got the same error. Since "frame is None," I decided to try an if statement around it - in case it was an initia...
17,466
10,002,937
I have some pom files in my project with the following structure ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactId>xparent</...
2012/04/03
[ "https://Stackoverflow.com/questions/10002937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164061/" ]
You could try: ``` sed -e '/<dependencies>/,/<\/dependencies>/ !{ s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>! }' MY_FILE ``` The `/<dependencies>/,/<\/dependencies>/` says "find all lines between `<dependencies>` and `</dependencies>`". The `!` after that says "perform the follo...
``` nawk '{ a=$0; getline; if($0!~/depend/ && a!~/version/) {gsub(/2.0.0/,"1.0.0",$0);print a"\n"$0} else print a"\n"$0 }' file3 ``` Below is the test: ``` pearl.302> cat file3 <parent> <aritifactID> </artifactID> <groupID> </groupID> <version>2.0.0</version> ...
17,469
10,211,188
I am using python2.7 and lxml. My code is as below ``` import urllib from lxml import html def get_value(el): return get_text(el, 'value') or el.text_content() response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Frisco/DavidMcDavidHondaofFrisco/fullsales-504210667.html').read() dom = html.fromstr...
2012/04/18
[ "https://Stackoverflow.com/questions/10211188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/952787/" ]
Your except clause only handles exceptions of the IndexError type. The problem was a UnicodeDecodeError, which is not an IndexError - so the exception is not handled by that except clause. It's also not clear what 'get\_value' does, and that may well be where the actual problem is arising.
1. * skip chars on Error, or decode it correctly to unicode. 2. * you only catch IndexError, not UnicodeDecodeError
17,474
19,637,346
I have python project that is already built based on Scons. I am trying to use Eclipse IDE and Pydev to fix some bugs in the source code. I have installed Eclispe Sconsolidator plugin. My project is like below Project A all source codes including Sconscript file which defines all the tager, environmet etc. Eclipse...
2013/10/28
[ "https://Stackoverflow.com/questions/19637346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1845278/" ]
**Gateway Pattern** > > A gateway encapsulates the semantic gap between the object-oriented > domain layer and the relation-oriented persistence layer. > > > Definition taken from [here](http://www.cs.sjsu.edu/~pearce/modules/patterns/enterprise/persistence/gateway.htm). The Gateway in your example is also ca...
Most of the Design patterns explanations become confusing at some time or other because originally it was named and explained by someone but in due course of time several other similar patterns come into existence which have similar usage and explanation but very little difference. This subtle difference then becomes a...
17,479
35,601,754
I want to encrypt a string in python. Every character in the char is mapped to some other character in the secret key. For example `'a'` is mapped to `'D'`, 'b' is mapped to `'d'`, `'c'` is mapped to `'1'` and so forth as shown below: ``` char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" secre...
2016/02/24
[ "https://Stackoverflow.com/questions/35601754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5948577/" ]
**As for replacing multiple characters in a string** You can use [`str.maketrans`](https://docs.python.org/3.5/library/stdtypes.html#str.maketrans) and [`str.translate`](https://docs.python.org/3.5/library/stdtypes.html#str.translate): ``` >>> char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" >>...
Ok, I am making two assumptions here. 1. I think the output you expect is wrong, for instance `L` should be mapped to `0`, not to `o`, right? 2. I am assuming you want to ignore whitespace, since it is not included in your mapping. So then the code would be: ``` to_encrypt = "Lets meet at the usual place at 9 am" ch...
17,482
15,750,681
I'm writing a simple game in python(2.7) in pygame. In this game, I have to store 2D coordinates. The number of these items will start from 0 and increase by 2 in each step. They will increase up to ~6000. In each step I have to check whether 9 specific coordinates are among them, or not. I've tried to store them simpl...
2013/04/01
[ "https://Stackoverflow.com/questions/15750681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2049320/" ]
Maintain a [set](http://docs.python.org/3.3/tutorial/datastructures.html#sets) alongside your list, or replacing the list entirely if you have no other use for it. Membership checking and adding are [O(1) on average](http://wiki.python.org/moin/TimeComplexity) for sets, so your overall algorithm will be O(N) compared t...
If I understand correctly, you're adding elements to `myList`, but never removing them. You're then testing every element of `valuesToCheck` for memebership in `myList`. If that's the case, you could boost performance by converting myList to a set instead of a list. Testing for membership in a list is O(n), while test...
17,483
37,866,313
I did `ls -l /usr/bin/python` I got [![enter image description here](https://i.stack.imgur.com/wvA2p.png)](https://i.stack.imgur.com/wvA2p.png) How can I fix that red symbolic link ?
2016/06/16
[ "https://Stackoverflow.com/questions/37866313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4480164/" ]
`ls -l /usr/bin/python` will only show the symbolic link. Use `ls -l /usr/bin/ | grep python2.7` to see if `python2.7` is in the directory. The output should be something like this: ``` lrwxrwxrwx 1 root root 9 Jun 3 16:39 python -> python2.7 lrwxrwxrwx 1 root root 9 Jun 3 16:39 python2 -> pyth...
You can enter ``` $which python ``` to see where your Python path is. You can then use ``` $ln -s /thepathfromabove/python2.7 python ```
17,484
66,406,182
I'm not the best with python and am trying to cipher shift text entered by the user. The way this cipher should work is disregarding symbols, numbers, etc. It also converts full stops to X's and must all be upper case. I currently have the code for that but am unsure as to how to take that converted text and shift it b...
2021/02/28
[ "https://Stackoverflow.com/questions/66406182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15299466/" ]
You can use ord()/chr() as suggested by @Girish Srivatsa: ``` alphabet_len = ord('Z') - ord('A') + 1 new_letter = chr((ord(letter.upper()) - ord('A') + shift) % alphabet_len + ord('A')) ``` But it might be cleaner if you just create a variable that holds your alphabet: ``` import string alphabet = "".join(list(stri...
If you want it to be formatted even more correctly, following all your rules but formatting in capitals and lowercase too. This shifts the dictionary, and runs if loops. I know you asked for all letters to be capitals, but this improves the code a little. Output of Code: ``` Do you want to... 1. Encode, or 2. Decode?...
17,485
66,894,868
My results is only empty loop logs. if i put manual in terminal this line command : ``` python3 -m PyInstaller --onefile --name SOCIAL_NETWORK_TEST --distpath packages/projectTest --workpath .cache/ app.py ``` then pack works fine. Any suggestion. ``` bashCommand = "python3 -m PyInstaller --onefile --name...
2021/03/31
[ "https://Stackoverflow.com/questions/66894868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513187/" ]
It seems you're running server and client in the same directory, and the server truncates the file before the client gets to read from it.
it works pefect for me with hello world but if you want to send a binary file maybe you can try base 64
17,486
21,940,911
I'm trying to apply a ripple effect to an image in python. I found Pillow's im.transform(im.size, Image.MESH,.... is it possible? Maybe I have to load the image with numpy and apply the algorithm. I also found this: <http://www.pygame.org/project-Water+Ripples-1239-.html> ![ripple](https://i.stack.imgur.com/iIWa0.png...
2014/02/21
[ "https://Stackoverflow.com/questions/21940911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1210984/" ]
You could use `np.roll` to rotate each row or column according to some sine function. ``` from scipy.misc import lena import numpy as np import matplotlib.pyplot as plt img = lena() A = img.shape[0] / 3.0 w = 2.0 / img.shape[1] shift = lambda x: A * np.sin(2.0*np.pi*x * w) for i in range(img.shape[0]): img[:,...
Why don't you try something like: ``` # import scipy # import numpy as np for x in range(cols): column = im[:,x] y = np.floor(sin(x)*10)+10 kernel = np.zeros((20,1)) kernel[y] = 1 scipy.ndimage.filters.convolve(col,kernel,'nearest') ``` I threw this together just right now, so you'll need to twea...
17,487
64,553,669
Does anyone know why I get an indentation error even though it (should) be correct? ``` while not stop: try: response += sock.recv(buffer_size) if header not in response: print("error in message format") return # this is where I get the error except socket.timeout: ...
2020/10/27
[ "https://Stackoverflow.com/questions/64553669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12781947/" ]
If you want to delete the command executing message, like `prefix test_welcome`, you can use `await ctx.message.delete()`.
You can use `await ctx.message.delete`, either way, i recommend you to read the [documentation](https://discordpy.readthedocs.io/en/latest/).
17,490
17,610,811
I want to make crontab where script occurs at different minutes for each hour like this `35 1,8,12,15,31 16,18,21 * * 0,1,2,3,4,5,6 python backup.py` I want script to run at `16hour and 31 minutes` but it is giving me error bad hour i want the cron occur at `1:35am` , then `16:31`, then `21:45`
2013/07/12
[ "https://Stackoverflow.com/questions/17610811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1667349/" ]
As there is not a pattern that can match the three times, it is not possible to schedule that just with one crontab expression. You will have to use three: ``` 45 21 * * * python backup.py 31 16 * * * python backup.py 35 1 * * * python backup.py ``` Note also that `python backup.py` will probably not work. You have ...
If the system which you are on has systemd, You can look into systemd timers(<https://www.freedesktop.org/software/systemd/man/systemd.time.html>). Then you might be able to achieve the randomness using the RandomizedDelaySec setting and an OnCalendar setting which will schedule the service to run every hour or interva...
17,491
21,192,133
Let's say I have a program that uses a .txt file to store data it needs to operate. Because it's a very large amount of data (just go with it) in the text file I was to use a generator rather than an iterator to go through the data in it so that my program leaves as much space as possible. Let's just say (I know this i...
2014/01/17
[ "https://Stackoverflow.com/questions/21192133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2945577/" ]
You can just iterate over the file handle directly, which will then iterate over it line-by-line: ``` for line in file: if username == line.strip(): validusername = True break ``` Other than that, you can’t really tell how many lines a file has without looking at it completely. You do know how big ...
If you want number of lines in a file so badly, why don't you use `len` ``` with open("filename") as f: num = len(f.readlines()) ```
17,492
29,191,405
I'm a little confused about when I need to explicitly copy an object in Python in order to make changes without altering the original. The [Python doc page](https://docs.python.org/3.4/library/copy.html) doesn't have too much detail, and simply says that "assignment statements do not create copies". Example 1: ``` >>...
2015/03/22
[ "https://Stackoverflow.com/questions/29191405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2856558/" ]
For starters, `(?<!...)` is **PCRE** in which the `perl = TRUE` parameter needs to be enabled. The trick is to use lookahead here instead of lookbehind and add [**word boundaries**](http://www.rexegg.com/regex-boundaries.html#wordboundary) to force the regular expression engine to match whole words. Also, you broadly...
You could try the below the PCRE regex ``` > gsub('\\bone\\b(*SKIP)(*F)|([A-Za-z]+)', "'\\1'", text, perl=TRUE) [1] "one 'two' 'three' 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one" ``` `\\bone\\b` matches the text `one` and the following `(*SKIP)(*F)` makes the match to skip and then fail. Now it...
17,495
68,199,583
As you can see [here](https://i.stack.imgur.com/knIlJ.png), after I attempt to train my model in this cell, the asterisk disappears and the brackets are blank instead of containing a number. Do you know why this is happening, and how I can fix it? I'm running python 3.7 and TensorFlow 2.5.0.
2021/06/30
[ "https://Stackoverflow.com/questions/68199583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13004323/" ]
Unfortunately, that is indeed an **issue of Eclipse 2021-06 (4.20)** that happens inside conditions and loops when there is trailing code not separated by a semicolon `;` ([similar but not the same as in this question](https://stackoverflow.com/q/68258236/6505250)). Example: ``` class Sample { void sample(String ...
Could it be the same as [here](https://stackoverflow.com/a/68265945/6167720)? (would have added comment, but too little rep)
17,498
37,422,530
Working my way through a beginners Python book and there's two fairly simple things I don't understand, and was hoping someone here might be able to help. The example in the book uses regular expressions to take in email addresses and phone numbers from a clipboard and output them to the console. The code looks like ...
2016/05/24
[ "https://Stackoverflow.com/questions/37422530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5195054/" ]
every opening left `(` marks the beginning of a capture group, and you can nest them: ``` ( #[1] around whole pattern (\d{3}|\(\d{3}\))? #[2] area code (\s|-|\.)? #[3] separator (\d{3}) #[4] first 3 digits (\s|-|\.) ...
``` ( #[1] around whole pattern (\d{3}|\(\d{3}\))? #[2] area code (\s|-|\.)? #[3] separator (\d{3}) #[4] first 3 digits (\s|-|\.) #[5] separator (\d{4}) #[6] last 4 digits (\s*(ext|x|ext...
17,499
14,074,149
I'm having a bit of difficulty figuring out what my next steps should be. I am using tastypie to create an API for my web application. From another application, specifically ifbyphone.com, I am receiving a POST with no headers that looks something like this: ``` post data:http://myapp.com/api/ callerid=1&someid=2&n...
2012/12/28
[ "https://Stackoverflow.com/questions/14074149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170352/" ]
This worked as expected when I edited my resource model to actually use the serializer class I created. This was not clear in the documentation. ``` class urlencodeSerializer(Serializer): formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencode'] content_types = { 'json': 'application/js...
I would add a modification to the from\_urlencode mentioned in Brandon Bertelsen's post to work better with international characters: ``` def from_urlencode(self, data, options=None): """ handles basic formencoded url posts """ qs = {} for k, v in urlparse.parse_qs(data).iteritems(): value = v if l...
17,501
65,934,494
I have three boolean arrays: shift\_list, shift\_assignment, work。 shift\_list:rows represent shift, columns represent time. shift\_assignment:rows represent employee, columns represent shifts work: rows represent employee, columns represent time. **I want to change the value in work by changing the value in shi...
2021/01/28
[ "https://Stackoverflow.com/questions/65934494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13863269/" ]
thank to @Laurent Perron! ``` from ortools.sat.python import cp_model model = cp_model.CpModel() solver = cp_model.CpSolver() shift_list=[[1,1,1,0,0,0,0], [0,1,1,1,0,0,0], [0,0,1,1,1,0,0], [0,0,0,1,1,1,0], [0,0,0,0,1,1,1]] num_emp = 5 num_shift=5 num_time = 7 work={} ...
Basically you need a set of implications. looking only at the first worker: work = [w0, w1, w2, w3, w4, w5, w6] shift = [s0, s1, s2, s3, s4] ``` shift_list=[[1,1,1,0,0,0,0], [0,1,1,1,0,0,0], [0,0,1,1,1,0,0], [0,0,0,1,1,1,0], [0,0,0,0,1,1,1]] ``` so ``` w0 <=> s0 w1...
17,502
30,893,843
I've the same issue as asked by the OP in [How to import or include data structures (e.g. a dict) into a Python file from a separate file](https://stackoverflow.com/questions/2132985/how-to-import-or-include-data-structures-e-g-a-dict-into-a-python-file-from-a). However for some reason i'm unable to get it working. My...
2015/06/17
[ "https://Stackoverflow.com/questions/30893843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3149936/" ]
There are two ways you can access variable `TMP_DATA_FILE` in file `file1.py`: ``` import file1 var = 'a' print(file1.TMP_DATA_FILE[var]) ``` or: ``` from file1 import TMP_DATA_FILE var = 'a' print(TMP_DATA_FILE[var]) ``` `file1.py` is in a directory contained in the python search path, or in the same directory a...
You calling it the wrong way. It should be like this : ``` print file1.TMP_DATA_FILE[var] ```
17,503
60,992,072
I have a mini-program that can read text files and turn simple phrases into python code, it has Lexer, Parser, everything, I managed to make it play sound using "winsound" but for some reason, it plays the sound as long as the function does not return, this specific part in the code looks like this: ``` wins...
2020/04/02
[ "https://Stackoverflow.com/questions/60992072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12420682/" ]
Add `update` to your `ChangeNotifierProxyProvider` and change `build` to `create`. ``` ChangeNotifierProxyProvider<MyModel, MyChangeNotifier>( create: (_) => MyChangeNotifier(), update: (_, myModel, myNotifier) => myNotifier ..update(myModel), child: ... ); ``` See: <https://github.com/rrousselGit/provide...
You can use it like this: ``` ListView.builder( physics: NeverScrollableScrollPhysics(), scrollDirection: Axis.vertical, itemCount: rrr.length, itemBuilder: (ctx, index) => ChangeNotifierProvider.value( value: rrr[index], c...
17,508
16,903,936
How can I change the location of the .vim folder and the .vimrc file so that I can use two (or more) independent versions of vim? Is there a way to configure that while compiling vim from source? (maybe an entry in the feature.h?) Why do I want to do such a thing?: I have to work on project that use python2 as well as...
2013/06/03
[ "https://Stackoverflow.com/questions/16903936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2344834/" ]
You can influence which `~/.vimrc` is used via the `-u vimrc-file` command-line argument. Since this is the first initialization, you can then influence from where plugins are loaded (i.e. the `.vim` location) by modifying `'runtimepath'` in there. Note that for editing Python files of different versions, those settin...
I think the easiest solution would be just to let pathogen handle your runtimepath for you. `pathogen#infect()` can take paths that specify different directories that you can use for your bundle directory. So if your `.vim` directory would look like this ``` .vim/ autoload/ pathogen.vim bundle_pytho...
17,509
16,130,549
I've got an internet site running on tornado, with video features (convert, cut, merge). The video traitement is quite long, so i want to move it to another python process, and keep the tornado process as light as possible. I use the mongo db for commun db functionalities, synchronously as the db will stay light.
2013/04/21
[ "https://Stackoverflow.com/questions/16130549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538095/" ]
There are several options: * [jQuery UI](http://jqueryui.com/) * [YUI](http://yuilibrary.com/) * [ninjaui](http://ninjaui.com/)
Use [kendo UI](http://www.kendoui.com/) Comprehensive HTML5/JavaScript framework for modern web and mobile app development Kendo UI is everything professional developers need to build HTML5 sites and mobile apps. Today, productivity of an average HTML/jQuery developer is hampered by assembling a Frankenstein framewo...
17,512
38,888,714
What is the python syntax to insert a line break after every occurrence of character "X" ? This below gave me a list object which has no split attribute error ``` for myItem in myList.split('X'): myString = myString.join(myItem.replace('X','X\n')) ```
2016/08/11
[ "https://Stackoverflow.com/questions/38888714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6284097/" ]
**Python 3.X** ``` myString.translate({ord('X'):'X\n'}) ``` `translate()` allows a dict, so, you can replace more than one different character at time. Why `translate()` over `replace()` ? Check [translate vs replace](https://stackoverflow.com/questions/31143290/python-str-translate-vs-str-replace) **Python 2.7**...
A list has no `split` method (as the error says). Assuming `myList` is a list of strings and you want to replace `'X'` with `'X\n'` in each once of them, you can use list comprehension: ``` new_list = [string.replace('X', 'X\n') for string in myList] ```
17,513
72,432,540
as you see "python --version show python3.10.4 but the interpreter show python 3.7.3 [![enter image description here](https://i.stack.imgur.com/RUqlc.png)](https://i.stack.imgur.com/RUqlc.png) how can i change the envirnment in vscode
2022/05/30
[ "https://Stackoverflow.com/questions/72432540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16776924/" ]
If you click on the interpreter version being used by VSCode, you should be able to select different versions across your device. [![Interpreter version](https://i.stack.imgur.com/6tWBe.png)](https://i.stack.imgur.com/6tWBe.png)
Selecting the interpreter in VSCode: <https://code.visualstudio.com/docs/python/environments#_work-with-python-interpreters> To run `streamlit` in `vscode`: Open the `launch.json` file of your project. Copy the following: ``` { "configurations": [ { "name": "Python:Streamlit", "t...
17,522
70,971,382
I want to compare two files and display the differences and the missing records in both files. Based on suggestions on this forum, I found awk is the fastest way to do it. Comparison is to be done based on composite key - match\_key and issuer\_grid\_id **Code:** ``` BEGIN { FS="[= ]" } { match(" "$0,/ match_key...
2022/02/03
[ "https://Stackoverflow.com/questions/70971382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17742463/" ]
Just tweak the setting of `key` at the top to use whatever set of fields you want, and the printing of the mismatch message to be `from key ... key` instead of `from line ... FNR`: ``` $ cat tst.awk BEGIN { FS="[= ]" } { match(" "$0,/ issuer_grid_id="[^"]+"/) key = substr($0,RSTART,RLENGTH) match(" "$0,/ m...
You can use ruby sets: ``` $ cat tst.rb def f2h(fn) data={} File.open(fn){|fh| fh. each_line{|line| h=line.scan(/(\w+)="([^"]+)"/).to_h k=h.slice("issuer_grid_id", "match_key"). map{|k,v| "#{k}=#{v}"}.join(", ") data[k]=h} } data end f1=f2h(ARGV[0]) f2=f2h(...
17,524
72,337,348
I would like to get all text separated by double quotes and commas using python Beautifulsoup. The sample has no class or ids. Could use the div with "Information:" for parent like this: ``` try: test_var = soup.find(text='Information:').find_next('ul').find_next('li') for ...
2022/05/22
[ "https://Stackoverflow.com/questions/72337348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615887/" ]
Just use the [:not](https://api.jquery.com/not-selector/) selector like this: ```js $('.one:not([data-id="two"])').on('click', function() { $('.A').show(); }); $("[data-id='two'].one").on('click', function() { $('.B').show(); }); ``` ```css .one {width: 50px;margin: 10px;padding: 10px 0;text-align: center;outline...
Change it to accept one or the other when any `$('.one')` is clicked: ``` $('.one').on('click', function() { if ($(this).data('id')) { $('.B').show(); } else { $('.A').show(); } }); ``` ```js if ($(this).data('id')) {... // if the `data-id` has a value ex. "2", then it is true ``` ```js $('.one').on(...
17,525
67,018,079
I have probem with this code , why ? the code : ``` import cv2 import numpy as np from PIL import Image import os import numpy as np import cv2 import os import h5py import dlib from imutils import face_utils from keras.models import load_model import sys from keras.models import Sequential from keras.layers import C...
2021/04/09
[ "https://Stackoverflow.com/questions/67018079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15558831/" ]
**Keras** is now fully intregrated into **Tensorflow**. So, importing only **Keras** causes error. It should be imported as: ``` from tensorflow.keras.utils import to_categorical ``` **Avoid** importing as: ``` from keras.utils import to_categorical ``` It is safe to use `from tensorflow.keras.` instead of `from...
First thing is you can install this `keras.utils` with ``` $!pip install keras.utils ``` or another simple method just import `to_categorical` module as ``` $ tensorflow.keras.utils import to_categorical ``` because keras comes under tensorflow package
17,528
4,424,004
I'm new with python programming and GUI. I search on internet about GUI programming and see that there are a lot of ways to do this. I see that easiest way for GUI in python might be tkinter(which is included in Python, and it's just GUI library not GUI builder)? I also read a lot about GLADE+PyGTK(and XML format), wha...
2010/12/12
[ "https://Stackoverflow.com/questions/4424004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/530877/" ]
``` bool perfectNumber(number); ``` This does not call the `perfectNumber` function; it declares a local variable named `perfectNumber` of type `bool` and initializes it with the value of `number` converted to type `bool`. In order to call the `perfectNumber` function, you need to use something along the lines of: ...
``` void primenum(long double x) { bool prime = true; int number2; number2 = (int) floor(sqrt(x));// Calculates the square-root of 'x' for (int i = 1; i <= x; i++) { for (int j = 2; j <= number2; j++) { if (i != j && i % j == 0) { prime = false; brea...
17,533
66,413,002
I'm attempting to translate the following curl request to something that will run in django. ``` curl -X POST https://api.lemlist.com/api/hooks --data '{"targetUrl":"https://example.com/lemlist-hook"}' --header "Content-Type: application/json" --user ":1234567980abcedf" ``` I've run this in git bash and it returns t...
2021/02/28
[ "https://Stackoverflow.com/questions/66413002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7609684/" ]
One way you can do this at the *word* level is: ``` select t.* from t cross apply (select count(*) as cnt from string_split(t.text, ' ') s1 cross join string_split(@sentence, ' ') s2 on s1.value = s2.value ) ss order by ss.cnt desc; ``` Notes: * This only looks for exact word m...
There's a lot of way two select item. For example: ``` SELECT 'I want to buy a ' + A.BrandName + ' cellphone and the model should be ' + A.ModelName FROM ( SELECT SUBSTRING(TEXT, 1, LEN('sumsung')) AS BrandName , SUBSTRING(TEXT, LEN(SUBSTRING(TEXT, 1, LEN('sumsung')))+1, LEN(TEXT)) AS ModelName FROM T...
17,538
66,755,583
I've tried all the installing methods in geopandas' [documentation](https://geopandas.org/getting_started/install.html) and nothing works. `conda install geopandas` gives ``` UnsatisfiableError: The following specifications were found to be incompatible with each other: Output in format: Requested package -> Availab...
2021/03/23
[ "https://Stackoverflow.com/questions/66755583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13083530/" ]
@duckboycool and @Ken Y-N are right, downgrading to Python 3.7 did the trick! Downgrading with conda `conda install python=3.7` and then `conda install geopandas`
You need to create an environment initially, Then inside the new environment try to install Geopandas: ```none 1- conda create -n geo_env 2- conda activate geo_env 3- conda config --env --add channels conda-forge 4- conda config --env --set channel_priority strict 5- conda install python=3 geopandas ``` and followin...
17,539
6,767,990
So, I use [SPM](http://www.fil.ion.ucl.ac.uk/spm/) to register fMRI brain images between the same patient; however, I am having trouble registering images between patients. Essentially, I want to register a brain atlas to a patient-specific scan, so that I can do some image patching. So register, then apply that warpi...
2011/07/20
[ "https://Stackoverflow.com/questions/6767990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402632/" ]
Freesurfer segments and annotates the brain in the patient's native space, resulting in patient-specific regions, like [so](http://dl.dropbox.com/u/2467665/freesurfer_segmentation.png). I'm not sure what you mean by patching, or to what other images you'd like to apply this transformation, but it seems like the softw...
I think [ITK](http://www.itk.org/) is made for this kind if purpose. A Python wrapper exists ([Paul Novotny](http://www.paulnovo.org/) distributes binaries for Ubuntu on his site), but this is mainly C++. If you work under Linux then it is quite simple to compile if you are familiar with cmake. As this toolkit is a ve...
17,542
23,533,566
I want to use /etc/sudoers to change the owner of a file from bangtest(user) to root. Reason to change: when I uploaded an image from bangtest(user) to my server using Django application then image file permission are like ``` ls -l /home/bangtest/alpha/media/products/image_2093.jpg -rw-r--r-- 1 bangtest bangtest 2...
2014/05/08
[ "https://Stackoverflow.com/questions/23533566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2479352/" ]
I strongly suggest you use a browser such as Firefox with Firebug installed. Load any page, hit Tools > Web Developer > Inspector (or its hot key equivalent), then click on your object, the HTML code inspector will reference the exact line of the css file that is governing the style being generated (either the style d...
After several attempts and some help from Zurb support the CSS i needed was: ``` .top-bar-section .dropdown li:not(.has-form) a:not(.button) { color: white; background: #740707; } ``` Thanks for the help
17,550
60,103,642
I already know how to open windows command prompt through python, but I was wondering how if there is a way to open a windows powershellx86 window and run commands through python 3.7 on windows 10?
2020/02/06
[ "https://Stackoverflow.com/questions/60103642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can just call out to powershell.exe using `subprocess.run` ``` import subprocess subprocess.run('powershell.exe Get-Item *') ```
If you know how to run the command prompt (CMD.EXE) then you should be able to use the same method to run PowerShell (PowerShell.EXE). PowerShell.EXE is located in c:\windows\system32\windowspowershell\v1.0\ by default. To run the shell with commands use: ``` c:\windows\system32\windowspowershell\v1.0\PowerShell.exe -...
17,553