qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
62,376,571
I want to read an array of integers from single line where size of array is given in python3. Like read this to list. ``` 5 //size 1 2 3 4 5 //input in one line ``` **while i have tried this** ``` arr = list(map(int, input().split())) ``` but dont succeed how to give size. **Please help** I am new to py...
2020/06/14
[ "https://Stackoverflow.com/questions/62376571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12206760/" ]
Since, the framework itself has exposed a method to do something which can be done through vanilla javascript, it certainly has added advantages. One of the scenario I can think of is using React.forwardRef which can be used for: * Forwarding refs to DOM components * Forwarding refs in higher-order-components As expl...
you don't need react or angular to do any web development, angular and react give us a wrapper which will try to give us optimize reusable component, all the component we are developing using react can be done by web-component but older browser don't support this. **i am listing some of benefit of using ref in React**...
725
21,617,416
I just started working with python + splinter <http://splinter.cobrateam.info/docs/tutorial.html> Unfortunately I can't get the example to work. I cannot tell if: ``` browser.find_by_name('btnG') ``` is finding anything. Second, I try to click the button with button = browser.find\_by\_name('btnG').first butt...
2014/02/07
[ "https://Stackoverflow.com/questions/21617416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1639926/" ]
When all else fails update firefox. I upgraded my Jan 9, 2014 version and things could click!
The name of the button in my (Chromium) browser as of now is `'btnK'`.
726
46,415,102
I am running a nodejs server on port 8080, so my server can only process one request at a time. I can see that if i send multiple requests in one single shot, new requests are queued and executed sequentially one after another. What I am trying to find is, how do i run multiple instances/threads of this process. Examp...
2017/09/25
[ "https://Stackoverflow.com/questions/46415102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7999545/" ]
**First off, make sure your node.js process is ONLY using asynchronous I/O.** If it's not compute intensive and using asynchronous I/O, it should be able to have many different requests "in-flight" at the same time. The design of node.js is particularly good at this if your code is designed properly. If you show us the...
Like @poke said, you would use a reverse proxy and/or a load balancer in front. But if you want a software to run multiple instances of node, with balancing and other stuffs, you should check pm2 <http://pm2.keymetrics.io/>
727
37,883,759
When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages? > > [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)] > handshake failed; returned -1, SSL e...
2016/06/17
[ "https://Stackoverflow.com/questions/37883759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1998220/" ]
You get this error when the browser asks you to accept the certificate from a website. You can set to ignore these errors by default in order avoid these errors. For Chrome, you need to add ***--ignore-certificate-errors*** and ***--ignore-ssl-errors*** ChromeOptions() argument: ``` options = webdriver.ChromeOptions(...
I was facing the same problem. The problem was I did set `webdriver.chrome.driver` system property to chrome.exe. But one should download `chromedriver.exe` and set the file path as a value to `webdriver.chrome.driver` system property. Once this is set, everything started working fine.
730
29,159,657
I am a beginner in python. I want to know if there is any in-built function or other way so I can achieve below in python 2.7: Find all **-letter** in list and sublist and replace it with **['not',letter]** Eg: Find all items in below list starting with - and replace them with ['not',letter] ``` Input : ['and', ['or...
2015/03/20
[ "https://Stackoverflow.com/questions/29159657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/960970/" ]
Try a bit of recursion: ``` def change(lol): for index,item in enumerate(lol): if isinstance(item, list): change(item) elif item.startswith('-'): lol[index] = ['not',item.split('-')[1]] return lol ``` In action: ``` In [24]: change(['and', ['or', '-S', 'Q'], ['or', '-...
You need to use a recursive function.The `isinstance(item, str)` simply checks to see if an item is string. ``` def dumb_replace(lst): for ind, item in enumerate(lst): if isinstance(item, str): if item.startswith('-'): lst[ind] = ['not', 'letter'] else: ...
740
14,286,200
I'm building a website using pyramid, and I want to fetch some data from other websites. Because there may be 50+ calls of `urlopen`, I wanted to use gevent to speed things up. Here's what I've got so far using gevent: ``` import urllib2 from gevent import monkey; monkey.patch_all() from gevent import pool gpool...
2013/01/11
[ "https://Stackoverflow.com/questions/14286200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are multiple ways to do what you want: * Create a dedicated `gevent` thread, and explicitly dispatch all of your URL-opening jobs to that thread, which will then do the gevented `urlopen` requests. * Use threads instead of greenlets. Running 50 threads isn't going to tax any modern OS. * Use a thread pool and a ...
I've had similar problems with gevent when trying to deploy a web application. The thing you could do that would take the least hassle is to use a WSGI deployment that runs on gevent; examples include gUnicorn, uWSGI, or one of gevent's built-in WSGI servers. Pyramid should have a way of using an alternate deployment. ...
743
11,267,347
I have been [compiling diagrams](https://stackoverflow.com/questions/11253303/how-does-the-java-runtime-environment-compare-with-the-net-framework-in-terms-o) (pun intended) in hope of understanding the different implementations of common programming languages. I understand whether code is compiled or interpreted depen...
2012/06/29
[ "https://Stackoverflow.com/questions/11267347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1405543/" ]
For the reference implementation of python: (.py) -> python (checks for .pyc) -> (.pyc) -> python (execution dynamically loads modules) There are [other implementations](http://wiki.python.org/moin/PythonImplementations). Most notable are: * [jython](http://www.jython.org/) which compiles (.py) to (.class) and follo...
Python is technically a scripted language but it is also compiled, python source is taken from its source file and fed into the interpreter which often compiles the source to bytecode either internally and then throws it away or externally and saves it like a .pyc Yes python is a single virtual machine that then sits...
744
57,395,610
I'm creating a REST-API for my Django-App. I have a function, that returns a list of dictionaries, that I would like to serialize and return with the rest-api. The list (nodes\_of\_graph) looks like this: [{'id': 50, position: {'x': 99.0, 'y': 234.0}, 'locked': True}, {'id': 62, position: {'x': 27.0, 'y': 162.0}, 'loc...
2019/08/07
[ "https://Stackoverflow.com/questions/57395610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11895645/" ]
You can register shortcut events on the page (such as MainPage). ```cs public MainPage() { this.InitializeComponent(); Window.Current.Dispatcher.AcceleratorKeyActivated += AccelertorKeyActivedHandle; } private async void AccelertorKeyActivedHandle(CoreDispatcher sender, AcceleratorKeyEventArgs args) { if ...
Try writing a function in your code which is triggered when a specific set of keys are pressed together. For example, if you want to print an emoji when the user presses "Ctrl + 1", write a function or a piece of code which is triggered when Ctrl and 1 are pressed together and appends the text in the multiline-textb...
747
54,040,018
I have a requirement of testing OSPF v2 and OSPF v3 routing protocols against their respective RFCs. Scapy module for python seems interesting solution to craft OSPF packets, but are there any open source OSPF libraries over scapy that one could use to create the test cases. Would appreciate any pointers in this direct...
2019/01/04
[ "https://Stackoverflow.com/questions/54040018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6192859/" ]
You should use the usual `tput` program for producing the correct escape sequences for the actual terminal, rather than hard-coding specific strings (that look ugly in an Emacs compilation buffer, for example): ``` printf-bold-1: @printf "normal text - `tput bold`bold text`tput sgr0`" .PHONY: printf-bold-1 ``` ...
Ok, I got it. I should have used `\033` instead of `\e` or `\x1b` : ``` printf-bold-1: @printf "normal text - \033[1mbold text\033[0m" ``` Or, as suggested in the comments, use simple quotes instead of double quotes : ``` printf-bold-1: @printf 'normal text - \e[1mbold text\e[0m' ``` `make printf-bold-1` ...
748
1,171,926
I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder. The issue here is not the poi...
2009/07/23
[ "https://Stackoverflow.com/questions/1171926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42546/" ]
In C, that would have been more or less legal. In C++, functions typically shouldn't do that. You should try to use [RAII](http://en.wikipedia.org/wiki/RAII) to guarantee memory doesn't get leaked. And now you might say "how would it leak memory, I call `delete[]` just there!", but what if an exception is thrown at ...
Use RAII (Resource Acquisition Is Initialization) design pattern. <http://en.wikipedia.org/wiki/RAII> [Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)](https://stackoverflow.com/questions/712639/please-help-us-non-c-developers-understand-what-raii-is)
749
52,019,077
``` from bs4 import BeautifulSoup import requests url = "https://www.104.com.tw/job/?jobno=5mjva&jobsource=joblist_b_relevance" r = requests.get(url) r.encoding = "utf-8" print(r.text) ``` I want to reach the content in div ("class=content")(p) but when I print the r.text out there's a big part disappear. But I a...
2018/08/25
[ "https://Stackoverflow.com/questions/52019077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10273637/" ]
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random\_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page . i would do that through database queries...
759
25,165,500
I'm trying to get zipline working with non-US, intraday data, that I've loaded into a pandas DataFrame: ``` BARC HSBA LLOY STAN Date 2014-07-01 08:30:00 321.250 894.55 112.105 1777.25 2014-07-01 08:32:00 321.150 894.70 112.095 ...
2014/08/06
[ "https://Stackoverflow.com/questions/25165500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2196034/" ]
I've got this working after fiddling around with the tutorial notebook. Code sample below. It's using the DF `mid`, as described in the original question. A few points bear mentioning: 1. **Trading Calendar** I create one manually and assign to `trading.environment`, by using non\_working\_days in *tradingcalendar\_ls...
@Luciano You can add `analyze(None, perf_manual)`at the end of your code for automatically running the analyze process.
760
54,119,766
I am using python2.7 I have a json i pull that is always changing when i request it. I need to pull out `Animal_Target_DisplayNam`e under Term7 Under Relation6 in my dict. The problem is sometimes the object Relation6 is in another part of the Json, it could be leveled deeper or in another order. I am trying to cre...
2019/01/09
[ "https://Stackoverflow.com/questions/54119766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6856433/" ]
I guess your only option is running through the entire dict and get the values of `Animal_Target_DisplayName` key, I propose the following recursive solution: ```py def run_json(dict_): animal_target_sons = [] if type(dict_) is list: for element in dict_: animal_target_sons.append(run_json(...
Since you're getting JSON, why not make use of the json module? That will do the parsing for you and allow you to use dictionary functions+features to get the information you need. ``` #!/usr/bin/python2.7 from __future__ import print_function import json # _somehow_ get your JSON in as a string. I'm calling it "jstr...
761
64,311,719
I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element. My script is as follows...
2020/10/12
[ "https://Stackoverflow.com/questions/64311719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9953181/" ]
If the script is working perfectly fine without headless mode, probably there is issue with the window size. Along with specifying --no-sandbox option, try changing the window size passed to the webdriver chrome\_options.add\_argument('--window-size=1920,1080') This window size worked in my case. Even if this dosen'...
I would refactor code in a way to wait until elements will be present on a web page: ``` from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.I...
762
15,642,581
I've installed numpy and when I go to install Matplotlib it fails. Regardless of the method I use to install it. Below are the errors I receive. ``` gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -O2 - DNDEBUG -g -O3 -DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 - I/...
2013/03/26
[ "https://Stackoverflow.com/questions/15642581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1238230/" ]
``` public static void Display_Grid(DataGrid d, List<string> S1) { ds = new DataSet(); DataTable dt = new DataTable(); ds.Tables.Add(dt); DataColumn cl = new DataColumn("Item Number", typeof(string)); cl.MaxLength = 200; dt.Columns.Add(cl); int i = 0; foreach (string s in S1) { ...
add new row in datagrid using observablecollection ItemCollection ``` itemmodel model=new itemmodel (); model.name='Rahul'; ItemCollection.add(model); ```
770
60,358,982
I am getting an **Internal Server Error** and not sure if i need to change something in wsgi. The app was working fine while tested on virtual environment on port 8000. I followed all the steps using the tutorial <https://www.youtube.com/watch?v=Sa_kQheCnds> the apache error log shows the following : ``` [Sun Feb 23...
2020/02/23
[ "https://Stackoverflow.com/questions/60358982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10881955/" ]
UPD: Now I'm sure the reason of such behavior is "AdBlock Plus" Chrome Extension (ID: cfhdojbkjhnklbpkdaibdccddilifddb). I think the refresh started to happen after the extension's update. When I open DevTools in Chrome Incognito mode AdBlock is disabled and I get no refresh, also there's no refresh on another PC I us...
I have found that some extensions cause page refreshes, such as "Awesome Color Picker"
771
54,390,224
My question is why can I not use a relative path to specify a bash script to run? I have a ansible file structure following [best practice](https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html#directory-layout). My directory structure for this role is: ``` . ├── files │   └── install-wat...
2019/01/27
[ "https://Stackoverflow.com/questions/54390224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10055448/" ]
I put together a test of this to see: <https://github.com/farrellit/ansible-demonstrations/tree/master/shell-cwd> It has convinced me that the short answer is probably, *ansible roles' `shell` tasks will by default have the working directory of the playbook that include that role*. It basically comes down to a role...
Shell will execute the command on the remote. You have copied the script to `/home/vagrant/install-watchman.bash` on your remote. Therefore you have to use that location for executing on the remote as well. ``` - name: install Watchman shell: /home/vagrant/install-watchman.bash ``` a relative path will work as wel...
772
68,759,605
> > {"name": "Sara", "grade": "1", "school": "Buckeye", "teacher": "Ms. Black", "sci": {"gr": "A", "perc": "93"}, "math": {"gr": "B+", "perc": "88"}, "eng": {"gr": "A-", "perc": "91"}} > > > I have the json file above (named test) and I am trying to turn it into a dataframe in python using pandas. The pd.read\_jso...
2021/08/12
[ "https://Stackoverflow.com/questions/68759605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10256905/" ]
Try with `pd.json_normalize()`, as follows: ``` df = pd.json_normalize(test) ``` **Result:** ``` print(df) name grade school teacher sci.gr sci.perc math.gr math.perc eng.gr eng.perc 0 Sara 1 Buckeye Ms. Black A 93 B+ 88 A- 91 ```
Use `pd.json_normalize` after convert json file to python data structure: ``` import pandas as pd import json data = json.load('data.json') df = pd.json_normalize(data) ``` ``` >>> df name grade school teacher sci.gr sci.perc math.gr math.perc eng.gr eng.perc 0 Sara 1 Buckeye Ms. Black A 9...
773
64,609,700
I have a script that imports another script, like this: ``` from mp_utils import * login_response = login(...) r = incomingConfig(...) ``` and mp\_utils.py is like this: ``` import requests import logging from requests.exceptions import HTTPError def login( ... ): ... def incomingConfig( ... ): ... ``` ...
2020/10/30
[ "https://Stackoverflow.com/questions/64609700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2115947/" ]
`from x import *` imports everything so that you don't have to name the module before you call a function. Try removing `mp_utils` from your function calls.
It is importing all the functions correctly, when you import using `from` then you don't have to prefix `mp_utils` to call the functions, just you can call it by their name. To call `mp_utils` prefixed, use `import mp_utils` instead.
774
5,082,697
I have created with the "extra" clause a concatenated field out of three text fields in a model - and I expect to be able to do this: q.filter(concatenated\_\_icontains="y") but it gives me an error. What alternatives are there? ``` >>> q = Patient.objects.extra(select={'concatenated': "mrn||' '||first_name||' '||last...
2011/02/22
[ "https://Stackoverflow.com/questions/5082697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443404/" ]
If you need something beyond this, ``` Patient.objects.filter(first_name__icointains='y' | last_name__icontains='y' | mrn__icontains='y') ``` you might have to resort to raw SQL. Of course, you can add in your `extra` either before or after the filter above.
My final solution based on Prasad's answer: ``` from django.db.models import Q searchterm='y' Patient.objects.filter(Q(mrn__icontains=searchterm) | Q(first_name__icontains=searchterm) | Q(last_name__icontains=searchterm)) ```
776
54,434,766
I have to define Instance variable, This Instance Variable is accessed in different Instance methods. Hence I am setting up Instance Variable under constructor. I see best of Initializing instance variables under constructor. Is it a Good practice to use if else condition under constructor to define instance variable....
2019/01/30
[ "https://Stackoverflow.com/questions/54434766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10966964/" ]
The relationship between teams and managers is very straightforward data; I would not like having it as code. Thus, a lookup dictionary would be my choice. ``` class Test: TEAM_MANAGERS = { "Dev": "Bob", "QA": "Kim", "Admin": "Jeff", } def __init__(self, emp_name, team): se...
There is nothing wrong with using `if-else` inside the `__init__()` method. Based upon the condition you want the specific variable to be initialized, this is appropriate.
777
17,297,230
I am new to python and have tried searching for help prior to posting. I have binary file that contains a number of values I need to parse. Each value has a hex header of two bytes and a third byte that gives a size of the data in that record to parse. The following is an example: ``` \x76\x12\x0A\x08\x00\x00\x00\x0...
2013/06/25
[ "https://Stackoverflow.com/questions/17297230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519943/" ]
Is something like this what you want? ``` >>> b = b'\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00' >>> from StringIO import StringIO >>> io = StringIO(b) >>> io.seek(0) >>> io.read(2) #read 2 bytes, maybe validate? 'v\x12' >>> import struct >>> nbytes = struct.unpack('B',io.read(1)) >>> print nbytes (10,) >>> data ...
This will treat the data as a raw string (to ignore '\' escape character and split into a list ``` a = r"\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00".split('\\') print a ``` output: ['', 'x76', 'x12', 'x0A', 'x08', 'x00', 'x00', 'x00', 'x00', 'x00', 'x00', 'x00', 'x00'] You can then iterate through the values ...
782
68,840,058
I would like to show the data of a hdf5 file in the ImageView() class from pyqtgraph. The bare code of displaying the plot for ImageView() is: ``` from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph as pg # Interpret image data as row-major instead of col-major pg.setConfigOptions(leftButtonPan = False, imageAxis...
2021/08/18
[ "https://Stackoverflow.com/questions/68840058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8313547/" ]
This should help with the second part. ```r df %>% group_by(species, native_region, intro_region) %>% filter(all(c(1,0) %in% invasive)) %>% filter(., invasive == 0) %>% anti_join(df, .) # A tibble: 11 × 4 species native_region invasive intro_region <chr> <dbl> <dbl> <dbl> 1 Ab...
Figured out the first part: ```r df %>% select(species, native_region) -> x df %>% group_by(species) %>% anti_join(., x, by = c("species", "intro_region" = "native_region")) # A tibble: 9 x 4 # Groups: species [3] species native_region invasive intro_region <chr> <dbl> <dbl> <dbl> 1 Abies ...
783
17,786,203
Consider the array `a= [1, 2, 3, 1, 2, 3]`. Now suppose I want to remove all the 2s in this array in python. So I apply `a.remove(2)`. However the result which comes out is `[1, 3, 1, 2, 3]`, i.e the only first 2 is removed. How can I remove all the 2s which appear in an array? In general, given an array and an element...
2013/07/22
[ "https://Stackoverflow.com/questions/17786203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2517072/" ]
Use a list comprehension to build a replacement list, where all elements are *not* equal to `p`: ``` a = [i for i in a if i != p] ``` Note that in Python, the datatype is called a `list`, not an array.
You can use [`filter()`](http://docs.python.org/2/library/functions.html#filter). ``` >>> a= [1, 2, 3, 1, 2, 3] >>> filter(lambda x: x != 2, a) [1, 3, 1, 3] ``` In a function : ``` >>> def removeAll(inList, num): return filter(lambda elem: elem != num, inList) >>> removeAll(a, 2) [1, 3, 1, 3] ```
784
9,845,354
I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains. So far I have this, which I can run through CDM, and state a file to open. I've messed around wi...
2012/03/23
[ "https://Stackoverflow.com/questions/9845354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289022/" ]
The Counter type is useful for counting items. It was added in python 2.7: ``` import collections counts = collections.Counter() for line in datafile: # remove the EOL and iterate over each character #if you desire the counts to be case insensitive, replace line.rstrip() with line.rstrip().lower() for c in...
If you want to use regular expressions, you can do as follows: ``` pattern = re.compile('[^a-zA-Z]+') # pattern for everything but letters only_letters = pattern.sub(text, '') # delete everything else count = len(only_letters) # total number of letters ``` For counting the number of distinct characters, use Counter ...
785
57,045,356
This is a problem given in ***HackWithInfy2019*** in hackerrank. I am stuck with this problem since yesterday. Question: --------- You are given array of N integers.You have to find a pair **(i,j)** which **maximizes** the value of **GCD(`a[i],a[j]`)+(`j - i`)** and 1<=i< j<=n Constraints are: ---------------- 2<=...
2019/07/15
[ "https://Stackoverflow.com/questions/57045356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11669081/" ]
Here is an approach that could work: ``` result = 0 min_i = array[1 ... 100000] initialized to 0 for j in [1, 2, ..., n] for d in divisors of a[j] let i = min_i[d] if i > 0 result = max(result, d + j - i) else min_i[d] = j ``` Here, `min_i[d]` for each `d` is the s...
Here is one way of doing it. Create a mutable class `MinMax` for storing the min. and max. index. Create a `Map<Integer, MinMax>` for storing the min. and max. index for a particular divisor. For each value in `a`, find all divisors for `a[i]`, and update the map accordingly, such that the `MinMax` object stores the...
791
44,794,782
I am in the process of downloading data from firebase, exporting it into a json. After this I am trying to upload it into bigquery but I need to remove the new line feed for big query to accept it. ``` { "ConnectionTime": 730669.644775033, "objectId": "eHFvTUNqTR", "CustomName": "Relay Controller", "F...
2017/06/28
[ "https://Stackoverflow.com/questions/44794782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8192249/" ]
Reading between the lines, I think the input format might be a single JSON array, and the desired output is newline-separated JSON representations of the elements of that array. If so, this is probably all that's needed: ``` with open('testnoline.json', 'w') as outfile: for obj in data_json: outfile.write(...
You only need to make sure that `indent=None` when you [`dump`](https://docs.python.org/2/library/json.html#basic-usage) you data to json: ``` with open('testnoline.json', 'w') as outfile: json.dump(data_json, outfile, indent=None) ``` Quoting from the doc: > > If `indent` is a non-negative integer, then JS...
792
42,281,484
I am attempting to measure the period of time from when a user submits a PHP form to when they submit again. The form's action is the same page so effectively it's just a refresh. Moreover, the user may input the same data again. I need it so that it begins counting before the page refreshes as the result must be as ac...
2017/02/16
[ "https://Stackoverflow.com/questions/42281484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could try a simple extension. Here's an example: ``` extension UIImageView { func render(with radius: CGFloat) { // add the shadow to the base view self.backgroundColor = UIColor.clear self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0, hei...
You can just add the image in and give it a few attributes to make it round. When you have the UImage selected click on the attributes tab and click on the '+' and type in ``` layer.cornerRadius ``` And change it to a number instead of a string. All number 1-50 work. If you want a perfect circle then type in 50.
793
37,083,591
I've been creating a studying program for learning japanese using python and tried condensing and randomizing it butnow it doesnt do the input,i have analyzed it multiple times and cant find any reason here is what i have for it so far,any suggestions would be appreciate ``` import sys import random start = input("Are...
2016/05/07
[ "https://Stackoverflow.com/questions/37083591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6302586/" ]
You can encrypt your parameters string and then send it as a message > > Encrypted URL form: > > > ``` myAppName://encrypted_query ``` Now when you get a call in your app, you should fetch the `encryptedt_data` out of the URL and should decrypt it before actually doing anything. > > Decrypted URL form: > > ...
> > So the best way to go about this is to insert the URL scheme `myAppName://someQuery?blablabla=123` and that should in turn fire the `openURL` command and open that specific view. > > > I'm assuming you're using a web view and that's why you want to handle things this way. But are you aware of the `WKScriptMess...
796
33,362,977
i got a program which needs to send a byte array via a serial communication. And I got no clue how one can make such a thing in python. I found a c/c++/java function which creates the needed byte array: ``` byte[] floatArrayToByteArray(float[] input) { int len = 4*input.length; int index=0; byte[] b = new byte[4...
2015/10/27
[ "https://Stackoverflow.com/questions/33362977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206668/" ]
Put your data to array (here are [0,1,2] ), and send with: serial.write(). I assume you've properly opened serial port. ``` >> import array >> tmp = array.array('B', [0x00, 0x01, 0x02]).tostring() >> ser.write(tmp.encode()) ``` Ansvered using: [Binary data with pyserial(python serial port)](https://stackoverflow.com...
It depends on if you are sending a signed or unsigned and other parameters. There is a bunch of documentation on this. This is an example I have used in the past. ``` x1= 0x04 x2 = 0x03 x3 = 0x02 x4 = x1+ x2+x3 input_array = [x1, x2, x3, x4] write_bytes = struct.pack('<' + 'B' * len(input_array), *input_array) ser....
797
35,877,007
I need a cron job to work on a file named like this: ``` 20160307_20160308_xxx_yyy.csv (yesterday_today_xxx_yyy.csv) ``` And my cron job looks like this: ``` 53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date -d "yesterday" +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron...
2016/03/08
[ "https://Stackoverflow.com/questions/35877007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351197/" ]
I found the answer to my own question. I needed to use this to get yesterday's date: ``` 53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date -v-1d +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1 ``` Hope it helps somebody!
This version worked for me. Maybe it can be helpful for someone: ``` 53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date --date '-1 day' +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1 ```
798
50,305,112
I am trying to install pandas in my company computer. I tried to do ``` pip install pandas ``` but operation retries and then timesout. then I downloaded the package: pandas-0.22.0-cp27-cp27m-win\_amd64.whl and install: ``` pip install pandas-0.22.0-cp27-cp27m-win_amd64 ``` But I get the following error: > >...
2018/05/12
[ "https://Stackoverflow.com/questions/50305112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4570833/" ]
This works for me: ``` pip --default-timeout=1000 install pandas ```
In my case, my network was configured to use IPV6 by default, so I changed it to work with IPV4 only. You can do that in the Network connections section in the control panel: `'Control Panel\All Control Panel Items\Network Connections'` [![enter image description here](https://i.stack.imgur.com/agR8k.png)](https://i...
799
37,015,123
I have a user defined dictionary (sub-classing python's built-in dict object), which does not allow modifying the dict directly: ``` class customDict(dict): """ This dict does not allow the direct modification of its entries(e.g., d['a'] = 5 or del d['a']) """ def __init__(self, *args, **kwargs): ...
2016/05/03
[ "https://Stackoverflow.com/questions/37015123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3076813/" ]
Your `deepcopy` implementation does not work because the values of `dict` is not stored in `__dict__`. `dict` is a special class. You can make it work calling `__init__` with a deepcopy of the dict. ``` def __deepcopy__(self, memo): def _deepcopy_dict(x, memo): y = {} memo[id(x)] = y for ke...
Something like this should work without having to change deepcopy. ``` x2 = customList(copy.deepcopy(list(x1))) ``` This will cast `x1` to a `list` deepcopy it then make it a `customList` before assigning to `x2`.
804
66,469,499
I made a memory game in python where players take turn picking two tiles in a grid to see if the revealed letters match. I used two lists for this, one to store the letters e.g. `letters = ['A', 'A', 'B', 'B']` and the other to record the revealed letters that matches so far in the game e.g. `correctly_revealed = ['A'...
2021/03/04
[ "https://Stackoverflow.com/questions/66469499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14026994/" ]
This is indeed Red, Green, Blue, and Alpha, mapped to the 0.0 to 1.0 range, but with an additional transformation as well: These values have been converted from the sRGB colorspace to linear using the [sRGB transfer function](https://en.wikipedia.org/wiki/SRGB). (The back story here is, the [baseColorTexture](https://g...
It is RGBA format, but with numbers between 0 and 1. If you want to insert a color in the Format: * RGB (255, 255, 255) [=white] divide all values by `255` and use `1` (=fully opaque for the last value * RGBA (255, 0, 0, 255) [=fully opaque red] divide all components by `255` Documentation can be found [here](http://...
805
64,399,807
I learning python web automation using selenium but when I trying to add a input for find\_element\_by\_name it is not working. ``` from selenium import webdriver PATH = 'C:\Program Files (x86)\chromedriver.exe' driver = webdriver.Chrome(PATH) driver.get('https://kahoot.it') codeInput = driver.find_element_by_nam...
2020/10/17
[ "https://Stackoverflow.com/questions/64399807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14466617/" ]
First make sure that you spelled it "gameId" and not "gadmeId" Also import send keys: ``` from selenium.webdriver.common.keys import Keys ``` Then you can send the gameId ``` codeInput = driver.find_element_by_name('gameId') codeInput.send_keys('202206') ```
To send value to the input tag. ``` codeInput.send_keys('202206') ``` Also ``` driver.find_element_by_name('gameId') ``` is suppose to be gameId. I would also use a wait after the driver.get() for page loading.
806
61,122,276
So I've been following Google's official tensorflow guide and trying to build a simple neural network using Keras. But when it comes to training the model, it does not use the entire dataset (with 60000 entries) and instead uses only 1875 entries for training. Any possible fix? ```py import tensorflow as tf from tenso...
2020/04/09
[ "https://Stackoverflow.com/questions/61122276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935310/" ]
The number `1875` shown during fitting the model is not the training samples; it is the number of *batches*. `model.fit` includes an optional argument `batch_size`, which, according to the [documentation](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit): > > If unspecified, `batch_size` will default to...
It does not train on 1875 samples. ``` Epoch 1/10 1875/1875 [=== ``` 1875 here is the number of steps, not samples. In `fit` method, there is an argument, `batch_size`. The default value for it is `32`. So `1875*32=60000`. The implementation is correct. If you train it with `batch_size=16`, you will see the number ...
808
24,070,856
I have a problem with QCheckBox. I am trying to connect a boolean variable to a QCheckBox so that **when I change the boolean variable, the QCheckBox will be automatically checked or unchecked.** My Question is similar to the Question below but in opposite way. [question: Python3 PyQt4 Creating a simple QCheckBox ...
2014/06/05
[ "https://Stackoverflow.com/questions/24070856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727296/" ]
[`property`](https://docs.python.org/2/library/functions.html#property) is the way to define a variable that does additional work upon assigning/accessing. Below is the code modified for that purpose. It changes `ILCheck` to a property such that it'll also update the checkbox upon assigning. Proper error checking for `...
just use `ILCheckbox.setCheckState(Qt.Checked)` after calling ILCheck. You don't neet signals here since you can call a slot sirectly. If you want to do use this feature more than once, you should consider writing a setter which changes the state of `self.ILCheck` and emits a signal. Edit after your clarification: ...
811
3,014,223
We build software using Hudson and Maven. We have C#, java and last, but not least PL/SQL sources (sprocs, packages, DDL, crud) For C# and Java we do unit tests and code analysis, but we don't really know the health of our PL/SQL sources before we actually publish them to the target database. ### Requirements There ...
2010/06/10
[ "https://Stackoverflow.com/questions/3014223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11562/" ]
I think that this blog describes the needed process: <http://www.theserverlabs.com/blog/?p=435> Please check and let me know what you think about it.
Our approach is to keep each database object (tables, views, functions, packages, sprocs etc) in its own file under source control and have an integration server ([TeamCity](http://www.jetbrains.com/teamcity/), [Hudson](http://hudson-ci.org/) etc) do a nightly build of the database - from source - where it drops and re...
814
17,410,970
In my program, many processes can try to create a file if the file doesnt exist currently. Now I want to ensure that only one of the processes is able to create the file and the rest get an exception if its already been created(kind of process safe and thread safe open() implementation). How can I achieve this in pyt...
2013/07/01
[ "https://Stackoverflow.com/questions/17410970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421499/" ]
In Python 2.x: ``` import os fd = os.open('filename', os.O_CREAT|os.O_EXCL) with os.fdopen(fd, 'w') as f: .... ``` In Python 3.3+: ``` with open('filename', 'x') as f: .... ```
If you're running on a Unix-like system, open the file like this: ``` f = os.fdopen(os.open(filename, os.O_CREAT | os.O_WRONLY | os.O_EXCL), 'w') ``` The `O_EXCL` flag to `os.open` ensures that the file will only be created (and opened) if it doesn't already exist, otherwise an `OSError` exception will be raised. Th...
816
69,499,962
So I have this big .csv in my work that looks something like this: ``` Name| Adress| Email| Paid Value John| x street | John@dmail.com| 0| Chris| c street | Chris@dmail.com| 100| Rebecca| y street| RebeccaFML|@dmail.com|177| Bozo | z street| BozoSMH|@yahow.com|976| ``` As you can see, the .csv is seperated by pi...
2021/10/08
[ "https://Stackoverflow.com/questions/69499962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14166159/" ]
with subset using `dplyr` you can use the code below ``` library(dplyr) df %>% subset(!is.na(value) & bs_Scores != "bs_24" ) ```
A `dplyr` solution: ```r library(tidyverse) bs_scores <- tibble::tribble( ~bs_Scores, ~value, "bs_0", 16.7, "bs_1", 41.7, "bs_12", 33.3, "bs_24", NA, "bs_0", 25, "bs_1", 41.7,...
817
50,675,758
Help me please with understanding some of asyncio things. I want to realize if its possible to do next: I have synchronous function that for example creates some data in remote API (API can returns success or fail): ``` def sync_func(url): ... do something return result ``` I have coroutine to run that sync o...
2018/06/04
[ "https://Stackoverflow.com/questions/50675758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235755/" ]
If you create a future (task) out of your coroutine before you shield it, you can always check it later. For example: ``` coro_task = loop.create_task(coro_func(url)) try: result = await asyncio.wait_for(asyncio.shield(coro_task), API_TIMEOUT) except asyncio.TimeoutError: pending_tasks[api_details['api_url']] ...
Ok, thanks @user4815162342 I figured out how to process tasks those were interrupted by timeout - in common my solution now looks like: ``` def sync_func(url): ... do something probably long return result async def coro_func(url) loop = asyncio.get_event_loop() fn = functools.partial(sync_func, url) ...
819
64,341,672
``` totalquestions = int(5) while totalquestions > 0 : num1 = randint(0,9) num2 = randint(0,9) print(num1) print(num2) answer = input(str("What is num1 ** num2?")) if answer == (num1 ** num2): print("correct") else: print("false") ``` I'm trying to create a quiz program whe...
2020/10/13
[ "https://Stackoverflow.com/questions/64341672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14444439/" ]
You need to collect the arguments first, *then* pass them to `Person`. ``` def getPeople(num): people = [] for i in range(num): name = input("What is the persons name?: ") age = input("What is the persons age?: ") computing = input("What is the persons Computing score?: ") math...
You have added an init method for the class, so you need to pass all those variables as arguments when you call the `Person()` class. As an example: ``` name = input() age = input() .... new_person = Person(name, age, ...) people.append(new_person) ```
820
39,225,263
The bottleneck of my code is currently a conversion from a Python list to a C array using ctypes, as described [in this question](https://stackoverflow.com/questions/4145775/how-do-i-convert-a-python-list-into-a-c-array-by-using-ctypes). A small experiment shows that it is indeed very slow, in comparison of other Pyth...
2016/08/30
[ "https://Stackoverflow.com/questions/39225263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110059/" ]
Here's a little trick, it works for all sorts of situations including yours. But also for trailing comma's for example. Concept ------- Instead of printing your text directly, store it in an array like so: ``` $information_to_print = ['col1', 'col2', 'col3']; $cols = []; foreach ($information_to_print as $col) { ...
I think this might be easier if the row elements are inside the loop rather than outside. For example here's a quick pseudocode: ``` array items sum = 0 loop through items open row print output for this item increment sum if sum is 1 set sum 0 close row if this is not t...
823
18,785,063
I've created virtualenv for Python 2.7.4 on Ubuntu 13.04. I've installed python-dev. I have [the error](http://pastebin.com/YQfdYDVK) when installing numpy in the virtualenv. Maybe, you have any ideas to fix?
2013/09/13
[ "https://Stackoverflow.com/questions/18785063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212100/" ]
The problem is `SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.` so do the following in order to obtain 'Python.h' make sure apt-get and gcc are up to date ``` sudo apt-get update sudo apt-get upgrade gcc ``` then install the python2.7-dev ``` sudo apt-get install ...
This is probably because you do not have the `python-dev` package installed. You can install it like this: ``` sudo apt-get install python-dev ``` You can also install it via the Software Center: ![enter image description here](https://i.stack.imgur.com/mNiu0.png)
824
22,099,882
I need some help with the encoding of a list. I'm new in python, sorry. First, I'm using Python 2.7.3 I have two lists (entidad & valores), and I need to get them encoded or something of that. My code: ``` import urllib from bs4 import BeautifulSoup import csv sock = urllib.urlopen("http://www.fatm.com.es/Datos_Equ...
2014/02/28
[ "https://Stackoverflow.com/questions/22099882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3361555/" ]
You should encode your data to utf-8 manually, csv.writer didnt do it for you: ``` w.writerow([s.encode("utf-8") for s in header]) w.writerow([s.encode("utf-8") for s in values]) #w.writerow(header) #w.writerow(values) ```
This appears to be the same type of problem as had been found here [UnicodeEncodeError in csv writer in Python](http://love-python.blogspot.com/2012/04/unicodeencodeerror-in-csv-writer-in.html) > > UnicodeEncodeError in csv writer in Python > > Today I was writing a > program that generates a csv file after some...
834
41,286,526
I am trying to setup a queue listener for laravel and cannot seem to get supervisor working correctly. I get the following error when I run `supervisorctl reload`: `error: <class 'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib/python2.7/socket.py line: 228` The file DOES exist. If try to run `sud...
2016/12/22
[ "https://Stackoverflow.com/questions/41286526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965066/" ]
You should run `sudo service supervisor start` when you are in the supervisor dir. Worked for me.
I had a very similar problem (Ubuntu 18.04) and searched similar threads to no avail so answering here with some more comprehensive answers. Lack of a sock file or socket error is only an indicator that supervisor is not running. If a simple restart doesn't work its either 1. not installed, or 2. failing to start. In ...
835
18,995,555
I'm trying check whether the short int have digits that contains in long int. Instead this came out: ``` long int: 198381998 short int: 19 Found a match at 0 Found a match at 1 Found a match at 2 Found a match at 3 Found a match at 4 Found a match at 5 Found a match at 6 Found a match at 7 ``` It's s...
2013/09/25
[ "https://Stackoverflow.com/questions/18995555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2811732/" ]
You're passing `allData` as an argument to the mapping, but it isn't defined anywhere. You want `data.users` instead (*not* `data` because then `ko.mapping.fromJSON` will return a single object with one key, `users` whose value will be an `observableArray`; you'll confuse Knockout if you try to use that object as the v...
Switching to this .ajax call seemed to resolve the issue. ``` // Load initial state from server, convert it to User instances, then populate self.users $.ajax({ url: '/sws/users/index', dataType: 'json', type: 'POST', success: function (data) { self.users(data['users']);...
845
63,087,586
In my views.py file of my Django application I'm trying to load the 'transformers' library with the following command: ``` from transformers import pipeline ``` This works in my local environment, but on my Linux server at Linode, when I try to load my website, the page tries to load for 5 minutes then I get a Timeo...
2020/07/25
[ "https://Stackoverflow.com/questions/63087586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4823067/" ]
Maybe you just have to create or update your *requirements.txt* file. Here is the command : `pip freeze > requirements.txt`
Based on this [answer](https://serverfault.com/a/514251) > > Some third party packages for Python which use C extension modules, and this includes scipy and numpy, will only work in the Python main interpreter and cannot be used in sub interpreters as mod\_wsgi by default uses. > > > `transformers` library uses n...
846
23,728,065
I have been banging my head against the wall with this for long enough that I am okay to turn here at this point. I have a page with iframe: ``` <iframe frameborder="0" allowtransparency="true" tabindex="0" src="" title="Rich text editor, listing_description" aria-describedby="cke_18" style="width:100%;height:100%"> ...
2014/05/19
[ "https://Stackoverflow.com/questions/23728065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360826/" ]
you need Wget for Windows, you can download it from here <http://gnuwin32.sourceforge.net/packages/wget.htm> open notepad and paste your code, save as "myscript.bat" make sure it doesn't have .txt put your "myscript.bat" in the same folder with wget.exe now try it, it should work
For a newer firmware version, U need to add referer and user-agent. Try this, work for me: ``` wget -qO- --user=admin --password=admin --referer http://192.168.0.1 --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://192.168.0.1/userRpm/SysRebootRpm.htm?Reboot=Reboot ...
847
55,603,451
I am trying to make a program that analyzes stocks, and right now I wrote a simple python script to plot moving averages. Extracting the CSV file from the native path works fine, but when I get it from the web, it doesn't work. Keeps displaying an error: 'list' object has no attribute 'Date' It worked fine with .CSV, ...
2019/04/10
[ "https://Stackoverflow.com/questions/55603451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11337553/" ]
The data got placed in a (one-element) list. If you do this, after the `read_html` call, it should work: ``` df = df[0] ```
Did you mean to access the Date feature from the DataFrame object? If that is the case, then change: `python x = df.Date` to `python x = df['Date']` `python y = df.Close` to `python y = df['Close']` EDIT: Also: `python df.plot(x='Date', y='Close', style='o')` works instead of plt.plot
848
3,949,727
For code: ``` #!/usr/bin/python src = """ print '!!!' import os """ obj = compile(src, '', 'exec') eval(obj, {'__builtins__': False}) ``` I get output: ``` !!! Traceback (most recent call last): File "./test.py", line 9, in <module> eval(obj, {'__builtins__': False}) File "", line 3, in <module> ImportEr...
2010/10/16
[ "https://Stackoverflow.com/questions/3949727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23712/" ]
The `__import__` method is invoked by the `import` keyword: [python.org](http://docs.python.org/library/functions.html?highlight=import#__import__) If you want to be able to import a module you need to leave the `__import__` method in the builtins: ``` src = """ print '!!!' import os """ obj = compile(src, '', 'exe...
In your `eval` the call to `import` is made successfully however `import` makes use of the `__import__` method in builtins which you have made unavailable in your `exec`. This is the reason why you are seeing ``` ImportError: __import__ not found ``` `print` doesn't depend on any builtins so works OK. You could pas...
849
26,797,378
I'm developing an aplication built on the python Bottle framework. It's amazing and i want to host it somewhere, but of course i need a service where i can run the server. What are the best options available (on costs too)? Thanks!
2014/11/07
[ "https://Stackoverflow.com/questions/26797378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2344954/" ]
I work for [PythonAnywhere](http://www.pythonanywhere.com/), a Python hosting company, so obviously I think we have a great Bottle hosting solution -- check it out :-) Some of our competitors -- ones where we feel proud if a customer leaves them to move to us, or where we don't feel too depressed if they leave us to g...
The easiest way to host is use Ngrok ,its an open source tool where use get a temporary link where you can access your local host server on any machine through that link .you can download it from here <https://ngrok.com/>
854
12,667,057
I want my Python program to be deterministic, so I have been using `OrderedDicts` extensively throughout the code. Unfortunately, while debugging memory leaks today, I discovered that OrderedDicts have a custom `__del__` method, making them uncollectable whenever there's a cycle. It's rather unfortunate that there's no...
2012/10/01
[ "https://Stackoverflow.com/questions/12667057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1420279/" ]
If the presence of the \_\_del\_\_ method is problematic for you, just remove it: ``` >>> import collections >>> del collections.OrderedDict.__del__ ``` You will gain the ability to use OrderedDicts in a reference cycle. You will lose having the OrderedDict free all its resources immediately upon deletion.
It sounds like you've tracked down a bug in `OrderedDict` that was fixed at some point after your version of 2.7. If it wasn't in any actual released versions, maybe you can just ignore it. But otherwise, yeah, you need a workaround. I would suggest that, instead of monkeypatching `collections.OrderedDict`, you should...
855
63,336,512
I have a python flask application which uses tabula internally to extract tables from pdf files.After I do 'cf push' and run the application on PCF,i load the pdf file to the application to read the table. When the app tries to extract the tabular data,I get the below error. ``` 2020-08-10T13:38:40.135+05:30 [APP/PROC...
2020/08/10
[ "https://Stackoverflow.com/questions/63336512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12403005/" ]
This is a java path error. Your python runtime is not able to find java at all. You need to ensure that your export java in your export path variables. If you are running this process on linux, you can export `export PATH=<your java bin dir>:$PATH`
The highlights: * You need multiple buildpacks, one for Java and one for Python * You want to use apt-buildpack, not the Java buildpack though * You need to set PATH to point to the location where the apt-buildpack installs Java (or have your app look for Java in this specific place) * You can set PATH in a `.profile`...
858
27,718,277
Well I have an assignment to implement DES and I chose python, only problem is I can't figure out how to XOR bits of a String or Byte String, I can manually XOR them if only I can manage to read the 1s and 0s in them. Example: ``` s1 = b'abc' s2 = b'efg' s3 = XOR(s1,s2) // my own method ``` How can I XOR them or ...
2014/12/31
[ "https://Stackoverflow.com/questions/27718277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3417451/" ]
First you need to `zip` your strings then use `ord` (in `python 2`) and `^` for each of characters : ``` >>> s1 = b'abc' >>> s2 = b'efg' >>> ''.join(chr(ord(i)^ord(j)) for i,j in zip(s1,s2)) '\x04\x04\x04' ``` the [`ord()`](https://docs.python.org/2/library/functions.html#ord) function retuen value of the byte when ...
``` >>> b''.join(chr(ord(a) ^ ord(b)) for a, b in zip(b'abc', b'efg')) '\x04\x04\x04' ```
859
13,768,118
I'm building a python app using the UPS Shipping API. On sending the request (see below) I keep getting the following error: ``` UPS Error 9370701: Invalid processing option. ``` I'm not sure what this means and there isn't much more info in the API documentation. Could someone help me figure out what's going wrong...
2012/12/07
[ "https://Stackoverflow.com/questions/13768118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1365008/" ]
Try this ``` DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(fp)); lb_Files.Items.Clear(); foreach (FileInfo file in dir.GetFiles()) { lb_Files.Items.Add(new RadListBoxItem(file.ToString(), file.ToString())); } ```
No you cannot cast a `String` object into a `RadListBoxItem`, you must create a `RadListBoxItem` using that string as your Value and Text properties: So replace this: ``` RadListBoxItem rlb = new RadListBoxItem(); rlb = (RadListBoxItem)file.ToString(); //radListBox lb_Files.Items.Add(rlb.ToString()); ``` With t...
862
2,100,233
I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python ``` numbersvar = [0,1,2,3] stringsvar = ['a','b','c'] ``` The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it.
2010/01/20
[ "https://Stackoverflow.com/questions/2100233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/228741/" ]
Maybe it will be better to use a **[json](http://www.google.com/url?sa=t&source=web&ct=res&cd=1&ved=0CDkQFjAA&url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Fjson.html&ei=b9pWS7mmO8eK_Abcppz-Aw&usg=AFQjCNG7_WS8ga_dF7-eGjquJarNhC5Eew&sig2=_SZrRNdbAGmbGuW9tVYgHw)** module to create a javascript lists? ``` >>> a = ['stste',...
What does stringsvar contain? The list, or the string representation of the list? I suggest you pass the correct javascript string representation of the list from the view method to the template to render. Python and javascript array literals have the same syntax, so you could do: ``` def my_view(request): return...
863
10,393,385
> > **Possible Duplicate:** > > [Instance variables vs. class variables in Python](https://stackoverflow.com/questions/2714573/instance-variables-vs-class-variables-in-python) > > > What is the difference between these two situations and how is it treated with in Python? Ex1 ``` class MyClass: anArray =...
2012/05/01
[ "https://Stackoverflow.com/questions/10393385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/751467/" ]
In the first example, `anArray` (which in Python is called a dictionary, not an array) is a class attribute. It can be accessed using `MyClass.anArray`. It exists as soon as the class is defined. In the second example, `anArray` is an instance attribute. It can be accessed using `MyClass().anArray`. (But note that do...
It is declared diffrent area. Ex1 is Like global or static variable. ``` obj = MyClass() obj2 = MyClass() print "IS one instance ", id(obj.anArray) == id(obj2.anArray) ``` Ex2 is local attribute. ``` obj = MyClass() obj2 = MyClass() print "IS one instance ", id(obj.anArray) == id(obj2.anArray) ```
864
46,374,747
it's kind of very daunting now. I've tried all I could possibly figure out, to no avail. I am using ElementaryOS Loki, based on Ubuntu 16.04 LTS. I have `boost 1.65.1` installed under `/usr/local` I am using `cmake 3.9.3` which is supporting building boost 1.65.0 and forward. I have tried every possible way to mess...
2017/09/23
[ "https://Stackoverflow.com/questions/46374747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436572/" ]
Thanks @JohnZwinck for pointing out the obvious over-looked error I had and @James for sharing his answer. but it seems his answer is for Boost 1.63.0, so I wanted to post a solution here so anyone who's having problem with latest CMAKE and Boost Python (up to today) can save some head scratching time. some prep work ...
There are some dependencies for both CMake and Boost, so I am removing my old answer and providing a link to the bash script on GitHubGist. The script can be found [here](https://gist.github.com/JamesKBowler/24228a401230c0279d9d966a18abc9e6) To run the script first make it executable ``` chmod +x boost_python3_insta...
865
32,462,512
I'm trying to create a simple markdown to latex converter, just to learn python and basic regex, but I'm stuck trying to figure out why the below code doesn't work: ``` re.sub (r'\[\*\](.*?)\[\*\]: ?(.*?)$', r'\\footnote{\2}\1', s, flags=re.MULTILINE|re.DOTALL) ``` I want to convert something like: ``` s = """This...
2015/09/08
[ "https://Stackoverflow.com/questions/32462512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4699624/" ]
Just lost a week trying to find a suitable tool for Neo4J. It has somehow gotten more difficult. My experience updated from the last post here (2015): Gephi: 2015: Supported Neo4j 2017: Doesn't support Neo4j Linxurious: 2015: Free 2017: Discontinued and doesn't list the price Neoclipse: 2017: No updates since 2014. ...
There are at least 3 GUI tools for neo4j that allow editing: * [neoclipse](https://github.com/neo4j-contrib/neoclipse/wiki) * [Gephi](http://gephi.github.io/) * [linkurious](http://linkurio.us/) `neoclipse` and `Gephi` are open source and free. `linkurous` has a free open-source community edition.
866
63,756,753
I need to be able to run python code on each "node" of the network so that I can test out the code properly. I can't use different port numbers and run the code since I need to handle various other things which kind of force using unique IP addresses.
2020/09/05
[ "https://Stackoverflow.com/questions/63756753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6740018/" ]
In my DHT p2p project, I have a specific object that abstract the network communication. During testing I mock that object with an object that operate in memory: ``` class MockProtocol: def __init__(self, network, peer): self.network = network self.peer = peer async def rpc(self, address, nam...
I think vmware or virtual box can help you.
872
62,813,690
I am writing a script which will poll Jenkins plugin API to fetch a list of plugin dependencies. For this I have used `requests` module of python. It keeps returning empty response, whereas I am getting a JSON response in Postman. ``` import requests def get_deps(): url = "https://plugins.jenkins.io/api/plugin/CF...
2020/07/09
[ "https://Stackoverflow.com/questions/62813690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5649739/" ]
what do you think abous this code : First i calculate the hash and send to server A for signature ``` PdfReader reader = new PdfReader(SRC); FileOutputStream os = new FileOutputStream(TEMP); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); PdfSignatureAppearance appearance = stamper.g...
Your `signDocument` method apparently does not accept a pre-calculated hash value but seems to calculate the hash of the data you give it, in your case the (lower case) hex presentation of the hash value you already calculated. In your first example document you have these values (all hashes are SHA256 hashes): * Has...
873
60,468,634
I'm fairly new to python and am doing some basic code. I need to know if i can repeat my iteration if the answer is not yes or no. Here is the code (sorry to those of you that think that im doing bad habits). I need the iteration to repeat during else. (The function just outputs text at the moment) ``` if remove_c...
2020/02/29
[ "https://Stackoverflow.com/questions/60468634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12985589/" ]
Just put the code into a loop: ``` while True: if remove_char1_attr1 = 'yes': char1_attr1.remove(min(char1_attr1)) char1_attr1_5 = random.randint(1,6) char1_attr1.append(char1_attr1_5) print("The numbers are now as follows: " +char1_attr1 ) elif remove_char1_attr1 = 'no' ...
You can try looping while it's not yes or no ```py while remove_char1_attr1 not in ('yes', 'no'): if remove_char1_attr1 = 'yes': char1_attr1.remove(min(char1_attr1)) char1_attr1_5 = random.randint(1,6) char1_attr1.append(char1_attr1_5) print("The numbers are now as follows: " +c...
874
52,415,096
I am calling a new object to manage an Azure Resource and using the Azure python packages. While calling it, i get a maximum depth exceeded error however if I step through the code in a python shell I don't get this issue. Below is the **init** method ``` class WindowsDeployer(object): def __init__(self, params): ...
2018/09/19
[ "https://Stackoverflow.com/questions/52415096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6781059/" ]
Thanks for the help above. The issue was with my gevent packages (not sure exactly what) however adding upgrading gevent and adding the following lines fixed it. ``` import gevent.monkey gevent.monkey.patch_all() ```
I had a similar problem when using the `azure-storage-blob` module, and adding the following lines fixed it. I do not know why. It makes me confused. Exception: > > maximum recursion depth exceeded while calling a Python object > > > Solution: ``` import gevent.monkey gevent.monkey.patch_all() ```
875
72,921,087
Taking this command to start local server for example, the command includes -m, what is the meaning of -m in genearl? ``` python3 -m http.server ```
2022/07/09
[ "https://Stackoverflow.com/questions/72921087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4877535/" ]
From the documentation, which can be invoked using `python3 --help`. ``` -m mod : run library module as a script (terminates option list) ``` Instead of importing the module in another script (like `import <module-name>`), you directly run it as a script.
The -m stands for module-name in Python.
876
27,793,025
I can't use Java and Python at the same time. When I set ``` %JAVAHOME%\bin; %PYTHONPATH%; ``` I can use java, but not python. When I set ``` %PYTHONPATH%; %JAVAHOME%\bin; ``` I can use python, but not java. I'm using windows 7. How can I go about fixing this problem?
2015/01/06
[ "https://Stackoverflow.com/questions/27793025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4422583/" ]
Don't put a space in your `PATH` entries ``` set "PATH=%JAVAHOME%\bin;%PYTHONPATH%;%PATH%" ```
1. Select Start, select Control Panel. double click System, and select the Advanced tab. 2. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. ... 3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variab...
877
40,652,793
I run a bash script with which start a python script to run in background ``` #!/bin/bash python test.py & ``` So how i can i kill the script with bash script also? I used the following command to kill but output `no process found` ``` killall $(ps aux | grep test.py | grep -v grep | awk '{ print $1 }') ``` I t...
2016/11/17
[ "https://Stackoverflow.com/questions/40652793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180818/" ]
Use `pkill` command as ``` pkill -f test.py ``` (or) a more fool-proof way using `pgrep` to search for the actual process-id ``` kill $(pgrep -f 'python test.py') ``` Or if more than one instance of the running program is identified and all of them needs to be killed, use [killall(1)](https://linux.die.net/man/1/...
You can use the `!` to get the PID of the last command. I would suggest something similar to the following, that also check if the process you want to run is already running: ``` #!/bin/bash if [[ ! -e /tmp/test.py.pid ]]; then # Check if the file already exists python test.py & #+and if so d...
880
25,065,017
I'm learning objective c a little bit to write an iPad app. I've mostly done some html5/php projects and learned some python at university. But one thing that really blows my mind is how hard it is to just style some text in an objective C label. Maybe I'm coming from a lazy markdown generation, but really, if I want ...
2014/07/31
[ "https://Stackoverflow.com/questions/25065017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2517546/" ]
You can use `NSAttributedString`'s `data:options:documentAttributes:error:` initializer (first available in iOS 7.0 SDK). ``` import UIKit let htmlString = "<b>Objective</b>: Construct an <i>equilateral</i> triangle from the line segment AB." let htmlData = htmlString.dataUsingEncoding(NSUTF8StringEncoding) let opti...
I faced similar frustrations while trying to use attributed text in Xcode, so I feel your pain. You can definitely use multiple `NSMutableAttributedtext`'s to get the job done, but this is very rigid. ``` UIFont *normalFont = [UIFont fontWithName:@"..." size:20]; UIFont *boldFont = [UIFont fontWithName:@"..." size:20]...
887
22,071,987
I haven't been able to find a function to generate an array of random floats of a given length between a certain range. I've looked at [Random sampling](http://docs.scipy.org/doc/numpy/reference/routines.random.html) but no function seems to do what I need. [random.uniform](http://docs.python.org/2/library/random.htm...
2014/02/27
[ "https://Stackoverflow.com/questions/22071987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391441/" ]
[`np.random.uniform`](https://numpy.org/doc/stable/reference/random/generated/numpy.random.uniform.html) fits your use case: ``` sampl = np.random.uniform(low=0.5, high=13.3, size=(50,)) ``` **Update Oct 2019:** While the syntax is still supported, it looks like the API changed with NumPy 1.17 to support greater co...
This is the simplest way ``` np.random.uniform(start,stop,(rows,columns)) ```
890
8,964,461
I would like to create a subclass of python's unittest.Testcase called BasicTest. I would like each subclass of BasicTest to run the same routine in main. How can I accomplish this? Example: ``` in basic_test.py: class BasicTest(unittest.TestCase): ... if __name__ == '__main__': # Do optparse stuff uni...
2012/01/22
[ "https://Stackoverflow.com/questions/8964461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766953/" ]
``` # basic_test.py class BasicTest(unittest.TestCase): @staticmethod def main(): # Do optparse stuff unittest.main() if __name__ == '__main__': BasicTest.main() # some_basic_test.py class SomeBasicTest(BasicTest): ... if __name__ == '__main__': BasicTest.main() ```
You cannot (re)import a module as a new **main**, thus the `if __name__=="__main__"` code is kind of unreachable. Dor’s suggestion or something similar seems most reasonable. However if you have no access to the module in question, you might consider looking at the [runpy.run\_module()](http://docs.python.org/library/...
900
4,879,324
Suppose I want to include a library: ``` #include <library.h> ``` but I'm not sure it's installed in the system. The usual way is to use tool like autotools. Is there a simpler way in C++? For example in python you can handle it with exceptions.
2011/02/02
[ "https://Stackoverflow.com/questions/4879324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238671/" ]
autotools is the best way to detect at *compile* time. It's very platform-specific, but assuming you're on Linux or similar, [dlopen](http://linux.die.net/man/3/dlopen) is how you check at *runtime*.
As far as I know, there's no way of checking whether a library is installed using code. However, you could create a bash script that could look for the library in the usual places, like /usr/lib or /usr/local/lib. Also, you could check /etc/ld.so.conf for the folders and then look for the libraries. Or something like...
902
14,983,015
I'm trying to write a large python/bash script which converts my html/css mockups to Shopify themes. One step in this process is changing out all the script sources. For instance: ``` <script type="text/javascript" src="./js/jquery.bxslider.min.js"></script> ``` becomes ``` <script type="text/javascript" src="{{ 'j...
2013/02/20
[ "https://Stackoverflow.com/questions/14983015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623223/" ]
You can just go to azure's control panel and add in a virtual directory path. Please visit this MDSN blog to see how its done. <http://blogs.msdn.com/b/kaushal/archive/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site.aspx>
If you use Web deploy publish method you can set in Site name `mydomain/mymvcsite` instead of `mydomain`. At least it works for me for default windows azure site `http://mydomain.azurewebsites.net/mymvcsite`. Or you can use FTP publish method.
903
52,241,986
I have the following code to add a table of contents to the beginning of my ipython notebooks. When I run the cell on jupyter on my computer I get [![enter image description here](https://i.stack.imgur.com/ESBlz.png)](https://i.stack.imgur.com/ESBlz.png) But when I upload the notebook to github and choose to view th...
2018/09/09
[ "https://Stackoverflow.com/questions/52241986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171138/" ]
Attachments (and rich text) are not yet supported by the POST /chatthreads API. The only way to post messages with attachments today is with our bot APIs. We are working on write APIs to match our recently-released read APIs but they aren't ready yet. There's no need to put anything on UserVoice though. Unfortunatel...
> > APIs under the /beta version in Microsoft Graph are in preview and are subject to change. Use of these APIs in production applications is not supported. > > > The returned value of **attachment** in the document is the embodiment of the product group design, and we cannot get the value should be the product gr...
906
22,521,912
I'm in the directory `/backbone/` which has a `main.js` file within scripts. I run `python -m SimpleHTTPServer` from the `backbone` directory and display it in the browser and the console reads the error `$ is not defined` and references a completely different `main.js` file from something I was working on days ago wit...
2014/03/20
[ "https://Stackoverflow.com/questions/22521912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066353/" ]
i have the same problem and solved it by (( Go to Setting >> Locations> mode>> Battery savings >> then restart your device and set up again your app ))
Google map now uses this to enable the My Location layer on the Map. ``` mMap.setMyLocationEnabled(true); ``` You can view the documentation for Google Maps Android API v2 [here](https://developers.google.com/maps/documentation/android/location). They're using Location Client now to Making Your App Location-Aware, ...
907
7,033,192
``` #!/usr/bin/python import os,sys from os import path input = open('/home/XXXXXX/ERR001268_1', 'r').read().split('\n') at = 1 for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.split(':')[4].split()[0] num4 = line4.split(':')[4].split()[0] print num1,num...
2011/08/11
[ "https://Stackoverflow.com/questions/7033192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815408/" ]
The problem is that `lines` has a maximum value of `len(input)-1` but then you let `line4` be `lines + 3`. So, when you're at your last couple of lines, `lines + 3` will be larger than the length of the list. ``` for lines in range(0, len(input)): line1 = input[lines] line4 = input[lines+3] num1 = line1.sp...
It seems that you want to read a file and get some info from it every 3 lines. I would recommend something simpler: ``` def get_num(line): return line.split(':')[4].split()[0] nums1 = [get_num(l) for l in open(fn, "r").readlines()] nums2 = nums1[3:] for i in range(len(nums2)): print nums1[i],nums2[i] ``` Th...
908
34,406,393
I try to make a script allowing to loop through a list (*tmpList = openFiles(cop\_node)*). This list contains 5 other sublists of 206 components. The last 200 components of the sublists are string numbers ( a line of 200 string numbers for each component separated with a space character). I need to loop through the ma...
2015/12/21
[ "https://Stackoverflow.com/questions/34406393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698216/" ]
`valueListStr = []*len(tmpList)` does not do what you think it does, if you want a list of lists use a *list comp* with range: ``` valueListStr = [[] for _ in range(len(tmpList))] ``` That will create a list of lists: ``` In [9]: valueListStr = [] * i In [10]: valueListStr Out[10]: [] In [11]: valueListStr = [[] ...
``` def valuesFiles(cop_node): valueListStr = [] for j in openFiles(cop_node): tmpList = j[6:] tmpList.reverse() tmp = [] for s in tmpList: tmp.extend(s.split(' ')) valueListStr.append(tmp) return valueListStr ``` After little modification I get it to work as excepted : ``` def valuesFile...
912
2,063,124
I am trying to read a \*.wav file using scipy. I do it in the following way: ``` import scipy.io x = scipy.io.wavfile.read('/usr/share/sounds/purple/receive.wav') ``` As a result I get the following error message: ``` Traceback (most recent call last): File "test3.py", line 1, in <module> import scipy.io Fi...
2010/01/14
[ "https://Stackoverflow.com/questions/2063124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245549/" ]
Looks like you have upgraded your numpy version but haven't installed a [corresponding scipy version](http://projects.scipy.org/scipy/ticket/916).
Do you have numpy installed? The package is most likely called `numpy` or `python-numpy` if you are running Linux If your OS package manager does not have numpy package, download it from [here](http://sourceforge.net/projects/numpy/files/)
913
49,016,216
Is there a way to know which element has failed the `any` built-in function? I was trying to solve [Euler 5](https://projecteuler.net/problem=5) and I want to find for which numbers my product isn't evenly divisible. Using the for loop it's easy to figure it out, but is it possible with `any` also? ``` from operator ...
2018/02/27
[ "https://Stackoverflow.com/questions/49016216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3512538/" ]
Is there any good reason to use `any`? If you want an one-liner to find out which numbers are not evenly divisible : ``` not_divisible = [i for i in range(1, 21) if product % i != 0] if len(not_divisible) > 0: print(not_divisible) ``` You can't really get all the non-divisible numbers with `any`, since it stop...
I probably wouldn't recommend actually doing this, as it feels a bit hacky (and uglier than just scrapping the `any()` for a `for` loop). That disclaimer aside, this could technically be accomplished by exploiting an iterator and `any()`'s property of stopping once it's found a truthy value: ``` rangemax = 21 rng = it...
914
6,712,051
I'm trying to do something that seems very simple, and falls within the range of standard python. The following function takes a collection of sets, and returns all of the items that are contained in two or more sets. To do this, while the collection of sets is not empty, it simply pops one set out of the collection, ...
2011/07/15
[ "https://Stackoverflow.com/questions/6712051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173292/" ]
[It's a bug](http://ironpython.codeplex.com/workitem/30386). It will be fixed in 2.7.1, but I don't think the fix is in the 2.7.1 Beta 1 release.
This is a [bug](http://ironpython.codeplex.com/workitem/30386) still present in the 2.7.1 Beta 1 release. It has been fixed in [master](https://github.com/IronLanguages/main), and the fix will be included in the next release. ``` IronPython 3.0 (3.0.0.0) on .NET 4.0.30319.235 Type "help", "copyright", "credits" or "...
915
3,400,847
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: * main.py * callback.py * helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but ma...
2010/08/03
[ "https://Stackoverflow.com/questions/3400847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216547/" ]
Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure.
I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something? If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the ...
916
42,292,272
How to identify the link, I have inspected the elements which are as below : ``` <div class="vmKOT" role="navigation"> <a class="Ml68il" href="https://www.google.com" aria-label="Search" data-track-as="Welcome Header Search"></a> <a class="WaidDw" href="https://mail.google.com" aria-label="Mail" data-track-as="Welcome...
2017/02/17
[ "https://Stackoverflow.com/questions/42292272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7579389/" ]
You can try ``` driver.find_element_by_class_name('WaidDw').click() ``` or ``` driver.find_element_by_xpath('//a[@href="https://mail.google.com" and @aria-label="Mail"]').click() ```
In your provided HTML all attribute's values are unique, you can locate easily that element by using their attribute value. As your question points to locate this `<a class="WaidDw" href="https://mail.google.com" aria-label="Mail" data-track-as="Welcome Header Mail"></a>` element. I'm providing you multiple `cssSelect...
925
36,244,077
So here is a breakdown of the task: 1) I have a 197x10 2D numpy array. I scan through this and identify specific cells that are of interest (criteria that goes into choosing these cells is not important.) These cells are not restricted to one specific area of the matrix. 2) I have 3247 other 2D Numpy arrays with the ...
2016/03/27
[ "https://Stackoverflow.com/questions/36244077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973851/" ]
Pythonic way: ``` answers = [] # this generates index matrix where the condition is met. idx = np.argwhere( your condition of (1) matrix comes here) for array2d in your_3247_arrays: answer = array2d[idx].mean() answers.append() print(answers) ```
Here is an example: ``` import numpy as np A = np.random.rand(197, 10) B = np.random.rand(3247, 197, 10) loc = np.where(A > 0.9) B[:, loc[0], loc[1]].mean(axis=1) ```
926
47,540,186
I want to dynamically start clusters from my Jupyter notebook for specific functions. While I can start the cluster and get the engines running, I am having two issues: (1) I am unable to run the ipcluster command in the background. When I run the command through notebook, the cell is running till the the time the clu...
2017/11/28
[ "https://Stackoverflow.com/questions/47540186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4059923/" ]
When I saw your answer unanswered on StackOverflow, I almost had a heart attack because I had the same problem. But running the ``` ipcluster start --help ``` command showed this: ``` --daemonize ``` This makes it run in the background. So in your notebook you can do this: ``` no_engines = 6 !ipcluster start...
I am not familiar with the details of the `commands` module (it's been deprecated since 2.6, according to <https://docs.python.org/2/library/commands.html>) but I know that with the `subprocess` module capturing output will make the make the interpreter block until the system call completes. Also, the number of engine...
927
40,839,114
I tried to fine-tune VGG16 on my dataset, but stuck on trouble of opening h5py file of VGG16-weights. I don't understand what does this error mean about: ``` OSError: Unable to open file (Truncated file: eof = 221184, sblock->base_addr = 0, stored_eoa = 58889256) ``` Does anyone know how to fix it? thanks ``` -----...
2016/11/28
[ "https://Stackoverflow.com/questions/40839114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7218907/" ]
There is a possibility that the download of the file has failed. Replacing a file that failed to open with the following file may resolve it. <https://github.com/fchollet/deep-learning-models/releases> My situation, That file was in the following path. C:\Users\MyName\.keras\models\vgg16\_weights\_tf\_dim\_ordering\_...
because the last time you file download is failed.but the bad file remains in the filepath. so you have to find the bad file. maybe u can use “find / -name 'vgg16\_weights\_tf\_dim\_ordering\_tf\_kernels\_notop.h5'” to find the path in unix-system. then delete it try agian!good luck!!
928
73,336,040
I'm calling `subprocess.Popen` on an `exe` file in [this script](https://github.com/PolicyEngine/openfisca-us/blob/6ae4e65f6883be598f342c445de1d52430db6b28/openfisca_us/tools/dev/taxsim/generate_taxsim_tests.py#L146), and it [throws](https://gist.github.com/MaxGhenis/b0eb890232363ed30efc1be505e1f257#file-gistfile1-txt-...
2022/08/12
[ "https://Stackoverflow.com/questions/73336040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1840471/" ]
`subprocess` can only start programs that your operating system knows how to execute. Your `taxsim35-unix.exe` is a Linux executable. MacOS cannot run them. You'll need to either use a Linux machine to run this executable (real or virtual), or get a version compiled for Mac. <https://back.nber.org/stata//taxsim35/tax...
I worked with the developers of taxsim for a while. I believe that the .exe files generated by taxsim were originally msdos only and then moved to Linux. They're not intended to be run by MacOS. I don't know if they ever released the FORTRAN code that generates them so that they can be run on MacOS. Your best bet for r...
930
48,590,488
Beginner with python - I'm looking to create a dictionary mapping of strings, and the associated value. I have a dataframe and would like create a new column where if the string matches, it tags the column as x. ``` df = pd.DataFrame({'comp':['dell notebook', 'dell notebook S3', 'dell notepad', 'apple ipad', 'apple ip...
2018/02/02
[ "https://Stackoverflow.com/questions/48590488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7237997/" ]
There are many ways to do this. One way to do it would be the following: ``` def like_function(x): group = "unknown" for key in product_map: if key in x: group = product_map[key] break return group df['company'] = df.comp.apply(like_function) ```
A vectorized solution inspired by [MaxU](https://stackoverflow.com/users/5741205/maxu)'s solution to a [similar problem](https://stackoverflow.com/questions/48510405/pandas-python-datafame-update-a-column/48510563). ``` x = df.comp.str.split(expand=True) df['company'] = None df['company'] = df['company'].fillna(x[x.is...
931
57,404,906
I have created an executable via pyinstaller. While running the exe found the error from pandas. ``` Traceback (most recent call last): File "score_python.py", line 3, in <module> import pandas as pd, numpy as np File "d:\virtual\sc\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec...
2019/08/08
[ "https://Stackoverflow.com/questions/57404906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4949165/" ]
This is an issue with virtualenv from version 16.4.0 onward, as indicated in the following issue on github: <https://github.com/pyinstaller/pyinstaller/issues/4064> These workarounds were suggested: 1. In the .spec file, at the line “hiddenimports=[]”, change to "hiddenimports=['distutils']", then run pyinstaller usi...
Found the solution, it's because of the virtual environment. The error occurred because of the creation of a new virtual environment while creating the project. I have deleted my existing virtual and created new virtual by setting up the python interpreter and opting the `pre-existing interpreter` option. The IDE wil...
934
32,007,199
Hi I'm currently trying to review some material in my course and I'm having a hard time coming up with a function that we will call 'unique' that produces a list of only unique numbers from a set of lists. So for python I was thinking of using OOP and using an iterator. ``` >>> You have a list (1, 3, 3, 3, 5) Retu...
2015/08/14
[ "https://Stackoverflow.com/questions/32007199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5101470/" ]
Probably the most straight forward way to do this is using Python's `set` builtin. ``` def unique(*args): result = set() # A set guarantees the uniqueness of elements result = result.union(*args) # Include elements from all args result = list(result) # Convert the set object to a list return result ...
Not necessary but you wanted to make classes. ``` class Unique: def __init__(self): self._list = self.user_input() def user_input(self): _list = raw_input() _list = _list.split(' ') [int(i) for i in _list] return _list def get_unique(self): self._set = s...
935
9,882,358
I'm writing a quick and dirty maintenace script to delete some rows and would like to avoid having to bring my ORM classes/mappings over from the main project. I have a query that looks similar to: ``` address_table = Table('address',metadata,autoload=True) addresses = session.query(addresses_table).filter(addresses_t...
2012/03/27
[ "https://Stackoverflow.com/questions/9882358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459082/" ]
Looking through some code where I did something similar, I believe this will do what you want. ``` d = addresses_table.delete().where(addresses_table.c.retired == 1) d.execute() ``` Calling `delete()` on a table object gives you a `sql.expression` (if memory serves), that you then execute. I've assumed above that th...
When you call `delete()` from a query object, SQLAlchemy performs a *bulk deletion*. And you need to choose a **strategy for the removal of matched objects from the session**. See the documentation [here](https://docs.sqlalchemy.org/en/14/orm/query.html#sqlalchemy.orm.Query.delete). If you do not choose a strategy for...
940
32,255,039
In ubuntu ubuntu-desktop needs python3-requsts package. But this package contain out-dated requests lib (2.4, current - 2.7). I need fresh version of requests, but i cant install him. ``` $ sudo pip3 install requests --upgrade Downloading/unpacking requests from https://pypi.python.org/packages/2.7/r/requests/requests...
2015/08/27
[ "https://Stackoverflow.com/questions/32255039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1064115/" ]
Finally, i solved this problem by manually installing requests. Just download archive with package and run: ``` python3 setup.py install ``` This will remove apt-get files and install fresh version.
You'd better be using virtualenv :-). The clean way to do what you are asking is creating an OS package (a ".deb") with the newer version and installing it with dpkg. The "unclean" way would be to delete the system-package using apt-get, synaptic, etc... and then use pip to install it on the system Python. That is b...
941
62,273,175
I have a python dictionary as below: ``` wordCountMap = {'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10} ``` I want to sort the dictionary such that it is the decreasing order of its values, followed by lexicographically increasing order for keys with same values. ``` result = {'zzz':10, 'bbb':2. 'bbz':2. 'aaa':1} ``` Here...
2020/06/09
[ "https://Stackoverflow.com/questions/62273175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846878/" ]
You can convert it to the sorted `list` by keying on the negation of the value, and the original key: ``` resultlist = sorted({'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10}.items(), key=lambda x: (-x[1], x[0])) ``` If it must be converted back to a `dict`, just wrap that in the `dict` constructor: ``` resultdict = dict(sort...
I got this answer from [here](https://stackoverflow.com/questions/9919342/sorting-a-dictionary-by-value-then-key). Assuming your dictionary is d, you can get it sorted with: ``` d = {'aaa':1, 'bbz':2, 'bbb':2, 'zzz':10} newD = [v[0] for v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))] ``` newD's value: ...
942
71,883,326
I'm having trouble figuring out how to do the opposite of the answer to this question (and in R not python). [Count the amount of times value A occurs with value B](https://stackoverflow.com/questions/47834225/count-the-amount-of-times-value-a-occurs-with-value-b) Basically I have a dataframe with a lot of combinatio...
2022/04/15
[ "https://Stackoverflow.com/questions/71883326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7257777/" ]
First `paste` the two id columns together to `id12` for later matching. Then use `sapply` to go through all rows to see the records where `id1` appears in `id12` but `id2` doesn't. `sum` that value and only output the `distinct` records. Finally, remove the `id12` column. ``` library(dplyr) df %>% mutate(id12 = paste...
A full `tidyverse` version: ```r library(tidyverse) df %>% mutate(id = paste(id1, id2), count = map(cur_group_rows(), ~ sum(str_detect(id, id1[.x]) & str_detect(id, id2[.x], negate = T)))) ```
943
52,056,004
I am trying to update the neo4j-flask application to Py2Neo V4 and i could not find how the "find\_one" function has been replaced. (Nicole White used Py2Neo V2) * <https://nicolewhite.github.io/neo4j-flask/> * <https://github.com/nicolewhite/neo4j-flask> * <https://neo4j.com/blog/building-python-web-application-using...
2018/08/28
[ "https://Stackoverflow.com/questions/52056004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4606342/" ]
py2neo v4 has a `first` function that can be used with a `NodeMatcher`. See: <https://py2neo.org/v4/matching.html#py2neo.matching.NodeMatch.first> That said... v4 has introduced GraphObjects which (so far at least) I've found pretty neat. In the linked github example Users are created with: ``` user = Node('User', u...
Building on the [answer above](https://stackoverflow.com/a/52058563), here is a minimal example showing the use of `self.match().first()` instead of `find_one()`. The attributes are set with `Property()` to provide an accessor to the property of the underlying node. (Documentation here: <https://py2neo.org/v4/ogm.html...
945
32,681,203
I use iPython mostly via notebooks but also in the terminal. I just created my default profile by running `ipython profile create`. I can't seem to figure out how to have the profile run several magic commands that I use every time. I tried to look this up online and in a book I'm reading but can't get it to work. For...
2015/09/20
[ "https://Stackoverflow.com/questions/32681203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238779/" ]
Execute magics as follows: ``` get_ipython().magic(u"%reload_ext autoreload") get_ipython().magic(u"%autoreload 2") ``` You can put those lines in your startup script here: ``` ~/.ipython/profile_default/startup/00-first.py ```
To start for example the %pylab magic command on startup do the following: ``` ipython profile create pylab ``` Add the following code to your .ipython\profile\_pylab\ipython\_config.py ``` c.InteractiveShellApp.exec_lines = ['%pylab'] ``` and start ipython ``` ipython --profile=pylab ```
950
29,658,335
I'm curious to know if it makes a difference where the '&' operator is used in code when a process has input/output redirection to run a process in the background What are the differences/are there any differences between these lines of code in terms of running the process in the background. If there are, how can I de...
2015/04/15
[ "https://Stackoverflow.com/questions/29658335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
### Control operator There are two uses of `&` here. One is as a so-called **control operator**. Every command is terminated by a control operator such as `&`, `;` or `<newline>` . The difference between them is that `;` and `<newline>` run the command in the foreground and `&` does it in the background. ``` setsid p...
It makes a difference. `&` doubles as a command separator (just like `;` is command separator). What you're really doing in something like ``` setsid python script.py & < /dev/zero > log.txt ``` is running `setsid python script.py` in the background and also running a "null" command (which comes after the `&`) in th...
951
9,343,498
I'm implementing the component labelling algorithm as in [this paper](http://www.iis.sinica.edu.tw/papers/fchang/1362-F.pdf) using python and opencv. It requires checking the input image pixel-by-pixel and perform the so-called contour tracing subroutine to assign label to the blobs of a binary image. I manage to hav...
2012/02/18
[ "https://Stackoverflow.com/questions/9343498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567989/" ]
I'm not sure if I understand your question, but each key can have only one object associated with it. In your case, you're using an NSString object. If you replaced the NSString with some object that you create, say AnObjectWithAThingAndAPersonAndAPlace, you could have multiple attributes associated with each key. ---...
RIght now your `datasource` object is an NSArray. You need to make it an NSMutableArray. Declare it as an NSMutableArray in your header file and then you can do this: ``` datasource = [[states allKeys] mutableCopy]; [datasource addObject:whatever]; ``` But, it sounds like the structure you are actually looking for i...
954
51,100,224
I've written a script in python to get different links leading to different articles from a webpage. Upon running my script I can get them flawlessly. However, the problem I'm facing is that the article links traverse multiple pages as they are of big numbers to fit within a single page. if I click on the next page but...
2018/06/29
[ "https://Stackoverflow.com/questions/51100224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9189799/" ]
The content is heavily dynamic, so it would be best to use `selenium` or similar clients, but I realize that this wouldn't be practical as the number of results is so large. So, we'll have to analyse the HTTP requests submitted by the browser and simulate them with `requests`. The contents of next page are loaded by ...
Not to treat this question as an XY problem, as, if solved, should pose a very interesting solution BUT I have found a solution for this *specific* issue that is much more efficient: Using the [NCBI's Entrez Programming Utilities](https://www.ncbi.nlm.nih.gov/books/NBK25497/) and a handy, [opensource, unofficial Entrez...
956
11,994,325
My flask application currently consists of a single `test.py` file with multiple routes and the `main()` route defined. Is there some way I could create a `test2.py` file that contains routes that were not handled in `test.py`? ``` @app.route('/somepath') def somehandler(): # Handler code here ``` I am concerned...
2012/08/16
[ "https://Stackoverflow.com/questions/11994325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
I would like to recommend [flask-empty](https://github.com/italomaia/flask-empty/) at GitHub. It provides an easy way to understand [Blueprints](http://flask.pocoo.org/docs/blueprints/), multiple views and [extensions](http://flask.pocoo.org/docs/extensiondev/).
Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files. I created a G...
957
45,776,460
What I'm trying to do is search StackOverflow for answers. I know it's probably been done before, but I'd like to do it again. With a GUI. Anyway that is a little bit down the road as right now i'm just trying to get to the page with the most votes for a question. I noticed while trying to see how to get into a nested ...
2017/08/19
[ "https://Stackoverflow.com/questions/45776460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/977034/" ]
Don't pass it as parameters, just add it to the URL: ``` page2 = requests.get("https://stackoverflow.com" + top) ``` Once you pass `requests` parameters it adds a `?` to the link before concatenating the new parameters to the link. [Requests - Passing Parameters In URLs](http://docs.python-requests.org/en/master/us...
Why not use the [API](https://api.stackexchange.com/docs)? There are plenty of search options (<https://api.stackexchange.com/docs/advanced-search>), and you get the response in JSON, no need for ugly HTML parsing.
967
55,318,093
i am learning and trying to make a snake game in Python3 i am importing turtle i am using: Linux mint 19, PyCharm, python37, python3-tk ``` Traceback (most recent call last): File "/home/buszter/PycharmProjects/untitled1/snake.py", line 2, in <module> import turtle ModuleNotFoundError: No module named 'turtle'...
2019/03/23
[ "https://Stackoverflow.com/questions/55318093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10909285/" ]
I know that it's kinda old topic, but I had the same problem right now on my Fedora 31. Reinstalling packages didn't work. What worked was installing IDLE programming tool (that's just Python IDE for kids), which installs also tkinter module. I think that installing just `python3-tkinter` (that's how this packag...
Most probably the python your `Pycharm` is using is not `Python3.7`. Try opening a Python prompt and running import turtle, because it should be packaged into `python` already. (<https://docs.python.org/3/library/turtle.html>)
968