prefix
stringclasses
1 value
input_text
stringlengths
10
172
target_text
stringlengths
18
33.9k
QA:
A column-vector y was passed when a 1d array was expected
<p>use below code:</p> <pre><code>model = forest.fit(train_fold, train_y.ravel()) </code></pre> <p>if you are still getting slap by error as identical as below ?</p> <pre><code>Unknown label type: %r" % y </code></pre> <p>use this code:</p> <pre><code>y = train_y.ravel() train_y = np.array(y).astype(int) model = forest.fit(train_fold, train_y) </code></pre>
QA:
Scrape Yahoo Finance Financial Ratios
<p>You can actually get the data is json format, there is a call to an api that returns a lot of the data including the current ratio:</p> <p><a href="https://i.stack.imgur.com/Zu7sP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Zu7sP.png" alt="enter image description here"></a></p> <pre><code>import requests params = {"formatted": "true", "crumb": "AKV/cl0TOgz", # works without so not sure of significance "lang": "en-US", "region": "US", "modules": "defaultKeyStatistics,financialData,calendarEvents", "corsDomain": "finance.yahoo.com"} r = requests.get("https://query1.finance.yahoo.com/v10/finance/quoteSummary/GSB", params=params) data = r.json()[u'quoteSummary']["result"][0] </code></pre> <p>That gives you a dict with numerous pieces of data:</p> <pre><code>from pprint import pprint as pp pp(data) {u'calendarEvents': {u'dividendDate': {u'fmt': u'2016-09-08', u'raw': 1473292800}, u'earnings': {u'earningsAverage': {}, u'earningsDate': [{u'fmt': u'2016-10-27', u'raw': 1477526400}], u'earningsHigh': {}, u'earningsLow': {}, u'revenueAverage': {u'fmt': u'8.72M', u'longFmt': u'8,720,000', u'raw': 8720000}, u'revenueHigh': {u'fmt': u'8.72M', u'longFmt': u'8,720,000', u'raw': 8720000}, u'revenueLow': {u'fmt': u'8.72M', u'longFmt': u'8,720,000', u'raw': 8720000}}, u'exDividendDate': {u'fmt': u'2016-05-19', u'raw': 1463616000}, u'maxAge': 1}, u'defaultKeyStatistics': {u'52WeekChange': {u'fmt': u'3.35%', u'raw': 0.033536673}, u'SandP52WeekChange': {u'fmt': u'5.21%', u'raw': 0.052093267}, u'annualHoldingsTurnover': {}, u'annualReportExpenseRatio': {}, u'beta': {u'fmt': u'0.23', u'raw': 0.234153}, u'beta3Year': {}, u'bookValue': {u'fmt': u'1.29', u'raw': 1.295}, u'category': None, u'earningsQuarterlyGrowth': {u'fmt': u'-28.00%', u'raw': -0.28}, u'enterpriseToEbitda': {u'fmt': u'9.22', u'raw': 9.215}, u'enterpriseToRevenue': {u'fmt': u'1.60', u'raw': 1.596}, u'enterpriseValue': {u'fmt': u'50.69M', u'longFmt': u'50,690,408', u'raw': 50690408}, u'fiveYearAverageReturn': {}, u'floatShares': {u'fmt': u'11.63M', u'longFmt': u'11,628,487', u'raw': 11628487}, u'forwardEps': {u'fmt': u'0.29', u'raw': 0.29}, u'forwardPE': {}, u'fundFamily': None, u'fundInceptionDate': {}, u'heldPercentInsiders': {u'fmt': u'36.12%', u'raw': 0.36116}, u'heldPercentInstitutions': {u'fmt': u'21.70%', u'raw': 0.21700001}, u'lastCapGain': {}, u'lastDividendValue': {}, u'lastFiscalYearEnd': {u'fmt': u'2015-12-31', u'raw': 1451520000}, u'lastSplitDate': {}, u'lastSplitFactor': None, u'legalType': None, u'maxAge': 1, u'morningStarOverallRating': {}, u'morningStarRiskRating': {}, u'mostRecentQuarter': {u'fmt': u'2016-06-30', u'raw': 1467244800}, u'netIncomeToCommon': {u'fmt': u'3.82M', u'longFmt': u'3,819,000', u'raw': 3819000}, u'nextFiscalYearEnd': {u'fmt': u'2017-12-31', u'raw': 1514678400}, u'pegRatio': {}, u'priceToBook': {u'fmt': u'2.64', u'raw': 2.6358302}, u'priceToSalesTrailing12Months': {}, u'profitMargins': {u'fmt': u'12.02%', u'raw': 0.12023}, u'revenueQuarterlyGrowth': {}, u'sharesOutstanding': {u'fmt': u'21.18M', u'longFmt': u'21,184,300', u'raw': 21184300}, u'sharesShort': {u'fmt': u'27.06k', u'longFmt': u'27,057', u'raw': 27057}, u'sharesShortPriorMonth': {u'fmt': u'36.35k', u'longFmt': u'36,352', u'raw': 36352}, u'shortPercentOfFloat': {u'fmt': u'0.20%', u'raw': 0.001977}, u'shortRatio': {u'fmt': u'0.81', u'raw': 0.81}, u'threeYearAverageReturn': {}, u'totalAssets': {}, u'trailingEps': {u'fmt': u'0.18', u'raw': 0.18}, u'yield': {}, u'ytdReturn': {}}, u'financialData': {u'currentPrice': {u'fmt': u'3.41', u'raw': 3.4134}, u'currentRatio': {u'fmt': u'1.97', u'raw': 1.974}, u'debtToEquity': {}, u'earningsGrowth': {u'fmt': u'-33.30%', u'raw': -0.333}, u'ebitda': {u'fmt': u'5.5M', u'longFmt': u'5,501,000', u'raw': 5501000}, u'ebitdaMargins': {u'fmt': u'17.32%', u'raw': 0.17318001}, u'freeCashflow': {u'fmt': u'4.06M', u'longFmt': u'4,062,250', u'raw': 4062250}, u'grossMargins': {u'fmt': u'79.29%', u'raw': 0.79288}, u'grossProfits': {u'fmt': u'25.17M', u'longFmt': u'25,172,000', u'raw': 25172000}, u'maxAge': 86400, u'numberOfAnalystOpinions': {}, u'operatingCashflow': {u'fmt': u'6.85M', u'longFmt': u'6,853,000', u'raw': 6853000}, u'operatingMargins': {u'fmt': u'16.47%', u'raw': 0.16465001}, u'profitMargins': {u'fmt': u'12.02%', u'raw': 0.12023}, u'quickRatio': {u'fmt': u'1.92', u'raw': 1.917}, u'recommendationKey': u'strong_buy', u'recommendationMean': {u'fmt': u'1.00', u'raw': 1.0}, u'returnOnAssets': {u'fmt': u'7.79%', u'raw': 0.07793}, u'returnOnEquity': {u'fmt': u'15.05%', u'raw': 0.15054}, u'revenueGrowth': {u'fmt': u'5.00%', u'raw': 0.05}, u'revenuePerShare': {u'fmt': u'1.51', u'raw': 1.513}, u'targetHighPrice': {}, u'targetLowPrice': {}, u'targetMeanPrice': {}, u'targetMedianPrice': {}, u'totalCash': {u'fmt': u'20.28M', u'longFmt': u'20,277,000', u'raw': 20277000}, u'totalCashPerShare': {u'fmt': u'0.96', u'raw': 0.957}, u'totalDebt': {u'fmt': None, u'longFmt': u'0', u'raw': 0}, u'totalRevenue': {u'fmt': u'31.76M', u'longFmt': u'31,764,000', u'raw': 31764000}}} </code></pre> <p>What you want is in <code>data[u'financialData']</code>:</p> <pre><code> pp(data[u'financialData']) {u'currentPrice': {u'fmt': u'3.41', u'raw': 3.4134}, u'currentRatio': {u'fmt': u'1.97', u'raw': 1.974}, u'debtToEquity': {}, u'earningsGrowth': {u'fmt': u'-33.30%', u'raw': -0.333}, u'ebitda': {u'fmt': u'5.5M', u'longFmt': u'5,501,000', u'raw': 5501000}, u'ebitdaMargins': {u'fmt': u'17.32%', u'raw': 0.17318001}, u'freeCashflow': {u'fmt': u'4.06M', u'longFmt': u'4,062,250', u'raw': 4062250}, u'grossMargins': {u'fmt': u'79.29%', u'raw': 0.79288}, u'grossProfits': {u'fmt': u'25.17M', u'longFmt': u'25,172,000', u'raw': 25172000}, u'maxAge': 86400, u'numberOfAnalystOpinions': {}, u'operatingCashflow': {u'fmt': u'6.85M', u'longFmt': u'6,853,000', u'raw': 6853000}, u'operatingMargins': {u'fmt': u'16.47%', u'raw': 0.16465001}, u'profitMargins': {u'fmt': u'12.02%', u'raw': 0.12023}, u'quickRatio': {u'fmt': u'1.92', u'raw': 1.917}, u'recommendationKey': u'strong_buy', u'recommendationMean': {u'fmt': u'1.00', u'raw': 1.0}, u'returnOnAssets': {u'fmt': u'7.79%', u'raw': 0.07793}, u'returnOnEquity': {u'fmt': u'15.05%', u'raw': 0.15054}, u'revenueGrowth': {u'fmt': u'5.00%', u'raw': 0.05}, u'revenuePerShare': {u'fmt': u'1.51', u'raw': 1.513}, u'targetHighPrice': {}, u'targetLowPrice': {}, u'targetMeanPrice': {}, u'targetMedianPrice': {}, u'totalCash': {u'fmt': u'20.28M', u'longFmt': u'20,277,000', u'raw': 20277000}, u'totalCashPerShare': {u'fmt': u'0.96', u'raw': 0.957}, u'totalDebt': {u'fmt': None, u'longFmt': u'0', u'raw': 0}, u'totalRevenue': {u'fmt': u'31.76M', u'longFmt': u'31,764,000', u'raw': 31764000}} </code></pre> <p>You can see <code>u'currentRatio'</code> in there, the fmt is the formatted output you see on the site, formatted to two decimal places. So to get the 1.97:</p> <pre><code>In [5]: import requests ...: data = {"formatted": "true", ...: "crumb": "AKV/cl0TOgz", ...: "lang": "en-US", ...: "region": "US", ...: "modules": "defaultKeyStatistics,financialData,calendarEvents", ...: "corsDomain": "finance.yahoo.com"} ...: r = requests.get("https://query1.finance.yahoo.com/v10/finance/quoteSumm ...: ary/GSB", params=data) ...: data = r.json()[u'quoteSummary']["result"][0][u'financialData'] ...: ratio = data[u'currentRatio'] ...: print(ratio) ...: print(ratio["fmt"]) ...: {'raw': 1.974, 'fmt': '1.97'} 1.97 </code></pre> <p>The equivalent code using <em>urllib</em>:</p> <pre><code>In [1]: import urllib ...: from urllib import urlencode ...: from json import load ...: ...: ...: data = {"formatted": "true", ...: "crumb": "AKV/cl0TOgz", ...: "lang": "en-US", ...: "region": "US", ...: "modules": "defaultKeyStatistics,financialData,calendarEvents", ...: "corsDomain": "finance.yahoo.com"} ...: url = "https://query1.finance.yahoo.com/v10/finance/quoteSummary/GSB" ...: r = urllib.urlopen(url, data=urlencode(data)) ...: data = load(r)[u'quoteSummary']["result"][0][u'financialData'] ...: ratio = data[u'currentRatio'] ...: print(ratio) ...: print(ratio["fmt"]) ...: {u'raw': 1.974, u'fmt': u'1.97'} 1.97 </code></pre> <p>It works fine for APPL also:</p> <pre><code>In [1]: import urllib ...: from urllib import urlencode ...: from json import load ...: data = {"formatted": "true", ...: "lang": "en-US", ...: "region": "US", ...: "modules": "defaultKeyStatistics,financialData,calendarEvents", ...: "corsDomain": "finance.yahoo.com"} ...: url = "https://query1.finance.yahoo.com/v10/finance/quoteSummary/AAPL" ...: r = urllib.urlopen(url, data=urlencode(data)) ...: data = load(r)[u'quoteSummary']["result"][0][u'financialData'] ...: ratio = data[u'currentRatio'] ...: print(ratio) ...: print(ratio["fmt"]) ...: {u'raw': 1.312, u'fmt': u'1.31'} 1.31 </code></pre> <p>Adding the crumb parameters seems to have no effect, if you need to get it at a later date:</p> <pre><code>soup = BeautifulSoup(urllib.urlopen("http://finance.yahoo.com/quote/GSB/key-statistics?p=GSB").read()) script = soup.find("script", text=re.compile("root.App.main")).text data = loads(re.search("root.App.main\s+=\s+(\{.*\})", script).group(1)) print(data["context"]["dispatcher"]["stores"]["CrumbStore"]["crumb"]) </code></pre>
QA:
Try and Except (TypeError)
<p>You are confused about what <code>try/except</code> does. <code>try/except</code> is used when an error is likely to be raised. No error will be raised because everything in your program is valid. Errors are raised only when there is an execution error in your code. Errors are not just raised when you need them to be.</p> <p><em>You</em>, however, want an error to be shown if the user does not enter a valid choice. You need to use an <code>if/else</code> logic instead, and print the error out yourself. And as a side note, the line <code>choice == "v" and "g"</code> does not test if choice is equal to <code>'v'</code> or <code>'g'</code>. It test if choice i equal to v and if the string <code>'g'</code> is "truthy". Your estenially saying</p> <p><code>if variable = value and True</code></p> <p>I'm pretty sure that is not what you want. Here is how I would re-write your code.</p> <pre><code>if choice.lower() in {"v", "g"}: # if choice is 'v' or 'g' # do stuff else: # otherwise print("Not a valid choice! Try again") # print a custom error message. </code></pre>
QA:
Try and Except (TypeError)
<p>The problem is not in your <code>try</code> and <code>except</code> but in the fact that you are using <code>try</code> and <code>except</code> at all. The code in your <code>try</code> block won't give you an error so <code>except</code> will never be triggered. You want to use an <code>if</code> statement.</p> <p>Also, your condition only checks for <code>choice == "v"</code> because it is evaluated as <code>(choice == "v") and "g"</code>, and <code>"g"</code> is a string not of length 0, so is always "truthy" (taken as true in a Boolean context). Anything <code>and</code> True is unchanged, so only the first test has any meaning. The best way to do this test is with <code>in</code>.</p> <p>Finally, you can and should use a <code>while</code> loop to repeat the prompt until the user enters a valid entry.</p> <p>Putting it all together, you want something like this:</p> <pre><code>prompt = "Enter v for validate, or g for generate &gt;" choice = input(prompt).strip().lower()[:1] # take at most 1 character while choice not in ("v", "g"): print("Not a valid choice! Try again.") choice = input(prompt).strip().lower()[:1] </code></pre> <p>If you think of how you might generalize the code to use it again (as you probably will in the rest of your script), it's easy and useful to do so. First, you can break out the <code>input</code> stuff into a separate function, since it's called twice:</p> <pre><code>def input1char(prompt): return input(prompt + " &gt;").strip().lower()[:1] </code></pre> <p>And then break out the while loop into its own function too:</p> <pre><code>def validinput(prompt, options): letters = tuple(options) choice = input1char(prompt) while choice not in options: print("'%s' is not a valid choice! Try again." % choice) choice = input1char(prompt) return choice </code></pre> <p>And then you just write:</p> <pre><code> choice = validinput("Enter v for validate, or g for generate", "vg") </code></pre>
QA:
if-else in python list comprehensions
<p>You can only construct one list at a time with list comprehension. You'll want something like:</p> <pre><code>nums = [foo for foo in mixed_list if foo.isdigit()] strings = [foo for foo in mixed_list if not foo.isdigit()] </code></pre>
QA:
if-else in python list comprehensions
<p>It's not possible as-is, but if you're looking for one-liners you can do that with a ternary expression inside your loop (saves a test and is compact):</p> <pre><code>num_list=[] string_list=[] for s in ["45","hello","56","foo"]: (num_list if s.isdigit() else string_list).append(s) print(num_list,string_list) </code></pre> <p>result:</p> <pre><code>['45', '56'] ['hello', 'foo'] </code></pre> <p>Notes:</p> <ul> <li>despite the parenthesized syntax and the context of the question, <code>(num_list if s.isdigit() else string_list)</code> is not a generator, a ternary expression (protected between parentheses to counter <code>.append</code> precedence) which returns <code>num_list</code> if s is a sequence of (positive) digits and <code>string_list</code> if s otherwise.</li> <li>this code won't work with negative numbers because <code>isdigits</code> will return false. You'll have to code a special function for that (classical problem here on SO)</li> </ul>
QA:
Pylatex error when generate PDF file - No such file or directory
<p>Based on the code around the error, you're probably missing a latex compiler:</p> <pre><code>compilers = ( ('latexmk', latexmk_args), ('pdflatex', []) ) </code></pre> <p>Try doing this:</p> <pre><code>apt-get install latexmk </code></pre>
QA:
if-else in python list comprehensions
<p>You can accomplish what you want with two list comprehensions:</p> <pre><code>num_list = [num for num in mixed_content if num.isdigit()] string_list = [string for string in mixed_content if not string.isdigit()] </code></pre> <p>The else clause is not supported in list comprehensions:</p> <pre><code>&gt;&gt;&gt; [c for c in range(5) if c == 1 else 0] SyntaxError: invalid syntax </code></pre>
QA:
Python Print %s
<p>You must pass a tuple when using <code>%</code>:</p> <pre><code># notice how package is wrapped in () print ("Your package is: %s" % (package)) # and do the same when you call os.system() os.system ("adb -d backup %s" % (package)) </code></pre>
QA:
if-else in python list comprehensions
<p>A super messy and unpractical way of doing is:</p> <pre><code>mixed_content = ['a','b','c',"4"] string_list = [] print [y for y in [x if mixed_content[x].isdigit() else string_list.append(mixed_content[x]) for x in range(0,len(mixed_content))] if y != None] print string_list </code></pre> <p>Returns: </p> <pre><code>[3] ['a', 'b', 'c'] </code></pre> <p>Basically list comprehension for your condition and then filter that list comprehension to only accept non <code>None</code></p>
QA:
if-else in python list comprehensions
<p>Let's initialize variables:</p> <pre><code>&gt;&gt;&gt; mixed_content='ab42c1'; num_list=[]; string_list=[] </code></pre> <p>Let's create the lists that you want with a single list comprehension:</p> <pre><code>&gt;&gt;&gt; [num_list.append(c) if c.isdigit() else string_list.append(c) for c in mixed_content] [None, None, None, None, None, None] </code></pre> <p>Let's verify that we have the lists that you want:</p> <pre><code>&gt;&gt;&gt; num_list, string_list (['4', '2', '1'], ['a', 'b', 'c']) </code></pre>
QA:
if-else in python list comprehensions
<p>Here is an example of using <code>x if b else y</code> in a list comprehension.</p> <pre><code>mixed_content = "y16m10" num_list, string_list = zip( *[(ch, None) if ch.isdigit() else (None, ch) for ch in mixed_content]) num_list = filter(None, num_list) string_list = filter(None, string_list) print num_list, string_list </code></pre>
QA:
Can I use PyQt for both C++ and Python?
<p>PyQt5 is for developing with Python.</p> <p>If you want to code in C++ the best you do is to download Qt5 and code inside QtCreator.</p> <p>Here is a link for <a href="https://www.qt.io/download-open-source/" rel="nofollow">Qt5 Opensource</a></p>
QA:
Calc value count in few columns of DataFrame (Pandas Python)
<p>Consider merging pivot_tables using the aggfunc <em>len</em> for counts.</p> <pre><code>from io import StringIO import pandas as pd data = ''' id code_1 code_2 11 1451 ffx 15 2233 ffx 24 1451 mmg 15 1451 ffx''' df = pd.read_table(StringIO(data), sep="\s+") df = pd.merge(df[['id', 'code_1']].pivot_table(index='id', columns='code_1', aggfunc=len).\ reset_index(drop=True), df[['id', 'code_2']].pivot_table(index='id', columns='code_2', aggfunc=len).\ reset_index(drop=True), left_index=True, right_index=True).fillna(0) # 1451 2233 ffx mmg # 0 1.0 0.0 1.0 0.0 # 1 1.0 1.0 2.0 0.0 # 2 1.0 0.0 0.0 1.0 </code></pre>
QA:
POST XML file with requests
<p>You want to give the XML data from a file to <code>requests.post</code>. But, this function will not open a file for you. It expects you to pass a file object to it, not a file name. You need to open the file before you call requests.post.</p> <p>Try this:</p> <pre><code>import requests # Set the name of the XML file. xml_file = "xxx.xml" headers = {'Content-Type':'text/xml'} # Open the XML file. with open(xml_file) as xml: # Give the object representing the XML file to requests.post. r = requests.post('https://example.com/serverxml.asp', data=xml) print (r.content); </code></pre>
QA:
language file dosen't load automaticaly in Django
<p>I have a similar working setup, the main difference seems to be that I'm using <code>ugettext_lazy</code>. That's because I need to translate these strings in my models or settings when they were accessed, rather than when they were called (which would happen only once: they would only be evaluated on server startup and would not recognize any further changes; e.g. switching the Django admin language). </p> <p>Reference: <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#lazy-translation" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#lazy-translation</a></p> <p>That's what I use (in this special case, german is the default language and I'm translating into english): </p> <h3>project/urls.py</h3> <pre><code>from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), ) </code></pre> <h3>project/settings.py</h3> <pre><code>from django.utils.translation import ugettext_lazy as _ MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'de-de' USE_I18N = True USE_L10N = True LANGUAGES = [ ('de', _('German')), ('en', _('English')), ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] </code></pre> <h3>app/models.py</h3> <pre><code>from django.utils.translation import ugettext_lazy as _ class Kindergarten(models.Model): stadt = models.CharField(verbose_name=_(Stadt)) class Meta: verbose_name = _('Kindergarten') verbose_name_plural = _('Kindergärten') </code></pre> <h3>Workflow</h3> <pre><code>$ python manage.py makemessages --locale en ... edit project/locale/en/LC_MESSAGES/django.po ... $ python manage.py compilemessages </code></pre> <p>Now I can access my translate Django admin (interface + models) via: </p> <ul> <li><a href="http://127.0.0.1:8000/de/admin/app/kindergarten/" rel="nofollow">http://127.0.0.1:8000/de/admin/app/kindergarten/</a></li> <li><a href="http://127.0.0.1:8000/en/admin/app/kindergarten/" rel="nofollow">http://127.0.0.1:8000/en/admin/app/kindergarten/</a></li> </ul> <h3>Notes</h3> <ul> <li>Pyhton 3.5.2</li> <li>Django 1.10.2</li> </ul>
QA:
How to add a timeout to a function in Python
<p>The <a href="https://pypi.python.org/pypi/Pebble" rel="nofollow">Pebble</a> library was designed to offer cross-platform implementation capable of dealing with problematic logic which could <a href="http://pythonhosted.org/Pebble/#concurrent-functions" rel="nofollow">crash, segfault or run indefinitely</a>. </p> <p>Decorator example:</p> <pre><code>from pebble import process @process.concurrent(timeout=5) def unstable_function(arg, kwarg=None): return task = unstable_function(1, kwarg=2) try: results = task.get() except TimeoutError: print("unstable_function took more than 5 seconds to complete") except ProcessExpired as error: print("%s. Exit code: %d" % (error, error.exitcode)) except Exception as error: print("unstable_function raised %s" % error) print(error.traceback) # Python's traceback of remote process </code></pre> <p>The decorator works as well with static and class methods. I would not recommend to decorate methods nevertheless as it's a quite error prone practice.</p>
QA:
Matplotlib: Sharing axes when having 3 graphs 2 at the left and 1 at the right
<p>Just use <code>plt.subplots</code> (different from <code>plt.subplot</code>) to define all your axes, with the option <code>sharex=True</code>:</p> <pre><code>f, axes = plt.subplots(2,2, sharex=True) plt.subplot(122) plt.show() </code></pre> <p>Note that the second call with larger subplot array overlay the preceding one.</p> <p><a href="https://i.stack.imgur.com/Y6SWD.png" rel="nofollow">Example</a> (could not display image due to reputation...)</p>
QA:
Scrape Yahoo Finance Financial Ratios
<p>One thing I'd add to Padriac's answer is to except KeyErrors, since you'll probably be scraping more than one ticker. </p> <pre><code>import requests a = requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/GSB?formatted=true&amp;crumb=A7e5%2FXKKAFa&amp;lang=en-US&amp;region=US&amp;modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&amp;corsDomain=finance.yahoo.com') b = a.json() try: ratio = b['quoteSummary']['result'][0]['financialData']['currentRatio']['raw'] print(ratio) #prints 1.974 except (IndexError, KeyError): pass </code></pre> <p>A cool thing about doing it like this is that you can easily change the keys for the information you want. A good way to see the way the dictionary is nested on the Yahoo! Finance pages is to use <code>pprint</code>. Furthermore, for the pages that have quarterly information just change <code>[0]</code> to <code>[1]</code> to get the info for the second quarter instead of the first.. and so on and so forth. </p>
QA:
Semi-supervised learning for regression by scikit-learn
<p>It looks like the error in the documentation, code itself clearly is classification only (beggining of the <code>.fit</code> call of the <a href="https://github.com/scikit-learn/scikit-learn/blob/412996f/sklearn/semi_supervised/label_propagation.py#L201" rel="nofollow">BasePropagation class</a>):</p> <pre><code> check_classification_targets(y) # actual graph construction (implementations should override this) graph_matrix = self._build_graph() # label construction # construct a categorical distribution for classification only classes = np.unique(y) classes = (classes[classes != -1]) </code></pre> <p>In theory you could remove the "check_classification_targets" call and use "regression like method", but it will not be the true regression since you will never "propagate" any value which is not encountered in the training set, you will simply treat the regression value as the class identifier. And you will be unable to use value "-1" since it is a codename for "unlabeled"...</p>
QA:
Print random line from txt file?
<p>You want to use <code>random.choice</code></p> <pre><code>import random with open(filename) as f: lines = f.readlines() print(random.choice(lines)) </code></pre>
QA:
Python - Making text files
<p>You have to add the <code>.txt</code> afther the filename. Also be sure that the file is in the same folder of the <code>.py</code> file. Pay attention to caps and spaces.</p> <p><code>pythonfile = open("User details.txt","w")</code></p> <p>If this does'nt work, try adding <code>os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))</code> afther the import, for me it fixed the problem.</p> <p>For the "spacing problem" try:</p> <p><code>pythonfile.write(name, '\n', postcode, '\n', dob)</code></p> <p>Also, when you create a alias for Tkinter use tk, and when you open a file try naming it file_it, or f_in, so it's more readable for other people ... When naming files don't use spaces, it's just going to make everything harder, try naming it like this: <code>userDetails.txt</code> or <code>user_details.txt</code></p>
QA:
Report progress to QProgressBar using variable from an imported module
<p>Make the <code>process_files</code> function a generator function that <em>yields</em> a value (the progress value) and pass it as a callback to a method in your <code>Window</code> class that updates the progress bar value. I have added a <code>time.sleep</code> call in your function so you can observe the progress:</p> <pre><code>import time from worker import process_files class Window(QtGui.QMainWindow): def __init__(self): ... def observe_process(self, func=None): try: for prog in func(): self.progress.setValue(prog) except TypeError: print('callback function must be a generator function that yields integer values') raise app = QtGui.QApplication(sys.argv) GUI = Window() # process files and report progress using .setValue(percent) GUI.observe_process(process_files) sys.exit(app.exec_()) </code></pre> <p><strong>worker.py</strong></p> <pre><code>def process_files(): file_list = ['file1', 'file2', 'file3'] counter = 0 for file in file_list: counter += 1 percent = 100 * counter / len(file_list) time.sleep(1) yield percent </code></pre> <hr> <p><strong>Result</strong>:</p> <p>After processing <code>file2</code></p> <p><a href="https://i.stack.imgur.com/10LSf.png" rel="nofollow"><img src="https://i.stack.imgur.com/10LSf.png" alt="enter image description here"></a></p>
QA:
Django get related objects ManyToMany relationships
<p>you would use...</p> <pre><code>cart = Cart.objects.first() objects = cart.cart_item.all() # this line return all related objects for CartToys # and in reverse cart_toy = CartToys.objects.first() carts = cart_toy.cart_set.all() # this line return all related objects for Cart </code></pre>
QA:
Print random line from txt file?
<p>This code is correct, assuming that you meant to pass a string to <code>open</code> function, and that you have no space after the dot... However, be careful to the indexing in Python, namely it starts at 0 and not 1, and then ends at <code>len(your_list)-1</code>.</p> <p>Using <code>random.choice</code> is better, but if you want to follow your idea it would rather be:</p> <pre><code>import random with open('name.txt') as f: lines = f.readlines() random_int = random.randint(0,len(lines)-1) print lines[random_int] </code></pre> <p>Since <code>randint</code> includes both boundary, you must look until <code>len(lines)-1</code>.</p>
QA:
Print random line from txt file?
<pre><code>f = open(filename. txt) lines = f.readlines() rand_line = random.randint(0, (len(lines) - 1)) # https://docs.python.org/2/library/random.html#random.randint print lines[rand_line] </code></pre>
QA:
Python documentation for django.views.generic
<p>while <a href="http://stackoverflow.com/users/400617/davidism">davidism</a>'s answer works for some things, it won't work for my own apps, as I got an <code>AppRegistryNotReady</code> exception. I found I needed to do some ad-hockery in my app files to get it to work:</p> <pre><code>import sys importer = sys.modules['__main__'].__spec__ if importer.name == 'pydoc': import django django.setup() </code></pre> <p>finally it works, at least for <code>views.py</code>. other files may need other solutions. and this is, I'm quite sure, brittle and version-dependent. it is working for Django 1.10.2 and Python 3.5.2.</p> <hr> <p>duh. sys.argv[0] has the same info, <code>/usr/lib/python3.5/pydoc.py</code>.</p> <p>so it could be accomplished more simply and reliably by:</p> <pre><code>import sys, os if os.path.splitext(os.path.basename(sys.argv[0]))[0] == 'pydoc': import django django.setup() </code></pre>
QA:
Python convert decimal to hex
<p>Python's string format method can take a format spec.</p> <p>From <strong>decimal</strong> to <strong>binary</strong></p> <pre><code>"{0:b}".format(154) '10011010' </code></pre> <p>From <strong>decimal</strong> to <strong>octal</strong></p> <pre><code>"{0:o}".format(154) '232' </code></pre> <p>From <strong>decimal</strong> to <strong>hexadecimal</strong></p> <pre><code>"{0:x}".format(154) '9a' </code></pre> <p><a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">Format spec docs for Python 2</a></p> <p><a href="https://docs.python.org/3.6/library/string.html#format-specification-mini-language" rel="nofollow">Format spec docs for Python 3</a></p>
QA:
How do you look for a line in a text file, from a sentence a user has inputted, by using its keywords?
<p>I assume your keywords is meant to be a list? </p> <p>Then you use <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> to check if any word out of the keywords is in the line. </p> <pre><code>a=input("Please enter your problem?") problem= ['#keywords', 'not', 'sure', 'how'] with open('solutions.txt', 'r') as searchfile: for line in searchfile: if any(word in line for word in problem): print (line) </code></pre> <p>Though, you may want to <code>split()</code> your line to improve that detection. </p> <p>Otherwise, you have <code>a</code>, which stores the user's input, so you can use that. </p> <pre><code>a=input("Please enter your problem?") problem= a.split() </code></pre> <p>Then, again <code>problem</code> is a list, so you use <code>any()</code> as before</p> <p>Or, if you want to check if the entire entered value is in a line, then </p> <pre><code>if a in line: print(line) </code></pre>
QA:
What do &=, |=, and ~ do in Pandas
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">documentation</a></p> <blockquote> <p>The operators are: | for or, &amp; for and, and ~ for not. These must be grouped by using parentheses.</p> </blockquote> <p><a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow">Augmented assignment statements</a></p> <blockquote> <p>An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.</p> </blockquote> <p>just like <code>a += 1</code> increments <code>a</code>, <code>a &amp;= b</code> compares <code>a</code> and <code>b</code> and assigns the result to <code>a</code>.</p> <pre><code>a = 1 b = 0 print(a &amp; b) &gt;&gt;&gt; 0 a &amp;= b print(a) &gt;&gt;&gt; 0 </code></pre> <p>And a <code>pandas</code> example</p> <p>Let's generate a dataframe of zeros and ones.</p> <pre><code>import numpy as np import pandas as pd a = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD')) b = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD')) </code></pre> <p>Our initial dataframe</p> <pre><code>print(a) </code></pre> <blockquote> <pre><code> A B C D 0 0 1 1 0 1 0 0 1 0 2 1 0 0 1 3 1 1 0 0 4 0 0 0 1 5 0 0 0 0 </code></pre> </blockquote> <pre><code>print(b) </code></pre> <blockquote> <pre><code> A B C D 0 0 0 0 0 1 1 1 1 0 2 0 1 1 1 3 0 1 1 1 4 1 1 1 0 5 1 1 1 1 </code></pre> </blockquote> <p>The 4th row of <code>a</code> and <code>b</code></p> <pre><code>print(a.loc[3]) </code></pre> <blockquote> <pre><code>A 1 B 1 C 0 D 0 Name: 1, dtype: int32 </code></pre> </blockquote> <pre><code>print(b.loc[3]) </code></pre> <blockquote> <pre><code>A 0 B 1 C 1 D 1 Name: 1, dtype: int32 </code></pre> </blockquote> <p>Now evaluate and assign row 4</p> <pre><code>a.loc[3] &amp;= b.loc[3] </code></pre> <p>Row 4 of <code>a</code> has changed. Only where both rows have 1 at the same position a 1 is written back to <code>a</code>.</p> <pre><code>print(a.loc[3]) </code></pre> <blockquote> <pre><code>A 0 B 1 C 0 D 0 Name: 3, dtype: int32 </code></pre> </blockquote>
QA:
Python creating objects from a class using multiple files
<p>First read your student/course and create a dictionary: key=student, value=list of courses</p> <p>The format is strange but the code below has been tested and works (maybe not as robust as it should, though). Read line by line, course first, and list of students. Add to dictionary (create empty list if key doesn't exist, nice <code>defaultdict</code> object does that):</p> <pre><code>from collections import defaultdict student_course = defaultdict(list) with open("CourseEnrollment.txt") as enr: while True: try: course_name = next(enr).strip() next(enr) # skip dashes while True: student = next(enr).strip() if student=="": break student_course[student].append(course_name) except StopIteration: break </code></pre> <p>and in your code, call <code>Student</code> constructor like this:</p> <pre><code>list_of_students.append(Student(last_name, '', first_name, student_id, student_course[student_id])) </code></pre>
QA:
Python Homework score of each name pair
<p>I have changed some aspects because I am not going to do your homework for you, but I understand just starting out on Stack and learning to program. It isn't easy so here's some explanation.</p> <p>So what you will want to do is loop through all of the possible combinations of the first and last names.</p> <p>I would do a nested for loop:</p> <p>here is the first part:</p> <pre><code>array1 = ['John', 'Kate', 'Oli'] array2 = ['Green', 'Fletcher' ,'Nelson'] for i in range(0,3): for k in range(0,3): val = array1[i] + " " + array2[k] print(val) </code></pre> <p>What you are doing is you are keeping <code>i</code> at zero, and then looping through everything in the second list. This way you can get every permutation of your list. To find the length you can do a for counting loop starting at position 0 or you can use the <code>.len()</code> function. To find the vowels you will need to look through each string you create and check to see if they match <code>[a, e, i, o, u]</code>. You can do something like </p> <p><code>if (val[k] == vowelList[j]): score += score</code> </p> <p>That is how I would do it, but I am not as experienced as other people here.</p> <p>Welcome to Stack! It is scary and a lot of people can be off putting and rude, just make sure to check other questions before you post and show some of your own work (what you have tried/attempted.)</p>
QA:
passing an array of COM pointers from Python to C++
<p>Once again, answering my own question. There is an additional level of indirection being introduced beyond what is required. Apparently, unlike a cast in C, ctypes.cast actually takes the address of the first argument.</p> <p>Change:</p> <pre><code>PointerArray = ctypes.c_void_p * len(exportLayers) </code></pre> <p>To:</p> <pre><code>PointerArray = comtypes.POINTER(esriCarto.IFeatureLayer) * len(exportLayers) </code></pre> <p>And eliminate the use of ctypes.cast in the call to ExportGeopackage():</p> <pre><code>export.ExportGeopackage(map, format, quality, min, max, pointers, title, desc, geopackage_path, 0) </code></pre>
QA:
Colorbar/plotting issue? "posx and posy should be finite values"
<p>So I found out that specifying <code>vmax</code> &amp; <code>vmin</code> solves the problem. I have no idea why, but once I did, my plot turned out correctly with the colorbar.</p> <pre><code>trend = m.pcolormesh(x,y,array[:,:,5],cmap='jet',norm=norm,shading='gouraud',vmin=0.,vmax=0.6) </code></pre> <p><a href="https://i.stack.imgur.com/4Wkft.png" rel="nofollow"><img src="https://i.stack.imgur.com/4Wkft.png" alt="enter image description here"></a></p>
QA:
Codecademy Practice Makes Perfect 10/15 (Word Censoring)
<p>I've made it quite simple and I don't see why no one mentioned this.</p> <pre><code>def censor(text, word): return text.replace(word,"*" * len(word)) </code></pre>
QA:
Implementing GLCM texture feature with scikit-image and Python
<p>I had the same problem, different data. Here is a script I wrote that uses parallel processing and a sliding window approach:</p> <pre><code>import gdal, osr import numpy as np from scipy.interpolate import RectBivariateSpline from numpy.lib.stride_tricks import as_strided as ast import dask.array as da from joblib import Parallel, delayed, cpu_count import os from skimage.feature import greycomatrix, greycoprops def im_resize(im,Nx,Ny): ''' resize array by bivariate spline interpolation ''' ny, nx = np.shape(im) xx = np.linspace(0,nx,Nx) yy = np.linspace(0,ny,Ny) try: im = da.from_array(im, chunks=1000) #dask implementation except: pass newKernel = RectBivariateSpline(np.r_[:ny],np.r_[:nx],im) return newKernel(yy,xx) def p_me(Z, win): ''' loop to calculate greycoprops ''' try: glcm = greycomatrix(Z, [5], [0], 256, symmetric=True, normed=True) cont = greycoprops(glcm, 'contrast') diss = greycoprops(glcm, 'dissimilarity') homo = greycoprops(glcm, 'homogeneity') eng = greycoprops(glcm, 'energy') corr = greycoprops(glcm, 'correlation') ASM = greycoprops(glcm, 'ASM') return (cont, diss, homo, eng, corr, ASM) except: return (0,0,0,0,0,0) def read_raster(in_raster): in_raster=in_raster ds = gdal.Open(in_raster) data = ds.GetRasterBand(1).ReadAsArray() data[data&lt;=0] = np.nan gt = ds.GetGeoTransform() xres = gt[1] yres = gt[5] # get the edge coordinates and add half the resolution # to go to center coordinates xmin = gt[0] + xres * 0.5 xmax = gt[0] + (xres * ds.RasterXSize) - xres * 0.5 ymin = gt[3] + (yres * ds.RasterYSize) + yres * 0.5 ymax = gt[3] - yres * 0.5 del ds # create a grid of xy coordinates in the original projection xx, yy = np.mgrid[xmin:xmax+xres:xres, ymax+yres:ymin:yres] return data, xx, yy, gt def norm_shape(shap): ''' Normalize numpy array shapes so they're always expressed as a tuple, even for one-dimensional shapes. ''' try: i = int(shap) return (i,) except TypeError: # shape was not a number pass try: t = tuple(shap) return t except TypeError: # shape was not iterable pass raise TypeError('shape must be an int, or a tuple of ints') def sliding_window(a, ws, ss = None, flatten = True): ''' Source: http://www.johnvinyard.com/blog/?p=268#more-268 Parameters: a - an n-dimensional numpy array ws - an int (a is 1D) or tuple (a is 2D or greater) representing the size of each dimension of the window ss - an int (a is 1D) or tuple (a is 2D or greater) representing the amount to slide the window in each dimension. If not specified, it defaults to ws. flatten - if True, all slices are flattened, otherwise, there is an extra dimension for each dimension of the input. Returns an array containing each n-dimensional window from a ''' if None is ss: # ss was not provided. the windows will not overlap in any direction. ss = ws ws = norm_shape(ws) ss = norm_shape(ss) # convert ws, ss, and a.shape to numpy arrays ws = np.array(ws) ss = np.array(ss) shap = np.array(a.shape) # ensure that ws, ss, and a.shape all have the same number of dimensions ls = [len(shap),len(ws),len(ss)] if 1 != len(set(ls)): raise ValueError(\ 'a.shape, ws and ss must all have the same length. They were %s' % str(ls)) # ensure that ws is smaller than a in every dimension if np.any(ws &gt; shap): raise ValueError(\ 'ws cannot be larger than a in any dimension.\ a.shape was %s and ws was %s' % (str(a.shape),str(ws))) # how many slices will there be in each dimension? newshape = norm_shape(((shap - ws) // ss) + 1) # the shape of the strided array will be the number of slices in each dimension # plus the shape of the window (tuple addition) newshape += norm_shape(ws) # the strides tuple will be the array's strides multiplied by step size, plus # the array's strides (tuple addition) newstrides = norm_shape(np.array(a.strides) * ss) + a.strides a = ast(a,shape = newshape,strides = newstrides) if not flatten: return a # Collapse strided so that it has one more dimension than the window. I.e., # the new array is a flat list of slices. meat = len(ws) if ws.shape else 0 firstdim = (np.product(newshape[:-meat]),) if ws.shape else () dim = firstdim + (newshape[-meat:]) # remove any dimensions with size 1 dim = filter(lambda i : i != 1,dim) return a.reshape(dim), newshape def CreateRaster(xx,yy,std,gt,proj,driverName,outFile): ''' Exports data to GTiff Raster ''' std = np.squeeze(std) std[np.isinf(std)] = -99 driver = gdal.GetDriverByName(driverName) rows,cols = np.shape(std) ds = driver.Create( outFile, cols, rows, 1, gdal.GDT_Float32) if proj is not None: ds.SetProjection(proj.ExportToWkt()) ds.SetGeoTransform(gt) ss_band = ds.GetRasterBand(1) ss_band.WriteArray(std) ss_band.SetNoDataValue(-99) ss_band.FlushCache() ss_band.ComputeStatistics(False) del ds #Stuff to change if __name__ == '__main__': win_sizes = [7] for win_size in win_sizes[:]: in_raster = #Path to input raster win = win_size meter = str(win/4) #Define output file names contFile = dissFile = homoFile = energyFile = corrFile = ASMFile = merge, xx, yy, gt = read_raster(in_raster) merge[np.isnan(merge)] = 0 Z,ind = sliding_window(merge,(win,win),(win,win)) Ny, Nx = np.shape(merge) w = Parallel(n_jobs = cpu_count(), verbose=0)(delayed(p_me)(Z[k]) for k in xrange(len(Z))) cont = [a[0] for a in w] diss = [a[1] for a in w] homo = [a[2] for a in w] eng = [a[3] for a in w] corr = [a[4] for a in w] ASM = [a[5] for a in w] #Reshape to match number of windows plt_cont = np.reshape(cont , ( ind[0], ind[1] ) ) plt_diss = np.reshape(diss , ( ind[0], ind[1] ) ) plt_homo = np.reshape(homo , ( ind[0], ind[1] ) ) plt_eng = np.reshape(eng , ( ind[0], ind[1] ) ) plt_corr = np.reshape(corr , ( ind[0], ind[1] ) ) plt_ASM = np.reshape(ASM , ( ind[0], ind[1] ) ) del cont, diss, homo, eng, corr, ASM #Resize Images to receive texture and define filenames contrast = im_resize(plt_cont,Nx,Ny) contrast[merge==0]=np.nan dissimilarity = im_resize(plt_diss,Nx,Ny) dissimilarity[merge==0]=np.nan homogeneity = im_resize(plt_homo,Nx,Ny) homogeneity[merge==0]=np.nan energy = im_resize(plt_eng,Nx,Ny) energy[merge==0]=np.nan correlation = im_resize(plt_corr,Nx,Ny) correlation[merge==0]=np.nan ASM = im_resize(plt_ASM,Nx,Ny) ASM[merge==0]=np.nan del plt_cont, plt_diss, plt_homo, plt_eng, plt_corr, plt_ASM del w,Z,ind,Ny,Nx driverName= 'GTiff' epsg_code=26949 proj = osr.SpatialReference() proj.ImportFromEPSG(epsg_code) CreateRaster(xx, yy, contrast, gt, proj,driverName,contFile) CreateRaster(xx, yy, dissimilarity, gt, proj,driverName,dissFile) CreateRaster(xx, yy, homogeneity, gt, proj,driverName,homoFile) CreateRaster(xx, yy, energy, gt, proj,driverName,energyFile) CreateRaster(xx, yy, correlation, gt, proj,driverName,corrFile) CreateRaster(xx, yy, ASM, gt, proj,driverName,ASMFile) del contrast, merge, xx, yy, gt, meter, dissimilarity, homogeneity, energy, correlation, ASM </code></pre> <p>This script calculates GLCM properties for a defined window size, with no overlap between adjacent windows. </p>
QA:
Use a xref of values to sub into tuple based on value - Python
<p>Unpack and access the dict using the first element, presuming you have an list of tuples:</p> <pre><code>internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'} lst = [('03', 'S/N A1631703'),('05', 'S/N A1631703')] lst[:] = ((internal_customer[a], b) for a,b in t) print(t) </code></pre> <p>tuples are immutable so there is no notion of mutating, you have to create a new tuple comprising of the new value from the dict and the existing second element. The <code>lst[:]</code> syntax at least allows you to modify the original list. You can of course just reassign the name or create a completely new list if you want to maintain the original.</p>
QA:
Java like function getLeastSignificantBits() & getMostSignificantBits in Python?
<p><code>efe640fc5d2f0036</code> in decimal is 17286575672347525174. Substract <code>0x10000000000000000</code> from it &amp; negate: you get <code>-1160168401362026442</code></p> <pre><code>int("efe640fc5d2f0036",16)-0x10000000000000000 -&gt; -1160168401362026442 </code></pre> <p>Note that it's only guesswork but seems to work with the sole test case you provided (fortunately it was negative). Call that reverse engineering.</p> <p>Take 2 last hex values (dash separated) and join them. I suppose the storage means that it becomes negative when first digit is above 7, so negate it with higher 2-power if that's the case:</p> <pre><code>def getLeastSignificantBits(s): hv = "".join(s.split("-")[-2:]) v = int(hv,16) if int(hv[0],16)&gt;7: # negative v = v-0x10000000000000000 return v print(getLeastSignificantBits('a316b044-0157-1000-efe6-40fc5d2f0036')) </code></pre> <p>result:</p> <pre><code>-1160168401362026442 </code></pre> <p>EDIT: providing a method which takes the whole string and returns lsb &amp; msb couple</p> <pre><code>def getLeastMostSignificantBits(s): sp=s.split("-") lsb_s = "".join(sp[-2:]) lsb = int(lsb_s,16) if int(lsb_s[0],16)&gt;7: # negative lsb = lsb-0x10000000000000000 msb_s = "".join(sp[:3]) msb = int(msb_s,16) if int(msb_s[0],16)&gt;7: # negative msb = msb-0x10000000000000000 return lsb,msb print(getLeastMostSignificantBits('a316b044-0157-1000-efe6-40fc5d2f0036')) </code></pre> <p>result:</p> <pre><code>(-1160168401362026442, -6694969989912915968) </code></pre>
QA:
Python/Spyder: General Working Directory
<p>The answer that you are technically looking for is using <code>os.chdir()</code> as follows</p> <pre><code>import os os.chdir('.', 'data') #THE REST OF THE CODE IS THE SAME with open(r'file.txt', 'r') as data_file: </code></pre> <p>A safer answer would however be </p> <pre><code>def doTheThing(fName): return os.path.join(os.getcwd(),'data',fName) with open(doTheThing('file.txt'), 'r') as data_file: </code></pre>
QA:
selenium run chrome on raspberry pi
<p>I have concluded that after hours and a hole night of debugging that you can't because there is no chromedriver compatible with a raspberry pi processor. Even if you download the linux 32bit. You can confirm this by running this in a terminal window <code>path/to/chromedriver</code> it will give you this error </p> <blockquote> <p>cannot execute binary file: Exec format error</p> </blockquote> <p>hope this helps anyone that wanted to do this :)</p>
QA:
Numpy: How to vectorize parameters of a functional form of a function applied to a data set
<p>One approach using a combination of <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>np.einsum('ij,jk-&gt;ik',nodes,x**np.array([2,1,0])[:,None]) </code></pre> <p>Another one using matrix-multiplication with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> -</p> <pre><code>nodes.dot(x**np.array([2,1,0])[:,None]) </code></pre>
QA:
How do you look for a line in a text file, from a sentence a user has inputted, by using its keywords?
<p>I am not sure I understood the question but is this what you want?. this will take the line containing the most words from the user input:</p> <pre><code>problem = a.split(' ') max_num, current_num = 0,0 #max_num count the maximum apparition of words from the input in the line| current_num count the current number of apparition of words of the user input in the line chosen_line = '' with open('solutions.txt', 'r') as searchfile: for line in searchfile: for word in problem: if word in line: current_num+=1 if current_num&gt;max_num: print line,max_num,current_num max_num=current_num chosen_line = line current_num = 0 print chosen_line </code></pre> <p>but it seems to me the easiest way to do what you want is to store at the start of each answer the question, or even easier - just ask the user the question number and return this corresponding answer.</p>
QA:
Filter by a Reference Property in Appnengine
<p>I haven't used <code>db</code> in a while, but I think something like this will work:</p> <pre><code>count = 0 # Get all blogs of the desired category blogs = Blog.all().filter("category =", cat.key()) for blog in blogs: # For each blog, count all the comments. count += Comment.all().filter("post =", blog.key()).count() </code></pre>
QA:
HTML select options from a python list
<p>You need to generate a list of "option"s and pass them over to your javascript to make the list</p> <pre><code>values = {"A": "One", "B": "Two", "C": "Three"} options = [] for value in sorted(values.keys()): options.append("&lt;option value='" + value + "'&gt;" + values[value] + "&lt;/option&gt;") </code></pre> <p>Then inject "options" into your html. Say, in your "template.html" there is a line:</p> <pre><code>var options = $python_list; </code></pre> <p>Then at the end of your python script:</p> <pre><code>####open the html template file, read it into 'content' html_file = "template.html" f = open(html_file, 'r') content = f.read() f.close() ####replace the place holder with your python-generated list content = content.replace("$python_list", json.dumps(options)) ####write content into the final html output_html_file = "index.html" f = open(output_html_file, 'w') f.write(temp_content) f.close() </code></pre> <p>In your "index.html", you should have one line after "var options = ..." that takes the list and generate the dropdown.</p> <pre><code>$('#my_dropdown').append(options.join("")).selectmenu(); </code></pre> <p>Alternatively, I suggest that you use your python to generate a json file (with json.dumps()), a file called "config.json" maybe. And your html javascript file should read this json file to render the final page. So in your json file, there should be something like:</p> <p>{ ... "options": ["One", "Two", "Three"] ...}</p> <p>And in your html section, you could read the option values</p> <pre><code>d3.json("config.json", function(data)) { var options = []; for (var i= 0; i &lt; data.options.length; i++) { options.push("&lt;option value='" + data.options[i] + "'&gt;" + data.options[i] + "&lt;/option&gt;"); } $('#my_dropdown').append(options.join("")).selectmenu(); } </code></pre>
QA:
Setting Image background for a line plot in matplotlib
<p>In order to overlay background image over plot, we need <code>imshow</code> and <code>extent</code> parameter from <code>matplotlib</code>.</p> <p>Here is an condensed version of your code. Didn't have time to clean up much.</p> <p>First a sample data is created for 11 countries as listed in your code. It is then <code>pickled</code> and saved to a file (since there is no pickle file data).</p> <pre><code>import quandl import pandas as pd import sys, os import matplotlib.pyplot as plt import seaborn as sns import numpy as np import itertools from scipy.misc import imread countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS'] df_sample = pd.DataFrame(np.random.randn(10, 11), columns=list(countries)) df_sample.to_pickle('c:\\temp\\neer.pickle') </code></pre> <p>Next the pickle file is read and we create bar plot directly from <code>pandas</code></p> <pre><code>df = pd.read_pickle('c:\\temp\\neer.pickle') my_plot = df.plot(kind='bar',stacked=True,title="Plot Over Image") my_plot.set_xlabel("countries") my_plot.set_ylabel("some_number") </code></pre> <p>Next we use <code>imread</code> to read image into <code>plot</code>.</p> <pre><code>img = imread("c:\\temp\\world.png") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.imshow(img,zorder=0, extent=[0.1, 10.0, -10.0, 10.0]) plt.show() </code></pre> <p>Here is an output plot with image as background. As stated this is crude and can be improved further. <a href="https://i.stack.imgur.com/UybYo.png" rel="nofollow"><img src="https://i.stack.imgur.com/UybYo.png" alt="enter image description here"></a></p>
QA:
Plot decision boundaries of classifier, ValueError: X has 2 features per sample; expecting 908430"
<p>The thing is you <strong>cannot</strong> plot decision boundary for a classifier for data which is not <strong>2 dimensional</strong>. Your data is clearly high dimensional, it has 908430 dimensions (NLP task I assume). There is no way to plot actual decision boundary for such a model. Example that you are using is trained on <strong>2D data</strong> (reduced Iris) and this is <strong>the only reason</strong> why they were able to plot it.</p>
QA:
JavaScript double backslash in WebSocket messages
<p>You should define the message as bytes and not as string:</p> <pre><code>var buffer = new Int8Array([5,0,0,0]) this.webSocket.send(buffer.buffer) </code></pre>
QA:
Python regex : trimming special characters
<p>You do not need regex for this simple task. Use <a href="https://docs.python.org/2/library/string.html#string.lstrip" rel="nofollow"><code>string.strip()</code></a> instead. For example:</p> <pre><code>&gt;&gt;&gt; my_string = '\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t' &gt;&gt;&gt; my_string.strip() 'Butte County High School' </code></pre> <p>In case it is must to use <code>regex</code>, your expression should be:</p> <pre><code>&gt;&gt;&gt; re.sub('[^A-Za-z0-9]\s+', '', my_string) 'Butte County High School' </code></pre> <p>It matches a string of characters that are not letters or numbers.</p>
QA:
Convert multiple columns to one column
<p>With the data that you provided, in the format you provided, you could do this with:</p> <pre><code>data.frame(ColumnD=c(t(df))) ColumnD 1 a1 2 b1 3 c1 4 b2 5 a2 6 e2 </code></pre> <p>We transpose the data, then combine it.</p>
QA:
Easier way to check if a string contains only one type of letter in python
<p>use <code>filter</code> with <code>str.isalpha</code> function to create a sublist containing only letters, then create a set. Final length must be one or your condition isn't met.</p> <pre><code>v="829383&amp;&amp;&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG" print(len(set(filter(str.isalpha,v)))==1) </code></pre>
QA:
How to create a web crawler to get multiple pages from agoda,with python3
<p>Examine closely in browser development tools what happens when you click next button. </p> <p>It has click event that sends xhr post request with a lot of parameters. One of the parameters is <code>PageNumber</code>. Most values for the parameters are straightforward to get, maybe except <code>SearchMessageID</code> that you have to find somewhere on page or is generated by javascript. </p>
QA:
How to overcome "datetime.datetime not JSON serializable" in python?
<p>Generally there are several ways to serialize datetimes, like:</p> <ol> <li>ISO string, short and can include timezone info, e.g. @jgbarah's <a href="http://stackoverflow.com/a/22238613/723090">answer</a></li> <li>Timestamp (timezone data is lost), e.g. @JayTaylor's <a href="http://stackoverflow.com/a/15823348/723090">answer</a></li> <li>Dictionary of properties (including timezone).</li> </ol> <p>If you're okay with the last way, the <a href="https://github.com/mverleg/pyjson_tricks" rel="nofollow">json_tricks</a> package handles dates, times and datetimes including timezones.</p> <pre><code>from datetime import datetime from json_tricks import dumps foo = {'title': 'String', 'datetime': datetime(2012, 8, 8, 21, 46, 24, 862000)} dumps(foo) </code></pre> <p>which gives:</p> <pre><code>{"title": "String", "datetime": {"__datetime__": null, "year": 2012, "month": 8, "day": 8, "hour": 21, "minute": 46, "second": 24, "microsecond": 862000}} </code></pre> <p>So all you need to do is</p> <pre><code>`pip install json_tricks` </code></pre> <p>and then import from <code>json_tricks</code> instead of <code>json</code>.</p> <p>The advantage of not storing it as a single string, int or float comes when decoding: if you encounter just a string or especially int or float, you need to know something about the data to know if it's a datetime. As a dict, you can store metadata so it can be decoded automatically, which is what <code>json_tricks</code> does for you. It's also easily editable for humans.</p> <p>Disclaimer: it's made by me. Because I had the same problem.</p>
QA:
Python regex : trimming special characters
<p>Except you have reasons to want to use regex, you can remove all edge white space with <code>.strip()</code> function in python</p>
QA:
Python regex : trimming special characters
<p>If you're really set on using regular expressions:</p> <pre><code>re.sub(r'^\s+|\s+$', '', schoolstring) </code></pre> <p>This will work for:</p> <pre><code>' this is a test ' # multiple leading and trailing spaces ' this is a test ' # one leading and trailing space 'this is a test' # no leading or trailing spaces '\t\tthis is a test\t\t' # leading or trailing whitespace characters </code></pre> <p>This expression one or more whitespace characters from the start <code>^\s+</code> of the string or <code>|</code> one or more whitespace characters from the end of the string <code>\s+$</code>.</p> <p>However, <code>string.strip()</code> is simpler for removing leading and trailing space.</p>
QA:
Yes or No answer from user with Validation and restart option?
<pre><code>def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"): while True: result = input(prompt) if result in choices: return result print(error) </code></pre> <p>is probably a nice generic way to approach this problem</p> <pre><code>result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C") </code></pre> <p>you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88) </p>
QA:
Yes or No answer from user with Validation and restart option?
<p>A recursive solution:</p> <pre><code>def get_input(): ans = input('Y/N? ') #Use raw_input in python2 if ans.lower() in ('y', 'n'): return ans else: print('Please try again.') return get_input() </code></pre> <p>If they're really stubborn this will fail when it reaches maximum recursion depth (~900 wrong answers)</p>
QA:
Sending Function as Argument to Another Function
<p>The passing of functions to other functions is a common idiom in so-called functional programming languages like LISP, Scheme, Haskell, etc. Python is sometimes referred to as a "multi-paradigm language" because it has some features of functional languages (as well as of imperative/structured and object-oriented languages). </p> <p>So while it is considered an advanced technique, it is hardly uncommon to see it in Python. Python even has a language keyword (<code>lambda</code>) to let you define short anonymous functions "in line" when calling a function, so you don't have to give them a name and define them elsewhere. It also has built-in functions like <code>map</code>, <code>filter</code>, and <code>reduce</code>, which are explicitly designed to work with functions passed in to them; these are borrowed from the aforementioned functional languages. And a commonly-used language feature, decorators, is basically a function that takes a function and returns a function.</p>
QA:
Django ImportError No module named x.settings
<p>You need to make sure the root of your project is in python path when you run the script. Something like this might help.</p> <pre> import os import sys projpath = os.path.dirname(__file__) sys.path.append(os.path.join(projpath, '..')) </pre>
QA:
Design: Google OAuth using AngularJS and Flask
<p>I gave up with manual implementation. There is a ready to use lib: <a href="https://github.com/sahat/satellizer" rel="nofollow">Satellizer</a> as well as server implementation (for Python example see the docs).</p>
QA:
How to do a substring using pandas or numpy
<p>Your square braces are not matching and you can easily slice with <code>[-2:]</code>.</p> <p><em>apply</em> <code>str.zfill</code> with a width of 2 to pad the items in the new series:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; ld = [{'REGION': '4', 'ORG': '413'}, {'REGION': '4', 'ORG': '414'}] &gt;&gt;&gt; df = pd.DataFrame(ld) &gt;&gt;&gt; df ORG REGION 0 413 4 1 414 4 &gt;&gt;&gt; df['UNIT'] = df['ORG'].str[-2:].apply(str.zfill, args=(2,)) &gt;&gt;&gt; df ORG REGION UNIT 0 413 4 13 1 414 4 14 2 3 4 03 </code></pre>
QA:
Python: Finding palindromes in a list
<p>I assume that you mean that you want the final list to contain the lowest palindrome in the sequence formed by the sum of the previous number in the sequence and the result of reversing the previous number in the sequence.</p> <p>If so, here is some code (not bulletproof):</p> <pre><code>#checks if a number is a palindrome by comparing the string written fowards #with the string written backwards def is_pal(x): if str(x)==str(x)[::-1]: return True return False #iterates a number by adding and reversing until it is a palindrom def iter_pal(x): while not is_pal(x): x+=int(str(x)[::-1]) #adds the number's reverse to itself return x #main program def main(): #gets input lower = int(input("Type the lower bound: ")) upper = int(input("Type the upper bound: ")) #uses range to make the sequence of numbers sequence = list(range(lower,upper+1)) #iterates through the list performing iter_pal for i in range(upper-lower+1): sequence[i]=iter_pal(sequence[i]) #prints the final sequence print(sequence) main() </code></pre> <p>I'm not sure what you will do with the <a href="https://en.wikipedia.org/wiki/Lychrel_number" rel="nofollow">Lychrel numbers</a>.</p>
QA:
Error when using sympy's solver on polynomials with complex coefficients (4th deg)
<p>Looks like you can work around the issue by using <code>solve(expr2, k, rational=False)</code>. </p>
QA:
django-pipeline throwing ValueError: the file could not be found
<p>Your problem is related to <a href="https://code.djangoproject.com/ticket/21080" rel="nofollow">this bug</a> on the Django project.</p> <p>In short, django-pipeline is post-processing the <code>url()</code> calls with Django's <code>CachedStaticFilesStorage</code> to append the md5 checksum to the filename (<a href="https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#manifeststaticfilesstorage" rel="nofollow">more details here</a>) and doesn't detect when it is inside a comment.</p> <p>If you look on the header of the <code>jquery-ui.css</code> (and similar) files there is a comment that starts with </p> <blockquote> <ul> <li>To view and modify this theme, visit [...]</li> </ul> </blockquote> <p>Inside the URL on this line there is a parameter that is being interpreted as an <code>url()</code> call and generating the error you see.</p> <p>To work around this issue you can simply remove the above line from <code>jquery-ui.css</code> and <code>collectstatic</code> should work properly.</p>
QA:
How can I extend the unit selection logic in my RTS game to apply to multiple units?
<p>There are few things to do:</p> <ol> <li>Change variables <code>character_*</code> to object that holds all data about the unit.</li> <li>Create array of units / characters. That way each unit in array can have unique position, velocity ets. </li> <li>Everywhere in code where you check <code>character_*</code>, change to for loops where you iterate over characters array to check every unit.</li> <li>Next step should be adding functions like move / shoot to character class, to make keypress event working for multiple units.</li> </ol> <p>That should give you code where you can select multiple units (if they occupy same spot) and move them independently of deselected units.</p>
QA:
pandas groupby transform behaving differently with seemingly equivalent representations
<p>It looks like a bug to me:</p> <pre><code>In [19]: df.groupby('A').transform(lambda x: x.sum()) Out[19]: B 0 1 1 1 In [20]: df.groupby('A').transform(lambda x: len(x)) Out[20]: B 0 2 1 2 In [21]: df.groupby('A').transform(lambda x: x.sum()/len(x)) Out[21]: B 0 0 1 0 </code></pre> <p>PS Pandas version: 0.19.0</p>
QA:
Why does json serialization of datetime objects in python not work out of the box for datetime objects
<p>If you want to get encoding and decoding of datetimes without having to implement it, you can use <a href="https://github.com/mverleg/pyjson_tricks" rel="nofollow">json_tricks</a>, which is a wrapper that adds encoding and decoding for various popular types. Just install:</p> <pre><code>pip install json_tricks </code></pre> <p>and then import from <code>json_tricks</code> instead of <code>json</code>, e.g.:</p> <pre><code>from json_tricks import dumps, loads json = dumps({'name': 'MyName', 'birthday': datetime.datetime(1992, 5, 23, 18, 38, 23, 37566)}) me = loads(json) </code></pre> <p>Disclaimer: it's made by me. Because I had the same problem.</p> <hr> <p>If you want to automatically serialize anything that can be stringified, you can do that with just the standard implementation very easily:</p> <pre><code>dumps(obj, default=str) </code></pre> <p>But note that this has disadvantages, e.g. none of it will be deserialized without extra effort, and maybe sometimes you just don't want to serialize something (like a function of a big numpy array) but get a warning instead, which this method will silence.</p>
QA:
recursively iterate nested python dictionary
<p>I found the bug in my code, which is I didn't return the recursive call back to the original loop. After going inside nested elements, it "returns" and doesn't get back to original loop. Instead of <code>return encode(subNode, val)</code>, saving in a variable <code>element = encode(subNode, val)</code> solves the problem. </p>
QA:
Easier way to check if a string contains only one type of letter in python
<p>Jean-Francois's answer is what I'd actually use 99% of the time, but for cases where the string is <em>huge</em> you might want a solution that will return as soon as the second unique character is detected, instead of finishing processing:</p> <pre><code>from future_builtins import map, filter # Only on Py2, to get lazy map/filter from itertools import groupby, islice from operator import itemgetter # Remove non-alphas, then reduce consecutive identical alphabetic characters # to a single instance of that character lets = map(itemgetter(0), groupby(filter(str.isalpha, somestr))) # Skip the first result, and if we find a second, then there was more than one # in the string if next(islice(lets, 1, None), None) is not None: # There were at least two unique alphabetic characters else: # There were only 0-1 unique alphabetic characters </code></pre> <p>Distinguishing no alphabetic from one alphabetic could instead be done without <code>islice</code> as:</p> <pre><code>atleastone = next(lets, None) is not None multiple = next(lets, None) is not None </code></pre>
QA:
Getting combinations back from memoized subset-sum algorithm?
<p>You may simplify your problem using <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> as:</p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; s = 6 &gt;&gt;&gt; my_list = range(1, s) # Value of 'my_list': # [1, 2, 3, 4, 5] &gt;&gt;&gt; my_combinations = [combinations(my_list, i) for i in range(2, s)] # Value of 'my_combinations' (in actual will be containg &lt;combinations&gt; objects): # [[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)], [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)], [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)], [(1, 2, 3, 4, 5)]] &gt;&gt;&gt; my_required_set = [my_set for my_sublist in my_combinations for my_set in my_sublist if sum(my_set) == s] &gt;&gt;&gt; my_required_set [(1, 5), (2, 4), (1, 2, 3)] </code></pre>
QA:
Efficiently summing outer product for 1D NumPy arrays
<p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>y = a*b - np.einsum('i,i,j-&gt;j',a,b,b) </code></pre> <p>We can also perform <code>a*b</code> and feed to <code>einsum</code> -</p> <pre><code>y = a*b - np.einsum('i,j-&gt;j',a*b,b) </code></pre> <p>On the second approach, we can save some runtime by storing <code>a*b</code> and reusing.</p> <p>Runtime test -</p> <pre><code>In [253]: a = np.random.rand(4000) In [254]: b = np.random.rand(4000) In [255]: %timeit np.sum(np.outer(a*b, b), axis=0) 10 loops, best of 3: 105 ms per loop In [256]: %timeit np.einsum('i,i,j-&gt;j',a,b,b) 10 loops, best of 3: 24.2 ms per loop In [257]: %timeit np.einsum('i,j-&gt;j',a*b,b) 10 loops, best of 3: 21.9 ms per loop </code></pre>
QA:
Python numpy.fft changes strides
<blockquote> <p>Any reasons why numpy.fft.fftn() changes the strides and ideas on how to prevent that except for reversing the axes (which would be just a workaround)?</p> </blockquote> <p>Computing the multidimensionnal DFT of an array consists in successively computing 1D DTFs over each dimensions. There are two strategies:</p> <ol> <li>Restrict 1D DTF computations to contiguous 1D arrays. As the array is contiguous, problem related to latency/cache misses will be reduced. This strategy has a major drawback: the array is to be transposed between each dimension. It is likely the strategy adopted by <code>numpy.fft</code>. At the end of computations, the array has been transposed. To avoid unnecessary computations, the transposed array is returned and strides are modified.</li> <li>Enable 1D DDFT computations for strided arrays. This might trigger some problem related to latency. It is the strategy of <code>fftw</code>, avaible through the interface <code>pyfftw</code>. As a result, the output array features the same strides as the input array.</li> </ol> <p>Timing <code>numpy.fftn</code> and <code>pyfftw.numpy.fftn</code> as performed <a href="http://stackoverflow.com/questions/40061307/comparatively-slow-python-numpy-3d-fourier-transformation/40064319?noredirect=1#comment67488042_40064319">here</a> and <a href="http://stackoverflow.com/questions/6365623/improving-fft-performance-in-python">there</a> or <a href="https://gist.github.com/fnielsen/99b981b9da34ae3d5035" rel="nofollow">there</a> will tell you whether FFTW is really the Fastest Fourier Transform in the West or not...</p> <ul> <li><p>To check that numpy uses the first strategy, take a look at <code>numpy/fft/fftpack.py</code>. At line 81-85, the call to <code>work_function(a, wsave)</code> (i.e. <code>fftpack.cfftf</code>, from <a href="http://www.netlib.org/fftpack/" rel="nofollow">FFTPACK</a>, arguments documented <a href="https://docs.oracle.com/cd/E19422-01/819-3691/cfftf.html" rel="nofollow">there</a>) is enclosed between calls to <code>numpy.swapaxes()</code> performing the transpositions.</p></li> <li><p><code>scipy.fftpack.fftn</code> does not seem to change the strides... Nevertheless, it seems that it makes use of the first strategy. <a href="https://github.com/scipy/scipy/blob/v0.18.1/scipy/fftpack/basic.py" rel="nofollow"><code>scipy.fftpack.fftn()</code></a> calls <a href="https://github.com/scipy/scipy/blob/master/scipy/fftpack/src/zfftnd.c" rel="nofollow"><code>scipy.fftpack.zfftnd()</code></a> which calls <a href="https://github.com/scipy/scipy/blob/master/scipy/fftpack/src/zfft.c" rel="nofollow"><code>zfft()</code></a>, based on <a href="https://github.com/scipy/scipy/blob/master/scipy/fftpack/src/dfftpack/zfftf1.f" rel="nofollow"><code>zfftf1</code></a> which does not seem to handle strided DFTs. Moreover, <code>zfftnd()</code> calls many times the function <a href="https://github.com/scipy/scipy/blob/master/scipy/fftpack/src/zfftnd.c" rel="nofollow"><code>flatten()</code></a> which performs the transposition.</p></li> <li><p>Another example: for parallel distributed memory multidimensionnal DFTs, <a href="http://www.fftw.org/fftw3_doc/Transposed-distributions.html#Transposed-distributions" rel="nofollow">FFTW-MPI uses the first strategy</a> to avoid any MPI communications between processes during 1D DTFs. Of course, <a href="http://www.fftw.org/fftw3_doc/FFTW-MPI-Transposes.html#FFTW-MPI-Transposes" rel="nofollow">functions to transpose the array</a> are not far away and a lot a MPI communications are involved in the process.</p></li> </ul> <blockquote> <p>Are there any other numpy array routines that could affect stride structure? What can be done in those cases?</p> </blockquote> <p>You can <a href="https://github.com/numpy/numpy/search?p=1&amp;q=swapaxes&amp;utf8=%E2%9C%93" rel="nofollow">search the github repository of numpy for <code>swapaxes</code></a>: this funtion is only used a couple of times. Hence, to my mind, this "change of strides" is particular to <code>fft.fftn()</code> and most numpy functions keep the strides unchanged.</p> <p>Finally, the "change of strides" is a feature of the first strategy and there is no way to prevent that. The only workaround is to swap the axes at the end of the computation, which is costly. But you can rely on <code>pyfftw</code> since <code>fftw</code> implements the second strategy in a very efficient way. The DFT computations will be faster, and subsequent computations will be faster as well if the strides of the different arrays become consistent.</p>
QA:
Characters from listbox are still recorded even when deleted from listbox
<p>Problem is because you use always <code>if left == 0: namel = "Rash" even if</code>"Rash"<code>was deleted from listbox and now</code>left == 0<code>means</code>"Untss".</p> <p>You have to get selected name instead of index </p> <pre><code> namel = lbox.get(lbox.curselection()[0]) namer = rbox.get(rbox.curselection()[0]) </code></pre> <p>and use it </p> <pre><code> if namel == "Rush": totalleft = Rash.total </code></pre> <p>But you could use dictionary to get data </p> <pre><code>left_characters = { "Rash": Character("Rash", 42, 50, 80), "Untss": Character("Untss", 15, 54, 100), "Ilora": Character("Ilora", 60, 35, 80), } right_characters = { "Zys": Character("Zys", 12, 97, 83), "Eentha": Character("Eentha", 55, 17, 90), "Dant": Character("Dant", 73, 28, 88), } leftnames = list(left_characters.keys()) rightnames = list(right_characters.keys()) </code></pre> <p>and then</p> <pre><code>def fight(): try: namel = lbox.get(lbox.curselection()[0]) namer = rbox.get(rbox.curselection()[0]) print(namel) print(namer) totalleft = left_characters[namel].total totalright = right_characters[namer].total lbox.delete(lbox.curselection()[0]) rbox.delete(rbox.curselection()[0]) if totalleft &gt; totalright : #Checks if won or lost wins.set(wins.get()+"\n"+namel) loss.set(loss.get()+"\n"+namer) else: wins.set(wins.get()+"\n"+namer) loss.set(loss.get()+"\n"+namel) except IndexError as e: print("ERROR:", e) </code></pre> <p>If you add new characters to dictionary then you don't have to change code.</p> <p>BTW: don't use <code>pass</code> in <code>except</code> because you don't see error if there is something wrong with code.</p>
QA:
Python netcdf plot data onto grid
<p>This is a crude way of doing it:</p> <pre><code>lat_1 = 58 lat_2 = 60 lon_1 = 2 lon_2 = 5 size = 0 age2 = 0 for parts in range(10): for length in range(len(lon)): if lon[length,parts] &lt; lon_2: if lon[length,parts] &gt; lon_1: if lat[length,parts] &gt; lat_1: if lat[length,parts] &lt; lat_2: age = (age[length, parts]) size = size + 1 age2 = age + age2 mean = age2/size </code></pre>
QA:
How to fix "TypeError: len() of unsized object"
<p>Use the arrays' <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.html" rel="nofollow"><code>size</code></a> attribute instead:</p> <pre><code>nv = v.size nu = u.size </code></pre> <hr> <p>You also probably want to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html#numpy.fromstring" rel="nofollow"><code>numpy.fromstring</code></a> to take and convert the input string into an array:</p> <pre><code>&gt;&gt;&gt; v = np.fromstring(input('enter the elements of the vector separated by comma: '), dtype=int, sep=',') enter the elements of the vector separated by comma: 1, 2, 3 &gt;&gt;&gt; v array([1, 2, 3]) &gt;&gt;&gt; len(v) 3 &gt;&gt;&gt; v.size 3 </code></pre>
QA:
How to fix "TypeError: len() of unsized object"
<p>The problem is that a <code>numpy</code>-<strong>scalar</strong> has no length. When you use <code>input</code> it returns a string (assuming Python3 here) and that's just converted to a numpy-string when you pass it to <code>numpy.array</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.array('abcdefg') array('abcdefg', dtype='&lt;U7') &gt;&gt;&gt; len(np.array('abcdefg')) TypeError </code></pre> <p>You need to parse it before you pass it to <code>numpy.array</code>. For example with <code>ast.literal_eval</code> (Thanks @PaulRooney for mentioning it):</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; np.array(ast.literal_eval(input('Enter vector'))) # input "[1, 2, 3]" array([1, 2, 3]) &gt;&gt;&gt; len(_) 3 </code></pre> <p>If you're dealing with multidimensional <code>array</code> you have to use <code>array.size</code> instead of <code>len</code>.</p>
QA:
Why to use Lambda to send Function as Argument to Another Function
<p><a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>lambda</code></a> functions work like normal function but are used in cases where they will be executed just once. Then, why to create the message body and define the function? For example, sorting the list of tuples:</p> <pre><code>&gt;&gt;&gt; my_list = [(1, 3) , (4, 8), (2, 3), (1, 6)] &gt;&gt;&gt; my_list.sort(key=lambda x: (x[0], -x[1])) &gt;&gt;&gt; my_list [(1, 6), (1, 3), (2, 3), (4, 8)] </code></pre> <p>Here, I am sorting <code>my_list</code> in increasing order of index <code>0</code> and then decreasing order of index <code>1</code>. But <code>list.sort()</code> accepts value of <code>key</code> as function. Instead of defining the function and then pass that function over here, it is cleaner to make a <code>lambda</code> call within it. </p> <p>Since these can be written as an expression, they are termed as <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>Lambda Expression</code></a> in document, instead of <em>Lambda Function</em>.</p> <p>Also read: <a href="http://stackoverflow.com/questions/890128/why-are-python-lambdas-useful">Why are Python lambdas useful?</a></p> <p>In the example that you have given, I do not think that using <code>lambda</code> there is any useful.</p>
QA:
pip install jupyter: "Unable to locate finder for 'pip._vendor.distlib'"
<p>uninstall current pip by typing:</p> <pre><code>python -m pip uninstall pip setuptools </code></pre> <p>download get-pip.py from <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">https://bootstrap.pypa.io/get-pip.py</a> and run it:</p> <pre><code>python get-pip.py </code></pre>
QA:
Build a single list of element from bi-dimensional array list
<p>I'm bad at python but I think like this when you result.get('rows'): row is [url1] not url1 Why don't you try extend? Sorry about my silly English ( I'm bat at English too)</p>
QA:
pandas.merge: match the nearest time stamp >= the series of timestamps
<p>Here is a simpler and more general method.</p> <pre><code># data and signal are want we want to merge keys = ['channel', 'timestamp'] # Could be simply ['timestamp'] index = data.loc[keys].set_index(keys).index # Make index from columns to merge on padded = signal.reindex(index, method='pad') # Key step -- reindex with filling joined = data.join(padded, on=keys) # Join to data if needed </code></pre>
QA:
Numbers separated by spaces in txt file into python list
<p>Following uses plain Python 3 (without NumPy)</p> <pre><code># open file with open('file.txt') as fp: # 1. iterate over file line-by-line # 2. strip line of newline symbols # 3. split line by spaces into list (of number strings) # 4. convert number substrings to int values # 5. convert map object to list data = [list(map(int, line.strip().split(' '))) for line in fp] </code></pre> <p>This provides the result you're looking for:</p> <pre><code>&gt;&gt;&gt; with open('data.txt') as fp: ... data = [list(map(int, line.strip().split(' '))) for line in fp] ... &gt;&gt;&gt; print(data) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] </code></pre>
QA:
Build a single list of element from bi-dimensional array list
<p>If you just want the <code>url</code>, and your data is basically a list of lists then you can just use the <code>index</code> number, in this case <code>[0]</code> as url is the 1st element in a nested list</p> <pre><code>l = [['url1', 'data1'],['url2', 'data2'],['url3', 'data3']] endlist = [] for i in l: endlist.append(i[0]) print endlist </code></pre> <p>Output:</p> <pre><code>['url1', 'url2', 'url3'] </code></pre> <p>However, make sure how your data is structured. A list of lists looks like <code>[[],[],[]]</code>, where each nested list is seperated by a <code>,</code> (comma) which is absent in the example you posted. </p>
QA:
Psycopg / Postgres : Connections hang out randomly
<p>Psycopg2 needs a commit or rollback after every transaction, including SELECT queries, or it leaves the connections "IDLE IN TRANSACTION". This is now a warning in the docs:</p> <blockquote>Warning: By default, any query execution, including a simple SELECT will start a transaction: for long-running programs, if no further action is taken, the session will remain “idle in transaction”, an undesirable condition for several reasons (locks are held by the session, tables bloat...). For long lived scripts, either ensure to terminate a transaction as soon as possible or use an autocommit connection.</blockquote>
QA:
Build a single list of element from bi-dimensional array list
<p>If I understood you correctly, you need this:</p> <pre><code>results = [[url_1, data_1], [url_2, data_2], ...] urls = list() for r in results: # r = [url_i, data_i] urls.append(r[0]) </code></pre>
QA:
How can I manipulate strings in a slice of a pandas MultiIndex
<p>I found the following method, but i think/hope there must be a more elegant way to achieve that:</p> <pre><code>In [101]: index_saved = df.index </code></pre> <p>Let's sort index in order to get rid of <code>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (0)'</code> error:</p> <pre><code>In [102]: df = df.sort_index() In [103]: df Out[103]: metric sensor variable side bar Speed Left Left_Speed Right Right_Speed Support Left Left_support Right Right_support baz Speed Left speed Support Left support foo Speed Left Left speed Right Right speed Support Left Left support Right Right support In [119]: df.loc[pd.IndexSlice['baz', :, 'Left'], 'metric'] = \ ...: 'AAA__' + df.loc[pd.IndexSlice['baz', :, 'Left'], 'metric'] In [120]: df Out[120]: metric sensor variable side bar Speed Left Left_Speed Right Right_Speed Support Left Left_support Right Right_support baz Speed Left AAA__speed Support Left AAA__support foo Speed Left Left speed Right Right speed Support Left Left support Right Right support </code></pre> <p>set back old (saved) index:</p> <pre><code>In [121]: df = df.reindex(index_saved) In [122]: df Out[122]: metric sensor variable side foo Speed Left Left speed Right Right speed bar Speed Left Left_Speed Right Right_Speed baz Speed Left AAA__speed foo Support Left Left support Right Right support bar Support Left Left_support Right Right_support baz Support Left AAA__support </code></pre>
QA:
Recursive functions : Inversing word
<p>Check this:</p> <pre><code>ch[len(ch)-1]+inverse(ch[0:len(ch)-1]) </code></pre>
QA:
Recursive functions : Inversing word
<p>You're indexing the string at its length, but remember that indexing is zero based so you'll have to slice at length minus 1 which is the maximum index you can safely use.</p> <p>You can however choose to be oblivious of the length by using <code>[-1]</code> to index the last item:</p> <pre><code>def inverse(ch): if ch=='' : return '' else: return ch[-1]+inverse(ch[:-1]) print inverse('hello') # olleh </code></pre> <p>And you also probably want to keep in mind that slicing with <code>[::-1]</code> provides the same result as your recursive function.</p>
QA:
How to split files according to a field and edit content
<p>This shell script should do the trick:</p> <pre><code>#!/usr/bin/env bash filename="data.txt" while read line; do id=$(echo "${line}" | awk '{print $1}') sequence=$(echo "${line}" | awk '{print $2}') group=$(echo "${line}" | awk '{print $3}') printf "&gt;${id}\n${sequence}\n" &gt;&gt; "${group}.txt" done &lt; "${filename}" </code></pre> <p>where <code>data.txt</code> is the name of the file containing the original data.</p> <p>Importantly, the Group-files should not exist prior to running the script.</p>
QA:
Sorting list with dictionaries values(Maximum to Minimum)
<p>try this:</p> <pre><code>my_list.sort(key=lambda my_dict: my_dict["num_gurus"], reverse=True) </code></pre> <p>what this does is basically two things:</p> <ul> <li>key paramater expects an anonymous function (lambda in python) and then sorts the original list values by the values returned by lambda function. <code>lambda my_dict: my_dict["num_gurus"]</code> returns the "num_gurus" item within each dictionary hence the list is sorted by those values.</li> <li><code>reverse=True</code> by default sort function sorts from min to max, hence this simply reverses that</li> </ul> <p>also I find this very "unsafe" as you have no guarentee for "num_gurus" key within your dictionaries, or a dictionary as a key value, hence I'd personally wrap this with some exception handler: <code>try</code> \ <code>except</code></p> <p>read more here: <a href="https://docs.python.org/2.7/tutorial/errors.html" rel="nofollow">https://docs.python.org/2.7/tutorial/errors.html</a>, remember better safe than sorry!</p>
QA:
I got error while using "git push heroku master"
<p>This happened to me after I cloned from heroku a second copy of my files. Suddenly <code>git push heroku master</code> wouldn't work and I'd get the same error as you. But when I tried <code>git push origin master</code>, it worked fine.</p>
QA:
Sorting list with dictionaries values(Maximum to Minimum)
<p>For <strong><em>storing the sorted list as new list</em></strong>, you can do it using <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> as:</p> <pre><code>sorted(my_list, key=lambda x: x['num_gurus'], reverse=True) # returns sorted list </code></pre> <p>where <code>my_list</code> is your <code>list</code> of <code>dict</code> objects.</p> <p>Else, if you want to <strong><em>sort the content of original list</em></strong>, i.e <code>my_list</code>, then use <code>list.sort()</code> as:</p> <pre><code>my_list.sort(key=lambda x: x["num_gurus"], reverse=True) # sorts the original list </code></pre> <p>Check document on: <a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">How to do Sorting in list</a></p>
QA:
Compare list of dictionary in Robot Framework
<p>If I understand your question correctly, you should be able to do this using the built in Collections library. This code took the values in one dictionary and checked to see if the value exists in the other. </p> <pre><code>*** Settings *** Library Collections *** Variables *** &amp;{DICTONARY_ONE} = name1=a name2=b name3=c name4=d &amp;{DICTONARY_TWO} = name1=c name2=a name3=d name4=b *** Test Cases *** Dictonary Test @{dictonary2_list} = Get Dictionary Values ${DICTONARY_TWO} :For ${item} in @{dictonary2_list} \ Dictionary Should Contain Value ${DICTONARY_ONE} ${item} </code></pre> <p>If this is not quite what you are after, there should be something in collections that will let you do what you need. Here is a link to the documentation.<br> <a href="http://robotframework.org/robotframework/latest/libraries/Collections.html" rel="nofollow">http://robotframework.org/robotframework/latest/libraries/Collections.html</a></p> <p>I hope that helps.</p>
QA:
Pandas df to dictionary with values as python lists aggregated from a df column
<p>Wouldn't <code>f.set_index('ticker').groupby('sector').groups</code> be what you want?</p> <p>For example:</p> <pre><code>f = DataFrame({ 'ticker': ('t1', 't2', 't3'), 'sector': ('sa', 'sb', 'sb'), 'name': ('n1', 'n2', 'n3')}) groups = f.set_index('ticker').groupby('sector').groups # {'sa': Index(['t1']), 'sb': Index(['t2', 't3'])} </code></pre> <p>To ensure that they have the type you want:</p> <pre><code>{k: list(v) for k, v in f.set_index('ticker').groupby('sector').groups.items()} </code></pre> <p>or:</p> <pre><code>f.set_index('ticker').groupby('sector').apply(lambda g: list(g.index)).to_dict() </code></pre>
QA:
Querying MySQL from multiple uWSGI workers returns mismatched rows
<p><strong>For anyone else facing this issue, I have found the following solution.</strong></p> <p>According to <a href="http://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html" rel="nofollow">http://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html</a>.</p> <blockquote> <p>uWSGI tries to (ab)use the Copy On Write semantics of the fork() call whenever possible. By default it will fork after having loaded your applications to share as much of their memory as possible. If this behavior is undesirable for some reason, use the lazy-apps option. This will instruct uWSGI to load the applications after each worker’s fork().</p> </blockquote> <p>After taking a look at <a href="http://stackoverflow.com/questions/22752521/uwsgi-flask-sqlalchemy-and-postgres-ssl-error-decryption-failed-or-bad-reco">uWSGI, Flask, sqlalchemy, and postgres: SSL error: decryption failed or bad record mac</a>, I realised my problem was to do with the fact that multiple processes were being created.</p> <p>However, because uWSGI loads all the processes from one master worker by default (and doesn't run the whole of the Flask application each time), it turns out that all the workers end up sharing a database connection (which doesn't end well!).</p> <p>The solution is to include the <code>lazy-apps</code> parameter, which forces all the code to be run when each worker is created.</p>
QA:
Python runs the commented-out code
<p>Due to an error in the script, worked two instance celery and this error occurred during the operation instance, who has worked with the old code.</p>
QA:
Django choices and dictionary
<p>Tuples are immutable.I Think it's impossible.</p>
QA:
How to do curvefitting using scipy.optimize.curve_fit
<pre><code>import numpy as np from scipy.optimize import curve_fit xdata= np.array([1, 8, 8, 21, 31, 42, 63, 64, 81, 110, 156, 211, 301, 336, 735]) ydata = np.array([0.018, 0.0164, 0.0042, 0.0072, 0.0108, 0.0044, 0.0035, 0.0036, 0.0042, 0.0051, 0.0019, 0.0042, 0.0019, 8e-4, 2e-4]) def func(x,a,b,m,n): return a*np.exp(m*x)+b*np.exp(n*x) curve_fit(func, xdata, ydata) </code></pre> <p>unfortunatly <code>Covariance of the parameters could not be estimated</code></p>
QA:
Python Array Reshaping Issue to Array with Shape (None, 192)
<p>This is an error in the library code, because <code>(None, 192)</code> is an invalid shape for a numpy array - the shape must be a tuple of integers. </p> <p>To investigate any further, we'll have to see the traceback and/or the code which is raising that exception. </p>
QA:
Remove the parentheses around the very first element in an expression tree and in each of its sub-expression trees in Python
<p>This can be viewed as a finite state machine (with three states) which you instantiate once per level, where each <code>(</code> symbol creates a new level. Alternatively, it is a deterministic <a href="https://en.wikipedia.org/wiki/Pushdown_automaton" rel="nofollow">pushdown automaton</a> with two trivial states (an in-progress state and a done state, neither of which we model explicitly) and three stack symbols, each representing the state of the machine for the current level:</p> <ul> <li><strong>Before</strong> - The state we are in immediately after entering a level. Encountering any characters except <code>)</code> transitions to some other state.</li> <li><strong>Inside</strong> - The state we are in while inside parentheses that need to be removed. Entered by encoutering a <code>(</code> while in <strong>Before</strong>.</li> <li><strong>Done</strong> - The state we are in when the current level has been processed. This means that either we already removed a set of parentheses or we did not need to, since the first element wasn't enclosed in them.</li> </ul> <p>Additionally, encountering a <code>(</code> pushes a new symbol onto the stack, which models entering a new level, and a <code>)</code> pops the one symbol from it, which models leaving from a level. All input characters get appended onto the result <em>except</em> when the <strong>Before</strong> → <strong>Inside</strong> and <strong>Inside</strong> → <strong>Done</strong> transitions occur.</p> <p>The following code is a simple translation of the above into Python:</p> <pre><code>from enum import Enum class State(Enum): Before = 0 Inside = 1 Done = 2 def simplify(expression): levels = [State.Before] result = [] for c in expression: if c == '(': if levels[-1] == State.Before: levels[-1] = State.Inside else: result.append(c) levels.append(State.Before) elif c == ')': levels.pop() if levels[-1] == State.Inside: levels[-1] = State.Done else: result.append(c) else: if levels[-1] == State.Before: levels[-1] = State.Done result.append(c) return ''.join(result) </code></pre> <p>Testing the above out, we get:</p> <pre><code>&gt;&gt;&gt; simplify('(12)3((45)6)') '123(456)' &gt;&gt;&gt; simplify('((12)3)4(((5)67)8)') '1234(5678)' &gt;&gt;&gt; simplify('(AB)C') 'ABC' &gt;&gt;&gt; simplify('((AB)C)') 'ABC' </code></pre>
QA:
Different result for String and Integers using JSON in python
<p>That is actually how your data is:</p> <pre><code>&gt;&gt;&gt; s = '{"92": {"children": [{"87": {"children": [87, 96]}}, {"96": {"children": [90, 105]}}]}}' &gt;&gt;&gt; print(json.dumps(json.loads(s), indent=2)) { "92": { "children": [ { "87": { "children": [ 87, 96 ] } }, { "96": { "children": [ 90, 105 ] } } ] } } </code></pre> <p><code>87</code> is listed as a child of <code>87</code>.</p>
QA:
Django choices and dictionary
<p>Choices in Django models are <code>(key, value)</code> tuples. The key is what's meant to be stored in the model's field when saved and the value is meant to be what's displayed as an option. You can't simply jam a dictionary into the value.</p> <p>For example, the below choices would store <code>human</code> in the database and display <code>Humans</code> in a select field.</p> <pre><code>species = [ ('human', 'Humans'), ('reptile', 'Reptiles'), ('cylons', 'Aliens'), ] </code></pre> <p>Instead, you need to restructure how your model your data. You should create a separate <code>Category</code> model that represents the choices which will contain fields for a slug, icon and title.</p> <pre><code>class Category(models.Model): slug = models.SlugField() title = models.CharField() icon = models.CharField() </code></pre> <p>You then point your current model at the <code>Category</code> model using a <code>ForeignKey()</code>. </p> <pre><code>class MyModel(models.Model): category = models.ForeignKey(Category) </code></pre> <p>Finally, you can use a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a> when rendering the form to render the related category models (related across the foreign key) as choices in a list. If you use a <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/" rel="nofollow"><code>ModelForm</code></a>, all foreign keys will be represented as <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a>s by default.</p>