qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
8,964,461 | I would like to create a subclass of python's unittest.Testcase called BasicTest. I would like each subclass of BasicTest to run the same routine in main. How can I accomplish this?
Example:
```
in basic_test.py:
class BasicTest(unittest.TestCase):
...
if __name__ == '__main__':
# Do optparse stuff
uni... | 2012/01/22 | [
"https://Stackoverflow.com/questions/8964461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/766953/"
] | ```
# basic_test.py
class BasicTest(unittest.TestCase):
@staticmethod
def main():
# Do optparse stuff
unittest.main()
if __name__ == '__main__':
BasicTest.main()
# some_basic_test.py
class SomeBasicTest(BasicTest):
...
if __name__ == '__main__':
BasicTest.main()
``` | You cannot (re)import a module as a new **main**, thus the `if __name__=="__main__"` code is kind of unreachable.
Dor’s suggestion or something similar seems most reasonable.
However if you have no access to the module in question, you might consider looking at the [runpy.run\_module()](http://docs.python.org/library/... |
8,964,461 | I would like to create a subclass of python's unittest.Testcase called BasicTest. I would like each subclass of BasicTest to run the same routine in main. How can I accomplish this?
Example:
```
in basic_test.py:
class BasicTest(unittest.TestCase):
...
if __name__ == '__main__':
# Do optparse stuff
uni... | 2012/01/22 | [
"https://Stackoverflow.com/questions/8964461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/766953/"
] | ```
# basic_test.py
class BasicTest(unittest.TestCase):
@staticmethod
def main():
# Do optparse stuff
unittest.main()
if __name__ == '__main__':
BasicTest.main()
# some_basic_test.py
class SomeBasicTest(BasicTest):
...
if __name__ == '__main__':
BasicTest.main()
``` | >
> I would like each subclass of BasicTest to run the same routine in main
>
>
>
I guess what you want is to run some setup/initialization code before running tests from any test case. In this case you might be interested in [`setUpClass`](http://docs.python.org/library/unittest.html#class-and-module-fixtures) cl... |
4,879,324 | Suppose I want to include a library:
```
#include <library.h>
```
but I'm not sure it's installed in the system. The usual way is to use tool like autotools. Is there a simpler way in C++? For example in python you can handle it with exceptions. | 2011/02/02 | [
"https://Stackoverflow.com/questions/4879324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238671/"
] | autotools is the best way to detect at *compile* time. It's very platform-specific, but assuming you're on Linux or similar, [dlopen](http://linux.die.net/man/3/dlopen) is how you check at *runtime*. | As far as I know, there's no way of checking whether a library is installed using code.
However, you could create a bash script that could look for the library in the usual places, like /usr/lib or /usr/local/lib. Also, you could check /etc/ld.so.conf for the folders and then look for the libraries.
Or something like... |
14,983,015 | I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes.
One step in this process is changing out all the script sources. For instance:
```
<script type="text/javascript" src="./js/jquery.bxslider.min.js"></script>
```
becomes
```
<script type="text/javascript" src="{{ 'j... | 2013/02/20 | [
"https://Stackoverflow.com/questions/14983015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623223/"
] | You can just go to azure's control panel and add in a virtual directory path.
Please visit this MDSN blog to see how its done.
<http://blogs.msdn.com/b/kaushal/archive/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site.aspx> | If you use Web deploy publish method you can set in Site name `mydomain/mymvcsite` instead of `mydomain`.
At least it works for me for default windows azure site `http://mydomain.azurewebsites.net/mymvcsite`.
Or you can use FTP publish method. |
14,983,015 | I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes.
One step in this process is changing out all the script sources. For instance:
```
<script type="text/javascript" src="./js/jquery.bxslider.min.js"></script>
```
becomes
```
<script type="text/javascript" src="{{ 'j... | 2013/02/20 | [
"https://Stackoverflow.com/questions/14983015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623223/"
] | If you use Web deploy publish method you can set in Site name `mydomain/mymvcsite` instead of `mydomain`.
At least it works for me for default windows azure site `http://mydomain.azurewebsites.net/mymvcsite`.
Or you can use FTP publish method. | **Basically this needs following steps to be done to make it working.**
Solution contains
i) sampleApp.API(.Net Core Web API)
ii)sampleApp.UI( Angular App)
Setting up Azure portal for two applications
1) Go to your web app in azure portal -> Settings->configurations
2) Select Path Mappings and here create new map... |
14,983,015 | I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes.
One step in this process is changing out all the script sources. For instance:
```
<script type="text/javascript" src="./js/jquery.bxslider.min.js"></script>
```
becomes
```
<script type="text/javascript" src="{{ 'j... | 2013/02/20 | [
"https://Stackoverflow.com/questions/14983015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623223/"
] | You can just go to azure's control panel and add in a virtual directory path.
Please visit this MDSN blog to see how its done.
<http://blogs.msdn.com/b/kaushal/archive/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site.aspx> | **Basically this needs following steps to be done to make it working.**
Solution contains
i) sampleApp.API(.Net Core Web API)
ii)sampleApp.UI( Angular App)
Setting up Azure portal for two applications
1) Go to your web app in azure portal -> Settings->configurations
2) Select Path Mappings and here create new map... |
52,241,986 | I have the following code to add a table of contents to the beginning of my ipython notebooks. When I run the cell on jupyter on my computer I get
[](https://i.stack.imgur.com/ESBlz.png)
But when I upload the notebook to github and choose to view th... | 2018/09/09 | [
"https://Stackoverflow.com/questions/52241986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10171138/"
] | Attachments (and rich text) are not yet supported by the POST /chatthreads API. The only way to post messages with attachments today is with our bot APIs.
We are working on write APIs to match our recently-released read APIs but they aren't ready yet. There's no need to put anything on UserVoice though.
Unfortunatel... | >
> APIs under the /beta version in Microsoft Graph are in preview and are subject to change. Use of these APIs in production applications is not supported.
>
>
>
The returned value of **attachment** in the document is the embodiment of the product group design, and we cannot get the value should be the product gr... |
22,521,912 | I'm in the directory `/backbone/` which has a `main.js` file within scripts. I run `python -m SimpleHTTPServer` from the `backbone` directory and display it in the browser and the console reads the error `$ is not defined` and references a completely different `main.js` file from something I was working on days ago wit... | 2014/03/20 | [
"https://Stackoverflow.com/questions/22521912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066353/"
] | i have the same problem and solved it by (( Go to Setting >> Locations> mode>> Battery savings >> then restart your device and set up again your app )) | Google map now uses this to enable the My Location layer on the Map.
```
mMap.setMyLocationEnabled(true);
```
You can view the documentation for Google Maps Android API v2 [here](https://developers.google.com/maps/documentation/android/location).
They're using Location Client now to Making Your App Location-Aware,
... |
7,033,192 | ```
#!/usr/bin/python
import os,sys
from os import path
input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n')
at = 1
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.split(':')[4].split()[0]
num4 = line4.split(':')[4].split()[0]
print num1,num... | 2011/08/11 | [
"https://Stackoverflow.com/questions/7033192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815408/"
] | The problem is that `lines` has a maximum value of `len(input)-1` but then you let `line4` be `lines + 3`. So, when you're at your last couple of lines, `lines + 3` will be larger than the length of the list.
```
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.sp... | It seems that you want to read a file and get some info from it every 3 lines. I would recommend something simpler:
```
def get_num(line):
return line.split(':')[4].split()[0]
nums1 = [get_num(l) for l in open(fn, "r").readlines()]
nums2 = nums1[3:]
for i in range(len(nums2)):
print nums1[i],nums2[i]
```
Th... |
7,033,192 | ```
#!/usr/bin/python
import os,sys
from os import path
input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n')
at = 1
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.split(':')[4].split()[0]
num4 = line4.split(':')[4].split()[0]
print num1,num... | 2011/08/11 | [
"https://Stackoverflow.com/questions/7033192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815408/"
] | The problem is that `lines` has a maximum value of `len(input)-1` but then you let `line4` be `lines + 3`. So, when you're at your last couple of lines, `lines + 3` will be larger than the length of the list.
```
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.sp... | I had a similar problem and here is the solution I came up with:
```
tuple = (1,2,3)
dogs = [ ]
cats = [ ]
one_two = [ ]
cats.apend(tuple)
dogs.apend(tuple)
file.apend(one_two)
file.apend("/")
print file
print cats
print dogs
```
Have an excellent day. |
7,033,192 | ```
#!/usr/bin/python
import os,sys
from os import path
input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n')
at = 1
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.split(':')[4].split()[0]
num4 = line4.split(':')[4].split()[0]
print num1,num... | 2011/08/11 | [
"https://Stackoverflow.com/questions/7033192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815408/"
] | Lets say `len(input) == 10`. `range(0, len(input))` iterates `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`. And when lines > 6 and you're trying to access `input[lines+3`], it clearly an IndexError, because there is no `index[10]`, `[11]` etc .
And `line1.split(':')[4]` can also raise an IndexError if `line1.count(":") < 4`.
I d... | It seems that you want to read a file and get some info from it every 3 lines. I would recommend something simpler:
```
def get_num(line):
return line.split(':')[4].split()[0]
nums1 = [get_num(l) for l in open(fn, "r").readlines()]
nums2 = nums1[3:]
for i in range(len(nums2)):
print nums1[i],nums2[i]
```
Th... |
7,033,192 | ```
#!/usr/bin/python
import os,sys
from os import path
input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n')
at = 1
for lines in range(0, len(input)):
line1 = input[lines]
line4 = input[lines+3]
num1 = line1.split(':')[4].split()[0]
num4 = line4.split(':')[4].split()[0]
print num1,num... | 2011/08/11 | [
"https://Stackoverflow.com/questions/7033192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815408/"
] | Lets say `len(input) == 10`. `range(0, len(input))` iterates `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`. And when lines > 6 and you're trying to access `input[lines+3`], it clearly an IndexError, because there is no `index[10]`, `[11]` etc .
And `line1.split(':')[4]` can also raise an IndexError if `line1.count(":") < 4`.
I d... | I had a similar problem and here is the solution I came up with:
```
tuple = (1,2,3)
dogs = [ ]
cats = [ ]
one_two = [ ]
cats.apend(tuple)
dogs.apend(tuple)
file.apend(one_two)
file.apend("/")
print file
print cats
print dogs
```
Have an excellent day. |
34,406,393 | I try to make a script allowing to loop through a list (*tmpList = openFiles(cop\_node)*). This list contains 5 other sublists of 206 components.
The last 200 components of the sublists are string numbers ( a line of 200 string numbers for each component separated with a space character).
I need to loop through the ma... | 2015/12/21 | [
"https://Stackoverflow.com/questions/34406393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5698216/"
] | `valueListStr = []*len(tmpList)` does not do what you think it does, if you want a list of lists use a *list comp* with range:
```
valueListStr = [[] for _ in range(len(tmpList))]
```
That will create a list of lists:
```
In [9]: valueListStr = [] * i
In [10]: valueListStr
Out[10]: []
In [11]: valueListStr = [[] ... | ```
def valuesFiles(cop_node):
valueListStr = []
for j in openFiles(cop_node):
tmpList = j[6:]
tmpList.reverse()
tmp = []
for s in tmpList:
tmp.extend(s.split(' '))
valueListStr.append(tmp)
return valueListStr
```
After little modification I get it to work as excepted :
```
def valuesFile... |
2,063,124 | I am trying to read a \*.wav file using scipy. I do it in the following way:
```
import scipy.io
x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav')
```
As a result I get the following error message:
```
Traceback (most recent call last):
File "test3.py", line 1, in <module>
import scipy.io
Fi... | 2010/01/14 | [
"https://Stackoverflow.com/questions/2063124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245549/"
] | Looks like you have upgraded your numpy version but haven't installed a [corresponding scipy version](http://projects.scipy.org/scipy/ticket/916). | Do you have numpy installed? The package is most likely called `numpy` or `python-numpy` if you are running Linux
If your OS package manager does not have numpy package, download it from [here](http://sourceforge.net/projects/numpy/files/) |
49,016,216 | Is there a way to know which element has failed the `any` built-in function?
I was trying to solve [Euler 5](https://projecteuler.net/problem=5) and I want to find for which numbers my product isn't evenly divisible. Using the for loop it's easy to figure it out, but is it possible with `any` also?
```
from operator ... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49016216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512538/"
] | Is there any good reason to use `any`?
If you want an one-liner to find out which numbers are not evenly divisible :
```
not_divisible = [i for i in range(1, 21) if product % i != 0]
if len(not_divisible) > 0:
print(not_divisible)
```
You can't really get all the non-divisible numbers with `any`, since it stop... | I probably wouldn't recommend actually doing this, as it feels a bit hacky (and uglier than just scrapping the `any()` for a `for` loop). That disclaimer aside, this could technically be accomplished by exploiting an iterator and `any()`'s property of stopping once it's found a truthy value:
```
rangemax = 21
rng = it... |
6,712,051 | I'm trying to do something that seems very simple, and falls within the range of standard python. The following function takes a collection of sets, and returns all of the items that are contained in two or more sets.
To do this, while the collection of sets is not empty, it simply pops one set out of the collection, ... | 2011/07/15 | [
"https://Stackoverflow.com/questions/6712051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173292/"
] | [It's a bug](http://ironpython.codeplex.com/workitem/30386). It will be fixed in 2.7.1, but I don't think the fix is in the 2.7.1 Beta 1 release. | This is a [bug](http://ironpython.codeplex.com/workitem/30386) still present in the 2.7.1 Beta 1 release.
It has been fixed in [master](https://github.com/IronLanguages/main), and the fix will be included in the next release.
```
IronPython 3.0 (3.0.0.0) on .NET 4.0.30319.235
Type "help", "copyright", "credits" or "... |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure. | I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something?
If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the ... |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure. | You should probably read up on [Dependency Inversion](http://www.c2.com/cgi/wiki?DependencyInversionPrinciple). |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure. | Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in *objects* and pass those around.
Read up on objects and classes and how... |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code f... | I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something?
If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the ... |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code. | I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something?
If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the ... |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code f... | You should probably read up on [Dependency Inversion](http://www.c2.com/cgi/wiki?DependencyInversionPrinciple). |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code f... | Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in *objects* and pass those around.
Read up on objects and classes and how... |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code. | You should probably read up on [Dependency Inversion](http://www.c2.com/cgi/wiki?DependencyInversionPrinciple). |
3,400,847 | I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.
instead of running everything from one file, I wanted to organize stuff in modules so I had:
* main.py
* callback.py
* helper.py
I ran into problems when I realized that helper.py needed to reference variables from main, but ma... | 2010/08/03 | [
"https://Stackoverflow.com/questions/3400847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216547/"
] | I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code. | Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in *objects* and pass those around.
Read up on objects and classes and how... |
42,292,272 | How to identify the link, I have inspected the elements which are as below :
```
<div class="vmKOT" role="navigation">
<a class="Ml68il" href="https://www.google.com" aria-label="Search" data-track-as="Welcome Header Search"></a>
<a class="WaidDw" href="https://mail.google.com" aria-label="Mail" data-track-as="Welcome... | 2017/02/17 | [
"https://Stackoverflow.com/questions/42292272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7579389/"
] | You can try
```
driver.find_element_by_class_name('WaidDw').click()
```
or
```
driver.find_element_by_xpath('//a[@href="https://mail.google.com" and @aria-label="Mail"]').click()
``` | In your provided HTML all attribute's values are unique, you can locate easily that element by using their attribute value.
As your question points to locate this `<a class="WaidDw" href="https://mail.google.com" aria-label="Mail" data-track-as="Welcome Header Mail"></a>` element. I'm providing you multiple `cssSelect... |
36,244,077 | So here is a breakdown of the task:
1) I have a 197x10 2D numpy array. I scan through this and identify specific cells that are of interest (criteria that goes into choosing these cells is not important.) These cells are not restricted to one specific area of the matrix.
2) I have 3247 other 2D Numpy arrays with the ... | 2016/03/27 | [
"https://Stackoverflow.com/questions/36244077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | Pythonic way:
```
answers = []
# this generates index matrix where the condition is met.
idx = np.argwhere( your condition of (1) matrix comes here)
for array2d in your_3247_arrays:
answer = array2d[idx].mean()
answers.append()
print(answers)
``` | Here is an example:
```
import numpy as np
A = np.random.rand(197, 10)
B = np.random.rand(3247, 197, 10)
loc = np.where(A > 0.9)
B[:, loc[0], loc[1]].mean(axis=1)
``` |
47,540,186 | I want to dynamically start clusters from my Jupyter notebook for specific functions. While I can start the cluster and get the engines running, I am having two issues:
(1) I am unable to run the ipcluster command in the background. When I run the command through notebook, the cell is running till the the time the clu... | 2017/11/28 | [
"https://Stackoverflow.com/questions/47540186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059923/"
] | When I saw your answer unanswered on StackOverflow, I almost had a heart attack because I had the same problem.
But running the
```
ipcluster start --help
```
command showed this:
```
--daemonize
```
This makes it run in the background.
So in your notebook you can do this:
```
no_engines = 6
!ipcluster start... | I am not familiar with the details of the `commands` module (it's been deprecated since 2.6, according to <https://docs.python.org/2/library/commands.html>) but I know that with the `subprocess` module capturing output will make the make the interpreter block until the system call completes.
Also, the number of engine... |
40,839,114 | I tried to fine-tune VGG16 on my dataset, but stuck on trouble of opening h5py file of VGG16-weights. I don't understand what does this error mean about:
```
OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256)
```
Does anyone know how to fix it? thanks
```
-----... | 2016/11/28 | [
"https://Stackoverflow.com/questions/40839114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7218907/"
] | There is a possibility that the download of the file has failed.
Replacing a file that failed to open with the following file may resolve it.
<https://github.com/fchollet/deep-learning-models/releases>
My situation,
That file was in the following path.
C:\Users\MyName\.keras\models\vgg16\_weights\_tf\_dim\_ordering\_... | because the last time you file download is failed.but the bad file remains in the filepath. so you have to find the bad file.
maybe u can use “find / -name 'vgg16\_weights\_tf\_dim\_ordering\_tf\_kernels\_notop.h5'” to find the path in unix-system.
then delete it
try agian!good luck!! |
40,839,114 | I tried to fine-tune VGG16 on my dataset, but stuck on trouble of opening h5py file of VGG16-weights. I don't understand what does this error mean about:
```
OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256)
```
Does anyone know how to fix it? thanks
```
-----... | 2016/11/28 | [
"https://Stackoverflow.com/questions/40839114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7218907/"
] | There is a possibility that the download of the file has failed.
Replacing a file that failed to open with the following file may resolve it.
<https://github.com/fchollet/deep-learning-models/releases>
My situation,
That file was in the following path.
C:\Users\MyName\.keras\models\vgg16\_weights\_tf\_dim\_ordering\_... | It is probably because the file download failed or the file is corrupt.
I found those corrupted files in `/tmp/.keras/models/vggface/`.
My system is Ubuntu 20.04. |
73,336,040 | I'm calling `subprocess.Popen` on an `exe` file in [this script](https://github.com/PolicyEngine/openfisca-us/blob/6ae4e65f6883be598f342c445de1d52430db6b28/openfisca_us/tools/dev/taxsim/generate_taxsim_tests.py#L146), and it [throws](https://gist.github.com/MaxGhenis/b0eb890232363ed30efc1be505e1f257#file-gistfile1-txt-... | 2022/08/12 | [
"https://Stackoverflow.com/questions/73336040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1840471/"
] | `subprocess` can only start programs that your operating system knows how to execute.
Your `taxsim35-unix.exe` is a Linux executable. MacOS cannot run them.
You'll need to either use a Linux machine to run this executable (real or virtual), or get a version compiled for Mac. <https://back.nber.org/stata//taxsim35/tax... | I worked with the developers of taxsim for a while. I believe that the .exe files generated by taxsim were originally msdos only and then moved to Linux. They're not intended to be run by MacOS. I don't know if they ever released the FORTRAN code that generates them so that they can be run on MacOS. Your best bet for r... |
48,590,488 | Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x.
```
df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ip... | 2018/02/02 | [
"https://Stackoverflow.com/questions/48590488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7237997/"
] | There are many ways to do this. One way to do it would be the following:
```
def like_function(x):
group = "unknown"
for key in product_map:
if key in x:
group = product_map[key]
break
return group
df['company'] = df.comp.apply(like_function)
``` | A vectorized solution inspired by [MaxU](https://stackoverflow.com/users/5741205/maxu)'s solution to a [similar problem](https://stackoverflow.com/questions/48510405/pandas-python-datafame-update-a-column/48510563).
```
x = df.comp.str.split(expand=True)
df['company'] = None
df['company'] = df['company'].fillna(x[x.is... |
48,590,488 | Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x.
```
df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ip... | 2018/02/02 | [
"https://Stackoverflow.com/questions/48590488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7237997/"
] | There are many ways to do this. One way to do it would be the following:
```
def like_function(x):
group = "unknown"
for key in product_map:
if key in x:
group = product_map[key]
break
return group
df['company'] = df.comp.apply(like_function)
``` | Here is an interesting way, especially if you are learning about python. You can subclass `dict` and override `__getitem__` to look for partial strings.
```
class dict_partial(dict):
def __getitem__(self, value):
for k in self.keys():
if k in value:
return self.get(k)
el... |
48,590,488 | Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x.
```
df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ip... | 2018/02/02 | [
"https://Stackoverflow.com/questions/48590488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7237997/"
] | There are many ways to do this. One way to do it would be the following:
```
def like_function(x):
group = "unknown"
for key in product_map:
if key in x:
group = product_map[key]
break
return group
df['company'] = df.comp.apply(like_function)
``` | To my knowledge, pandas does not come with a "substring mapping" method. The [`.map()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html) method does not support substrings, and the [`.str.contains()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains... |
57,404,906 | I have created an executable via pyinstaller. While running the exe found the error from pandas.
```
Traceback (most recent call last):
File "score_python.py", line 3, in <module>
import pandas as pd, numpy as np
File "d:\virtual\sc\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec... | 2019/08/08 | [
"https://Stackoverflow.com/questions/57404906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949165/"
] | This is an issue with virtualenv from version 16.4.0 onward, as indicated in the following issue on github:
<https://github.com/pyinstaller/pyinstaller/issues/4064>
These workarounds were suggested:
1. In the .spec file, at the line “hiddenimports=[]”, change to "hiddenimports=['distutils']", then run pyinstaller usi... | Found the solution, it's because of the virtual environment.
The error occurred because of the creation of a new virtual environment while creating the project. I have deleted my existing virtual and created new virtual by setting up the python interpreter and opting the `pre-existing interpreter` option.
The IDE wil... |
32,007,199 | Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists.
So for python I was thinking of using OOP and using an iterator.
```
>>> You have a list (1, 3, 3, 3, 5)
Retu... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32007199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5101470/"
] | Probably the most straight forward way to do this is using Python's `set` builtin.
```
def unique(*args):
result = set() # A set guarantees the uniqueness of elements
result = result.union(*args) # Include elements from all args
result = list(result) # Convert the set object to a list
return result
... | Not necessary but you wanted to make classes.
```
class Unique:
def __init__(self):
self._list = self.user_input()
def user_input(self):
_list = raw_input()
_list = _list.split(' ')
[int(i) for i in _list]
return _list
def get_unique(self):
self._set = s... |
32,007,199 | Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists.
So for python I was thinking of using OOP and using an iterator.
```
>>> You have a list (1, 3, 3, 3, 5)
Retu... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32007199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5101470/"
] | Probably the most straight forward way to do this is using Python's `set` builtin.
```
def unique(*args):
result = set() # A set guarantees the uniqueness of elements
result = result.union(*args) # Include elements from all args
result = list(result) # Convert the set object to a list
return result
... | In scheme, using a `union` function like that defined for instance in [How to write a scheme function that takes two lists and returns four lists](https://stackoverflow.com/questions/765484/how-to-write-a-scheme-function-that-takes-two-lists-and-returns-four-lists) , you could write something like this:
```lisp
(defin... |
32,007,199 | Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists.
So for python I was thinking of using OOP and using an iterator.
```
>>> You have a list (1, 3, 3, 3, 5)
Retu... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32007199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5101470/"
] | Probably the most straight forward way to do this is using Python's `set` builtin.
```
def unique(*args):
result = set() # A set guarantees the uniqueness of elements
result = result.union(*args) # Include elements from all args
result = list(result) # Convert the set object to a list
return result
... | Here is a solution in Racket:
```
(define (unique xs) (set->list (list->set xs)))
```
An explanation:
```
> (list->set '(1 2 2 4 7))
(set 1 2 4 7)
```
The function `list->set` turns a list into a set.
If we want a list of the elements rather than a set, we can use `set->list` to convert the set back to a list.
... |
32,007,199 | Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists.
So for python I was thinking of using OOP and using an iterator.
```
>>> You have a list (1, 3, 3, 3, 5)
Retu... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32007199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5101470/"
] | In scheme, using a `union` function like that defined for instance in [How to write a scheme function that takes two lists and returns four lists](https://stackoverflow.com/questions/765484/how-to-write-a-scheme-function-that-takes-two-lists-and-returns-four-lists) , you could write something like this:
```lisp
(defin... | Not necessary but you wanted to make classes.
```
class Unique:
def __init__(self):
self._list = self.user_input()
def user_input(self):
_list = raw_input()
_list = _list.split(' ')
[int(i) for i in _list]
return _list
def get_unique(self):
self._set = s... |
32,007,199 | Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists.
So for python I was thinking of using OOP and using an iterator.
```
>>> You have a list (1, 3, 3, 3, 5)
Retu... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32007199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5101470/"
] | In scheme, using a `union` function like that defined for instance in [How to write a scheme function that takes two lists and returns four lists](https://stackoverflow.com/questions/765484/how-to-write-a-scheme-function-that-takes-two-lists-and-returns-four-lists) , you could write something like this:
```lisp
(defin... | Here is a solution in Racket:
```
(define (unique xs) (set->list (list->set xs)))
```
An explanation:
```
> (list->set '(1 2 2 4 7))
(set 1 2 4 7)
```
The function `list->set` turns a list into a set.
If we want a list of the elements rather than a set, we can use `set->list` to convert the set back to a list.
... |
9,882,358 | I'm writing a quick and dirty maintenace script to delete some rows and would like to avoid having to bring my ORM classes/mappings over from the main project. I have a query that looks similar to:
```
address_table = Table('address',metadata,autoload=True)
addresses = session.query(addresses_table).filter(addresses_t... | 2012/03/27 | [
"https://Stackoverflow.com/questions/9882358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459082/"
] | Looking through some code where I did something similar, I believe this will do what you want.
```
d = addresses_table.delete().where(addresses_table.c.retired == 1)
d.execute()
```
Calling `delete()` on a table object gives you a `sql.expression` (if memory serves), that you then execute. I've assumed above that th... | When you call `delete()` from a query object, SQLAlchemy performs a *bulk deletion*. And you need to choose a **strategy for the removal of matched objects from the session**. See the documentation [here](https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.delete).
If you do not choose a strategy for... |
32,255,039 | In ubuntu ubuntu-desktop needs python3-requsts package. But this package contain out-dated requests lib (2.4, current - 2.7). I need fresh version of requests, but i cant install him.
```
$ sudo pip3 install requests --upgrade
Downloading/unpacking requests from https://pypi.python.org/packages/2.7/r/requests/requests... | 2015/08/27 | [
"https://Stackoverflow.com/questions/32255039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1064115/"
] | Finally, i solved this problem by manually installing requests. Just download archive with package and run:
```
python3 setup.py install
```
This will remove apt-get files and install fresh version. | You'd better be using virtualenv :-).
The clean way to do what you are asking is creating an OS package (a ".deb") with the newer version and installing it with dpkg.
The "unclean" way would be to delete the system-package using apt-get, synaptic, etc... and then use pip to install it on the system Python. That is b... |
62,273,175 | I have a python dictionary as below:
```
wordCountMap = {'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}
```
I want to sort the dictionary such that it is the decreasing order of its values, followed by lexicographically increasing order for keys with same values.
```
result = {'zzz':10, 'bbb':2. 'bbz':2. 'aaa':1}
```
Here... | 2020/06/09 | [
"https://Stackoverflow.com/questions/62273175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2846878/"
] | You can convert it to the sorted `list` by keying on the negation of the value, and the original key:
```
resultlist = sorted({'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}.items(), key=lambda x: (-x[1], x[0]))
```
If it must be converted back to a `dict`, just wrap that in the `dict` constructor:
```
resultdict = dict(sort... | I got this answer from [here](https://stackoverflow.com/questions/9919342/sorting-a-dictionary-by-value-then-key).
Assuming your dictionary is d, you can get it sorted with:
```
d = {'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}
newD = [v[0] for v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))]
```
newD's value:
... |
71,883,326 | I'm having trouble figuring out how to do the opposite of the answer to this question (and in R not python).
[Count the amount of times value A occurs with value B](https://stackoverflow.com/questions/47834225/count-the-amount-of-times-value-a-occurs-with-value-b)
Basically I have a dataframe with a lot of combinatio... | 2022/04/15 | [
"https://Stackoverflow.com/questions/71883326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7257777/"
] | First `paste` the two id columns together to `id12` for later matching. Then use `sapply` to go through all rows to see the records where `id1` appears in `id12` but `id2` doesn't. `sum` that value and only output the `distinct` records. Finally, remove the `id12` column.
```
library(dplyr)
df %>% mutate(id12 = paste... | A full `tidyverse` version:
```r
library(tidyverse)
df %>%
mutate(id = paste(id1, id2),
count = map(cur_group_rows(), ~ sum(str_detect(id, id1[.x]) & str_detect(id, id2[.x], negate = T))))
``` |
71,883,326 | I'm having trouble figuring out how to do the opposite of the answer to this question (and in R not python).
[Count the amount of times value A occurs with value B](https://stackoverflow.com/questions/47834225/count-the-amount-of-times-value-a-occurs-with-value-b)
Basically I have a dataframe with a lot of combinatio... | 2022/04/15 | [
"https://Stackoverflow.com/questions/71883326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7257777/"
] | First `paste` the two id columns together to `id12` for later matching. Then use `sapply` to go through all rows to see the records where `id1` appears in `id12` but `id2` doesn't. `sum` that value and only output the `distinct` records. Finally, remove the `id12` column.
```
library(dplyr)
df %>% mutate(id12 = paste... | A more efficient approach would be to work on a tabulation format:
```
tab = crossprod(table(rep(seq_len(nrow(df)), ncol(df)), c(df$id1, df$id2)))
#tab
#
# 1 2 3 4
# 1 7 3 2 2
# 2 3 6 1 2
# 3 2 1 4 1
# 4 2 2 1 5
```
So, now, we have the times each value appears with another (irrespectively of their order i... |
52,056,004 | I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2)
* <https://nicolewhite.github.io/neo4j-flask/>
* <https://github.com/nicolewhite/neo4j-flask>
* <https://neo4j.com/blog/building-python-web-application-using... | 2018/08/28 | [
"https://Stackoverflow.com/questions/52056004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606342/"
] | py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first>
That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat.
In the linked github example Users are created with:
```
user = Node('User', u... | Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`.
The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html... |
52,056,004 | I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2)
* <https://nicolewhite.github.io/neo4j-flask/>
* <https://github.com/nicolewhite/neo4j-flask>
* <https://neo4j.com/blog/building-python-web-application-using... | 2018/08/28 | [
"https://Stackoverflow.com/questions/52056004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606342/"
] | py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first>
That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat.
In the linked github example Users are created with:
```
user = Node('User', u... | This worked for me instead. reference the link below
```py
def find(self):
user = graph.nodes.match("User", self.username).first()
return user
```
<https://py2neo.org/v5/_modules/py2neo/database.html> |
52,056,004 | I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2)
* <https://nicolewhite.github.io/neo4j-flask/>
* <https://github.com/nicolewhite/neo4j-flask>
* <https://neo4j.com/blog/building-python-web-application-using... | 2018/08/28 | [
"https://Stackoverflow.com/questions/52056004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606342/"
] | py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first>
That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat.
In the linked github example Users are created with:
```
user = Node('User', u... | Another simpler way to solve this would be to replace `find_one` with the below:
```
from py2neo import Graph, NodeMatcher
matcher = NodeMatcher(graph)
user = matcher.match('user', name='name').first()
``` |
52,056,004 | I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2)
* <https://nicolewhite.github.io/neo4j-flask/>
* <https://github.com/nicolewhite/neo4j-flask>
* <https://neo4j.com/blog/building-python-web-application-using... | 2018/08/28 | [
"https://Stackoverflow.com/questions/52056004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606342/"
] | This worked for me instead. reference the link below
```py
def find(self):
user = graph.nodes.match("User", self.username).first()
return user
```
<https://py2neo.org/v5/_modules/py2neo/database.html> | Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`.
The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html... |
52,056,004 | I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2)
* <https://nicolewhite.github.io/neo4j-flask/>
* <https://github.com/nicolewhite/neo4j-flask>
* <https://neo4j.com/blog/building-python-web-application-using... | 2018/08/28 | [
"https://Stackoverflow.com/questions/52056004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4606342/"
] | Another simpler way to solve this would be to replace `find_one` with the below:
```
from py2neo import Graph, NodeMatcher
matcher = NodeMatcher(graph)
user = matcher.match('user', name='name').first()
``` | Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`.
The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html... |
32,681,203 | I use iPython mostly via notebooks but also in the terminal. I just created my default profile by running `ipython profile create`.
I can't seem to figure out how to have the profile run several magic commands that I use every time. I tried to look this up online and in a book I'm reading but can't get it to work. For... | 2015/09/20 | [
"https://Stackoverflow.com/questions/32681203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238779/"
] | Execute magics as follows:
```
get_ipython().magic(u"%reload_ext autoreload")
get_ipython().magic(u"%autoreload 2")
```
You can put those lines in your startup script here:
```
~/.ipython/profile_default/startup/00-first.py
``` | To start for example the %pylab magic command on startup do the following:
```
ipython profile create pylab
```
Add the following code to your .ipython\profile\_pylab\ipython\_config.py
```
c.InteractiveShellApp.exec_lines = ['%pylab']
```
and start ipython
```
ipython --profile=pylab
``` |
29,658,335 | I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background
What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I de... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29658335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ### Control operator
There are two uses of `&` here. One is as a so-called **control operator**. Every command is terminated by a control operator such as `&`, `;` or `<newline>` . The difference between them is that `;` and `<newline>` run the command in the foreground and `&` does it in the background.
```
setsid p... | It makes a difference. `&` doubles as a command separator (just like `;` is command separator). What you're really doing in something like
```
setsid python script.py & < /dev/zero > log.txt
```
is running `setsid python script.py` in the background and also running a "null" command (which comes after the `&`) in th... |
29,658,335 | I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background
What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I de... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29658335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | So the `&` means different things, depending on the context.
In the first case:
```
setsid python script.py < /dev/zero &> log.txt &
```
the first `&` is used together with a `>` as `&>` which means redirect both stderr and stdout. The last `&` means run in the background
In the second case:
```
setsid python scr... | It makes a difference. `&` doubles as a command separator (just like `;` is command separator). What you're really doing in something like
```
setsid python script.py & < /dev/zero > log.txt
```
is running `setsid python script.py` in the background and also running a "null" command (which comes after the `&`) in th... |
29,658,335 | I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background
What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I de... | 2015/04/15 | [
"https://Stackoverflow.com/questions/29658335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ### Control operator
There are two uses of `&` here. One is as a so-called **control operator**. Every command is terminated by a control operator such as `&`, `;` or `<newline>` . The difference between them is that `;` and `<newline>` run the command in the foreground and `&` does it in the background.
```
setsid p... | So the `&` means different things, depending on the context.
In the first case:
```
setsid python script.py < /dev/zero &> log.txt &
```
the first `&` is used together with a `>` as `&>` which means redirect both stderr and stdout. The last `&` means run in the background
In the second case:
```
setsid python scr... |
9,343,498 | I'm implementing the component labelling algorithm as in [this paper](http://www.iis.sinica.edu.tw/papers/fchang/1362-F.pdf) using python and opencv. It requires checking the input image pixel-by-pixel and perform the so-called contour tracing subroutine to assign label to the blobs of a binary image.
I manage to hav... | 2012/02/18 | [
"https://Stackoverflow.com/questions/9343498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567989/"
] | I'm not sure if I understand your question, but each key can have only one object associated with it. In your case, you're using an NSString object. If you replaced the NSString with some object that you create, say AnObjectWithAThingAndAPersonAndAPlace, you could have multiple attributes associated with each key.
---... | RIght now your `datasource` object is an NSArray. You need to make it an NSMutableArray. Declare it as an NSMutableArray in your header file and then you can do this:
```
datasource = [[states allKeys] mutableCopy];
[datasource addObject:whatever];
```
But, it sounds like the structure you are actually looking for i... |
9,343,498 | I'm implementing the component labelling algorithm as in [this paper](http://www.iis.sinica.edu.tw/papers/fchang/1362-F.pdf) using python and opencv. It requires checking the input image pixel-by-pixel and perform the so-called contour tracing subroutine to assign label to the blobs of a binary image.
I manage to hav... | 2012/02/18 | [
"https://Stackoverflow.com/questions/9343498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567989/"
] | I'm not sure if I understand your question, but each key can have only one object associated with it. In your case, you're using an NSString object. If you replaced the NSString with some object that you create, say AnObjectWithAThingAndAPersonAndAPlace, you could have multiple attributes associated with each key.
---... | There are numerous ways (better than your given example) to do this. But I'll follow your example.
You are assigning an **NSString Object** to your keys.
What you can do is create a class **Thing** that contains all your attributes. and assign an instance of that class to your keys. ie.
```
[states setObject:myThing... |
51,100,224 | I've written a script in python to get different links leading to different articles from a webpage. Upon running my script I can get them flawlessly. However, the problem I'm facing is that the article links traverse multiple pages as they are of big numbers to fit within a single page. if I click on the next page but... | 2018/06/29 | [
"https://Stackoverflow.com/questions/51100224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | The content is heavily dynamic, so it would be best to use `selenium` or similar clients, but I realize that this wouldn't be practical as the number of results is so large. So, we'll have to analyse the HTTP requests submitted by the browser and simulate them with `requests`.
The contents of next page are loaded by ... | Not to treat this question as an XY problem, as, if solved, should pose a very interesting solution BUT I have found a solution for this *specific* issue that is much more efficient: Using the [NCBI's Entrez Programming Utilities](https://www.ncbi.nlm.nih.gov/books/NBK25497/) and a handy, [opensource, unofficial Entrez... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub.
It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/). | Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.
I created a G... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/)
However,
>
> Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.... | I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub.
It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/). |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/)
However,
>
> Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.... | If you need split blueprint to separate files you can use snippet:
```
# app.py
from blueprint_module import blueprint
app = Flask(__name__)
app.register_blueprint(blueprint)
```
```
# blueprint_module\__init__.py
from flask import Blueprint
blueprint = Blueprint('my_blueprint', __name__)
from . import page
``... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/)
However,
>
> Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.... | This task can be accomplished without blueprints and tricky imports using [Centralized URL Map](https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map)
**app.py**
```py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | This task can be accomplished without blueprints and tricky imports using [Centralized URL Map](https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map)
**app.py**
```py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)... | If you need split blueprint to separate files you can use snippet:
```
# app.py
from blueprint_module import blueprint
app = Flask(__name__)
app.register_blueprint(blueprint)
```
```
# blueprint_module\__init__.py
from flask import Blueprint
blueprint = Blueprint('my_blueprint', __name__)
from . import page
``... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use simple trick which is import flask app variable from main inside another file, like:
**test\_routes.py**
```
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
```
and in your main files, where you declared flask app, import test-routes, like:
**app.py**
... | Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.
I created a G... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use the usual Python package structure to divide your App into multiple modules, [see the Flask docs.](http://flask.pocoo.org/docs/patterns/packages/)
However,
>
> Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.... | You can use simple trick which is import flask app variable from main inside another file, like:
**test\_routes.py**
```
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
```
and in your main files, where you declared flask app, import test-routes, like:
**app.py**
... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use simple trick which is import flask app variable from main inside another file, like:
**test\_routes.py**
```
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
```
and in your main files, where you declared flask app, import test-routes, like:
**app.py**
... | If you need split blueprint to separate files you can use snippet:
```
# app.py
from blueprint_module import blueprint
app = Flask(__name__)
app.register_blueprint(blueprint)
```
```
# blueprint_module\__init__.py
from flask import Blueprint
blueprint = Blueprint('my_blueprint', __name__)
from . import page
``... |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use simple trick which is import flask app variable from main inside another file, like:
**test\_routes.py**
```
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
```
and in your main files, where you declared flask app, import test-routes, like:
**app.py**
... | I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub.
It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/). |
11,994,325 | My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`?
```
@app.route('/somepath')
def somehandler():
# Handler code here
```
I am concerned... | 2012/08/16 | [
"https://Stackoverflow.com/questions/11994325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | You can use simple trick which is import flask app variable from main inside another file, like:
**test\_routes.py**
```
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
```
and in your main files, where you declared flask app, import test-routes, like:
**app.py**
... | This task can be accomplished without blueprints and tricky imports using [Centralized URL Map](https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map)
**app.py**
```py
import views
from flask import Flask
app = Flask(__name__)
app.add_url_rule('/', view_func=views.index)... |
45,776,460 | What I'm trying to do is search StackOverflow for answers. I know it's probably been done before, but I'd like to do it again. With a GUI. Anyway that is a little bit down the road as right now i'm just trying to get to the page with the most votes for a question. I noticed while trying to see how to get into a nested ... | 2017/08/19 | [
"https://Stackoverflow.com/questions/45776460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/977034/"
] | Don't pass it as parameters, just add it to the URL:
```
page2 = requests.get("https://stackoverflow.com" + top)
```
Once you pass `requests` parameters it adds a `?` to the link before concatenating the new parameters to the link.
[Requests - Passing Parameters In URLs](http://docs.python-requests.org/en/master/us... | Why not use the [API](https://api.stackexchange.com/docs)?
There are plenty of search options (<https://api.stackexchange.com/docs/advanced-search>), and you get the response in JSON, no need for ugly HTML parsing. |
55,318,093 | i am learning and trying to make a snake game in Python3
i am importing turtle
i am using: Linux mint 19, PyCharm, python37, python3-tk
```
Traceback (most recent call last):
File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module>
import turtle
ModuleNotFoundError: No module named 'turtle'... | 2019/03/23 | [
"https://Stackoverflow.com/questions/55318093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10909285/"
] | I know that it's kinda old topic, but I had the same problem right now on my Fedora 31.
Reinstalling packages didn't work.
What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module.
I think that installing just `python3-tkinter` (that's how this packag... | Most probably the python your `Pycharm` is using is not `Python3.7`. Try opening a Python prompt and running import turtle, because it should be packaged into `python` already.
(<https://docs.python.org/3/library/turtle.html>) |
55,318,093 | i am learning and trying to make a snake game in Python3
i am importing turtle
i am using: Linux mint 19, PyCharm, python37, python3-tk
```
Traceback (most recent call last):
File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module>
import turtle
ModuleNotFoundError: No module named 'turtle'... | 2019/03/23 | [
"https://Stackoverflow.com/questions/55318093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10909285/"
] | I know that it's kinda old topic, but I had the same problem right now on my Fedora 31.
Reinstalling packages didn't work.
What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module.
I think that installing just `python3-tkinter` (that's how this packag... | You can't install turtle library via pip, it must be in the standart library.
`pip install turtle` installs [this 3rd party](https://pypi.org/project/turtle/) library. You can look at download file ([this](https://pypi.org/project/turtle/#files) tar.gz file) link of above library and link in the output of pip. They ar... |
55,318,093 | i am learning and trying to make a snake game in Python3
i am importing turtle
i am using: Linux mint 19, PyCharm, python37, python3-tk
```
Traceback (most recent call last):
File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module>
import turtle
ModuleNotFoundError: No module named 'turtle'... | 2019/03/23 | [
"https://Stackoverflow.com/questions/55318093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10909285/"
] | I know that it's kinda old topic, but I had the same problem right now on my Fedora 31.
Reinstalling packages didn't work.
What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module.
I think that installing just `python3-tkinter` (that's how this packag... | The screenshot of your settings shows no PythonTurtle package.
Simply click on + and find the package named "PythonTurtle" click install package. |
56,305,416 | Hi I am following this tutorial
<https://stackabuse.com/association-rule-mining-via-apriori-algorithm-in-python/>
and am getting the following error when I run the below code.
I am honestly not sure what to try as I am following the tutorial verbatim.
I don't see what the issue is.
```
#import numpy as np
#import... | 2019/05/25 | [
"https://Stackoverflow.com/questions/56305416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11554788/"
] | Your code is very similar to this one I found on medium:
<https://medium.com/@deepak.r.poojari/apriori-algorithm-in-python-recommendation-engine-5ba89bd1a6da>
I guess you wanted to do `print(len(association_results))` instead of association\_rules, as is done in the linked article? | it's a generator, and it only point's to the first block of your code list, if u want to find length , then iterate over it first and then use length ie `print(len(list(association_rules)))` |
14,669,990 | How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters?
```
t=int(input())
while t>0:
n=int(input())
s=sum(1/(2.0*i+1) for i in range(n))
print "%.15f"%s
t-=1
``` | 2013/02/03 | [
"https://Stackoverflow.com/questions/14669990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1440140/"
] | You're welcome
```
for t in range(int(input()), 0, -1): print '%.15f' % sum(1/(2.0*i+1) for i in range(int(input())))
```
**EDIT** (explanation):
Firstly, instead of a while loop you can use a [for loop](http://docs.python.org/2/reference/compound_stmts.html#for) in a [range](http://docs.python.org/2/library/functi... | `exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()`
I know I am too late for answering this question.but above code gives same result.
It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4 |
14,669,990 | How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters?
```
t=int(input())
while t>0:
n=int(input())
s=sum(1/(2.0*i+1) for i in range(n))
print "%.15f"%s
t-=1
``` | 2013/02/03 | [
"https://Stackoverflow.com/questions/14669990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1440140/"
] | ```
for _ in range(input()):print"%.15f"%sum(1/(2.0*i+1)for i in range(input()))
``` | `exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()`
I know I am too late for answering this question.but above code gives same result.
It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4 |
58,599,829 | I have a python script called "server.py" and inside it I have a function `def calcFunction(arg1): ... return output` How can I call the function calcFunction with arguments and use the return value in autohotkey? This is what I want to do in autohotkey:
```
ToSend = someString ; a string
output = Run server.py, calc... | 2019/10/28 | [
"https://Stackoverflow.com/questions/58599829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11340003/"
] | You can define a custom GHCi command using `:def` in this way:
```
> :def foo (\_ -> return "print 100\nprint 200\n:t length")
> :foo
100
200
length :: Foldable t => t a -> Int
```
In the returned string, `:`-commands can be included as well, like `:t` above. | One way I've found is creating a separate file:
```
myfunction 0 100
myfunction 0 200
myfunction 0 300
:r
```
and then using:
`:script path/to/file` |
58,599,829 | I have a python script called "server.py" and inside it I have a function `def calcFunction(arg1): ... return output` How can I call the function calcFunction with arguments and use the return value in autohotkey? This is what I want to do in autohotkey:
```
ToSend = someString ; a string
output = Run server.py, calc... | 2019/10/28 | [
"https://Stackoverflow.com/questions/58599829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11340003/"
] | You can define a custom GHCi command using `:def` in this way:
```
> :def foo (\_ -> return "print 100\nprint 200\n:t length")
> :foo
100
200
length :: Foldable t => t a -> Int
```
In the returned string, `:`-commands can be included as well, like `:t` above. | One way of doing it is to create a testing suite in your Cabal file in which you place your function calls as tests, then use `stack test --file-watch`. That recompiles and reruns the tests every time you save a file. |
58,736,009 | I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here:
<https://github.com/puckel/docker-airflow>
I am not able to get airflow to send me emails on failure or retry.
I've tried the following:
1. Editing the config file with the smtp host name
```
[smtp]
# If you want ai... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7470072/"
] | You can groupby and transform for idxmax, eg:
```
dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax')
``` | Given your example, you can use reset\_index() together with groupby and then merge it into the original dataframe:
```
import pandas as pd
data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 21],
['AAA','2019-02-01', 30], ['AAA','2019-02-02', 45],
['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60]... |
58,736,009 | I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here:
<https://github.com/puckel/docker-airflow>
I am not able to get airflow to send me emails on failure or retry.
I've tried the following:
1. Editing the config file with the smtp host name
```
[smtp]
# If you want ai... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7470072/"
] | Given your example, you can use reset\_index() together with groupby and then merge it into the original dataframe:
```
import pandas as pd
data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 21],
['AAA','2019-02-01', 30], ['AAA','2019-02-02', 45],
['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60]... | I will do `sort_values` + `drop_duplicates` + `merge`
```
df.merge(df.sort_values('VALUE').
drop_duplicates('NAME',keep='last')['NAME'].
reset_index(),on='NAME')
Out[73]:
NAME TIMESTAMP VALUE index
0 AAA 2019-01-01 10 3
1 AAA 2019-01-02 21 3
2 AAA 2019-02-01 30 ... |
58,736,009 | I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here:
<https://github.com/puckel/docker-airflow>
I am not able to get airflow to send me emails on failure or retry.
I've tried the following:
1. Editing the config file with the smtp host name
```
[smtp]
# If you want ai... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7470072/"
] | You can groupby and transform for idxmax, eg:
```
dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax')
``` | The following code solved my problem for me, thanks to @Jon and @Celius.
```
dfx.reset_index(drop=False)
dfx['MAXIDX'] = dfx.groupby('NAME')['index'].transform(max)
``` |
58,736,009 | I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here:
<https://github.com/puckel/docker-airflow>
I am not able to get airflow to send me emails on failure or retry.
I've tried the following:
1. Editing the config file with the smtp host name
```
[smtp]
# If you want ai... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7470072/"
] | You can groupby and transform for idxmax, eg:
```
dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax')
``` | I will do `sort_values` + `drop_duplicates` + `merge`
```
df.merge(df.sort_values('VALUE').
drop_duplicates('NAME',keep='last')['NAME'].
reset_index(),on='NAME')
Out[73]:
NAME TIMESTAMP VALUE index
0 AAA 2019-01-01 10 3
1 AAA 2019-01-02 21 3
2 AAA 2019-02-01 30 ... |
58,736,009 | I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here:
<https://github.com/puckel/docker-airflow>
I am not able to get airflow to send me emails on failure or retry.
I've tried the following:
1. Editing the config file with the smtp host name
```
[smtp]
# If you want ai... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7470072/"
] | The following code solved my problem for me, thanks to @Jon and @Celius.
```
dfx.reset_index(drop=False)
dfx['MAXIDX'] = dfx.groupby('NAME')['index'].transform(max)
``` | I will do `sort_values` + `drop_duplicates` + `merge`
```
df.merge(df.sort_values('VALUE').
drop_duplicates('NAME',keep='last')['NAME'].
reset_index(),on='NAME')
Out[73]:
NAME TIMESTAMP VALUE index
0 AAA 2019-01-01 10 3
1 AAA 2019-01-02 21 3
2 AAA 2019-02-01 30 ... |
44,424,308 | C++ part
I have a class `a` with a **public** variable 2d int array `b` that I want to print out in python.(The way I want to access it is `a.b`)
I have been able to wrap the most part of the code and I can call most of the functions in class a in python now.
So how can I read b in python? How to read it into an nump... | 2017/06/07 | [
"https://Stackoverflow.com/questions/44424308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7967265/"
] | There's some relevant information in the Fetch specification.
As per <https://fetch.spec.whatwg.org/#forbidden-response-header-name>:
>
> A forbidden response-header name is a header name that is a
> byte-case-insensitive match for one of:
>
>
> * `Set-Cookie`
> * `Set-Cookie2`
>
>
>
And then as per item 6 in... | You may try following:
```
async function handleRequest(request) {
let response = await fetch(request.url, request);
// Copy the response so that we can modify headers.
response = new Response(response.body, response)
response.headers.set("Set-Cookie", "test=1234");
return response;
}
``` |
38,722,340 | Let's consider the code below
code:
```
#!/usr/bin/env python
class Foo():
def __init__(self, b):
self.a = 0.0
self.b = b
def count_a(self):
self.a += 0.1
foo = Foo(1)
for i in range(0, 15):
foo.count_a()
print "a =", foo.a, "b =", foo.b, '"a == b" ->', foo.a == foo.b
```
O... | 2016/08/02 | [
"https://Stackoverflow.com/questions/38722340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/829496/"
] | This has nothing to do with Object Orientation - it has to do with the way computers represent floating point numbers internally, and rounding errors.
<http://floating-point-gui.de/basic/>
The Python specificity here is the default string representation of floating point numbers, which will round them at less decimal ... | Aside from the, correct, explanation by jsbueno, remember that Python often allows casting of "basic types" to themselves.
i.e. str("a") == "a"
So, if you need a workaround in addition to the reason, just convert your int/float mix to all floats and test those.
```
a = 2.0
b = 2
print "a == b", float(a) == float(... |
58,721,480 | I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/m... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58721480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11757353/"
] | As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**.
If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**contain... | wrap your row class div inside of a container or container-fluid class div
```html
<div class='container'>
<div class='row'>
<!--your grid-->
</div>
</div>
``` |
58,721,480 | I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/m... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58721480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11757353/"
] | As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**.
If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**contain... | Try add .container OR .container-fluid class in parent div in your HTML.
```
<div class="container">
<div class="row" id="navcols">
<div class="col">
<div class="row h-50">Row</div>
<div class="row h-50">Row</div>
</div>
<div class="col-sm-6">
<div class="row h-100">Row</div>
... |
58,721,480 | I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/m... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58721480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11757353/"
] | As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**.
If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**contain... | Your Bootstrap class contains -15px margin from left and right; that's why it is cutting your screen. So, you can fix it by making it 0.
```
<div class="row" id="navcols" style="margin-left:0; margin-right:0;">
<div class="col">
<div class="row h-50">Row</div>
<div class="row h-50">Row</div>
... |
5,159,351 | urllib fetches data from urls right? is there a python library that can do the reverse of that and send data to urls instead (for example, to a site you are managing)? and if so, is that library compatible with apache?
thanks. | 2011/03/01 | [
"https://Stackoverflow.com/questions/5159351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/582485/"
] | What does sending data to a URL mean? The usual way to do that is just via an HTTP POST, and `urllib` (and `urllib2`) handle that just fine. | urllib can send data associated with a request by using GET or POST.
`urllib2.urlopen(url, data)` where data is a dict of key-values representing the data you're sending. See [this link on usage](http://www.java2s.com/Code/Python/Network/SubmitPOSTData.htm).
Then process that data on the server-side.
If you want to ... |
63,894,354 | i'm very much a newbie to python. I've read a csv file correctly, and if i do a print(row[0]) in a for loop it prints the first column. But now within the loop, i'd like to do a conditional. Obviously using row[0] in it doesn't work. what's the correct syntax?
here's my code
```
video_choice = input("What movie would ... | 2020/09/15 | [
"https://Stackoverflow.com/questions/63894354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8628471/"
] | you could do
```
if video_choice in row[0]:
...
``` | nvm, I have the if as "If". I'm def a newb |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | Don't know how efficient, but why not use an xrange as a mask and use set minus?
```
>>> myList = [1,14,2,5,3,7,8,12]
>>> min(set(xrange(1, len(myList) + 1)) - set(myList))
4
```
You're only creating a set as big as `myList`, so it can't be that bad :)
This won't work for "full" lists:
```
>>> myList = range(1, 5)... | I just solved this in a probably non pythonic way
```
def solution(A):
# Const-ish to improve readability
MIN = 1
if not A: return MIN
# Save re-computing MAX
MAX = max(A)
# Loop over all entries with minimum of 1 starting at 1
for num in range(1, MAX):
# going for greatest missing ... |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | you can try this
```
for i in range(1,max(arr1)+2):
if i not in arr1:
print(i)
break
``` | Keep incrementing a counter in a loop until you find the first positive integer that's not in the list.
```
def getSmallestIntNotInList(number_list):
"""Returns the smallest positive integer that is not in a given list"""
i = 0
while True:
i += 1
if i not in number_list:
return ... |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | I just solved this in a probably non pythonic way
```
def solution(A):
# Const-ish to improve readability
MIN = 1
if not A: return MIN
# Save re-computing MAX
MAX = max(A)
# Loop over all entries with minimum of 1 starting at 1
for num in range(1, MAX):
# going for greatest missing ... | you can try this
```
for i in range(1,max(arr1)+2):
if i not in arr1:
print(i)
break
``` |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | A for loop with the list will do it.
```
l = [1,14,2,5,3,7,8,12]
for i in range(1, max(l)):
if i not in l: break
print(i) # result 4
``` | My effort, no itertools. Sets "current" to be the one less than the value you are expecting.
```
list = [1,2,3,4,5,7,8]
current = list[0]-1
for i in list:
if i != current+1:
print current+1
break
current = i
``` |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | I would suggest you to use a generator and use enumerate to determine the missing element
```
>>> next(a for a, b in enumerate(myList, myList[0]) if a != b)
4
```
[enumerate](https://docs.python.org/2/library/functions.html#enumerate) maps the index with the element so your goal is to determine that element which di... | A solution that returns all those values is
```
free_values = set(range(1, max(L))) - set(L)
```
it does a full scan, but those loops are implemented in C and unless the list or its maximum value are huge this will be a win over more sophisticated algorithms performing the looping in Python.
Note that if this searc... |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | A for loop with the list will do it.
```
l = [1,14,2,5,3,7,8,12]
for i in range(1, max(l)):
if i not in l: break
print(i) # result 4
``` | Easy to read, easy to understand, gets the job done:
```
def solution(A):
smallest = 1
unique = set(A)
for int in unique:
if int == smallest:
smallest += 1
return smallest
``` |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | Easy to read, easy to understand, gets the job done:
```
def solution(A):
smallest = 1
unique = set(A)
for int in unique:
if int == smallest:
smallest += 1
return smallest
``` | Keep incrementing a counter in a loop until you find the first positive integer that's not in the list.
```
def getSmallestIntNotInList(number_list):
"""Returns the smallest positive integer that is not in a given list"""
i = 0
while True:
i += 1
if i not in number_list:
return ... |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | This makes use of the property of sets
```
>>> l = [1,2,3,5,7,8,12,14]
>>> m = range(1,len(l))
>>> min(set(m)-set(l))
4
``` | The naive way is to traverse the list which is an O(n) solution. However, since the list is sorted, you can use this feature to perform binary search (a modified version for it). Basically, you are looking for the last occurance of A[i] = i.
The pseudo algorithm will be something like:
```
binarysearch(A):
start = ... |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | I just solved this in a probably non pythonic way
```
def solution(A):
# Const-ish to improve readability
MIN = 1
if not A: return MIN
# Save re-computing MAX
MAX = max(A)
# Loop over all entries with minimum of 1 starting at 1
for num in range(1, MAX):
# going for greatest missing ... | The following solution loops all numbers in between 1 and the length of the input list and breaks the loop whenever a number is not found inside it. Otherwise the result is the length of the list plus one.
```
listOfNumbers=[1,14,2,5,3,7,8,12]
for i in range(1, len(listOfNumbers)+1):
if not i in listOfNumbers:
... |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | The naive way is to traverse the list which is an O(n) solution. However, since the list is sorted, you can use this feature to perform binary search (a modified version for it). Basically, you are looking for the last occurance of A[i] = i.
The pseudo algorithm will be something like:
```
binarysearch(A):
start = ... | Keep incrementing a counter in a loop until you find the first positive integer that's not in the list.
```
def getSmallestIntNotInList(number_list):
"""Returns the smallest positive integer that is not in a given list"""
i = 0
while True:
i += 1
if i not in number_list:
return ... |
8,616,617 | I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code:
```
import logging
import logging.handlers
import time
gm = logging.handlers.SMTPHandler(("localhost", 25), 'in... | 2011/12/23 | [
"https://Stackoverflow.com/questions/8616617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | The simplest form of asynchronous smtp handler for me is just to override `emit` method and use the original method in a new thread. GIL is not a problem in this case because there is an I/O call to SMTP server which releases GIL. The code is as follows
```
class ThreadedSMTPHandler(SMTPHandler):
def emit(self, re... | Here's the implementation I'm using, which I based on Jonathan Livni code.
```
import logging.handlers
import smtplib
from threading import Thread
# File with my configuration
import credentials as cr
host = cr.set_logSMTP["host"]
port = cr.set_logSMTP["port"]
user = cr.set_logSMTP["user"]
pwd = cr.set_logSMTP["pwd"... |
8,616,617 | I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code:
```
import logging
import logging.handlers
import time
gm = logging.handlers.SMTPHandler(("localhost", 25), 'in... | 2011/12/23 | [
"https://Stackoverflow.com/questions/8616617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | Here's the implementation I'm using, which I based on [this Gmail adapted SMTPHandler](http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt).
I took the part that sends to SMTP and placed it in a different thread.
```
import logging.handlers
import smtplib
from threadi... | Most probably you need to write your own logging handler that would do the sending of the email in the background. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.