qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
8,997,431
A common pattern in python is to catch an error in an upstream module and re-raise that error as something more useful. ``` try: config_file = open('config.ini', 'r') except IOError: raise ConfigError('Give me my config, user!') ``` This will generate a stack trace of the form ``` Traceback (most recent ca...
2012/01/25
[ "https://Stackoverflow.com/questions/8997431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234254/" ]
This is known as *Exception Chaining* and is suported in Python 3. PEP 3134: <http://www.python.org/dev/peps/pep-3134/> In Python 2, the old exception is lost when you raise a new one, unless you save it in the `except` block.
Use the `traceback` [module](http://docs.python.org/library/traceback.html). It will allow you to access the most recent traceback and store it in a string. For example, ``` import traceback try: config_file = open('config.ini', 'r') except OSError: tb = traceback.format_exc() raise ConfigError('Give me my...
8,997,431
A common pattern in python is to catch an error in an upstream module and re-raise that error as something more useful. ``` try: config_file = open('config.ini', 'r') except IOError: raise ConfigError('Give me my config, user!') ``` This will generate a stack trace of the form ``` Traceback (most recent ca...
2012/01/25
[ "https://Stackoverflow.com/questions/8997431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234254/" ]
Use the `traceback` [module](http://docs.python.org/library/traceback.html). It will allow you to access the most recent traceback and store it in a string. For example, ``` import traceback try: config_file = open('config.ini', 'r') except OSError: tb = traceback.format_exc() raise ConfigError('Give me my...
Here is an example of how to unwind [PEP-3134](http://www.python.org/dev/peps/pep-3134/) exception chains. Note that due to legacy reasons some Python frameworks may not use exception chaining, but instead of wrap exceptions in their own way. For example. [SQLALchemy DBABIError uses `orig` attribute](https://docs.sqla...
8,997,431
A common pattern in python is to catch an error in an upstream module and re-raise that error as something more useful. ``` try: config_file = open('config.ini', 'r') except IOError: raise ConfigError('Give me my config, user!') ``` This will generate a stack trace of the form ``` Traceback (most recent ca...
2012/01/25
[ "https://Stackoverflow.com/questions/8997431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234254/" ]
This is known as *Exception Chaining* and is suported in Python 3. PEP 3134: <http://www.python.org/dev/peps/pep-3134/> In Python 2, the old exception is lost when you raise a new one, unless you save it in the `except` block.
Here is an example of how to unwind [PEP-3134](http://www.python.org/dev/peps/pep-3134/) exception chains. Note that due to legacy reasons some Python frameworks may not use exception chaining, but instead of wrap exceptions in their own way. For example. [SQLALchemy DBABIError uses `orig` attribute](https://docs.sqla...
51,247,566
It looks like I can only change the value of mutable variables using a function, but is it possible to change immutable ### Code ``` def f(a, b): a += 1 b.append('hi') x = 1 y = ['hello'] f(x, y) print(x, y) #x didn't change, but y did ``` ### Result ``` 1 [10, 1] ``` So, my question is that is it poss...
2018/07/09
[ "https://Stackoverflow.com/questions/51247566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9273687/" ]
In python, the list is passed by **object-reference**. Actually, everything in python is an object but when you pass a single variable to function it creates a local copy of that if a value is changed but in case of a list if it creates a local copy even than the reference remains to the previous list object. Hence the...
Y is not value its just some bindings to memory. When You pass it to function its memory address is passed to function (call by reference). On the other hand x is value and when you pass it to function new local variable is created with same value. (At the assembly level all parameters of function are passed via stack ...
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
You can't create an object like that - the "key" in an object literal must be a constant, not a variable or expression. If the key is a variable you need the array-like syntax instead: ``` myArray[key] = value; ``` Hence you need: ``` var data = {}; // empty object data[$(this).attr('id')] = $(this).val(); ``` ...
You can't build property names dynamically like that. ``` function ArrayPush($group) { var arr = new Array(); $group.find('input[type=text],textarea').each(function () { var data = {}; data [$(this).attr('id')] = $(this).val(); arr.push(data); }); return arr; } ```
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
You can't create an object like that - the "key" in an object literal must be a constant, not a variable or expression. If the key is a variable you need the array-like syntax instead: ``` myArray[key] = value; ``` Hence you need: ``` var data = {}; // empty object data[$(this).attr('id')] = $(this).val(); ``` ...
``` var data = {}; data[$(this).attr('id')] = $(this).val(); ``` Use that instead. Otherwise you're trying to do some kind of eval...
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
You can't create an object like that - the "key" in an object literal must be a constant, not a variable or expression. If the key is a variable you need the array-like syntax instead: ``` myArray[key] = value; ``` Hence you need: ``` var data = {}; // empty object data[$(this).attr('id')] = $(this).val(); ``` ...
Try changing that to. ``` var data = {}; data[$(this).attr('id')] = $(this).val(); ```
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
You can't create an object like that - the "key" in an object literal must be a constant, not a variable or expression. If the key is a variable you need the array-like syntax instead: ``` myArray[key] = value; ``` Hence you need: ``` var data = {}; // empty object data[$(this).attr('id')] = $(this).val(); ``` ...
Try this: ``` function ArrayPush($group) { var arr = new Array(); $group.find('input[type=text],textarea').each(function () { arr[$(this).attr('id')] = $(this).val(); }); return arr; } ```
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
You can't build property names dynamically like that. ``` function ArrayPush($group) { var arr = new Array(); $group.find('input[type=text],textarea').each(function () { var data = {}; data [$(this).attr('id')] = $(this).val(); arr.push(data); }); return arr; } ```
Try this: ``` function ArrayPush($group) { var arr = new Array(); $group.find('input[type=text],textarea').each(function () { arr[$(this).attr('id')] = $(this).val(); }); return arr; } ```
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
``` var data = {}; data[$(this).attr('id')] = $(this).val(); ``` Use that instead. Otherwise you're trying to do some kind of eval...
Try this: ``` function ArrayPush($group) { var arr = new Array(); $group.find('input[type=text],textarea').each(function () { arr[$(this).attr('id')] = $(this).val(); }); return arr; } ```
8,933,380
I'm developing a web application in python for which each user request makes an API call to an external service and takes about **20 seconds** to receive response. As a result, in the event of several concurrent requests being made, the CPU load goes crazy (>95%) with several idle processes. The server consists of a 1...
2012/01/19
[ "https://Stackoverflow.com/questions/8933380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1159455/" ]
Try changing that to. ``` var data = {}; data[$(this).attr('id')] = $(this).val(); ```
Try this: ``` function ArrayPush($group) { var arr = new Array(); $group.find('input[type=text],textarea').each(function () { arr[$(this).attr('id')] = $(this).val(); }); return arr; } ```
61,388,487
Was trying to learn itertools from the python docs. I was going through `count` function and replicated the example given. However, I did not get any output to view. ``` def count(start=0, step=1): n = start while True: yield n n += step ``` output was : ``` >>> print(count(2.5,0.5)) <gener...
2020/04/23
[ "https://Stackoverflow.com/questions/61388487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13146477/" ]
if u want set the icon size small then u can do like that ``` Tab( text: "Category List", icon: Icon(Icons.home,size: 15,), ), Tab( text: "Product List", icon: Icon(Icons.view_list,size: 15,), ), Tab( ...
You gotta make custom TabBar for customization. Something like this. **CustomTabbar** ``` import 'package:flutter/material.dart'; class ChangeTextSizeTabbar extends StatefulWidget { @override ChangeTextSizeTabbarState createState() { return new ChangeTextSizeTabbarState(); } } class ChangeTextSizeTabbar...
31,715,184
I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like *date=now - timedelta(days=days)* instead of argument days.
2015/07/30
[ "https://Stackoverflow.com/questions/31715184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4947801/" ]
`timedelta` does not support months, but you can try using [`dateutil.relativedelta`](http://dateutil.readthedocs.org/en/latest/relativedelta.html#dateutil.relativedelta.relativedelta) for your calculations , which do support months. Example - ``` >>> from dateutil import relativedelta >>> from datetime import dateti...
If you are only interested in what the month was 6 months ago then try this: ``` import datetime month = datetime.datetime.now().month - 6 if month < 1: month = 12 + month # At this point month is 0 or a negative number so we add ```
31,715,184
I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like *date=now - timedelta(days=days)* instead of argument days.
2015/07/30
[ "https://Stackoverflow.com/questions/31715184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4947801/" ]
If you are only interested in what the month was 6 months ago then try this: ``` import datetime month = datetime.datetime.now().month - 6 if month < 1: month = 12 + month # At this point month is 0 or a negative number so we add ```
Following function should work fine for both month add and month substract. ``` import datetime import calendar def add_months(sourcedate, months): month = sourcedate.month - 1 + months year = sourcedate.year + month / 12 month = month % 12 + 1 day = min(sourcedate.day,calendar.monthrange(year,mon...
31,715,184
I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like *date=now - timedelta(days=days)* instead of argument days.
2015/07/30
[ "https://Stackoverflow.com/questions/31715184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4947801/" ]
`timedelta` does not support months, but you can try using [`dateutil.relativedelta`](http://dateutil.readthedocs.org/en/latest/relativedelta.html#dateutil.relativedelta.relativedelta) for your calculations , which do support months. Example - ``` >>> from dateutil import relativedelta >>> from datetime import dateti...
Following function should work fine for both month add and month substract. ``` import datetime import calendar def add_months(sourcedate, months): month = sourcedate.month - 1 + months year = sourcedate.year + month / 12 month = month % 12 + 1 day = min(sourcedate.day,calendar.monthrange(year,mon...
52,805,041
Say im having scrapper\_1.py , scrapper\_2.py, scrapper\_3.py. The way i run it now its from pycharm run/execute each in separate, this way i can see the 3 python.exe in execution at task manager. Now im trying to write a master script say scrapper\_runner.py that imports this scrappers as modules and run them all in...
2018/10/14
[ "https://Stackoverflow.com/questions/52805041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662409/" ]
A subprocess in python may or may not show up as a separate process, depending on your OS and your task manager. `htop` in linux, for example, will display subprocesses under the parent process in tree-view. I recommend taking a look at this in depth tutorial on the `multiprocessing` module in python: <https://pymotw....
Your problem is in how you setup the processes. You are not running the processes in parallel, even though you think you are. You are actually running them, when you add them to the `runners_list` and then you are running the result of each runner in parallel as multiprocesses. What you want to do, is to add the funct...
52,902,158
I have the following list: ``` o_dict_list = [(OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Coffee')]), 'Ambiguous'), (OrderedDict([('StreetNamePreType', 'AVENUE'), ('StreetName', 'Washington')]), 'Ambiguous'), (OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Quartz')])...
2018/10/20
[ "https://Stackoverflow.com/questions/52902158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6930132/" ]
I would use list comprehension to do this as follows. ``` pd.DataFrame([o_dict_list[i][0] for i, j in enumerate(o_dict_list)]) ``` > > > > > > See the output below. > > > > > > > > > ``` StreetNamePreType StreetName 0 ROAD Coffee 1 AVENUE Washington 2 ROAD Quartz ```
extracting the `OrderedDict` objects from your list and then use `pd.Dataframe` should work ``` values= [] for i in range(len(o_dict_list)): values.append(o_dict_list[i][0]) pd.DataFrame(values) StreetNamePreType StreetName 0 ROAD Coffee 1 AVENUE Washington 2 ROAD Quartz ```
52,902,158
I have the following list: ``` o_dict_list = [(OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Coffee')]), 'Ambiguous'), (OrderedDict([('StreetNamePreType', 'AVENUE'), ('StreetName', 'Washington')]), 'Ambiguous'), (OrderedDict([('StreetNamePreType', 'ROAD'), ('StreetName', 'Quartz')])...
2018/10/20
[ "https://Stackoverflow.com/questions/52902158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6930132/" ]
I would use list comprehension to do this as follows. ``` pd.DataFrame([o_dict_list[i][0] for i, j in enumerate(o_dict_list)]) ``` > > > > > > See the output below. > > > > > > > > > ``` StreetNamePreType StreetName 0 ROAD Coffee 1 AVENUE Washington 2 ROAD Quartz ```
``` d = [{'points': 50, 'time': '5:00', 'year': 2010}, {'points': 25, 'time': '6:00', 'month': "february"}, {'points':90, 'time': '9:00', 'month': 'january'}, {'points_h1':20, 'month': 'june'}] pd.DataFrame(d) ```
5,980,863
In my django app I call `location.reload();` in an Ajax routine in some rare circumstances. That works well with Chrome, but with Firefox4 I get an `error: [Errno 32] Broken pipe` twice on my development server (Django 1.2.5, Python 2.7), which takes about 10 sec. And the error seems to eat the message I'm trying to...
2011/05/12
[ "https://Stackoverflow.com/questions/5980863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/526169/" ]
First of all, that's an issue with some specific browsers (and, probably, long processing on the server side) not a problem in django. From the [bug report](http://code.djangoproject.com/ticket/4444#comment:14) on django: > > This is common error which happens whenever your browser closes the connection while the de...
The broken pipe error can also be down to lack of support for certain functionality in the Django debug server - one notable issue is Django's lack of support for [`Range` HTTP requests](https://www.rfc-editor.org/rfc/rfc7233) (see here for details: [Byte Ranges in Django](https://stackoverflow.com/questions/14324250/b...
50,014,265
I'm trying to write a python script that can echo whatever a user types when running the script Right now, the code I have is (version\_msg and usage\_msg don't matter right now) ``` from optparse import OptionParser version_msg = "" usage_msg = "" parser = OptionParser(version=version_msg, usage=usage_msg) parser....
2018/04/25
[ "https://Stackoverflow.com/questions/50014265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6642021/" ]
A slightly hacky way of doing it: ``` from optparse import OptionParser version_msg = "" usage_msg = "" parser = OptionParser(version=version_msg, usage=usage_msg) parser.add_option("-e", "--echo", action="append", dest="input_lines", default=[]) options, arguments = parser.parse_args() print(options.input_lines + ...
I think this is best accomplished by quoting the argument ie hello world becomes 'hello world' this ensures that the -e option consumes the entire string. If you really need the string to be broken up into pieces ie ['hello', 'world'] instead of ['hello world'] you could easily call split() on options.e[0] ``` string...
50,014,265
I'm trying to write a python script that can echo whatever a user types when running the script Right now, the code I have is (version\_msg and usage\_msg don't matter right now) ``` from optparse import OptionParser version_msg = "" usage_msg = "" parser = OptionParser(version=version_msg, usage=usage_msg) parser....
2018/04/25
[ "https://Stackoverflow.com/questions/50014265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6642021/" ]
In `argparse` this is quite easy, with its `nargs` parameter: ``` In [245]: parser = argparse.ArgumentParser() In [246]: parser.add_argument('-e','--echo', nargs='+'); In [247]: parser.parse_args(['-e','hello','world']) Out[247]: Namespace(echo=['hello', 'world']) ``` `nargs` is used to specify how many strings the ...
I think this is best accomplished by quoting the argument ie hello world becomes 'hello world' this ensures that the -e option consumes the entire string. If you really need the string to be broken up into pieces ie ['hello', 'world'] instead of ['hello world'] you could easily call split() on options.e[0] ``` string...
14,404,744
I'm trying to read a CSV file using `numpy.recfromcsv(...)` where some of the fields have commas in them. The fields that have commas in them are surrounded by quotes i.e., `"value1, value2"`. Numpy see's the quoted field as two different fields and it doesn't work very well. The command I'm using right now is ``` ...
2013/01/18
[ "https://Stackoverflow.com/questions/14404744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633318/" ]
It is possible to do this with [pandas](http://pandas.pydata.org/): ``` np_array = pandas.io.parsers.read_csv("file_with_comma_fields_quoted.csv").as_matrix() ```
If you consider using native Python csv reader, with Python doc [here](http://docs.python.org/2/library/csv.html#csv-fmt-params): Python csv reader defines some optional `Dialect.quotechar` options, which defaults to `'"'`. In the csv format standard, quotechar is another field delimiter, and the delimiter (comma in ...
14,404,744
I'm trying to read a CSV file using `numpy.recfromcsv(...)` where some of the fields have commas in them. The fields that have commas in them are surrounded by quotes i.e., `"value1, value2"`. Numpy see's the quoted field as two different fields and it doesn't work very well. The command I'm using right now is ``` ...
2013/01/18
[ "https://Stackoverflow.com/questions/14404744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633318/" ]
It is possible to do this with [pandas](http://pandas.pydata.org/): ``` np_array = pandas.io.parsers.read_csv("file_with_comma_fields_quoted.csv").as_matrix() ```
It turns out the easiest way to do this is to use the standard library module, `csv` to read in the file into a tuple, then use the tuple as input to a numpy array. I wish I could just read it in with numpy, but that doesn't seem to work.
25,426,447
I was trying to understand how non-blocking sockets work ,so I wrote this simple server in python . ``` import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1',1000)) s.listen(5) s.setblocking(0) while True: try: conn, addr = s.accept() print ('connection f...
2014/08/21
[ "https://Stackoverflow.com/questions/25426447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2789669/" ]
`setblocking` only affects the socket you use it on. So you have to add `conn.setblocking(0)` to see an effect: The `recv` will then return immediately if there is no data available.
You just need to call `setblocking(0)` on the *connected* socket, i.e. `conn`. ``` import socket s = socket.socket() s.bind(('127.0.0.1', 12345)) s.listen(5) s.setblocking(0) >>> conn, addr = s.accept() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.7/socket.py", l...
25,426,447
I was trying to understand how non-blocking sockets work ,so I wrote this simple server in python . ``` import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1',1000)) s.listen(5) s.setblocking(0) while True: try: conn, addr = s.accept() print ('connection f...
2014/08/21
[ "https://Stackoverflow.com/questions/25426447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2789669/" ]
`setblocking` only affects the socket you use it on. So you have to add `conn.setblocking(0)` to see an effect: The `recv` will then return immediately if there is no data available.
<https://docs.python.org/3/library/socket.html#socket.setdefaulttimeout> You can use `s.setdefaulttimeout(1.0)` to apply all connection sockets as default.
25,426,447
I was trying to understand how non-blocking sockets work ,so I wrote this simple server in python . ``` import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1',1000)) s.listen(5) s.setblocking(0) while True: try: conn, addr = s.accept() print ('connection f...
2014/08/21
[ "https://Stackoverflow.com/questions/25426447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2789669/" ]
You just need to call `setblocking(0)` on the *connected* socket, i.e. `conn`. ``` import socket s = socket.socket() s.bind(('127.0.0.1', 12345)) s.listen(5) s.setblocking(0) >>> conn, addr = s.accept() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.7/socket.py", l...
<https://docs.python.org/3/library/socket.html#socket.setdefaulttimeout> You can use `s.setdefaulttimeout(1.0)` to apply all connection sockets as default.
23,785,259
I'm new using Python 3.4 and I'll be using it for my internship in the next month. However, my instructor gave me a task to practice while I haven't started it yet. Thus, he gave me a set of data and he asked me to figure how to load this out. However, it keep showing me this: ``` Traceback (most recent call last): ...
2014/05/21
[ "https://Stackoverflow.com/questions/23785259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661013/" ]
On the SelectionChanged event you can do this: ``` private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (dataGridView1.SelectedCells.Count > 2) { dataGridView1.SelectedCells[0].Selected = false; } } ``` This will prevent/undo selecting any more cells after selecting two. Fo...
You could try overriding SetSelectedRowCore, calling the base with adding your new limitation to the selected condition. ``` protected virtual void SetSelectedRowCore(int rowIndex,bool selected ) { base(rowIndex, selected && currentSelection < allowedSelectionCount); } ``` [SetSelectedRowCore](http://msdn.micr...
23,785,259
I'm new using Python 3.4 and I'll be using it for my internship in the next month. However, my instructor gave me a task to practice while I haven't started it yet. Thus, he gave me a set of data and he asked me to figure how to load this out. However, it keep showing me this: ``` Traceback (most recent call last): ...
2014/05/21
[ "https://Stackoverflow.com/questions/23785259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661013/" ]
This always leave selected 2 last selected rows ``` private void dataGridView1_SelectionChanged(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 2) { for (int i = 2; i < dataGridView1.SelectedRows.Count; i++) { dataGridView1.SelectedRows[i...
You could try overriding SetSelectedRowCore, calling the base with adding your new limitation to the selected condition. ``` protected virtual void SetSelectedRowCore(int rowIndex,bool selected ) { base(rowIndex, selected && currentSelection < allowedSelectionCount); } ``` [SetSelectedRowCore](http://msdn.micr...
38,994,265
When we input : 10 output :01 02 03 04 05 06 07 08 09 10 When we input :103 output :001 002 003...010 011 012 013.....100 101 002 103 How to create this sequence in ruby or python ?
2016/08/17
[ "https://Stackoverflow.com/questions/38994265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ruby implementation: ``` n = gets p (1..n.to_i).map{ |i| i.to_s.rjust(n.to_s.length, "0") }.join(" ") ``` Here `rjust` will add leading zeros.
A very basic Python implementation. Note that it's a generator so it returns one value at a time. ``` def get_range(n): len_n = len(str(n)) for num in range(1, n + 1): output = str(num) while len(output) < len_n: output = '0' + output yield output for i in get_range(100): ...
38,994,265
When we input : 10 output :01 02 03 04 05 06 07 08 09 10 When we input :103 output :001 002 003...010 011 012 013.....100 101 002 103 How to create this sequence in ruby or python ?
2016/08/17
[ "https://Stackoverflow.com/questions/38994265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Another one in Ruby: ``` n = gets.chomp '1'.rjust(n.size, '0').upto(n) { |s| puts s } ``` [`String#upto`](http://ruby-doc.org/core-2.3.1/String.html#method-i-upto) handles numeric strings in a special way: ``` '01'.upto('10').to_a #=> ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"] ```
A very basic Python implementation. Note that it's a generator so it returns one value at a time. ``` def get_range(n): len_n = len(str(n)) for num in range(1, n + 1): output = str(num) while len(output) < len_n: output = '0' + output yield output for i in get_range(100): ...
38,994,265
When we input : 10 output :01 02 03 04 05 06 07 08 09 10 When we input :103 output :001 002 003...010 011 012 013.....100 101 002 103 How to create this sequence in ruby or python ?
2016/08/17
[ "https://Stackoverflow.com/questions/38994265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ruby implementation: ``` n = gets p (1..n.to_i).map{ |i| i.to_s.rjust(n.to_s.length, "0") }.join(" ") ``` Here `rjust` will add leading zeros.
Using `zfill` you can add leading zeroes. ``` num=input() for i in range(1,int(num)+1): print (str(i).zfill(len(num))) ```
38,994,265
When we input : 10 output :01 02 03 04 05 06 07 08 09 10 When we input :103 output :001 002 003...010 011 012 013.....100 101 002 103 How to create this sequence in ruby or python ?
2016/08/17
[ "https://Stackoverflow.com/questions/38994265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Another one in Ruby: ``` n = gets.chomp '1'.rjust(n.size, '0').upto(n) { |s| puts s } ``` [`String#upto`](http://ruby-doc.org/core-2.3.1/String.html#method-i-upto) handles numeric strings in a special way: ``` '01'.upto('10').to_a #=> ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"] ```
Using `zfill` you can add leading zeroes. ``` num=input() for i in range(1,int(num)+1): print (str(i).zfill(len(num))) ```
38,994,265
When we input : 10 output :01 02 03 04 05 06 07 08 09 10 When we input :103 output :001 002 003...010 011 012 013.....100 101 002 103 How to create this sequence in ruby or python ?
2016/08/17
[ "https://Stackoverflow.com/questions/38994265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ruby implementation: ``` n = gets p (1..n.to_i).map{ |i| i.to_s.rjust(n.to_s.length, "0") }.join(" ") ``` Here `rjust` will add leading zeros.
Another one in Ruby: ``` n = gets.chomp '1'.rjust(n.size, '0').upto(n) { |s| puts s } ``` [`String#upto`](http://ruby-doc.org/core-2.3.1/String.html#method-i-upto) handles numeric strings in a special way: ``` '01'.upto('10').to_a #=> ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"] ```
51,325,955
I am trying to scrape a website using `Selenium Firefox` (headless) driver in `python`. I read all the anchors in the webpage and go through them all one by one. But I want for the browser to wait for the `Ajax` calls on the page to be over before moving to another page. My code is the following: ``` import time fr...
2018/07/13
[ "https://Stackoverflow.com/questions/51325955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2378622/" ]
You should add a `0` in your conversion specification to indicate that you want zero-padding: ``` $test = sprintf('%06d', rand(1, 1000000)); // ^-- here ``` The conversion specifications are documented on [the `sprintf` manual page](http://php.net/manual/en/function.sprintf.php).
You can just replace the empty character with 0. ``` $test = str_replace(" ", "0", sprintf('%6d', rand(1, 1000000))); ```
51,325,955
I am trying to scrape a website using `Selenium Firefox` (headless) driver in `python`. I read all the anchors in the webpage and go through them all one by one. But I want for the browser to wait for the `Ajax` calls on the page to be over before moving to another page. My code is the following: ``` import time fr...
2018/07/13
[ "https://Stackoverflow.com/questions/51325955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2378622/" ]
You should add a `0` in your conversion specification to indicate that you want zero-padding: ``` $test = sprintf('%06d', rand(1, 1000000)); // ^-- here ``` The conversion specifications are documented on [the `sprintf` manual page](http://php.net/manual/en/function.sprintf.php).
If you don't want to use `sprintf` (some dont!), an alternative way to do it would be: ``` $test = str_pad(mt_rand(1, 999999),6,0,STR_PAD_LEFT); ``` Example output: ``` 736523 024132 003145 ``` Using `mt_rand` here because its a better random number function (not perfect, but better than just `rand`). Also adjust...
39,948,588
How can I read the contents of a binary or a text file in a non-blocking mode? For binary files: when I `open(filename, mode='rb')`, I get an instance of `io.BufferedReader`. The documentation fort `io.BufferedReader.read` [says](https://docs.python.org/3.5/library/io.html#io.BufferedReader.read): > > Read and retur...
2016/10/09
[ "https://Stackoverflow.com/questions/39948588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336527/" ]
File operations are blocking. There is no non-blocking mode. But you can create a thread which reads the file in the background. In Python 3, [`concurrent.futures` module](https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures) can be useful here. ``` from concurrent.futures import Thre...
I suggest using [**aiofiles**](https://github.com/Tinche/aiofiles) - a library for handling local disk files in asyncio applications. ``` import aiofiles async def read_without_blocking(): f = await aiofiles.open('filename', mode='r') try: contents = await f.read() finally: await f.close()...
39,948,588
How can I read the contents of a binary or a text file in a non-blocking mode? For binary files: when I `open(filename, mode='rb')`, I get an instance of `io.BufferedReader`. The documentation fort `io.BufferedReader.read` [says](https://docs.python.org/3.5/library/io.html#io.BufferedReader.read): > > Read and retur...
2016/10/09
[ "https://Stackoverflow.com/questions/39948588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336527/" ]
File operations are blocking. There is no non-blocking mode. But you can create a thread which reads the file in the background. In Python 3, [`concurrent.futures` module](https://docs.python.org/3.4/library/concurrent.futures.html#module-concurrent.futures) can be useful here. ``` from concurrent.futures import Thre...
Python does support non-blocking reads, at least on Unix type systems, by setting the [`O_NONBLOCK` flag](https://docs.python.org/3/library/os.html#os.O_NONBLOCK). In Python 3.5+, there is the [`os.set_blocking()` function](https://docs.python.org/3/library/os.html#os.set_blocking) which makes this easier: ``` import ...
48,146,921
I have a script that builds llvm/clang 3.42 from source (with configure+make). **It runs smooth on ubuntu 14.04.5 LTS**. When I upgraded to **ubuntu 17.04**, the build fails. Here is the building script: ``` svn co https://llvm.org/svn/llvm-project/llvm/tags/RELEASE_342/final llvm svn co https://llvm.org/svn/llvm-pro...
2018/01/08
[ "https://Stackoverflow.com/questions/48146921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3357352/" ]
That seems to be an issue with LLVM 3.4.2`tsan` (Thread Sanitizer) failing to build with GCC 6.x, as previously reported here: <https://aur.archlinux.org/packages/clang34-analyzer-split> It seems the inclusion of `stdlib.h` and `malloc.h` is conflicting, since both define `malloc` and friends. It's possible that thi...
I faced the same problem on my Ubuntu 16.10. It has default gcc 6.2. You need to instruct LLVM build system to use gcc 4.9. Also, I suggest you remove GCC6 completely. ``` $ sudo apt-get remove g++-6 gcc-6 cpp $ sudo apt-get install gcc-4.9 g++4.9 $ export CC=/usr/bin/gcc-4.9 $ export CXX=/usr/bin/g++-4.9 $ export CPP...
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
Pip dependencies can be included in the `environment.yml` file like this ([docs](https://conda.io/docs/user-guide/tasks/manage-environments.html#create-env-file-manually)): ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anaconda - pip - numpy=1.13.3 # pin version for c...
Just want to add that adding a wheel in the directory also works. I was getting this error when using the entire URL: ``` HTTP error 404 while getting http://www.lfd.uci.edu/~gohlke/pythonlibs/f9r7rmd8/opencv_python-3.1.0-cp35-none-win_amd64.whl ``` Ended up downloading the wheel and saving it into the same directo...
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
Pip dependencies can be included in the `environment.yml` file like this ([docs](https://conda.io/docs/user-guide/tasks/manage-environments.html#create-env-file-manually)): ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anaconda - pip - numpy=1.13.3 # pin version for c...
One can also use the `requirements.txt` directly in the YAML. For example, ``` name: test-env dependencies: - python>=3.5 - anaconda - pip - pip: - -r requirements.txt ``` Basically, [any option you can run with `pip install`](https://pip.pypa.io/en/stable/reference/pip_install/) you can run in a YAML. S...
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
Pip dependencies can be included in the `environment.yml` file like this ([docs](https://conda.io/docs/user-guide/tasks/manage-environments.html#create-env-file-manually)): ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anaconda - pip - numpy=1.13.3 # pin version for c...
If you want to do it automatically it seems that if you do: ``` conda env export > environment.yml` ``` already has the pip things you need. No need to run `pip freeze > requirements4pip.txt` separately for me or include it as an ``` - pip: - -r file:requirements.txt ``` as another answer mentioned. See my...
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
One can also use the `requirements.txt` directly in the YAML. For example, ``` name: test-env dependencies: - python>=3.5 - anaconda - pip - pip: - -r requirements.txt ``` Basically, [any option you can run with `pip install`](https://pip.pypa.io/en/stable/reference/pip_install/) you can run in a YAML. S...
Just want to add that adding a wheel in the directory also works. I was getting this error when using the entire URL: ``` HTTP error 404 while getting http://www.lfd.uci.edu/~gohlke/pythonlibs/f9r7rmd8/opencv_python-3.1.0-cp35-none-win_amd64.whl ``` Ended up downloading the wheel and saving it into the same directo...
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
Just want to add that adding a wheel in the directory also works. I was getting this error when using the entire URL: ``` HTTP error 404 while getting http://www.lfd.uci.edu/~gohlke/pythonlibs/f9r7rmd8/opencv_python-3.1.0-cp35-none-win_amd64.whl ``` Ended up downloading the wheel and saving it into the same directo...
If you want to do it automatically it seems that if you do: ``` conda env export > environment.yml` ``` already has the pip things you need. No need to run `pip freeze > requirements4pip.txt` separately for me or include it as an ``` - pip: - -r file:requirements.txt ``` as another answer mentioned. See my...
35,245,401
I work with conda environments and need some pip packages as well, e.g. pre-compiled wheels from [~gohlke](http://www.lfd.uci.edu/~gohlke/pythonlibs/). At the moment I have two files: `environment.yml` for conda with: ``` # run: conda env create --file environment.yml name: test-env dependencies: - python>=3.5 - anac...
2016/02/06
[ "https://Stackoverflow.com/questions/35245401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5276734/" ]
One can also use the `requirements.txt` directly in the YAML. For example, ``` name: test-env dependencies: - python>=3.5 - anaconda - pip - pip: - -r requirements.txt ``` Basically, [any option you can run with `pip install`](https://pip.pypa.io/en/stable/reference/pip_install/) you can run in a YAML. S...
If you want to do it automatically it seems that if you do: ``` conda env export > environment.yml` ``` already has the pip things you need. No need to run `pip freeze > requirements4pip.txt` separately for me or include it as an ``` - pip: - -r file:requirements.txt ``` as another answer mentioned. See my...
55,746,170
I am trying to implement a neural network for an NLP task with a convolutional layer followed up by an LSTM layer. I am currently experimenting with the new Tensorflow 2.0 to do this. However, when building the model, I've encountered an error that I could not understand. ``` # Input shape of training and validation s...
2019/04/18
[ "https://Stackoverflow.com/questions/55746170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7274157/" ]
The issue is a dimensionality issue. Your feature is of shape `[..., 1, 512]`; therefore, `MaxPooling1D` `pooling_size` 2 is bigger than 1 causing the issue. Adding `padding="same"` will solve the issue. ``` model = tf.keras.Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(None, 512))) model.add(tf.ker...
**padding="same"** should solve your issue. Change below line: `model.add(tf.keras.layers.MaxPooling1D(2, padding="same"))`
23,793,774
``` omnia@ubuntu:~$ psql --version psql (PostgreSQL) 9.3.4 omnia@ubuntu:~$ pg_dump --version pg_dump (PostgreSQL) 9.2.8 omnia@ubuntu:~$ dpkg -l | grep pg ii gnupg 1.4.11-3ubuntu2.5 GNU privacy guard - a free PGP replacement ii gpgv 1.4.11-3ubuntu2...
2014/05/21
[ "https://Stackoverflow.com/questions/23793774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
``` sudo rm /usr/bin/pg_dump sudo ln -s /usr/lib/postgresql/9.3/bin/pg_dump /usr/bin/pg_dump ```
The `pgdg60` package suffix leads me to believe these packages are not from the official Ubuntu repository. Try looking into `/etc/apt/sources.list` or `/etc/apt/sources.list.d` and see if you have any third party PPA's or repositories specified. Try getting the Postgresql packages either from your Ubuntu repo (althou...
23,793,774
``` omnia@ubuntu:~$ psql --version psql (PostgreSQL) 9.3.4 omnia@ubuntu:~$ pg_dump --version pg_dump (PostgreSQL) 9.2.8 omnia@ubuntu:~$ dpkg -l | grep pg ii gnupg 1.4.11-3ubuntu2.5 GNU privacy guard - a free PGP replacement ii gpgv 1.4.11-3ubuntu2...
2014/05/21
[ "https://Stackoverflow.com/questions/23793774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
If your *pg\_dump* is sym-linked to *pg\_wrapper*, then the best fix is to tell *pg\_wrapper* which version to use. Append ``` * * 9.6 localhost:5432 * ``` to `/etc/postgresql-common/user_clusters`, (assuming your postmaster is listening on localhost:5432 of course). This then fixes the problem for a...
The `pgdg60` package suffix leads me to believe these packages are not from the official Ubuntu repository. Try looking into `/etc/apt/sources.list` or `/etc/apt/sources.list.d` and see if you have any third party PPA's or repositories specified. Try getting the Postgresql packages either from your Ubuntu repo (althou...
23,793,774
``` omnia@ubuntu:~$ psql --version psql (PostgreSQL) 9.3.4 omnia@ubuntu:~$ pg_dump --version pg_dump (PostgreSQL) 9.2.8 omnia@ubuntu:~$ dpkg -l | grep pg ii gnupg 1.4.11-3ubuntu2.5 GNU privacy guard - a free PGP replacement ii gpgv 1.4.11-3ubuntu2...
2014/05/21
[ "https://Stackoverflow.com/questions/23793774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
``` sudo rm /usr/bin/pg_dump sudo ln -s /usr/lib/postgresql/9.3/bin/pg_dump /usr/bin/pg_dump ```
If your *pg\_dump* is sym-linked to *pg\_wrapper*, then the best fix is to tell *pg\_wrapper* which version to use. Append ``` * * 9.6 localhost:5432 * ``` to `/etc/postgresql-common/user_clusters`, (assuming your postmaster is listening on localhost:5432 of course). This then fixes the problem for a...
64,808,992
I am stuck with code below. Either I cannot find simple answer to my problem due to not narrow enough search or I am just too blind to see. Anyway I am looking to put the "+" and "-" buttons to use. They suppose to literally do what their assigned symbols do. With my level of python knowledge I can only achieve that by...
2020/11/12
[ "https://Stackoverflow.com/questions/64808992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11618118/" ]
Currently, there is one solution **Real-World Super-Resolution via Kernel Estimation and Noise Injection**. The author proposes a degradation framework RealSR, which provides realistic images for super-resolution learning. It is a promising method for shakiness or motion effect images super-resolution. The method is d...
I've also been working on this super-resolution field and found some promising results but haven't tried yet, [first paper](https://doi.org/10.1016/j.heliyon.2021.e08341) (license plate base text) they implement the image enhancement first then do the super-resolution in a later stage. [second paper](https://arxiv.org/...
69,280,273
So, I have a list of dicts in python that looks like this: ``` lis = [ {'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}, {'action': 'Notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'} ... ] ``` Now I want `lis` to be in a way, such that **each individu...
2021/09/22
[ "https://Stackoverflow.com/questions/69280273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11903403/" ]
You might harness [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) for this task as follows ``` import collections order = ['date', 'Genre', 'action', 'type'] dct1 = {'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'} dct2 = {'act...
Try this: ``` def sort_dct(li, mapping): return {v: li[v] for k,v in mapping.items()} out = [] mapping = {1:'date', 2:'Genre', 3:'action', 4:'type'} for li in lis: out.append(sort_dct(li,mapping)) print(out) ``` Output: ``` [{'date': '2021-05-07 01:59:37', 'Genre': 10, 'action': 'Notify', 'type': 'S...
69,280,273
So, I have a list of dicts in python that looks like this: ``` lis = [ {'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}, {'action': 'Notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'} ... ] ``` Now I want `lis` to be in a way, such that **each individu...
2021/09/22
[ "https://Stackoverflow.com/questions/69280273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11903403/" ]
With a list comprehension: ```py lis = [ {'action': 'Notify', 'type': 'Something', 'Genre': 10, 'date': '2021-05-07 01:59:37'}, {'action': 'Notify', 'type': 'Something Else', 'Genre': 20, 'date': '2021-05-07 01:59:37'} ] mapping = {1:'date', 2:'Genre', 3:'action', 4:'type'} sorted_lis = [ {field: record[field] f...
Try this: ``` def sort_dct(li, mapping): return {v: li[v] for k,v in mapping.items()} out = [] mapping = {1:'date', 2:'Genre', 3:'action', 4:'type'} for li in lis: out.append(sort_dct(li,mapping)) print(out) ``` Output: ``` [{'date': '2021-05-07 01:59:37', 'Genre': 10, 'action': 'Notify', 'type': 'S...
36,534,186
I'm having this problem with a python script I'm writing that calls an exe file (subrocess.Popen). I'm redirecting the stdout and stderr to PIPE, but i cant read (subprocess.Popen.stdout.readline()) any output. I did try to run the exec file in windows cli and redirecting both stdout and stderr... and nothing happens....
2016/04/10
[ "https://Stackoverflow.com/questions/36534186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6185152/" ]
Does this work? Set the alpha of the extra lines to 0 (so they become transparent. Using geom\_line as geom\_density uses alpha for fill only. (system problems prevent testing) ``` ggplotly( ggplot(diamonds, aes(depth, colour = cut)) + geom_density() + geom_line(aes(text = paste("Clarity: ", clarity)), stat=...
I realize that this is an old answer, but the main problem here is that you're trying to do something that's logically impossible. `clarity` and `cut` are two separate dimensions, so you can't simply put the `clarity` in a tooltip on the line that's grouped by `cut`, because that line represents diamonds of all differ...
54,900,964
Hi I have a question with regards to python programming for my assignment The task is to replace the occurrence of a number in a given value in a recursive manner, and the final output must be in integer i.e. digit\_swap(521, 1, 3) --> 523 where 1 is swapped out for 3 Below is my code and it works well for s = 0 - 9...
2019/02/27
[ "https://Stackoverflow.com/questions/54900964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9369481/" ]
Conversion to string is unnecessary, this can be implemented much easier ``` def digit_swap(n, d, s): if n == 0: return 0 lower_n = (s if (n % 10) == d else (n % 10)) higher_n = digit_swap(n // 10, d, s) * 10 return higher_n + lower_n assert digit_swap(521, 1, 3) == 523 assert digit_swap(65132, 1...
For example `int(00)` is casted to 0. Therefore a zero is discarded. I suggest not to cast, instead leave it as a string. If you have to give back an `int`, you should not cast until you return the number. However, you still discard 0s at the beginning. So all in all, I would suggest just return strings instead of ints...
54,900,964
Hi I have a question with regards to python programming for my assignment The task is to replace the occurrence of a number in a given value in a recursive manner, and the final output must be in integer i.e. digit\_swap(521, 1, 3) --> 523 where 1 is swapped out for 3 Below is my code and it works well for s = 0 - 9...
2019/02/27
[ "https://Stackoverflow.com/questions/54900964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9369481/" ]
Conversion to string is unnecessary, this can be implemented much easier ``` def digit_swap(n, d, s): if n == 0: return 0 lower_n = (s if (n % 10) == d else (n % 10)) higher_n = digit_swap(n // 10, d, s) * 10 return higher_n + lower_n assert digit_swap(521, 1, 3) == 523 assert digit_swap(65132, 1...
do not return int from method, instead convert it to int from where you are calling method. Problem lies where your code trying to convert string to int `return int(result)`. So if result is `03` then function will return `int('03')` i.e `3`. **call your method like this `print int(digit_swap(65132, 1, 0))` so you will...
13,083,026
Imagine I have a script, let's say `my_tools.py` that I import as a module. But `my_tools.py` is saved twice: at `C:\Python27\Lib` and at the same directory from where the script is run that does the import. Can I change the order where python looks for `my_tools.py` first? That is, to check first if it exists at `C...
2012/10/26
[ "https://Stackoverflow.com/questions/13083026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105929/" ]
You can manipulate `sys.path` as much as you want... If you wanted to move the current directory to be scanned last, then just do `sys.path[1:] + sys.path[:1]`. Otherwise, if you want to get into the nitty gritty then the [imp module](http://docs.python.org/library/imp.html) can be used to customise until your hearts c...
You can modify [`sys.path`](http://docs.python.org/library/sys.html#sys.path), which will determine the order and locations that Python searches for imports. (Note that you must do this *before* the import statement.)
13,083,026
Imagine I have a script, let's say `my_tools.py` that I import as a module. But `my_tools.py` is saved twice: at `C:\Python27\Lib` and at the same directory from where the script is run that does the import. Can I change the order where python looks for `my_tools.py` first? That is, to check first if it exists at `C...
2012/10/26
[ "https://Stackoverflow.com/questions/13083026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105929/" ]
You can manipulate `sys.path` as much as you want... If you wanted to move the current directory to be scanned last, then just do `sys.path[1:] + sys.path[:1]`. Otherwise, if you want to get into the nitty gritty then the [imp module](http://docs.python.org/library/imp.html) can be used to customise until your hearts c...
if you don't want python to search builtin modules then search in current folder first,, you can change `sys.path` `upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter` `sys.path[0] is the empty string, which directs Python...
46,092,292
I would like to split strings like the following: ``` x <- "abc-1230-xyz-[def-ghu-jkl---]-[adsasa7asda12]-s-[klas-bst-asdas foo]" ``` by dash (`-`) on the condition that those dashes must not be contained inside a pair of `[]`. The expected result would be ``` c("abc", "1230", "xyz", "[def-ghu-jkl---]", "[adsasa7as...
2017/09/07
[ "https://Stackoverflow.com/questions/46092292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3521006/" ]
You could use look ahead to verify that there is no `]` following sooner than a `[`: [`-(?![^[]*\])`](https://regex101.com/r/x0WbVt/2) So in R: ``` strsplit(x, "-(?![^[]*\\])", perl=TRUE) ``` ### Explanation: * `-`: match the hyphen * `(?! )`: negative look ahead: if that part is found after the previously matche...
I am not familiar with `r` language, but I believe it can do regex based search and replace. Instead of struggling with one single regex split function, I would go in 3 steps: * replace `-` in all `[....]` parts by a invisible char, like `\x99` * split by `-` * for each element in the above split result(array/list), r...
46,092,292
I would like to split strings like the following: ``` x <- "abc-1230-xyz-[def-ghu-jkl---]-[adsasa7asda12]-s-[klas-bst-asdas foo]" ``` by dash (`-`) on the condition that those dashes must not be contained inside a pair of `[]`. The expected result would be ``` c("abc", "1230", "xyz", "[def-ghu-jkl---]", "[adsasa7as...
2017/09/07
[ "https://Stackoverflow.com/questions/46092292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3521006/" ]
Instead of splitting, extract the parts: ``` library(stringr) str_extract_all(x, "(\\[[^\\[]*\\]|[^-])+") ```
I am not familiar with `r` language, but I believe it can do regex based search and replace. Instead of struggling with one single regex split function, I would go in 3 steps: * replace `-` in all `[....]` parts by a invisible char, like `\x99` * split by `-` * for each element in the above split result(array/list), r...
46,092,292
I would like to split strings like the following: ``` x <- "abc-1230-xyz-[def-ghu-jkl---]-[adsasa7asda12]-s-[klas-bst-asdas foo]" ``` by dash (`-`) on the condition that those dashes must not be contained inside a pair of `[]`. The expected result would be ``` c("abc", "1230", "xyz", "[def-ghu-jkl---]", "[adsasa7as...
2017/09/07
[ "https://Stackoverflow.com/questions/46092292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3521006/" ]
You could use look ahead to verify that there is no `]` following sooner than a `[`: [`-(?![^[]*\])`](https://regex101.com/r/x0WbVt/2) So in R: ``` strsplit(x, "-(?![^[]*\\])", perl=TRUE) ``` ### Explanation: * `-`: match the hyphen * `(?! )`: negative look ahead: if that part is found after the previously matche...
Instead of splitting, extract the parts: ``` library(stringr) str_extract_all(x, "(\\[[^\\[]*\\]|[^-])+") ```
57,398,668
I don't have o picture but I am asking did question because I am a beginner using python
2019/08/07
[ "https://Stackoverflow.com/questions/57398668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11897155/" ]
`input()` takes user input as a string. It's very safe. ``` >>> usr = input('Enter some input: ') Enter some input: hello, world >>> usr "hello, world" ``` `eval()` will execute a string as if it were python code. It's very dangerous. ``` >>>eval(input('Make it happen!')) Make it happen! print('hello') hello >>>eva...
`eval()` is used to evaluate an expression and `input()` is used to take user input. Here are the examples: ``` #evaluates expression >> eval('5+2') >> 7 # Takes user input >> input() 10 (user enters) >> 10 #evaluates user input >> eval('input()') 15 (user enters) >> 15 ```
37,776,724
I've just completed [Tatiana Tylosky's tutorial for Python](https://www.thinkful.com/learn/intro-to-python-tutorial/#Creating-Your-Pypet) and created my own Python pypet. In her tutorial, she shows how to do a "for" loop consisting of: ``` cat = { 'name': 'Fluffy', 'hungry': True, 'weight': 9.5, 'age'...
2016/06/12
[ "https://Stackoverflow.com/questions/37776724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6456667/" ]
I would enclose your feed `for` loop in a `for` loop that iterates three times. I would use something like: ``` for _ in range(3): for pet in pets: feed(pet) print pet ``` `for _ in range(3)` iterates three times. Note that I used `_` because you are not using the iteration variable, see e.g. [Wh...
Programming languages let you embed one structure in another. Put your current loop under a for loop that runs three times, as @intboolstring's answer already showed. Here are two more things you should do now: 1. Don't compare against `True`. `if pet["Hungry"] == True:` is better written as ``` if pet["Hungry"]: ...
37,776,724
I've just completed [Tatiana Tylosky's tutorial for Python](https://www.thinkful.com/learn/intro-to-python-tutorial/#Creating-Your-Pypet) and created my own Python pypet. In her tutorial, she shows how to do a "for" loop consisting of: ``` cat = { 'name': 'Fluffy', 'hungry': True, 'weight': 9.5, 'age'...
2016/06/12
[ "https://Stackoverflow.com/questions/37776724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6456667/" ]
I would enclose your feed `for` loop in a `for` loop that iterates three times. I would use something like: ``` for _ in range(3): for pet in pets: feed(pet) print pet ``` `for _ in range(3)` iterates three times. Note that I used `_` because you are not using the iteration variable, see e.g. [Wh...
If you don't want to use nested for loops you could also extend the pet list temporarily like this: ``` for pet in pets * 3: feed(pet) ``` that works because `pet * 3` creates the following list: `[cat, mouse, cat, mouse, cat, mouse]` If you need more control over the feeding order ( e.g. first feed all cats th...
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
1. Close `Visual Studio`. 2. Delete the `*.testlog` files in: *solutionfolder*\.vs\*solution name*\v16\TestStore\*number*.
I faced the same issue right now. A cleanup helped. As I had cleanup issues with VS in the last time (some DB-lock prevents a real cleanup to happen), my working cleanup was this way: 1. Close VS. 2. Git Bash in solution folder: `git clean -xfd` Probably it helps.
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
I faced the same issue right now. A cleanup helped. As I had cleanup issues with VS in the last time (some DB-lock prevents a real cleanup to happen), my working cleanup was this way: 1. Close VS. 2. Git Bash in solution folder: `git clean -xfd` Probably it helps.
Neither of these solutions worked for me. I was able to get the test explorer working by **closing visual studio** and **deleting** the "**.vs**" folder. Then **reopen the solution** and let it rebuild it.
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
I faced the same issue right now. A cleanup helped. As I had cleanup issues with VS in the last time (some DB-lock prevents a real cleanup to happen), my working cleanup was this way: 1. Close VS. 2. Git Bash in solution folder: `git clean -xfd` Probably it helps.
According to the Visual Studio developer community (found by going to the Help menu and selecting Feedback), an update to Visual Studio to version 16.5.5 will resolve the issue. FYI: They released this in February 2020 I can confirm it works (I was on VS 16.4.6)
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
I faced the same issue right now. A cleanup helped. As I had cleanup issues with VS in the last time (some DB-lock prevents a real cleanup to happen), my working cleanup was this way: 1. Close VS. 2. Git Bash in solution folder: `git clean -xfd` Probably it helps.
Steps as below 1. Close Visual Studio 2. Go to the project folder 3. Find the ".vs" folder. (Make sure you are also checking hidden item) 4. Delete ".vs" folder. 5. Good to go, Open visual studio, build and run project.
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
1. Close `Visual Studio`. 2. Delete the `*.testlog` files in: *solutionfolder*\.vs\*solution name*\v16\TestStore\*number*.
Neither of these solutions worked for me. I was able to get the test explorer working by **closing visual studio** and **deleting** the "**.vs**" folder. Then **reopen the solution** and let it rebuild it.
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
1. Close `Visual Studio`. 2. Delete the `*.testlog` files in: *solutionfolder*\.vs\*solution name*\v16\TestStore\*number*.
According to the Visual Studio developer community (found by going to the Help menu and selecting Feedback), an update to Visual Studio to version 16.5.5 will resolve the issue. FYI: They released this in February 2020 I can confirm it works (I was on VS 16.4.6)
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
1. Close `Visual Studio`. 2. Delete the `*.testlog` files in: *solutionfolder*\.vs\*solution name*\v16\TestStore\*number*.
Steps as below 1. Close Visual Studio 2. Go to the project folder 3. Find the ".vs" folder. (Make sure you are also checking hidden item) 4. Delete ".vs" folder. 5. Good to go, Open visual studio, build and run project.
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
Neither of these solutions worked for me. I was able to get the test explorer working by **closing visual studio** and **deleting** the "**.vs**" folder. Then **reopen the solution** and let it rebuild it.
Steps as below 1. Close Visual Studio 2. Go to the project folder 3. Find the ".vs" folder. (Make sure you are also checking hidden item) 4. Delete ".vs" folder. 5. Good to go, Open visual studio, build and run project.
59,391,988
I am trying to set up dockerized production environment for Flask application with gunicorn. I follow this [Digital Ocean's](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04) instructions together with [testdriven's one](https://testdriven.io/blog/...
2019/12/18
[ "https://Stackoverflow.com/questions/59391988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4765864/" ]
According to the Visual Studio developer community (found by going to the Help menu and selecting Feedback), an update to Visual Studio to version 16.5.5 will resolve the issue. FYI: They released this in February 2020 I can confirm it works (I was on VS 16.4.6)
Steps as below 1. Close Visual Studio 2. Go to the project folder 3. Find the ".vs" folder. (Make sure you are also checking hidden item) 4. Delete ".vs" folder. 5. Good to go, Open visual studio, build and run project.
52,305,075
Per [Google's Cloud Datastore Emulator installation instructions](https://cloud.google.com/datastore/docs/tools/datastore-emulator), I was able to install and run the emulator in a *bash* terminal window without problem with `gcloud beta emulators datastore start --project gramm-id`. I also setup the environment varia...
2018/09/13
[ "https://Stackoverflow.com/questions/52305075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1181911/" ]
> > gcloud auth application-default login > > > This will prompt you to login through a browser window and will set your GOOGLE\_APPLICATION\_CREDENTIALS correctly for you. [[1]](https://cloud.google.com/docs/authentication/production#calling)
In theory you should be able to use mock credentials, e.g.: ``` class EmulatorCreds(google.auth.credentials.Credentials): def __init__(self): self.token = b'secret' self.expiry = None @property def valid(self): return True def refresh(self, _): raise RuntimeError('Sho...
42,068,203
I am learning to use scrapinghub.com which runs in python 2.x I have written a script which uses Scrapy, I have crawled a string like below: ``` %3Ctable%20width%3D%22100%25%22%3E%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Ctr%3E%3Ctd%3E%3Cp%20style%3D%22colo...
2017/02/06
[ "https://Stackoverflow.com/questions/42068203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339229/" ]
Your data is perfectly valid UTF-8, encoded into a URL (so URLEncoded). Your output indicates you are looking at a [Mojibake](https://en.wikipedia.org/wiki/Mojibake), where your own software (console, terminal, text editor), is using a *different* codec to interpret the UTF-8 data. I suspect your setup is using CP-1254...
I don't know why, but for some reason I get it to work on scrapinghub.com like below. Let say I have an HTML text like: ``` <html> <div class="a"> Some chinese text </div> <div class="b"> QUOTED text got chinese in it %3Ctable%20width%3D%22100%25%22%3E%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20...
9,851,156
I am managing a quite large python code base (>2000 lines) that I want anyway to be available as a single runnable python script. So I am searching for a method or a tool to merge a development folder, made of different python files into a single running script. The thing/method I am searching for should take code sp...
2012/03/24
[ "https://Stackoverflow.com/questions/9851156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/749014/" ]
It sounds like you're asking how to merge your codebase into a single 2000-plus source file-- are you really, really sure you want to do this? It will make your code harder to maintain. Python files correspond to modules, so unless your main script does `from modname import *` for all its parts, you'll lose the module ...
[waffles](https://bitbucket.org/ArneBab/waffles) seems to do exactly what you're after, although I've not tried it You could probably do this manually, something like: ``` # file1.py from .file2 import func1, func2 def something(): func1() + func2() # file2.py def func1(): pass def func2(): pass # __init__.py f...
61,452,787
I cannot install Django 3 on my Debian 9 system. I follow <https://www.rosehosting.com/blog/how-to-install-python-3-6-4-on-debian-9/> this guide to install a Python 3 because there is no Python 3 in Debian repositories: ```sh :~# python3 Python 3.5.3 (default, Sep 27 2018, 17:25:39) ``` ```sh ~# pip3 -V pip 9.0.1 f...
2020/04/27
[ "https://Stackoverflow.com/questions/61452787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4003516/" ]
For the latest versions of Django you must be using python 3.6, 3.7, or 3.8. You're currently using 3.5 <https://docs.djangoproject.com/en/3.0/faq/install/#faq-python-version-support>
install python3-venv by command: ``` sudo apt install python3-venv ``` and ``` mkdir my_django_app cd my_django_app; python3 -m venv venv ``` ref: <https://linuxize.com/post/how-to-install-django-on-debian-9>
39,849,641
I am using `flask migrate` to for database creation & migration in flask with flask-sqlalchemy. Everything was working fine until I changed my database user password contains '@' then it stopped working so, I updated my code based on [Writing a connection string when password contains special characters](https://stac...
2016/10/04
[ "https://Stackoverflow.com/questions/39849641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873416/" ]
I have a solution for this issue after experiencing it as well. There's an issue with '%' (percent signs) in the db connection URI after you urlencode the string. I tried substituting the percent sign with double percent signs ('%%') which gets me past the interpolation error. However, that resulted in not being able...
You may want to look at <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql-unicode> I was having the same issue with my password and the mysql connector. using the mysql+pymysql connector allowed me to connect in application and in migration scripts.
39,849,641
I am using `flask migrate` to for database creation & migration in flask with flask-sqlalchemy. Everything was working fine until I changed my database user password contains '@' then it stopped working so, I updated my code based on [Writing a connection string when password contains special characters](https://stac...
2016/10/04
[ "https://Stackoverflow.com/questions/39849641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873416/" ]
In the `migrations/env.py` file, you will find the code that is responsible for this issue. ``` config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) ``` If there are `%` signs in the `SQLALCHEMY_DATABASE_URI`, this will cause an error. You can solve this...
I have a solution for this issue after experiencing it as well. There's an issue with '%' (percent signs) in the db connection URI after you urlencode the string. I tried substituting the percent sign with double percent signs ('%%') which gets me past the interpolation error. However, that resulted in not being able...
39,849,641
I am using `flask migrate` to for database creation & migration in flask with flask-sqlalchemy. Everything was working fine until I changed my database user password contains '@' then it stopped working so, I updated my code based on [Writing a connection string when password contains special characters](https://stac...
2016/10/04
[ "https://Stackoverflow.com/questions/39849641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/873416/" ]
In the `migrations/env.py` file, you will find the code that is responsible for this issue. ``` config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')) ``` If there are `%` signs in the `SQLALCHEMY_DATABASE_URI`, this will cause an error. You can solve this...
You may want to look at <http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql-unicode> I was having the same issue with my password and the mysql connector. using the mysql+pymysql connector allowed me to connect in application and in migration scripts.
36,329,606
This was the example picked from bokeh documentation. It is showing attribute error. I am using ipython in anaconda environment. ``` import pandas as pd from bokeh.charts import TimeSeries, output_file, show AAPL = pd.read_csv( "http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010", ...
2016/03/31
[ "https://Stackoverflow.com/questions/36329606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6139075/" ]
Check which version you are using, If you are using 0.11.1 then you can use <http://docs.bokeh.org/en/0.11.1/docs/user_guide/plotting.html> for doing the same.
instead of using attribute index, set x = 'Date'. ``` p = TimeSeries(data, x ='Date', title="APPL", ylabel='Stock Prices') ```
55,648,776
In apache beam pipeline, I am taking input from cloud storage and trying to write it in biqguery table. But during the execution of pipeline getting this error. "AttributeError: 'module' object has no attribute 'storage'" ``` def run(argv=None): with open('gl_ledgers.json') as json_file: schema = json.load...
2019/04/12
[ "https://Stackoverflow.com/questions/55648776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11303943/" ]
This is probably related to `pipeline_options.view_as(SetupOptions).save_main_session = True`. Do you need that line? Try removing that and see if it fixes the problem. It is likely that one of your imports can not be pickled. Without imports I can't help you debug further. You could also try moving your imports into ...
Possibly a [duplicate](https://stackoverflow.com/questions/53860066/gitlab-ci-runner-cant-import-google-cloud-in-python), in which case the problem would be that `google-cloud-storage` needs to be installed, not `google-cloud`.
14,909,365
I Have planned to build an application with a server and multiple clients.When the clients connect to the server for the first time it must be given a id.Each time the client sends a request,the server sends the client a set of strings.the client then processes these strings and once it is done it again sends a request...
2013/02/16
[ "https://Stackoverflow.com/questions/14909365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078134/" ]
Reason why your app is crashing because you are trying to deal with your GUI elements i.e `UIAlertView` in background thread, you need to run it on the main thread or try to use dispatch queues Using Dispatch Queues ``` dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispat...
Try to ``` - (IBAction)sendForm:(id)sender { [self performSelectorInBackground:@selector(loadData) withObject:activityIndicator]; [activityIndicator startAnimating]; UIAlertView* ahtung = [[UIAlertView alloc] initWithTitle:@"Спасибо" message:@"Ваша заявка принята!\nВ течение часа, Вам поступит звонок для подтвержд...
14,909,365
I Have planned to build an application with a server and multiple clients.When the clients connect to the server for the first time it must be given a id.Each time the client sends a request,the server sends the client a set of strings.the client then processes these strings and once it is done it again sends a request...
2013/02/16
[ "https://Stackoverflow.com/questions/14909365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078134/" ]
The crash occurs because you are trying to display the `UIAlertView` from a background thread. Never do that, all UI changes should be handled from main thread. Replace: ``` UIAlertView* ahtung = [[UIAlertView alloc] initWithTitle:@"Спасибо" message:@"Ваша заявка принята!\nВ течение часа, Вам поступит звонок для под...
Try to ``` - (IBAction)sendForm:(id)sender { [self performSelectorInBackground:@selector(loadData) withObject:activityIndicator]; [activityIndicator startAnimating]; UIAlertView* ahtung = [[UIAlertView alloc] initWithTitle:@"Спасибо" message:@"Ваша заявка принята!\nВ течение часа, Вам поступит звонок для подтвержд...
36,076,012
Say I have some class that manages a database connection. The user is supposed to call `close()` on instances of this class so that the db connection is terminated cleanly. Is there any way in python to get this object to call `close()` if the interpreter is closed or the object is otherwise picked up by the garbage c...
2016/03/18
[ "https://Stackoverflow.com/questions/36076012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391717/" ]
The only way to ensure such a method is called if you don't trust users is using `__del__` ([docs](https://docs.python.org/2/reference/datamodel.html#object.__del__)). From the docs: > > Called when the instance is about to be destroyed. > > > Note that there are lots of issues that make using del tricky. For exa...
Define [`__enter__`](https://docs.python.org/2/reference/datamodel.html#object.__enter__) and [`__exit__`](https://docs.python.org/2/reference/datamodel.html#object.__exit__) methods on your class and then use it with the [`with` statement](https://docs.python.org/2/reference/compound_stmts.html#with): ``` with MyClas...
64,160,370
I am writhing a python script in order to communicate to my tello drone via wifi. Once connected with the drone I can send UDP packets to send commands (this works perfectly fine). I want to receive the video stream from the drone via UDP packets arriving at my udp server on port 11111. This is described in the SDK doc...
2020/10/01
[ "https://Stackoverflow.com/questions/64160370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13410369/" ]
Hi Those who are following murtaza workshop , and unable to get the video stream , Use Open CV library version 4.4.0.46, and python interpreter 3.9.0. Try to make sure you use the above specified versions.
I play with tello a lot recently. what I saw from you code is you have entered "command" by right the light should turn green. The once you "stream on" the should be a return message. Check this message to see if there is any error. The only apparent error is video source ID. You did what manually said. [![enter ima...
64,160,370
I am writhing a python script in order to communicate to my tello drone via wifi. Once connected with the drone I can send UDP packets to send commands (this works perfectly fine). I want to receive the video stream from the drone via UDP packets arriving at my udp server on port 11111. This is described in the SDK doc...
2020/10/01
[ "https://Stackoverflow.com/questions/64160370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13410369/" ]
The problem on my side was solved as follows, it appear that my antivirus was blocking the incoming video packets from the tello drone. If you have windows defender, turn off public and private network firewalls wile you use the tello drone.
I play with tello a lot recently. what I saw from you code is you have entered "command" by right the light should turn green. The once you "stream on" the should be a return message. Check this message to see if there is any error. The only apparent error is video source ID. You did what manually said. [![enter ima...
64,160,370
I am writhing a python script in order to communicate to my tello drone via wifi. Once connected with the drone I can send UDP packets to send commands (this works perfectly fine). I want to receive the video stream from the drone via UDP packets arriving at my udp server on port 11111. This is described in the SDK doc...
2020/10/01
[ "https://Stackoverflow.com/questions/64160370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13410369/" ]
Hi Those who are following murtaza workshop , and unable to get the video stream , Use Open CV library version 4.4.0.46, and python interpreter 3.9.0. Try to make sure you use the above specified versions.
The problem on my side was solved as follows, it appear that my antivirus was blocking the incoming video packets from the tello drone. If you have windows defender, turn off public and private network firewalls wile you use the tello drone.
15,167,615
So basically my question relates to 'zip' (or izip), and this question which was asked before.... [Is there a better way to iterate over two lists, getting one element from each list for each iteration?](https://stackoverflow.com/questions/1919044/is-there-a-better-way-to-iterate-over-two-lists-getting-one-element-fro...
2013/03/01
[ "https://Stackoverflow.com/questions/15167615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448052/" ]
If you want to force broadcasting, you can use `numpy.lib.stride_tricks.broadcast_arrays`. Reusing your `cfun`: ``` def pyfun(a, b) : if not (np.isscalar(a) and np.isscalar(b)) : a_bcast, b_bcast = np.lib.stride_tricks.broadcast_arrays(a, b) return np.array([cfun(j, k) for j, k in zip(a_bcast, b_bc...
A decorator that optinally converts each of the arguments to a sequence might help. Here is the ordinary python (not numpy) version: ``` # TESTED def listify(f): def dolistify(*args): from collections import Iterable return f(*(a if isinstance(a, Iterable) else (a,) for a in args)) return dolistify @listi...
15,167,615
So basically my question relates to 'zip' (or izip), and this question which was asked before.... [Is there a better way to iterate over two lists, getting one element from each list for each iteration?](https://stackoverflow.com/questions/1919044/is-there-a-better-way-to-iterate-over-two-lists-getting-one-element-fro...
2013/03/01
[ "https://Stackoverflow.com/questions/15167615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448052/" ]
Since you use numpy, you don't need `zip()` to iterate several arrays and scalars. You can use `numpy.broadcast()`: ``` In [5]: list(np.broadcast([1,2,3], 10)) Out[5]: [(1, 10), (2, 10), (3, 10)] In [6]: list(np.broadcast([1,2,3], [10, 20, 30])) Out[6]: [(1, 10), (2, 20), (3, 30)] In [8]: list(np.broadcast([1...
A decorator that optinally converts each of the arguments to a sequence might help. Here is the ordinary python (not numpy) version: ``` # TESTED def listify(f): def dolistify(*args): from collections import Iterable return f(*(a if isinstance(a, Iterable) else (a,) for a in args)) return dolistify @listi...
15,167,615
So basically my question relates to 'zip' (or izip), and this question which was asked before.... [Is there a better way to iterate over two lists, getting one element from each list for each iteration?](https://stackoverflow.com/questions/1919044/is-there-a-better-way-to-iterate-over-two-lists-getting-one-element-fro...
2013/03/01
[ "https://Stackoverflow.com/questions/15167615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448052/" ]
Since you use numpy, you don't need `zip()` to iterate several arrays and scalars. You can use `numpy.broadcast()`: ``` In [5]: list(np.broadcast([1,2,3], 10)) Out[5]: [(1, 10), (2, 10), (3, 10)] In [6]: list(np.broadcast([1,2,3], [10, 20, 30])) Out[6]: [(1, 10), (2, 20), (3, 30)] In [8]: list(np.broadcast([1...
If you want to force broadcasting, you can use `numpy.lib.stride_tricks.broadcast_arrays`. Reusing your `cfun`: ``` def pyfun(a, b) : if not (np.isscalar(a) and np.isscalar(b)) : a_bcast, b_bcast = np.lib.stride_tricks.broadcast_arrays(a, b) return np.array([cfun(j, k) for j, k in zip(a_bcast, b_bc...
68,077,240
I have a python file that runs a machine learning algorithm that identifies circles in an image. From this python file, I am able to get all the coordinates (x and y) of every bounding box placed around the circles. I am appending all the coordinates into a local variable `xlist`/`ylist` (a list of all the integer valu...
2021/06/22
[ "https://Stackoverflow.com/questions/68077240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the pickle library. It saves the data as its original data type only.
You can store them in a `.txt` file. **Try this** ``` file = open('xlistFile.txt', 'w') for item in xlist: file.write(str(item)) file.close() ``` You can do the same for ylist
68,077,240
I have a python file that runs a machine learning algorithm that identifies circles in an image. From this python file, I am able to get all the coordinates (x and y) of every bounding box placed around the circles. I am appending all the coordinates into a local variable `xlist`/`ylist` (a list of all the integer valu...
2021/06/22
[ "https://Stackoverflow.com/questions/68077240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the pickle library. It saves the data as its original data type only.
You can save it to pickle like: ``` with open("xlist.pkl", "wb") as fw: pickle.dump(xlist, fw) ```
74,060,609
Despite im used to program stuff, im new in Python so i decide to learn by myself. So, i install VS code and python. At the moment i tryied to use stuff like *tensorflow*, is showing an error saying that **my imports are missing**. I've already tryed to install everything again, search for a solution online and nothin...
2022/10/13
[ "https://Stackoverflow.com/questions/74060609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20234417/" ]
Whether there are **multiple versions of python** in your environment, which will make the pip installed in one version of python instead of the python you are using. Use shortcuts **"Ctrl+shift+P"** and type **"Python: Select Interpreter"** to choose the correct python. Then use `pip install packagename` to reinstall...
Confirm you have downloaded python correctly: * Open terminal * Run `python --version` + (if that doesn't work try `python3 --version`
73,269,344
I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line: ``` while True: s=file.readline().strip() # this strip method cuts the '' character presents at the end # if we reach at the end of the file we'll b...
2022/08/07
[ "https://Stackoverflow.com/questions/73269344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711709/" ]
The thing you are looking for is called "end of file" character or EOF [how to find out wether a file is at its eof](https://stackoverflow.com/questions/10140281/how-to-find-out-whether-a-file-is-at-its-eof)
You can iterate on the opened file ``` lines = [] with open("some-file.txt") as some_file: for line in some_file: lines.append(line) ```
73,269,344
I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line: ``` while True: s=file.readline().strip() # this strip method cuts the '' character presents at the end # if we reach at the end of the file we'll b...
2022/08/07
[ "https://Stackoverflow.com/questions/73269344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711709/" ]
You'll be much better off using a `with open()` construct and an iterator on the file: ```py with open('myfile.txt') as f: for line in f: # do whatever with line or line.rstrip() ``` For example, you can read all the lines in one go into a `list`: ```py with open('myfile.txt') as f: lines = list(f) ...
The thing you are looking for is called "end of file" character or EOF [how to find out wether a file is at its eof](https://stackoverflow.com/questions/10140281/how-to-find-out-whether-a-file-is-at-its-eof)
73,269,344
I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line: ``` while True: s=file.readline().strip() # this strip method cuts the '' character presents at the end # if we reach at the end of the file we'll b...
2022/08/07
[ "https://Stackoverflow.com/questions/73269344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711709/" ]
The thing you are looking for is called "end of file" character or EOF [how to find out wether a file is at its eof](https://stackoverflow.com/questions/10140281/how-to-find-out-whether-a-file-is-at-its-eof)
Only print **Non-Empty** lines: ``` # Opening file file = open("text.txt","r") # Reading lines of file Lines = file.readlines() # Using conditional loop as lines are limited for line in Lines: # If line is empty simply pass if line.strip() == "": pass else: # Print line print(line....
73,269,344
I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line: ``` while True: s=file.readline().strip() # this strip method cuts the '' character presents at the end # if we reach at the end of the file we'll b...
2022/08/07
[ "https://Stackoverflow.com/questions/73269344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711709/" ]
You'll be much better off using a `with open()` construct and an iterator on the file: ```py with open('myfile.txt') as f: for line in f: # do whatever with line or line.rstrip() ``` For example, you can read all the lines in one go into a `list`: ```py with open('myfile.txt') as f: lines = list(f) ...
You can iterate on the opened file ``` lines = [] with open("some-file.txt") as some_file: for line in some_file: lines.append(line) ```
73,269,344
I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line: ``` while True: s=file.readline().strip() # this strip method cuts the '' character presents at the end # if we reach at the end of the file we'll b...
2022/08/07
[ "https://Stackoverflow.com/questions/73269344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19711709/" ]
You'll be much better off using a `with open()` construct and an iterator on the file: ```py with open('myfile.txt') as f: for line in f: # do whatever with line or line.rstrip() ``` For example, you can read all the lines in one go into a `list`: ```py with open('myfile.txt') as f: lines = list(f) ...
Only print **Non-Empty** lines: ``` # Opening file file = open("text.txt","r") # Reading lines of file Lines = file.readlines() # Using conditional loop as lines are limited for line in Lines: # If line is empty simply pass if line.strip() == "": pass else: # Print line print(line....
35,360,863
I'm trying to code a python script that finds an unknown number with the least amount of tries possible. All I know is the number is < 10000 Everytime I make a wrong input I get an "error" response. When I find the right number I get a "success" response. Let's assume in this case the number is 124. How would you ...
2016/02/12
[ "https://Stackoverflow.com/questions/35360863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5647184/" ]
If the number being `< 10000` is *all* you know, you have to try all numbers between `1` and `9999` (inclusive). The binary search algorithm as suggested in the comments does not help since a miss does not tell you if you are too high or too low. ``` for i in range(1, 10000): if i == number_you_are_looking_for: ...
I believe the fastest way is to use binary search which gives the answer in O(log n). ``` def binary_search(n, min_value, max_value): tries = 0 found = False if max_value < min_value: print("Maximum value must be bigger than the minimum value") elif n < min_value or n > max_value: pri...
34,032,681
Hi I'm seriously stuck when trying to filter out my xml document. Here is some example of the contents: ``` <sentence id="1" document_id="Perseus:text:1999.02.0029" > <primary>millermo</primary> <word id="1" /> <word id="2" /> <word id="3" /> <word id="4" /> </sentence> <sentence id="2" document_i...
2015/12/02
[ "https://Stackoverflow.com/questions/34032681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5628041/" ]
A loop and `String.format` should give you what you need: ``` for (int i = 1; i <= 10; i++) { String bob = String.format("C:\\bob\\Myfile%02d.txt", Integer.valueOf(i)); // ... } ``` The format pattern `%02d` pads an integer with a zero given that it is less than two digits in length, as defined in the [synta...
If you want to walk through subdirectories you may also try: ``` try { Files.walk(Paths.get(directory)).filter(f -> Pattern.matches("myFile\\d{2}\\.txt", f.toFile().getName())).forEach(f -> { System.out.println("WHAT YOU WANT TO DO WITH f"); }); } catch (IOException e) { e.printStackTrace()...
49,627,914
I'm trying to execute a shell command through python. The command is like the following one: ``` su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ filename.pdf' " someuser ``` So, when I try to do it in python: ``` command = "su -c \"lftp -c 'open -u user,password ftp://127.0.0.1; get ivan\'s\ f...
2018/04/03
[ "https://Stackoverflow.com/questions/49627914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8369505/" ]
If you printed your test string you would notice that it results in the following: ``` su -c "lftp -c 'open -u user,password ftp://127.0.0.1; get ivan's\ filename.pdf' " someuser ``` The problem is that you need to escape the slash that you use to escape the single quote in order to keep Python from eating it. ``` ...
Using subprocess.call() is the best and more secure way to perform this task. Here's an example from the [documentation page](https://docs.python.org/2/library/subprocess.html#subprocess.call): ``` subprocess.call(["ls", "-l"]) # As you can see we have here the command and a parameter ``` About the error I think it...